问:
how to model a many-to-many relationship, associated with a has-many relationship rails
I have the following scenario:

Students belongs_to and has many courses,

courses has_many lessons

lessons belongs_to course

This is my current model:

```<code>class Student < ActiveRecord::Base
  has_many  :studentcourses
  has_many  :courses, :through => :studentcourses
end

class StudentCourse < ActiveRecord::Base //join table
  belongs_to :course
  belongs_to :student
end

class Course < ActiveRecord::Base
  has_many  :studentcourses
  has_many  :students, :through => :studentcourses
  has_many  :lessons
end

class Lesson < ActiveRecord::Base
  belongs_to :course
end
</code>```

Therefore students get assigned to 1 or many Courses, and Courses have many lessons.
How can I model it so that I can retrieve all lessons of all the courses of a student and all the students that belong to lesson?

答:
Use native has_and_belongs_to_many relationship and specify than Student has many Lessons through Courses:

```<code>class Student < ActiveRecord::Base
  has_and_belongs_to_many :courses
  has_many :lessons, through: :courses
end

class Course < ActiveRecord::Base
  has_and_belongs_to_many :students
  has_many :lessons
end

class Lesson < ActiveRecord::Base
  belongs_to :course
end
</code>```

And this is a migration for HABTM relationship:

```<code>class CreateStudentsCourses < ActiveRecord::Migration
  create_table :students_courses, id: false do |t|
    t.belongs_to :student, index: true
    t.belongs_to :course, index: true
  end
end
</code>```

This way you can get all student's lessons @some_student.lessons, but, unfortunately, you can't get @some_lesson.students, because there's no belongs_to :through association, but you can delegate students method:

```<code>class Lesson < ActiveRecord::Base
  belongs_to :course
  delegate :students, to: :course
end
</code>```

This way, calling @lesson.students, method students will be called on an associated Course, which has this method defined.

Body:
I have the following scenario:

Students belongs_to and has many courses,

courses has_many lessons

lessons belongs_to course

This is my current model:

class Student < ActiveRecord::Base
  has_many  :studentcourses
  has_many  :courses, :through => :studentcourses
end

class StudentCourse < ActiveRecord::Base //join table
  belongs_to :course
  belongs_to :student
end

class Course < ActiveRecord::Base
  has_many  :studentcourses
  has_many  :students, :through => :studentcourses
  has_many  :lessons
end

class Lesson < ActiveRecord::Base
  belongs_to :course
end

Therefore students get assigned to 1 or many Courses, and Courses have many lessons.
How can I model it so that I can retrieve all lessons of all the courses of a student and all the students that belong to lesson?

Body:
Use native has_and_belongs_to_many relationship and specify than Student has many Lessons through Courses:

class Student < ActiveRecord::Base
  has_and_belongs_to_many :courses
  has_many :lessons, through: :courses
end

class Course < ActiveRecord::Base
  has_and_belongs_to_many :students
  has_many :lessons
end

class Lesson < ActiveRecord::Base
  belongs_to :course
end

And this is a migration for HABTM relationship:

class CreateStudentsCourses < ActiveRecord::Migration
  create_table :students_courses, id: false do |t|
    t.belongs_to :student, index: true
    t.belongs_to :course, index: true
  end
end

This way you can get all student's lessons @some_student.lessons, but, unfortunately, you can't get @some_lesson.students, because there's no belongs_to :through association, but you can delegate students method:

class Lesson < ActiveRecord::Base
  belongs_to :course
  delegate :students, to: :course
end

This way, calling @lesson.students, method students will be called on an associated Course, which has this method defined.


来源: stackexchange

问:
How to send data to php from angularjs and ionic
I am an angular begginer, and I am currently trying to save some data in a data base with the $http() service, but it does not work. Could you help me, please? This is what I am trying to do:

Form:

<form name="form">
  <input ng-model="model.text" type="text" name="text">
  <button class="button" ng-click="saveData()"> Save </button>
</form>
```

<p>Controller of that page:</p>

<pre class="lang-js prettyprint-override"><code>.controller('pagCtrl', function ($scope, $http) {
  $scope.saveData = function () {

    $http ({
        url : 'http://localhost/prueba/www/php/enviar_datos.php',
        method : 'POST',
        data : { text : $scope.form.text.value }
    }).then (function (response) {

    }, function (response) {

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

PHP:

<?php
    $link = mysqli_connect("localhost", "root", "", "testDB");

    if (mysqli_connect_errno()) {
        die("Error de conexión: " . mysqli_connect_error());
    }

    mysqli_set_charset($link, 'utf8');
    mysqli_query($link, "INSERT INTO tabla_prueba (texto) VALUES ('" . $_POST['text'] . "')");
    mysqli_close($link);
?>
```

I think the problem is that it does not connect correctly to the php url.
I am working with Ionic. Thank you for your attention!

答:
add $scope.form.text={} and in your js

data:$.param($scope.form.text);

and remove ng-click in button put ng-submit in form ng-submit="saveData()"

So you should rename your model . it hard to read.

```<code>ng-model="formData.text"
</code>```

and in js

```<code>$scope.formData ={}
data:$.param($scope.formData)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am an angular begginer, and I am currently trying to save some data in a data base with the $http() service, but it does not work. Could you help me, please? This is what I am trying to do:

Form:

<form name="form">
  <input ng-model="model.text" type="text" name="text">
  <button class="button" ng-click="saveData()"> Save </button>
</form>

Controller of that page:

.controller('pagCtrl', function ($scope, $http) {
  $scope.saveData = function () {

    $http ({
        url : 'http://localhost/prueba/www/php/enviar_datos.php',
        method : 'POST',
        data : { text : $scope.form.text.value }
    }).then (function (response) {

    }, function (response) {

    });
  }
})

PHP:

<?php
    $link = mysqli_connect("localhost", "root", "", "testDB");

    if (mysqli_connect_errno()) {
        die("Error de conexión: " . mysqli_connect_error());
    }

    mysqli_set_charset($link, 'utf8');
    mysqli_query($link, "INSERT INTO tabla_prueba (texto) VALUES ('" . $_POST['text'] . "')");
    mysqli_close($link);
?>

I think the problem is that it does not connect correctly to the php url.
I am working with Ionic. Thank you for your attention!

Body:
add $scope.form.text={} and in your js

data:$.param($scope.form.text);

and remove ng-click in button put ng-submit in form ng-submit="saveData()"

So you should rename your model . it hard to read.

ng-model="formData.text"

and in js

$scope.formData ={}
data:$.param($scope.formData)


问:
CodeIgniter Hosting 500 Error
I have uploaded my project on a domian www.abc.com/beta using CodeIgniter on my localhost server.  Everything is working fine but when I upload it on the server I am getting a 500 server error.

My .htacess code is

```<code>RewriteEngine On
RewriteBase http://www.example.com/beta/
RewriteCond %{REQUEST_URI} ^system.*
RewriteCond $1 !^(index\.php|images|js|uploads|css|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</code>```

My config file base_url,

```<code>$config['base_url'] = 'http://www.example.com/beta/';
</code>```

答:
Change...

```<code>RewriteBase http://www.example.com/beta/
</code>```

into this...

```<code>RewriteBase "/beta/"
</code>```

See:  http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritebase

Title: CodeIgniter Hosting 500 Error

Body:
I have uploaded my project on a domian www.abc.com/beta using CodeIgniter on my localhost server.  Everything is working fine but when I upload it on the server I am getting a 500 server error.

My .htacess code is

RewriteEngine On
RewriteBase http://www.example.com/beta/
RewriteCond %{REQUEST_URI} ^system.*
RewriteCond $1 !^(index\.php|images|js|uploads|css|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

My config file base_url,

$config['base_url'] = 'http://www.example.com/beta/';

Body:
Change...

RewriteBase http://www.example.com/beta/

into this...

RewriteBase "/beta/"

See:  http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritebase


问:
Neo4J: shortest paths with specific relation types sequence constrain
I need to find shortest paths between nodes, but with some restrictions on relations types in good paths.

I have two relation types: A & B.
Path is considered bad if it has two or more consecutive relation of type B:

Good path: ()-A->()-A->()<-A-()-B->()-A->()-B->()

Bad path: ()-A->()-A->()<-A-()-B->()<-B-()-A->()

The Cypher query:

```<code>MATCH path=allShortestPaths( (p:P{idp:123})-[rel:A|B*]-(p2:P{idp:124}) )
WHERE *some-predicate-on-path-or-rel*
RETURN path
</code>```

is not a solution because the shortest good path may be longer than shortest bad paths.

Q1: Can this problem be solved by some Cypher query?

I can solve my problem with the embedded Java Neo4J API:

```<code>GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase("db/store/dir/path");
TraversalDescription td = graphDb.traversalDescription()
    .breadthFirst()
    .evaluator(Evaluators.toDepth(max_depth))
    .evaluator(Evaluators.endNodeIs(Evaluation.INCLUDE_AND_PRUNE, Evaluation.EXCLUDE_AND_CONTINUE, endNode))
    .evaluator(new DoubleB_PruneEvaluator());

static class DoubleB_PruneEvaluator implements Evaluator {
    @Override
    public Evaluation evaluate(final Path path) {
        Iterator<Relationship> lRels = path.reverseRelationships().iterator();
        if (lRels.hasNext()  &&  lRels.next().isType(MyRelTypes.B)) {
            if (lRels.hasNext()  &&  lRels.next().isType(MyRelTypes.B))
                return Evaluation.EXCLUDE_AND_PRUNE;
        }
        return Evaluation.INCLUDE_AND_CONTINUE;
    }
}
</code>```

Q2: Is this solution is quite efficient? Or how to improve?

But my application is written on PHP and interacts with Neo4j server via REST protocol.

Q3: How can I run this solution by some REST query?

答:
No intelligent person wouldn't answer me. So I will try myself.

A1: This problem cannot be solved by standard Cypher query. (My Neo4j version 3.1.1)

A2: This solution is not quite efficient for several reasons:

The standard function shortestPath is implemented by using more
efficient Bidirectional BFS.

This traversal description does not contain a stop condition when
the solution is found. The traversal will continue until the maximum
depth.

In addition, this solution finds only one path. The other paths of the same length will not be found.

A3: Java coded solutions can be added to a server by extending Neo4j.
I solve my problem using user-defined procedures:

my/app/RelType.java:

```<code>package my.app;

import org.neo4j.graphdb.*;

public enum RelType implements RelationshipType {
    A, B
}
</code>```

my/app/DoubleB_PruneEvaluator.java:

```<code>package my.app;

import java.util.*;
import org.neo4j.graphdb.*;
import org.neo4j.graphdb.traversal.*;

public class DoubleB_PruneEvaluator implements Evaluator {
    @Override
    public Evaluation evaluate(final Path path) {
        Iterator<Relationship> lRels = path.reverseRelationships().iterator();
        if (lRels.hasNext()  &&  lRels.next().isType(RelType.marry)) {
            if (lRels.hasNext()  &&  lRels.next().isType(RelType.marry))
                return Evaluation.EXCLUDE_AND_PRUNE;
        }
        return Evaluation.INCLUDE_AND_CONTINUE;
    }
}
</code>```

my/app/Procedures.java:

```<code>package my.app;

import java.util.stream.Stream;

import org.neo4j.graphdb.*;
import org.neo4j.procedure.*;
import org.neo4j.graphdb.traversal.*;

public class Procedures {
    @Context
    public GraphDatabaseService db;

    @Procedure
    public Stream<PathHit> shortestWo2B(
                                @Name("from") Node fromNode,
                                @Name("to")   Node toNode,
                                @Name("maxDepth") long maxDepth)
    {
        TraversalDescription td = db.traversalDescription()
            .breadthFirst()
            .relationships(RelType.A)
            .relationships(RelType.B)
            .evaluator(Evaluators.toDepth((int)maxDepth))
            .evaluator(Evaluators.endNodeIs(Evaluation.INCLUDE_AND_PRUNE, Evaluation.EXCLUDE_AND_CONTINUE, toNode))
            .evaluator(new DoubleB_PruneEvaluator());

        return td.traverse(fromNode)
                .stream()
                .map( PathHit::new );
    }

    public static class PathHit {
        public Path path;

        public PathHit(Path path) {
            this.path = path;
        }
    }
}
</code>```

Doc: https://neo4j.com/docs/java-reference/3.1/javadocs/index.html?org/neo4j/procedure/Procedure.html

A few words about the compilation and installation plugin:

As a beginner in Java, I decided that utilities Eclipse and Maven is too heavy. I prefer to use simple javac & jar:

```<code>$ export CLASSPATH=/path/to/neo4j-install-dir/lib/*:.
$ javac my/app/*.java
$ jar -cf my-neo4j-plugin.jar my/app/*.class
$ cp my-neo4j-plugin.jar /path/to/neo4j-install-dir/plugins/
$ /path/to/neo4j-install-dir/bin/neo4j restart
</code>```

Now we can run the Cypher query:

```<code>MATCH (p1:P{idp:123})
MATCH (p2:P{idp:124})
CALL my.app.shortestWo2B(p1,p2,100) YIELD path
RETURN path;
</code>```

Body:
I need to find shortest paths between nodes, but with some restrictions on relations types in good paths.

I have two relation types: A & B.
Path is considered bad if it has two or more consecutive relation of type B:

Good path: ()-A->()-A->()<-A-()-B->()-A->()-B->()

Bad path: ()-A->()-A->()<-A-()-B->()<-B-()-A->()

The Cypher query:

MATCH path=allShortestPaths( (p:P{idp:123})-[rel:A|B*]-(p2:P{idp:124}) )
WHERE *some-predicate-on-path-or-rel*
RETURN path

is not a solution because the shortest good path may be longer than shortest bad paths.

Q1: Can this problem be solved by some Cypher query?

I can solve my problem with the embedded Java Neo4J API:

GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase("db/store/dir/path");
TraversalDescription td = graphDb.traversalDescription()
    .breadthFirst()
    .evaluator(Evaluators.toDepth(max_depth))
    .evaluator(Evaluators.endNodeIs(Evaluation.INCLUDE_AND_PRUNE, Evaluation.EXCLUDE_AND_CONTINUE, endNode))
    .evaluator(new DoubleB_PruneEvaluator());

static class DoubleB_PruneEvaluator implements Evaluator {
    @Override
    public Evaluation evaluate(final Path path) {
        Iterator<Relationship> lRels = path.reverseRelationships().iterator();
        if (lRels.hasNext()  &&  lRels.next().isType(MyRelTypes.B)) {
            if (lRels.hasNext()  &&  lRels.next().isType(MyRelTypes.B))
                return Evaluation.EXCLUDE_AND_PRUNE;
        }
        return Evaluation.INCLUDE_AND_CONTINUE;
    }
}

Q2: Is this solution is quite efficient? Or how to improve?

But my application is written on PHP and interacts with Neo4j server via REST protocol.

Q3: How can I run this solution by some REST query?

Body:
No intelligent person wouldn't answer me. So I will try myself.

A1: This problem cannot be solved by standard Cypher query. (My Neo4j version 3.1.1)

A2: This solution is not quite efficient for several reasons:

The standard function shortestPath is implemented by using more
efficient Bidirectional BFS.

This traversal description does not contain a stop condition when
the solution is found. The traversal will continue until the maximum
depth.

In addition, this solution finds only one path. The other paths of the same length will not be found.

A3: Java coded solutions can be added to a server by extending Neo4j.
I solve my problem using user-defined procedures:

my/app/RelType.java:

package my.app;

import org.neo4j.graphdb.*;

public enum RelType implements RelationshipType {
    A, B
}

my/app/DoubleB_PruneEvaluator.java:

package my.app;

import java.util.*;
import org.neo4j.graphdb.*;
import org.neo4j.graphdb.traversal.*;

public class DoubleB_PruneEvaluator implements Evaluator {
    @Override
    public Evaluation evaluate(final Path path) {
        Iterator<Relationship> lRels = path.reverseRelationships().iterator();
        if (lRels.hasNext()  &&  lRels.next().isType(RelType.marry)) {
            if (lRels.hasNext()  &&  lRels.next().isType(RelType.marry))
                return Evaluation.EXCLUDE_AND_PRUNE;
        }
        return Evaluation.INCLUDE_AND_CONTINUE;
    }
}

my/app/Procedures.java:

package my.app;

import java.util.stream.Stream;

import org.neo4j.graphdb.*;
import org.neo4j.procedure.*;
import org.neo4j.graphdb.traversal.*;

public class Procedures {
    @Context
    public GraphDatabaseService db;

    @Procedure
    public Stream<PathHit> shortestWo2B(
                                @Name("from") Node fromNode,
                                @Name("to")   Node toNode,
                                @Name("maxDepth") long maxDepth)
    {
        TraversalDescription td = db.traversalDescription()
            .breadthFirst()
            .relationships(RelType.A)
            .relationships(RelType.B)
            .evaluator(Evaluators.toDepth((int)maxDepth))
            .evaluator(Evaluators.endNodeIs(Evaluation.INCLUDE_AND_PRUNE, Evaluation.EXCLUDE_AND_CONTINUE, toNode))
            .evaluator(new DoubleB_PruneEvaluator());

        return td.traverse(fromNode)
                .stream()
                .map( PathHit::new );
    }

    public static class PathHit {
        public Path path;

        public PathHit(Path path) {
            this.path = path;
        }
    }
}

Doc: https://neo4j.com/docs/java-reference/3.1/javadocs/index.html?org/neo4j/procedure/Procedure.html

A few words about the compilation and installation plugin:

As a beginner in Java, I decided that utilities Eclipse and Maven is too heavy. I prefer to use simple javac & jar:

$ export CLASSPATH=/path/to/neo4j-install-dir/lib/*:.
$ javac my/app/*.java
$ jar -cf my-neo4j-plugin.jar my/app/*.class
$ cp my-neo4j-plugin.jar /path/to/neo4j-install-dir/plugins/
$ /path/to/neo4j-install-dir/bin/neo4j restart

Now we can run the Cypher query:

MATCH (p1:P{idp:123})
MATCH (p2:P{idp:124})
CALL my.app.shortestWo2B(p1,p2,100) YIELD path
RETURN path;


问:
Exact Online API Returns XML Error

What I do

I'm really confused about the following.

I'm logged in via Exact Online oAuth2 (works)

I'm redirected to the set redirect url (works)

Now, I'm doing a POST request for creating an CRM Account to

https://start.exactonline.com/api/v1/1645882/crm/Accounts

with headers:

Authorization: Bearer MY_TOKEN

Content-Type: application/json

with json data:

```<code>{
    "Name": "James Fellows",
    "Code": "JF"
}
</code>```

Code (simplified)

```<code>$this->client->request('POST', 'https://start.exactonline.com/api/v1/1645882/crm/Accounts', ['headers' => ['Authorization' => 'Bearer MY_TOKEN']], ['json' => json_encode(['Name' => 'James Fellows', 'Code' => 'JF'])]);
</code>```

Problem

And now the problem. I always get this error:

```<code><?xml version="1.0" encoding="utf-8" standalone="yes"?>
<error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">\r\n
    <code></code>
    <message xml:lang="">Error processing request stream. JSON text specified is not valid.
</message>
</error>
</code>```

Documentation

I used the following api documentation:

https://developers.exactonline.com/#RestSampleCode.html%3FTocPath%3DExact%2520Online%2520REST%2520API%7CCode%2520examples%7C_____1

https://start.exactonline.com/docs/HlpRestAPIResourcesDetails.aspx?name=CRMAccounts

答:
You should omit the ID field. That field will be auto-filled.

There are also some problems with the formatting of your JSON (quotes to be specific). This one should do:

```<code>{ Code : 'JF'
, Name : 'Jeff Fellows'
}
</code>```

Title: Exact Online API Returns XML Error

Body:
What I do

I'm really confused about the following.

I'm logged in via Exact Online oAuth2 (works)

I'm redirected to the set redirect url (works)

Now, I'm doing a POST request for creating an CRM Account to

https://start.exactonline.com/api/v1/1645882/crm/Accounts

with headers:

Authorization: Bearer MY_TOKEN

Content-Type: application/json

with json data:

{
    "Name": "James Fellows",
    "Code": "JF"
}

Code (simplified)

$this->client->request('POST', 'https://start.exactonline.com/api/v1/1645882/crm/Accounts', ['headers' => ['Authorization' => 'Bearer MY_TOKEN']], ['json' => json_encode(['Name' => 'James Fellows', 'Code' => 'JF'])]);

Problem

And now the problem. I always get this error:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">\r\n

    <message xml:lang="">Error processing request stream. JSON text specified is not valid.
</message>
</error>

Documentation

I used the following api documentation:

https://developers.exactonline.com/#RestSampleCode.html%3FTocPath%3DExact%2520Online%2520REST%2520API%7CCode%2520examples%7C_____1

https://start.exactonline.com/docs/HlpRestAPIResourcesDetails.aspx?name=CRMAccounts

Body:
You should omit the ID field. That field will be auto-filled.

There are also some problems with the formatting of your JSON (quotes to be specific). This one should do:

{ Code : 'JF'
, Name : 'Jeff Fellows'
}


问:
Allowing a process to use more than 4GB RAM
I am running a 64-bit Ubuntu 12.04 on a machine with 8GB RAM. I wrote a C++ program that I compiled with the -m64 (force 64-bit executable) flag in gcc. I checked that the resulting executable is indeed 64-bit.

However, the process caps at using 4GB RAM. How can I allow it to use more?

Edit: output of ulimit -a

```<code>ulimit -a
core file size          (blocks, -c) 0

data seg size           (kbytes, -d) unlimited

scheduling priority             (-e) 0

file size               (blocks, -f) unlimited

pending signals                 (-i) 62900

max locked memory       (kbytes, -l) 64

max memory size         (kbytes, -m) unlimited

open files                      (-n) 1024

pipe size            (512 bytes, -p) 8

POSIX message queues     (bytes, -q) 819200

real-time priority              (-r) 0

stack size              (kbytes, -s) 8192

cpu time               (seconds, -t) unlimited

max user processes              (-u) 62900

virtual memory          (kbytes, -v) unlimited

file locks                      (-x) unlimited
</code>```

Edit 2: link to output of dstat -cdgms --vm

https://www.dropbox.com/s/927s5x6v4bhp4qs/dstat_log.xlsx?dl=0

答: As best as I can tell, adding the -m64 compilation flag (force 64 bit executable) actually solved my initial problem (app crashing), and what followed was a coincidence that my app actually required so little memory over 4GB (limit for a 32-bit executable) that it showed up as 4GB flat in System Monitor. Thank you to all who contributed, there are a number of things in the comments that might help people trying to diagnose similar issues.</p>

Body:
I am running a 64-bit Ubuntu 12.04 on a machine with 8GB RAM. I wrote a C++ program that I compiled with the -m64 (force 64-bit executable) flag in gcc. I checked that the resulting executable is indeed 64-bit.

However, the process caps at using 4GB RAM. How can I allow it to use more?

Edit: output of ulimit -a

ulimit -a
core file size          (blocks, -c) 0

data seg size           (kbytes, -d) unlimited

scheduling priority             (-e) 0

file size               (blocks, -f) unlimited

pending signals                 (-i) 62900

max locked memory       (kbytes, -l) 64

max memory size         (kbytes, -m) unlimited

open files                      (-n) 1024

pipe size            (512 bytes, -p) 8

POSIX message queues     (bytes, -q) 819200

real-time priority              (-r) 0

stack size              (kbytes, -s) 8192

cpu time               (seconds, -t) unlimited

max user processes              (-u) 62900

virtual memory          (kbytes, -v) unlimited

file locks                      (-x) unlimited

Edit 2: link to output of dstat -cdgms --vm

https://www.dropbox.com/s/927s5x6v4bhp4qs/dstat_log.xlsx?dl=0


问:
FLTK - Can't find headers even if I include the correct directory
I am trying to compile a FLTK project from linux, using the output of the commands:

fltk-config --use-gl --use-images --ldflags

And:

fltk-config --use-gl --use-images --cxxflags

I am using this makefile to compile the project:

I installed the latest FLTK version by just downloading it from fltk.org, and then I compiled and installed it. I also installed X11 and OpenGL. But I still get these errors:

I checked the file system and these headers are in /usr/local/include/FL even if they are not recognized, although I included the directory (-I/usr/local/include) and then in the .cpp and .h files:

```<code>#include <FL/Fl_PNG_Image.H>
#include <FL/Fl_Box.H>
etc...
</code>```

What could be the problem? do I need to install more libraries?

EDIT

I tried to change the makefile:

```<code>CXXFLAGS=-I/usr/local/include -I/usr/local/include/FL/images -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_THREAD_SAFE -D_REENTRANT -I/home/ramy/boost_1_63_0 -std=c++11

LDFLAGS=-L/usr/local/lib -lfltk_images -lfltk_png -lz -lfltk_jpeg -lfltk_gl -lGLU -lGL -lfltk -lXrender -lXcursor -lXfixes -lXext -lXinerama -lpthread -ldl -lm -lX11 -L/home/ramy/boost_1_63_0/lib

SOURCES=Car.cpp Map.cpp CarState.cpp Utilities.cpp CarCollection.cpp TableView.cpp MapView.cpp
OBJECTS=Car.o Map.o CarState.o Utilities.o CarCollection.o TableView.o MapView.o

make:
    g++ $(LDFLAGS) $(CXXFLAGS) -c $(SOURCES)
    g++ $(LDFLAGS) $(CXXFLAGS) -o ../Evolution table-example.cpp $(OBJECTS)
clean:
    rm -f $(OBJECTS) ../Evolution
</code>```

But I still get the same errors.

答:
Those errors don't mean that you are lacking headers, but libraries.

Here you can read the basis (go down to "Compiling Programs with Standard Compilers").
Basically add -L/usr/local/lib -lfltk -lXext -lX11 -lm to your app compiler command; or use fltk-config --cxxflags.

Body:
I am trying to compile a FLTK project from linux, using the output of the commands:

fltk-config --use-gl --use-images --ldflags

And:

fltk-config --use-gl --use-images --cxxflags

I am using this makefile to compile the project:

I installed the latest FLTK version by just downloading it from fltk.org, and then I compiled and installed it. I also installed X11 and OpenGL. But I still get these errors:

I checked the file system and these headers are in /usr/local/include/FL even if they are not recognized, although I included the directory (-I/usr/local/include) and then in the .cpp and .h files:

#include <FL/Fl_PNG_Image.H>
#include <FL/Fl_Box.H>
etc...

What could be the problem? do I need to install more libraries?

EDIT

I tried to change the makefile:

CXXFLAGS=-I/usr/local/include -I/usr/local/include/FL/images -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_THREAD_SAFE -D_REENTRANT -I/home/ramy/boost_1_63_0 -std=c++11

LDFLAGS=-L/usr/local/lib -lfltk_images -lfltk_png -lz -lfltk_jpeg -lfltk_gl -lGLU -lGL -lfltk -lXrender -lXcursor -lXfixes -lXext -lXinerama -lpthread -ldl -lm -lX11 -L/home/ramy/boost_1_63_0/lib

SOURCES=Car.cpp Map.cpp CarState.cpp Utilities.cpp CarCollection.cpp TableView.cpp MapView.cpp
OBJECTS=Car.o Map.o CarState.o Utilities.o CarCollection.o TableView.o MapView.o

make:
    g++ $(LDFLAGS) $(CXXFLAGS) -c $(SOURCES)
    g++ $(LDFLAGS) $(CXXFLAGS) -o ../Evolution table-example.cpp $(OBJECTS)
clean:
    rm -f $(OBJECTS) ../Evolution

But I still get the same errors.


问:
Proxymillion IPs with cURL
I am using proxymillion to scrape data from google. I am using cURL but not getting the result and getting error Error 405 (Method Not Allowed)!!1

my code

```<code>$proxies[] = 'username:password@IP:port';  // Some proxies require user, password, IP and port number
$proxies[] = 'username:password@IP:port';  // Some proxies require user,   password, IP and port number
$proxies[] = 'username:password@IP:port';  // Some proxies require user,     password, IP and port number
$proxies[] = 'username:password@IP:port';  // Some proxies require user,  password, IP and port number

if (isset($proxies)) {  // If the $proxies array contains items, then
$proxy = $proxies[array_rand($proxies)];    // Select a random proxy from the array and assign to $proxy variable
}
$ch = curl_init();
if (isset($proxy)) {    // If the $proxy variable is set, then
    curl_setopt($ch, CURLOPT_PROXY, $proxy);    // Set CURLOPT_PROXY with proxy in $proxy variable
}
$url="https://www.google.com.pk/?gws_rd=cr,ssl&ei=8kXQWNChIsTSvgSZ3J24DA#q=pakistan&*";

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
// curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies.txt");
// curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies.txt");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$page = curl_exec($ch);
curl_close($ch);
$dom = new simple_html_dom();
$html = $dom->load($page);

$title=$html->find("title",0);
echo $title->innertext;
</code>```

答:
If I guess right you are looking for a budget solution for scraping Google, that's why you switched out for the proxymillion provider in the sample code you linked  in comments ?

You can not scrape with massively shared proxies (that's the provider you took), Google will spot them either directly or within a few pages and block.

Also using "&ei=8kXQWNChIsTSvgSZ3J24DA" is not the best idea, that's not a default entry into Google and will probably link your scrape request with your browser (where you have that parameter from originally).

If you look for a budget solution you can consider using a scraping service (php source code here: http://scraping.services/?api&chapter=Source%20Code ), that's cheaper than private proxies in most cases and allows to scrape ten thousands of keywords for a few USD.

Alternatively, if you want to continue that route I would suggest testing your proxymillion performance using a simple bash script.

Use curl or lynx in a bash script (If you use linux, otherwise you can do the same on windows with MinGW/msys) and just make them access Google with the proxies. See if it works at all or if you get blocked within a few pages.

But even if you succeed: any shared proxy provider will be unreliable in "performance".

Title: Proxymillion IPs with cURL

Body:
I am using proxymillion to scrape data from google. I am using cURL but not getting the result and getting error Error 405 (Method Not Allowed)!!1

my code

$proxies[] = 'username:password@IP:port';  // Some proxies require user, password, IP and port number
$proxies[] = 'username:password@IP:port';  // Some proxies require user,   password, IP and port number
$proxies[] = 'username:password@IP:port';  // Some proxies require user,     password, IP and port number
$proxies[] = 'username:password@IP:port';  // Some proxies require user,  password, IP and port number

if (isset($proxies)) {  // If the $proxies array contains items, then
$proxy = $proxies[array_rand($proxies)];    // Select a random proxy from the array and assign to $proxy variable
}
$ch = curl_init();
if (isset($proxy)) {    // If the $proxy variable is set, then
    curl_setopt($ch, CURLOPT_PROXY, $proxy);    // Set CURLOPT_PROXY with proxy in $proxy variable
}
$url="https://www.google.com.pk/?gws_rd=cr,ssl&ei=8kXQWNChIsTSvgSZ3J24DA#q=pakistan&*";

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
// curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies.txt");
// curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies.txt");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$page = curl_exec($ch);
curl_close($ch);
$dom = new simple_html_dom();
$html = $dom->load($page);

$title=$html->find("title",0);
echo $title->innertext;


问:
Limiting CPU speed for profiling
I'm trying to optimize several bottlenecks on an application which is supposed to run on a really wide range of CPUs and architectures (some of them very close to embeded devices).

The results of my profiler, however, aren't really significant because of the speed of my CPU. Is there any way (preferably under Windows or Mac OS X) to limit the speed of my CPU for profiling purposes?

I've thought about using a virtual machine, but haven't found any with such functionality.

答:
I've thought about using a virtual
  machine, but haven't found any with
  such functionality.

Why do you need a VM that explicitly offers that functionality? Just limit the CPU usage of the VM in the host OS (where it is just a regular process). That should have exactly the same effect.

You can do this e.g. using cpulimit on Linux; similar solutions exist for MS Windows.

OwnerDisplayName: Tanoku

ContentLicense: CC BY-SA 2.5

Title: Limiting CPU speed for profiling


问:
MongoError: connection 4 to cluster closed
I have a function in NodeJS using Mongoose driver like below:

Pseudocode:

```<code>function someFn(someParams) {
    // Step 1: a couple of very fast mongo queries (in milliseconds)
    // Step 2: HUGE CPU processing - think millions of data grouped, mapped, etc. (takes about a minute)
    // Step 3: another mongo query which inserts the results from Step 2 into a collection
}
</code>```

At step 3, I get the following error:

```<code>MongoError: connection 4 to cluster closed
at Function.MongoError.create (/home/some-user/my-repo/node_modules/mongodb-core/lib/error.js:29:11)
at TLSSocket.<anonymous> (/home/some-user/my-repo/node_modules/mongodb-core/lib/connection/connection.js:202:22)
at Object.onceWrapper (events.js:293:19)
at emitOne (events.js:101:20)
at TLSSocket.emit (events.js:191:7)
at _handle.close (net.js:513:12)
at Socket.done (_tls_wrap.js:332:7)
at Object.onceWrapper (events.js:293:19)
at emitOne (events.js:101:20)
at Socket.emit (events.js:191:7)
at TCP._handle.close [as _onclose] (net.js:513:12)
</code>```

My MongoDB connection params are as follows:

```<code>mongoose.connect(connStr, {
    server: {
        socketOptions: {
            keepAlive: 300000,
            connectTimeoutMS: 300000,
            socketTimeoutMS: 300000,
            auto_reconnect: true
        }
    }
});
</code>```

I don't understand why I'm getting this error at Step 3. Can someone help me out with this, please?

答: Figured out the issue after hours of debugging. My Step 3 mongoose query had too many documents(in the order of millions, from Step 2). The error from mongoose gives no reason why the connection is closing. A message like Too many documents or Too large query would've gone a long way in saving a lot of time.

Body:
I have a function in NodeJS using Mongoose driver like below:

Pseudocode:

function someFn(someParams) {
    // Step 1: a couple of very fast mongo queries (in milliseconds)
    // Step 2: HUGE CPU processing - think millions of data grouped, mapped, etc. (takes about a minute)
    // Step 3: another mongo query which inserts the results from Step 2 into a collection
}

At step 3, I get the following error:

MongoError: connection 4 to cluster closed
at Function.MongoError.create (/home/some-user/my-repo/node_modules/mongodb-core/lib/error.js:29:11)
at TLSSocket.<anonymous> (/home/some-user/my-repo/node_modules/mongodb-core/lib/connection/connection.js:202:22)
at Object.onceWrapper (events.js:293:19)
at emitOne (events.js:101:20)
at TLSSocket.emit (events.js:191:7)
at _handle.close (net.js:513:12)
at Socket.done (_tls_wrap.js:332:7)
at Object.onceWrapper (events.js:293:19)
at emitOne (events.js:101:20)
at Socket.emit (events.js:191:7)
at TCP._handle.close [as _onclose] (net.js:513:12)

My MongoDB connection params are as follows:

mongoose.connect(connStr, {
    server: {
        socketOptions: {
            keepAlive: 300000,
            connectTimeoutMS: 300000,
            socketTimeoutMS: 300000,
            auto_reconnect: true
        }
    }
});

I don't understand why I'm getting this error at Step 3. Can someone help me out with this, please?


问:
XPath select element but exclude children in the result
Is it possible to create an XPath that selects an element but removes some children? I have an RSS feed that looks like:

```<code><rss>
  <channel>
    <title>My Feed</title>
    <item>...</item>
    <item>...</item>
    <item>...</item>
  </channel>
</rss>
</code>```

I want an XPath expression that will return the following XML:

```<code><rss>
  <channel>
    <title>My Feed</title>
  </channel>
</rss>
</code>```

Which is just the above XML, but without the <item> tags. Is this possible to do with XPath, and if so what does the XPath expression look like?

答:
Your XPath expression selects nodes in the source tree (think of it as returning references to those nodes). Those nodes are still in the original tree, and you can navigate from the selected nodes to their ancestors, descendants, and siblings.

It's very common for applications that use XPath to select nodes to then display the entire tree rooted at that node. It's less common (but equally feasible) for the application to navigate to ancestors or siblings of those nodes.

So the first thing is: there aren't any children in the result. You see the children because the application that issues the XPath expression is choosing to navigate from the returned nodes to their children.

If you want to retain some children and drop others, then you are doing transformation rather than just selection, and XPath is therefore no longer the tool for the job: you need XSLT or XQuery.

Body:
Is it possible to create an XPath that selects an element but removes some children? I have an RSS feed that looks like:

<rss>
  <channel>
    <title>My Feed</title>
    <item>...</item>
    <item>...</item>
    <item>...</item>
  </channel>
</rss>

I want an XPath expression that will return the following XML:

<rss>
  <channel>
    <title>My Feed</title>
  </channel>
</rss>

Which is just the above XML, but without the <item> tags. Is this possible to do with XPath, and if so what does the XPath expression look like?


问:
Calculating an Avg in SQL excluding the current row
I have a DB where certain records are tagged with an ID and I want create a view that contains the Average of all those records with the same ID, EXCLUDING the current record.  For example, if my data looks like this:

```<code>ROW - ID - Value
1     1    20
2     1    30
3     1    40
4     2    60
5     2    80
6     2    40
7     3    50
8     3    20
9     3    40
</code>```

My view needs to calculate the average of every row with the same ID, EXCLUDING the row it's on, so my output would look something like this:

```<code>ROW - ID - Value AVG
1     1    20    35
2     1    30    30
3     1    40    25
4     2    60    60
5     2    80    50
6     2    40    70
7     3    50    30
8     3    20    55
9     3    40    35
</code>```

So, in the case of row 3, it's extracted rows 1 and 2, as they have the same ID and given me the avg of their values - 25.

I'm gone round the houses on this for a while now, but can't seem to nail it.  Any help would be appreciated.

Body:
I have a DB where certain records are tagged with an ID and I want create a view that contains the Average of all those records with the same ID, EXCLUDING the current record.  For example, if my data looks like this:

ROW - ID - Value
1     1    20
2     1    30
3     1    40
4     2    60
5     2    80
6     2    40
7     3    50
8     3    20
9     3    40

My view needs to calculate the average of every row with the same ID, EXCLUDING the row it's on, so my output would look something like this:

ROW - ID - Value AVG
1     1    20    35
2     1    30    30
3     1    40    25
4     2    60    60
5     2    80    50
6     2    40    70
7     3    50    30
8     3    20    55
9     3    40    35

So, in the case of row 3, it's extracted rows 1 and 2, as they have the same ID and given me the avg of their values - 25.

I'm gone round the houses on this for a while now, but can't seem to nail it.  Any help would be appreciated.

Body:
This query works for me:

select t1.row, t1.id, t1.value, (select avg(value) from test_table as t2 where t1.id = t2.id and t1.row != t2.row) as avg from test_table as t1;

Data in table created by me (i assume is simmilar to Yours):

mysql> select * from test_table;
+-----+------+-------+
| row | id   | value |
+-----+------+-------+
|   1 |    1 |    20 |
|   2 |    1 |    30 |
|   3 |    1 |    40 |
|   4 |    2 |    60 |
|   5 |    2 |    80 |
|   6 |    2 |    40 |
|   7 |    3 |    50 |
|   8 |    3 |    20 |
|   9 |    3 |    40 |
+-----+------+-------+

Result of query:

+-----+------+-------+---------+
| row | id   | value | avg     |
+-----+------+-------+---------+
|   1 |    1 |    20 | 35.0000 |
|   2 |    1 |    30 | 30.0000 |
|   3 |    1 |    40 | 25.0000 |
|   4 |    2 |    60 | 60.0000 |
|   5 |    2 |    80 | 50.0000 |
|   6 |    2 |    40 | 70.0000 |
|   7 |    3 |    50 | 30.0000 |
|   8 |    3 |    20 | 45.0000 |
|   9 |    3 |    40 | 35.0000 |
+-----+------+-------+---------+


问:
Excel pivot condition cell
how can i set condition inside pivot sum data to refer label row ?

I need to sum data only if row label is equal to specific value.

I'm trying to use standard IF but it doesn't work.

Thanks.

答:
I would use a sumproduct function if I were you.

https://www.ablebits.com/office-addins-blog/2016/08/24/excel-sumproduct-function-formula-examples/#Conditionally

To sum Apples sales for North:
=SUMPRODUCT(--(A2:A12="north"), --(B2:B12="apples"), C2:C12)

Title: Excel pivot condition cell


问:
Angular 2 translations with Webpack
I'm trying to follow the Angular cookbook for internationalization, but we're using Webpack instead of SystemJS.
In the cookbook there's the following snippet:

```<code>function getTranslationsWithSystemJs(file: string) {
  return System.import(file + '!text'); // relies on text plugin
}
</code>```

It uses SystemJS for loading the translation file. What should we use instead?

答:
With Webpack 2 I use the current configuration:

In my webpack.config.js I set raw-loader to handle .xlf files, this tell Webpack to load the file as pure text.

```<code>{
    test: /\.xlf/,
    loader: 'raw-loader'
}
</code>```

Then in i18n.providers.js I defined the function as following:

```<code>function getTranslationsWithES6Import(locale: string) {
/**
 * System.import in Webpack is an alias of the standard dynamic import()
 * but the latter can't be used because Typescript would complain.
 * @see https://webpack.js.org/guides/code-splitting-import/#dynamic-import
 * @see https://github.com/Microsoft/TypeScript/issues/12364
 *
 * Also the file name must not used backticks and the file extension must be
 * within the function call otherwise Webpack won't know how to load it.
 * @see https://github.com/angular/angular-cli/issues/5285#issuecomment-285059969
 */
return System.import('../assets/locale/messages.' + locale + '.xlf');
</code>```

}

Title: Angular 2 translations with Webpack

Body:
I'm trying to follow the Angular cookbook for internationalization, but we're using Webpack instead of SystemJS.
In the cookbook there's the following snippet:

function getTranslationsWithSystemJs(file: string) {
  return System.import(file + '!text'); // relies on text plugin
}

It uses SystemJS for loading the translation file. What should we use instead?

Body:
With Webpack 2 I use the current configuration:

In my webpack.config.js I set raw-loader to handle .xlf files, this tell Webpack to load the file as pure text.

{
    test: /\.xlf/,
    loader: 'raw-loader'
}

Then in i18n.providers.js I defined the function as following:

function getTranslationsWithES6Import(locale: string) {
/**
 * System.import in Webpack is an alias of the standard dynamic import()
 * but the latter can't be used because Typescript would complain.
 * @see https://webpack.js.org/guides/code-splitting-import/#dynamic-import
 * @see https://github.com/Microsoft/TypeScript/issues/12364
 *
 * Also the file name must not used backticks and the file extension must be
 * within the function call otherwise Webpack won't know how to load it.
 * @see https://github.com/angular/angular-cli/issues/5285#issuecomment-285059969
 */
return System.import('../assets/locale/messages.' + locale + '.xlf');

}


问:
Spring findBy with unordered array
I'm using Spring MVC, and have a Conversation entity with the property participants. This is a List of userId Strings who are involved in a particular Conversation. I am trying to retrieve all Conversations whose participants are equal to some List of userIds from a MongoRepository. How do I do this?

I have tried the following:

```<code>Conversation findByParticipantsEquals(List<String> participantId);
</code>```

However the order of participantIds is kind of random so it doesn't necessarily work.

答:
You can actually use $in operator as shown below:

```<code>@Query(value = "{ 'participantId': { $in: ?0 } }")
public List<Conversation> findByParticipantsEquals(List<String> participantIds);
</code>```

Title: Spring findBy with unordered array

Body:
I'm using Spring MVC, and have a Conversation entity with the property participants. This is a List of userId Strings who are involved in a particular Conversation. I am trying to retrieve all Conversations whose participants are equal to some List of userIds from a MongoRepository. How do I do this?

I have tried the following:

Conversation findByParticipantsEquals(List<String> participantId);

However the order of participantIds is kind of random so it doesn't necessarily work.

Body:
You can actually use $in operator as shown below:

@Query(value = "{ 'participantId': { $in: ?0 } }")
public List<Conversation> findByParticipantsEquals(List<String> participantIds);


问:
React-Native: LayoutAnimation
I am using react-native's LayoutAnimation to implement a custom switch component.

I am animating the movement of the circle using LayoutAnimation like so:

```<code>componentWillUpdate() {
  let switchAnimation = {
    duration: 250,
     update: {
       type: LayoutAnimation.Types.linear,
       property: LayoutAnimation.Properties.opacity,
     },
  };
  LayoutAnimation.configureNext(switchAnimation);
}
</code>```

The switch is its own component. It recieves props to set the circle to be on the left or right using css (justifyContent flex-start or flex-end)

Problem is in my view when the switch changes value other components change as well: Namely when the switch is hit:

1) Switch changes

2) An icon changes

3) Some text changes

All of the above animate. I want to reduce the animation to affect the switch only

UPDATE: I have tried using the Animated API but it doesnt seem to support animating flex properties. Is there really no one out there that uses The Animated API extensively?

答: LayoutAnimation does a lot under the hood. Unless you are willing to go through the source you can set and vary a margin value in order to move the circle in the container. You can make all the calculations within the component and expose some styles as props.</p>

Title: React-Native: LayoutAnimation

Body:
I am using react-native's LayoutAnimation to implement a custom switch component.

I am animating the movement of the circle using LayoutAnimation like so:

componentWillUpdate() {
  let switchAnimation = {
    duration: 250,
     update: {
       type: LayoutAnimation.Types.linear,
       property: LayoutAnimation.Properties.opacity,
     },
  };
  LayoutAnimation.configureNext(switchAnimation);
}

The switch is its own component. It recieves props to set the circle to be on the left or right using css (justifyContent flex-start or flex-end)

Problem is in my view when the switch changes value other components change as well: Namely when the switch is hit:

1) Switch changes

2) An icon changes

3) Some text changes

All of the above animate. I want to reduce the animation to affect the switch only

UPDATE: I have tried using the Animated API but it doesnt seem to support animating flex properties. Is there really no one out there that uses The Animated API extensively?


问:
Publish data in Power BI
How can I make our software's data available as an app in Power BI so our customers can choose to integrate their data in Power BI?

I know there is a Rest API and I have seem many samples of how to use this for internal software.  However I don't want each customer to have to create an api application.  I want our app to appear like Salesforce & Zendesk etc. do so the customer can simply pick us from the list.

Hope this makes sense.

答: I have helped a client of mine work through the process and it involves working with Microsoft to get the public content pack published. The process is outlined here. I would start by following the steps indicated there like filling out the nomination form and reaching out to support before you begin. There are a number of constraints around authentication and APIs and refresh you need to be aware of before you begin development and it is best to discuss this with support. </p>

Title: Publish data in Power BI


问:
How can I restore the "default" button style
I have a save button, and when the user mouses over it, I change some styles - for example:

```<code>$('.saveButton').mouseover(function() {
   $(this).css("background-color", "red");
   $(this).parents('fieldset').css("border", "2px solid red");
});
</code>```

When the mouse leaves the button, I would like to restore the original:

```<code>$('.saveButton').mouseout(function() {
   $(this).css("background-color", "#EEE");
   $(this).parents('fieldset').css("border", "1px solid gray");
});
</code>```

However, leaving aside the matter of whether or not the default button background color is #EEE, when this code executes the button loses its rounded look, and has square corners.

Is it possible to do this?

答:
Yes, you can set up a class for the mouseEnter that make the  bg color and border color in red.

Than you can use toggleClass for the event, so that it will toggle your event adding and removing the class, restoring always the default button.

Body:
I have a save button, and when the user mouses over it, I change some styles - for example:

$('.saveButton').mouseover(function() {
   $(this).css("background-color", "red");
   $(this).parents('fieldset').css("border", "2px solid red");
});

When the mouse leaves the button, I would like to restore the original:

$('.saveButton').mouseout(function() {
   $(this).css("background-color", "#EEE");
   $(this).parents('fieldset').css("border", "1px solid gray");
});

However, leaving aside the matter of whether or not the default button background color is #EEE, when this code executes the button loses its rounded look, and has square corners.

Is it possible to do this?


问:
Python 3.4 Panda sort market-data by Date
I am trying to set up Python (3.4) code to sort a time-series by date.

In python shell, I key in the following

```<code>>>>data = quandl.get("YAHOO/INDEX_GSPC", start_date="2017-01-01", end_date="2017-01-20")
>>>print(data)
</code>```

So, I can load in the data. But when I try to use sort by the command

```<code>>>>data = data.sort_values(by='Date')
</code>```

I get the following list of errors messages. I can't seem to understand/get the syntax for date sort from http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sort_values.html

Experts out there......., many thanks for advice.

```<code>Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\pandas\indexes\base.py", line 2134, in get_loc
    return self._engine.get_loc(key)
  File "pandas\index.pyx", line 132, in pandas.index.IndexEngine.get_loc (pandas\index.c:4433)
  File "pandas\index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas\index.c:4279)
  File "pandas\src\hashtable_class_helper.pxi", line 732, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13742)
  File "pandas\src\hashtable_class_helper.pxi", line 740, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13696)
KeyError: 'Date'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<pyshell#37>", line 1, in <module>
    data = data.sort_values(by='Date')
  File "C:\Python34\lib\site-packages\pandas\core\frame.py", line 3230, in sort_values
    k = self.xs(by, axis=other_axis).values
  File "C:\Python34\lib\site-packages\pandas\core\generic.py", line 1770, in xs
    return self[key]
  File "C:\Python34\lib\site-packages\pandas\core\frame.py", line 2059, in __getitem__
    return self._getitem_column(key)
  File "C:\Python34\lib\site-packages\pandas\core\frame.py", line 2066, in _getitem_column
    return self._get_item_cache(key)
  File "C:\Python34\lib\site-packages\pandas\core\generic.py", line 1386, in _get_item_cache
    values = self._data.get(item)
  File "C:\Python34\lib\site-packages\pandas\core\internals.py", line 3543, in get
    loc = self.items.get_loc(item)
  File "C:\Python34\lib\site-packages\pandas\indexes\base.py", line 2136, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas\index.pyx", line 132, in pandas.index.IndexEngine.get_loc (pandas\index.c:4433)
  File "pandas\index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas\index.c:4279)
  File "pandas\src\hashtable_class_helper.pxi", line 732, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13742)
  File "pandas\src\hashtable_class_helper.pxi", line 740, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13696)
KeyError: 'Date'
</code>```

答:
Make sure you look at the error. You are getting a KeyError which means that the column Date does not exist in your DataFrame. It's like that the dates are stored in the index which requires the sort_index method instead. The 'Date' name that you see in your DataFrame is the name of the index and not a column.

```<code>data.sort_index()
</code>```

Body:
I am trying to set up Python (3.4) code to sort a time-series by date.

In python shell, I key in the following

>>>data = quandl.get("YAHOO/INDEX_GSPC", start_date="2017-01-01", end_date="2017-01-20")
>>>print(data)

So, I can load in the data. But when I try to use sort by the command

>>>data = data.sort_values(by='Date')

I get the following list of errors messages. I can't seem to understand/get the syntax for date sort from http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sort_values.html

Experts out there......., many thanks for advice.

Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\pandas\indexes\base.py", line 2134, in get_loc
    return self._engine.get_loc(key)
  File "pandas\index.pyx", line 132, in pandas.index.IndexEngine.get_loc (pandas\index.c:4433)
  File "pandas\index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas\index.c:4279)
  File "pandas\src\hashtable_class_helper.pxi", line 732, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13742)
  File "pandas\src\hashtable_class_helper.pxi", line 740, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13696)
KeyError: 'Date'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<pyshell#37>", line 1, in <module>
    data = data.sort_values(by='Date')
  File "C:\Python34\lib\site-packages\pandas\core\frame.py", line 3230, in sort_values
    k = self.xs(by, axis=other_axis).values
  File "C:\Python34\lib\site-packages\pandas\core\generic.py", line 1770, in xs
    return self[key]
  File "C:\Python34\lib\site-packages\pandas\core\frame.py", line 2059, in __getitem__
    return self._getitem_column(key)
  File "C:\Python34\lib\site-packages\pandas\core\frame.py", line 2066, in _getitem_column
    return self._get_item_cache(key)
  File "C:\Python34\lib\site-packages\pandas\core\generic.py", line 1386, in _get_item_cache
    values = self._data.get(item)
  File "C:\Python34\lib\site-packages\pandas\core\internals.py", line 3543, in get
    loc = self.items.get_loc(item)
  File "C:\Python34\lib\site-packages\pandas\indexes\base.py", line 2136, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas\index.pyx", line 132, in pandas.index.IndexEngine.get_loc (pandas\index.c:4433)
  File "pandas\index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas\index.c:4279)
  File "pandas\src\hashtable_class_helper.pxi", line 732, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13742)
  File "pandas\src\hashtable_class_helper.pxi", line 740, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13696)
KeyError: 'Date'

Body:
Make sure you look at the error. You are getting a KeyError which means that the column Date does not exist in your DataFrame. It's like that the dates are stored in the index which requires the sort_index method instead. The 'Date' name that you see in your DataFrame is the name of the index and not a column.

data.sort_index()


问:
How can I modify the XMLHttpRequest responsetext received by another function?
I am trying to modify the responseText received by a function that I cannot modify. This function creates a XMLHttpRequest that I can attach to, but I have been unable to "wrap" the responseText in a way that allows me to modify the content before the original function receives it.

Here's the full original function:

```<code>function Mj(a, b, c, d, e) {
    function k() {
        4 == (m && 'readyState' in m ? m.readyState : 0) && b && ff(b) (m)
    }
    var m = new XMLHttpRequest;
    'onloadend' in m ? m.addEventListener('loadend', k, !1)  : m.onreadystatechange = k;
    c = ('GET').toUpperCase();
    d = d || '';
    m.open(c, a, !0);
    m.send(d);
    return m
}
function ff(a) {
    return a && window ? function () {
        try {
            return a.apply(this, arguments)
        } catch(b) {
            throw jf(b),
                b;
        }
    } : a
}
</code>```

I have also tried to manipulate the reiceiving function k(); in an attempt to reach my goal, but since it doesn't depend on any data passing to the function (for example k(a.responseText);) I had no success.

Is there any way that I can achieve this? I do not wish to use js libraries (such as jQuery);

EDIT: I understand that I cannot change .responseText directly since it is read-only, but I am trying to find a way to change the content between the response and receiving function.

EDIT2: Added below one of the methods I have tried to intercept and change .responseText which has been addapted from here: Monkey patch XMLHTTPRequest.onreadystatechange

```<code>(function (open) {
XMLHttpRequest.prototype.open = function (method, url, async, user, pass) {
    if(/results/.test(url)) {
      console.log(this.onreadystatechange);
        this.addEventListener("readystatechange", function () {
            console.log('readystate: ' + this.readyState);
            if(this.responseText !== '') {
                this.responseText = this.responseText.split('&')[0];
            }
        }, false);
    }
    open.call(this, method, url, async, user, pass);
};
})(XMLHttpRequest.prototype.open);
</code>```

EDIT3: I forgot to include that the functions Mj and ff are not globally available, they are both contained inside an anonymous function (function(){functions are here})();

EDIT4: I have changed the accepted answer because AmmarCSE's does not have any of the problems and complexity linked to jfriend00's answer.

The best answer explained in short is as follows:

Listen to whichever request you want to modify (make sure your listener will intercept it before the original function destination does, otherwise there is no point in modifying it after the response has already been used).

Save the original response (if you want to modify it) in a temporary variable

Change the property you want to modify to "writable: true", it will erase whichever value it had. In my case I use

```<code>Object.defineProperty(event, 'responseText', {
    writable: true
});
</code>```

Where event is the object returned by listening to the load or readystatechange event of the xhr request

Now you can set anything you want for your response, if all you wanted was to modify the original response then you can use that data from your temporary variable and then save the modifications in the response.

答:
I needed to intercept and modify a request response so I came up with a little bit of code. I also found that some websites like to use response as well as the responseText which is why my code modifies both.

The Code

```<code>var open_prototype = XMLHttpRequest.prototype.open,
intercept_response = function(urlpattern, callback) {
   XMLHttpRequest.prototype.open = function() {
      arguments['1'].match(urlpattern) && this.addEventListener('readystatechange', function(event) {
         if ( this.readyState === 4 ) {
            var response = callback(event.target.responseText);
            Object.defineProperty(this, 'response',     {writable: true});
            Object.defineProperty(this, 'responseText', {writable: true});
            this.response = this.responseText = response;
         }
      });
      return open_prototype.apply(this, arguments);
   };
};
</code>```

the first param of the intercept_response function is a regular expression to match the request url and the second param is the function to be used on the response to modify it.

Example Of Usage

```<code>intercept_response(/fruit\.json/i, function(response) {
   var new_response = response.replace('banana', 'apple');
   return new_response;
});
</code>```

Body:
I am trying to modify the responseText received by a function that I cannot modify. This function creates a XMLHttpRequest that I can attach to, but I have been unable to "wrap" the responseText in a way that allows me to modify the content before the original function receives it.

Here's the full original function:

function Mj(a, b, c, d, e) {
    function k() {
        4 == (m && 'readyState' in m ? m.readyState : 0) && b && ff(b) (m)
    }
    var m = new XMLHttpRequest;
    'onloadend' in m ? m.addEventListener('loadend', k, !1)  : m.onreadystatechange = k;
    c = ('GET').toUpperCase();
    d = d || '';
    m.open(c, a, !0);
    m.send(d);
    return m
}
function ff(a) {
    return a && window ? function () {
        try {
            return a.apply(this, arguments)
        } catch(b) {
            throw jf(b),
                b;
        }
    } : a
}

I have also tried to manipulate the reiceiving function k(); in an attempt to reach my goal, but since it doesn't depend on any data passing to the function (for example k(a.responseText);) I had no success.

Is there any way that I can achieve this? I do not wish to use js libraries (such as jQuery);

EDIT: I understand that I cannot change .responseText directly since it is read-only, but I am trying to find a way to change the content between the response and receiving function.

EDIT2: Added below one of the methods I have tried to intercept and change .responseText which has been addapted from here: Monkey patch XMLHTTPRequest.onreadystatechange

(function (open) {
XMLHttpRequest.prototype.open = function (method, url, async, user, pass) {
    if(/results/.test(url)) {
      console.log(this.onreadystatechange);
        this.addEventListener("readystatechange", function () {
            console.log('readystate: ' + this.readyState);
            if(this.responseText !== '') {
                this.responseText = this.responseText.split('&')[0];
            }
        }, false);
    }
    open.call(this, method, url, async, user, pass);
};
})(XMLHttpRequest.prototype.open);

EDIT3: I forgot to include that the functions Mj and ff are not globally available, they are both contained inside an anonymous function (function(){functions are here})();

EDIT4: I have changed the accepted answer because AmmarCSE's does not have any of the problems and complexity linked to jfriend00's answer.

The best answer explained in short is as follows:

Listen to whichever request you want to modify (make sure your listener will intercept it before the original function destination does, otherwise there is no point in modifying it after the response has already been used).

Save the original response (if you want to modify it) in a temporary variable

Change the property you want to modify to "writable: true", it will erase whichever value it had. In my case I use

Object.defineProperty(event, 'responseText', {
    writable: true
});

Where event is the object returned by listening to the load or readystatechange event of the xhr request

Now you can set anything you want for your response, if all you wanted was to modify the original response then you can use that data from your temporary variable and then save the modifications in the response.

Body:
I needed to intercept and modify a request response so I came up with a little bit of code. I also found that some websites like to use response as well as the responseText which is why my code modifies both.

The Code

var open_prototype = XMLHttpRequest.prototype.open,
intercept_response = function(urlpattern, callback) {
   XMLHttpRequest.prototype.open = function() {
      arguments['1'].match(urlpattern) && this.addEventListener('readystatechange', function(event) {
         if ( this.readyState === 4 ) {
            var response = callback(event.target.responseText);
            Object.defineProperty(this, 'response',     {writable: true});
            Object.defineProperty(this, 'responseText', {writable: true});
            this.response = this.responseText = response;
         }
      });
      return open_prototype.apply(this, arguments);
   };
};

the first param of the intercept_response function is a regular expression to match the request url and the second param is the function to be used on the response to modify it.

Example Of Usage

intercept_response(/fruit\.json/i, function(response) {
   var new_response = response.replace('banana', 'apple');
   return new_response;
});


问:
How to make a masonry layout grid in bootstrap 3?
I am using boostrap to make a masonry layout. But I am having a problem. As you can see in my code, I have 5 divs. I want Div 4 and 5 to move up(check the attached image) but I have no idea how to do it. I can do it with margin-top but it will break the responsive layout. So, what's the possible solution for this? I am a newbie, it will be a great help. Thanks in advance.

```<code><html>
<head>

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="css/font-awesome.min.css">
    <style>
        .div1{
            border: 2px solid;
        }
        .div2{
            border: 2px solid;
        }
        .div3{
            border: 2px solid;
            height: 100px;
        }
        .div4{
            border: 2px solid;
        }
        .div5{
            border: 2px solid;
            height: 40px;
        }
    </style>
</head>
<body>
    <div class="col-md-12">
        <div class="col-md-4 div1">Div1</div>
        <div class="col-md-4 div2">Div2</div>
        <div class="col-md-4 div3">Div3</div>
        <div class="col-md-8 div4">Div4</div>
        <div class="col-md-8 div5">Div5</div>
    </div>
<!-- Loading minified js. jQuery and Bootstrap -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</body>
</html>
</code>```

The current layout is:

But I want it like this:

答:
It wouldn't be masonry, per say, but from your image what you want is</p>

```<code><div class='row'>
    <div class='col-md-8'>
        <div class='row'>
            <div class='col-md-6 div1'>Div1</div>
            <div class='col-md-6 div2'>Div2</div>
            <div class='col-md-12 div4'>Div4</div>
            <div class='col-md-12 div5'>Div5</div>
        </div>
    </div>
    <div class='col-md-4 div3'>Div3</div>
</div>
</code>```

Body:
I am using boostrap to make a masonry layout. But I am having a problem. As you can see in my code, I have 5 divs. I want Div 4 and 5 to move up(check the attached image) but I have no idea how to do it. I can do it with margin-top but it will break the responsive layout. So, what's the possible solution for this? I am a newbie, it will be a great help. Thanks in advance.

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="css/font-awesome.min.css">

Div1

Div2

Div3

Div4

Div5

The current layout is:

But I want it like this:

Body:
It wouldn't be masonry, per say, but from your image what you want is

<div class='row'>
    <div class='col-md-8'>
        <div class='row'>
            <div class='col-md-6 div1'>Div1</div>
            <div class='col-md-6 div2'>Div2</div>
            <div class='col-md-12 div4'>Div4</div>
            <div class='col-md-12 div5'>Div5</div>
        </div>
    </div>
    <div class='col-md-4 div3'>Div3</div>
</div>


问:
failed to open stream: Permission denied in /opt/lampp/htdocs
I am using Ubuntu 16.04 & xampp 5.6.30.  I am trying to create a simple login program using file with validation but I am facing problem while putting my data into a file named "login.txt".

Error:

```<code>file_put_contents(login.txt): failed to open stream: Permission denied in /opt/lampp/htdocs/PHP/Practice/PHP Functions/Login Validation/login.php on line 38
</code>```

My code:

```<code>$input = $userName.'|'.$userPassword.'\n';

$myfile = file_put_contents('login.txt', $input.PHP_EOL , FILE_APPEND | LOCK_EX);
</code>```

答:
This error is due to file permissions. The php/apache user does not have the permissions to write in the directory. One way of fixing that is to change the mod byte of the directory with the command chmod. You need super permissions to execute this modification if your session user does not own the directory.

```<code>$ sudo chmod -R 777 /path/to/directory
</code>```

The mod 777 set read/write and execution to directory for every users on the system. The R option applies recursively the modification to every files and sub-directories. So, you can change the permission of all the contents of your htdocs directory all at once.

https://linux.die.net/man/1/chmod

Body:
I am using Ubuntu 16.04 & xampp 5.6.30.  I am trying to create a simple login program using file with validation but I am facing problem while putting my data into a file named "login.txt".

Error:

file_put_contents(login.txt): failed to open stream: Permission denied in /opt/lampp/htdocs/PHP/Practice/PHP Functions/Login Validation/login.php on line 38

My code:

$input = $userName.'|'.$userPassword.'\n';

$myfile = file_put_contents('login.txt', $input.PHP_EOL , FILE_APPEND | LOCK_EX);

Body:
This error is due to file permissions. The php/apache user does not have the permissions to write in the directory. One way of fixing that is to change the mod byte of the directory with the command chmod. You need super permissions to execute this modification if your session user does not own the directory.

$ sudo chmod -R 777 /path/to/directory

The mod 777 set read/write and execution to directory for every users on the system. The R option applies recursively the modification to every files and sub-directories. So, you can change the permission of all the contents of your htdocs directory all at once.

https://linux.die.net/man/1/chmod


问:
Spark kryo_serializers and Broadcast<Map<Object, Iterable<GowallaDataLocation>>> java.io.IOException: java.lang.UnsupportedOperationException
When I try to access a Broadcast variable I receive this Exception:

17/03/26 03:04:23 WARN TaskSetManager: Lost task 0.0 in stage 3.0 (TID 10, 192.168.56.5, executor 1): java.io.IOException: java.lang.UnsupportedOperationException
      at org.apache.spark.util.Utils$.tryOrIOException(Utils.scala:1276)
      at org.apache.spark.broadcast.TorrentBroadcast.readBroadcastBlock(TorrentBroadcast.scala:206)
      at org.apache.spark.broadcast.TorrentBroadcast._value$lzycompute(TorrentBroadcast.scala:66)
      at org.apache.spark.broadcast.TorrentBroadcast._value(TorrentBroadcast.scala:66)
      at org.apache.spark.broadcast.TorrentBroadcast.getValue(TorrentBroadcast.scala:96)
      at GowallaTask$2.call(GowallaTask.java:214)
      at org.apache.spark.api.java.JavaRDDLike$$anonfun$foreach$1.apply(JavaRDDLike.scala:351)
      at org.apache.spark.api.java.JavaRDDLike$$anonfun$foreach$1.apply(JavaRDDLike.scala:351)
      at scala.collection.Iterator$class.foreach(Iterator.scala:893)
      at org.apache.spark.InterruptibleIterator.foreach(InterruptibleIterator.scala:28)
      at org.apache.spark.rdd.RDD$$anonfun$foreach$1$$anonfun$apply$28.apply(RDD.scala:917)
      at org.apache.spark.rdd.RDD$$anonfun$foreach$1$$anonfun$apply$28.apply(RDD.scala:917)
      at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1944)
      at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1944)
      at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
      at org.apache.spark.scheduler.Task.run(Task.scala:99)
      at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:282)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
      at java.lang.Thread.run(Thread.java:745)

Caused by: java.lang.UnsupportedOperationException
      at java.util.AbstractMap.put(AbstractMap.java:209)
      at com.esotericsoftware.kryo.serializers.MapSerializer.read(MapSerializer.java:162)
      at com.esotericsoftware.kryo.serializers.MapSerializer.read(MapSerializer.java:39)
      at com.esotericsoftware.kryo.Kryo.readClassAndObject(Kryo.java:790)
      at org.apache.spark.serializer.KryoDeserializationStream.readObject(KryoSerializer.scala:244)
      at org.apache.spark.broadcast.TorrentBroadcast$$anonfun$10.apply(TorrentBroadcast.scala:286)
      at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1303)
      at org.apache.spark.broadcast.TorrentBroadcast$.unBlockifyObject(TorrentBroadcast.scala:287)
      at org.apache.spark.broadcast.TorrentBroadcast$$anonfun$readBroadcastBlock$1.apply(TorrentBroadcast.scala:221)
      at org.apache.spark.util.Utils$.tryOrIOException(Utils.scala:1269)
      ... 19 more

I received the exception when I use KryoSerializer

```<code>    conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer");
    conf.set("spark.kryoserializer.buffer.mb", "24");
</code>```

This is my code.

```<code>JavaPairRDD<Object, Iterable<GowallaDataLocation>> line_RDD_2 = sc
            .textFile("/home/piero/gowalla_location.txt", 2).map(new GowallaMapperDataLocation())
            .groupBy(new Function<GowallaDataLocation, Object>() {

                /**
                 *
                 */
                private static final long serialVersionUID = -6773509902594100325L;

                @Override
                public Object call(GowallaDataLocation v1) throws Exception {
                    DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

                    return dateFormat.format(v1.getDATE());
                }
            }).persist(StorageLevel.MEMORY_AND_DISK_SER());

Broadcast<Map<Object, Iterable<GowallaDataLocation>>> broadcastVar_2 = sc.broadcast(line_RDD_2.collectAsMap());
    //System.out.println(broadcastVar_2.getValue().size());

    JavaRDD<Object> keys = line_RDD_2.keys().persist(StorageLevel.MEMORY_ONLY_SER());
    line_RDD_2.unpersist();

    keys.foreach(new VoidFunction<Object>() {

        /**
         *
         */
        private static final long serialVersionUID = -8148877518271969523L;

        @Override
        public void call(Object t) throws Exception {
            // TODO Auto-generated method stub
            //System.out.println("KEY:" + t + " ");
            Iterable<GowallaDataLocation> dr = broadcastVar_2.getValue().get(t);

        }

    });
</code>```

答:
I suspect this happens because you are broadcasting the line_RDD_2.collectAsMap() directly: this means the type broadcasted is Map and kryo doesn't know the correct implementation and will use an AbstractMap for it's inner work

Like if i do this:

```<code>Map<String, String> a = new HashMap<String, String>();
a.put("a", "b");
Set<String> c = a.keySet();
c.add("e");
</code>```

i will get unsupported operation for AbstractCollection, easily resolved:

```<code>Map<String, String> a = new HashMap<String, String>();
a.put("a", "b");
Set<String> c = new TreeSet<String>();
c.addAll(a.keySet());
c.add("e");
</code>```

if my guess is right you can probably resolve it like this:

```<code>Map<Object, Iterable<GowallaDataLocation>> a = new HashMap<>();
a.putAll(line_RDD_2.collectAsMap());
Broadcast<Map<Object, Iterable<GowallaDataLocation>>> broadcastVar_2 = sc.broadcast(a);
</code>```

let me know if this works

Body:
When I try to access a Broadcast variable I receive this Exception:

17/03/26 03:04:23 WARN TaskSetManager: Lost task 0.0 in stage 3.0 (TID 10, 192.168.56.5, executor 1): java.io.IOException: java.lang.UnsupportedOperationException
      at org.apache.spark.util.Utils$.tryOrIOException(Utils.scala:1276)
      at org.apache.spark.broadcast.TorrentBroadcast.readBroadcastBlock(TorrentBroadcast.scala:206)
      at org.apache.spark.broadcast.TorrentBroadcast._value$lzycompute(TorrentBroadcast.scala:66)
      at org.apache.spark.broadcast.TorrentBroadcast._value(TorrentBroadcast.scala:66)
      at org.apache.spark.broadcast.TorrentBroadcast.getValue(TorrentBroadcast.scala:96)
      at GowallaTask$2.call(GowallaTask.java:214)
      at org.apache.spark.api.java.JavaRDDLike$$anonfun$foreach$1.apply(JavaRDDLike.scala:351)
      at org.apache.spark.api.java.JavaRDDLike$$anonfun$foreach$1.apply(JavaRDDLike.scala:351)
      at scala.collection.Iterator$class.foreach(Iterator.scala:893)
      at org.apache.spark.InterruptibleIterator.foreach(InterruptibleIterator.scala:28)
      at org.apache.spark.rdd.RDD$$anonfun$foreach$1$$anonfun$apply$28.apply(RDD.scala:917)
      at org.apache.spark.rdd.RDD$$anonfun$foreach$1$$anonfun$apply$28.apply(RDD.scala:917)
      at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1944)
      at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1944)
      at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
      at org.apache.spark.scheduler.Task.run(Task.scala:99)
      at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:282)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
      at java.lang.Thread.run(Thread.java:745)

Caused by: java.lang.UnsupportedOperationException
      at java.util.AbstractMap.put(AbstractMap.java:209)
      at com.esotericsoftware.kryo.serializers.MapSerializer.read(MapSerializer.java:162)
      at com.esotericsoftware.kryo.serializers.MapSerializer.read(MapSerializer.java:39)
      at com.esotericsoftware.kryo.Kryo.readClassAndObject(Kryo.java:790)
      at org.apache.spark.serializer.KryoDeserializationStream.readObject(KryoSerializer.scala:244)
      at org.apache.spark.broadcast.TorrentBroadcast$$anonfun$10.apply(TorrentBroadcast.scala:286)
      at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1303)
      at org.apache.spark.broadcast.TorrentBroadcast$.unBlockifyObject(TorrentBroadcast.scala:287)
      at org.apache.spark.broadcast.TorrentBroadcast$$anonfun$readBroadcastBlock$1.apply(TorrentBroadcast.scala:221)
      at org.apache.spark.util.Utils$.tryOrIOException(Utils.scala:1269)
      ... 19 more

I received the exception when I use KryoSerializer

    conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer");
    conf.set("spark.kryoserializer.buffer.mb", "24");

This is my code.

JavaPairRDD<Object, Iterable<GowallaDataLocation>> line_RDD_2 = sc
            .textFile("/home/piero/gowalla_location.txt", 2).map(new GowallaMapperDataLocation())
            .groupBy(new Function<GowallaDataLocation, Object>() {

                /**
                 *
                 */
                private static final long serialVersionUID = -6773509902594100325L;

                @Override
                public Object call(GowallaDataLocation v1) throws Exception {
                    DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

                    return dateFormat.format(v1.getDATE());
                }
            }).persist(StorageLevel.MEMORY_AND_DISK_SER());

Broadcast<Map<Object, Iterable<GowallaDataLocation>>> broadcastVar_2 = sc.broadcast(line_RDD_2.collectAsMap());
    //System.out.println(broadcastVar_2.getValue().size());

    JavaRDD<Object> keys = line_RDD_2.keys().persist(StorageLevel.MEMORY_ONLY_SER());
    line_RDD_2.unpersist();

    keys.foreach(new VoidFunction<Object>() {

        /**
         *
         */
        private static final long serialVersionUID = -8148877518271969523L;

        @Override
        public void call(Object t) throws Exception {
            // TODO Auto-generated method stub
            //System.out.println("KEY:" + t + " ");
            Iterable<GowallaDataLocation> dr = broadcastVar_2.getValue().get(t);

        }

    });

Body:
I suspect this happens because you are broadcasting the line_RDD_2.collectAsMap() directly: this means the type broadcasted is Map and kryo doesn't know the correct implementation and will use an AbstractMap for it's inner work

Like if i do this:

Map<String, String> a = new HashMap<String, String>();
a.put("a", "b");
Set<String> c = a.keySet();
c.add("e");

i will get unsupported operation for AbstractCollection, easily resolved:

Map<String, String> a = new HashMap<String, String>();
a.put("a", "b");
Set<String> c = new TreeSet<String>();
c.addAll(a.keySet());
c.add("e");

if my guess is right you can probably resolve it like this:

Map<Object, Iterable<GowallaDataLocation>> a = new HashMap<>();
a.putAll(line_RDD_2.collectAsMap());
Broadcast<Map<Object, Iterable<GowallaDataLocation>>> broadcastVar_2 = sc.broadcast(a);

let me know if this works

ContentLicense: CC BY-SA 4.0


问:
How to check connection to mongodb
I use MongoDB drivers to connect to the database. When my form loads, I want to set up connection and to check whether it is ok or not. I do it like this:

```<code>var connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString);
var server = client.GetServer();
var database = server.GetDatabase("reestr");
</code>```

But I do not know how to check connection. I tried to overlap this code with try-catch, but to no avail. Even if I make an incorrect connectionString, I still can not get any error message.

答:
If you want to handle connection issues in your program you can use the ICluster.Description event.

When the MongoClient is created, it will continue to attempt connections in the background until it succeeds.

```<code>using MongoDB.Driver;
using MongoDB.Driver.Core.Clusters;

var mongoClient = new MongoClient("localhost")
mongoClient.Cluster.DescriptionChanged += Cluster_DescriptionChanged;

public void Cluster_DescriptionChanged(object sender, ClusterDescriptionChangedEventArgs e)
{
    switch (e.NewClusterDescription.State)
    {
        case ClusterState.Disconnected:
            break;
        case ClusterState.Connected:
            break;
    }
}
</code>```

Title: How to check connection to mongodb

Body:
I use MongoDB drivers to connect to the database. When my form loads, I want to set up connection and to check whether it is ok or not. I do it like this:

var connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString);
var server = client.GetServer();
var database = server.GetDatabase("reestr");

But I do not know how to check connection. I tried to overlap this code with try-catch, but to no avail. Even if I make an incorrect connectionString, I still can not get any error message.

Body:
If you want to handle connection issues in your program you can use the ICluster.Description event.

When the MongoClient is created, it will continue to attempt connections in the background until it succeeds.

using MongoDB.Driver;
using MongoDB.Driver.Core.Clusters;

var mongoClient = new MongoClient("localhost")
mongoClient.Cluster.DescriptionChanged += Cluster_DescriptionChanged;

public void Cluster_DescriptionChanged(object sender, ClusterDescriptionChangedEventArgs e)
{
    switch (e.NewClusterDescription.State)
    {
        case ClusterState.Disconnected:
            break;
        case ClusterState.Connected:
            break;
    }
}


问:
Initializing Class Properties In Swift
So I'm trying to create a Playground that functions as a 'presentation', meaning that I have multiple slides and it's interactive-ish. I'm new to Swift, so would really use some help.

This is my main code

```<code>import UIKit
import SpriteKit
import PlaygroundSupport

let frame = CGRect(x: 0, y: 0, width: 640, height: 480)

let view = SKView(frame: frame)
view.showsDrawCount = true
view.showsNodeCount = true
view.showsFPS = true

let scene = MainScene(size: CGSize(width: 640, height: 480))
view.presentScene(scene) //error here, explained below
PlaygroundPage.current.liveView = view
</code>```

This is my MainScene.swift code -

```<code>import UIKit
import SpriteKit
import PlaygroundSupport

public class Slide: SKView {

    public var title: SKLabelNode!
    public var info: UITextView!

    public func setter() {

        self.title = SKLabelNode(fontNamed: "Chalkduster")
        self.title.verticalAlignmentMode = .center
        self.title.color = SKColor.white
        self.title.position = CGPoint(x: frame.midX, y: 440)

        let framer = CGRect(x: 40, y: 60, width: 560, height: 360)

        self.info = UITextView(frame: framer)
        self.info.font = UIFont(name: "Chalkduster", size: 20)
        self.info.textAlignment = .center
        self.info.textColor = UIColor.white
        self.info.backgroundColor = UIColor.black
    }

}

public class MainScene: SKScene {

    public var button1 = SKSpriteNode(imageNamed: "Next")
    public var button2 = SKSpriteNode(imageNamed: "Previous")

    public var scene1: Slide?

    public override func didMove(to view: SKView) {

        backgroundColor = SKColor.black
        scene1?.setter()
        setScene1()
    }

    public func setScene1() {

        scene1?.title = SKLabelNode(fontNamed: "Chalkduster")
        scene1?.title.text = "Title."
        scene1?.title.position = CGPoint(x: frame.midX, y: frame.midY)
        scene1?.info.text = "Text."

        addChild(scene1?.title)
        addButtons()
    }

    public func addButtons() {

        self.button1.position = CGPoint(x: 600, y: 40)
        self.button2.position = CGPoint(x: 40, y: 40)
        addChild(self.button1)
        addChild(self.button2)
    }

}
</code>```

Basically, I was tying to setup multiple slides through functions that would change the previous slide's title/info. However, I thought it would be much better to have an SKView class defined for my slides in order to use SKTransition.

However, with my current code, I'm running into an execution interrupted error. Also, when I change stuff around, the error kind of followed me into either Expected Declaration or no Class Initializers for MainScene.swift.

Really, I just want to fix up my declaration of the class Slide and then use that class to make multiple slides.

答:
Here's an example without SpriteKit.  You should really review some basic Swift and UIKit lessons to get a good foundation on the language</p>

```<code>import UIKit
import PlaygroundSupport

public class Slide: UIView {

    public var title: UILabel
    public var info: UITextView

    required public override init(frame:CGRect) {
        self.title = UILabel()
        self.title.font = UIFont(name: "Chalkduster", size: 20)
        self.title.textColor = UIColor.white
        self.title.backgroundColor = UIColor.red
        self.title.center = CGPoint(x: frame.midX, y: 440)

        self.info = UITextView()
        self.info.font = UIFont(name: "Chalkduster", size: 20)
        self.info.textAlignment = .center
        self.info.textColor = UIColor.white
        self.info.backgroundColor = UIColor.blue

        super.init(frame: frame)
        addSubview(title)
        addSubview(info)

    }
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

public class MainScene: UIView {
    public var scene1: Slide

    required public override init(frame: CGRect) {
        scene1 = Slide()
        super.init(frame: frame)
        scene1.title.text = "Title."
        scene1.title.sizeToFit()
        scene1.title.center = CGPoint(x: frame.midX, y: frame.midY - 20)
        scene1.info.text = "Text."
        scene1.info.sizeToFit()
        scene1.info.center = CGPoint(x: frame.midX, y: frame.midY + scene1.title.frame.height + 20)
        addSubview(scene1)
    }
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

let frame = CGRect(x: 0, y: 0, width: 640, height: 480)

let view = UIView(frame: frame)

let scene = MainScene(frame: frame)
view.addSubview(scene)
PlaygroundPage.current.liveView = view
</code>```

Title: Initializing Class Properties In Swift

Body:
So I'm trying to create a Playground that functions as a 'presentation', meaning that I have multiple slides and it's interactive-ish. I'm new to Swift, so would really use some help.

This is my main code

import UIKit
import SpriteKit
import PlaygroundSupport

let frame = CGRect(x: 0, y: 0, width: 640, height: 480)

let view = SKView(frame: frame)
view.showsDrawCount = true
view.showsNodeCount = true
view.showsFPS = true

let scene = MainScene(size: CGSize(width: 640, height: 480))
view.presentScene(scene) //error here, explained below
PlaygroundPage.current.liveView = view

This is my MainScene.swift code -

import UIKit
import SpriteKit
import PlaygroundSupport

public class Slide: SKView {

    public var title: SKLabelNode!
    public var info: UITextView!

    public func setter() {

        self.title = SKLabelNode(fontNamed: "Chalkduster")
        self.title.verticalAlignmentMode = .center
        self.title.color = SKColor.white
        self.title.position = CGPoint(x: frame.midX, y: 440)

        let framer = CGRect(x: 40, y: 60, width: 560, height: 360)

        self.info = UITextView(frame: framer)
        self.info.font = UIFont(name: "Chalkduster", size: 20)
        self.info.textAlignment = .center
        self.info.textColor = UIColor.white
        self.info.backgroundColor = UIColor.black
    }

}

public class MainScene: SKScene {

    public var button1 = SKSpriteNode(imageNamed: "Next")
    public var button2 = SKSpriteNode(imageNamed: "Previous")

    public var scene1: Slide?

    public override func didMove(to view: SKView) {

        backgroundColor = SKColor.black
        scene1?.setter()
        setScene1()
    }

    public func setScene1() {

        scene1?.title = SKLabelNode(fontNamed: "Chalkduster")
        scene1?.title.text = "Title."
        scene1?.title.position = CGPoint(x: frame.midX, y: frame.midY)
        scene1?.info.text = "Text."

        addChild(scene1?.title)
        addButtons()
    }

    public func addButtons() {

        self.button1.position = CGPoint(x: 600, y: 40)
        self.button2.position = CGPoint(x: 40, y: 40)
        addChild(self.button1)
        addChild(self.button2)
    }

}

Basically, I was tying to setup multiple slides through functions that would change the previous slide's title/info. However, I thought it would be much better to have an SKView class defined for my slides in order to use SKTransition.

However, with my current code, I'm running into an execution interrupted error. Also, when I change stuff around, the error kind of followed me into either Expected Declaration or no Class Initializers for MainScene.swift.

Really, I just want to fix up my declaration of the class Slide and then use that class to make multiple slides.

Body:
Here's an example without SpriteKit.  You should really review some basic Swift and UIKit lessons to get a good foundation on the language

import UIKit
import PlaygroundSupport

public class Slide: UIView {

    public var title: UILabel
    public var info: UITextView

    required public override init(frame:CGRect) {
        self.title = UILabel()
        self.title.font = UIFont(name: "Chalkduster", size: 20)
        self.title.textColor = UIColor.white
        self.title.backgroundColor = UIColor.red
        self.title.center = CGPoint(x: frame.midX, y: 440)

        self.info = UITextView()
        self.info.font = UIFont(name: "Chalkduster", size: 20)
        self.info.textAlignment = .center
        self.info.textColor = UIColor.white
        self.info.backgroundColor = UIColor.blue

        super.init(frame: frame)
        addSubview(title)
        addSubview(info)

    }
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

public class MainScene: UIView {
    public var scene1: Slide

    required public override init(frame: CGRect) {
        scene1 = Slide()
        super.init(frame: frame)
        scene1.title.text = "Title."
        scene1.title.sizeToFit()
        scene1.title.center = CGPoint(x: frame.midX, y: frame.midY - 20)
        scene1.info.text = "Text."
        scene1.info.sizeToFit()
        scene1.info.center = CGPoint(x: frame.midX, y: frame.midY + scene1.title.frame.height + 20)
        addSubview(scene1)
    }
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

let frame = CGRect(x: 0, y: 0, width: 640, height: 480)

let view = UIView(frame: frame)

let scene = MainScene(frame: frame)
view.addSubview(scene)
PlaygroundPage.current.liveView = view


问:
Unpacked javascript doesn't work
I found this script (http://coolersport.info/) and downloaded it. I want change some things in javascript code, so I opened cshout.js (unpacked version) and do changes. I saved it as "cshout.packed.js" (replaced with original packed version).

But now I go to my script index, I can't see any thing, And I see only a white blank page...

Why unpacked version doesn't work? The packed version was create from original unpacked file  (I have same problem with some other scripts...it is an example!)

I debugging it with FireBug. Firebug said:

```<code>ajaxCS is not defined
localhost/cshout/cshout.js Line 49
cshout is not defined localhost/cshout
Line 14
</code>```

答:
you are looking for problem in wrong place

you need to include ajaxcs.js

Title: Unpacked javascript doesn't work

Body:
I found this script (http://coolersport.info/) and downloaded it. I want change some things in javascript code, so I opened cshout.js (unpacked version) and do changes. I saved it as "cshout.packed.js" (replaced with original packed version).

But now I go to my script index, I can't see any thing, And I see only a white blank page...

Why unpacked version doesn't work? The packed version was create from original unpacked file  (I have same problem with some other scripts...it is an example!)

I debugging it with FireBug. Firebug said:

ajaxCS is not defined
localhost/cshout/cshout.js Line 49
cshout is not defined localhost/cshout
Line 14