问:
Custom Materials With Three.ShaderMaterial in A-Frame
I'm trying to use THREE.ShaderMaterial to make a custom material in A-Frame. Apparently A-Frame doesn't compile the shader if it's not coming through the registerShader API. The wireframe property takes effect but the shader doesn't work. In particular, I wanted to have wireframe rendering besides my shader which simply changes the color of vertices based on their distance from a particular point (pos). Is there any way to either change this code to force A-Frame to compile the shader or to use the shader API and still achieve the wireframe and other properties of THREE.ShaderMaterial.

```<code>AFRAME.registerShader('shellmaterial', {

schema: {
    color: {default: {value: new THREE.Color(255, 255, 255)}},
    pos: {default: {value: {x: 132.89, y: 50.64, z: -106.52}}}
},

init: function (data) {
    let uniformsObj = {color: data.color, pos: data.pos};

    this.material = new THREE.ShaderMaterial({
        wireframe: true,
        shading: THREE.SmoothShading,
        uniforms: uniformsObj,
        vertexShader: this.vertexShader,
        fragmentShader: this.fragmentShader
    });
},

update: function (data) {
    let uniformsObj = {color: data.color, pos: data.pos};

    this.material = new THREE.ShaderMaterial({
        wireframe: true,
        shading: THREE.SmoothShading,
        uniforms: uniformsObj,
        vertexShader: this.vertexShader,
        fragmentShader: this.fragmentShader
    });
},

vertexShader:

 `
   uniform vec3 color;
   uniform vec3 pos;
   varying vec3 vColor;
   varying float dist;

   void main(){
        dist = distance(position,pos);
            if (dist<500.0){
                vColor = vec3(1.0,dist/500.0,dist/500.0);
            }
            else{
                vColor = vec3(1.0);
            }
        gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );}
    `,

fragmentShader: `
uniform vec3 color;
varying vec3 vColor;

void main(){
  gl_FragColor = vec4( color*vColor, 1.0 );
}
`
});
</code>```

答: You could build the wireframe shader into your custom shader or try two renders of the same object with a different material and composite them on top of each other?  Either should work, rendering twice means more draw calls but if you don't care about frame rate too much it might be easier than combining the two shaders depending upon your knowledge of shader code.</p>

Body:
I'm trying to use THREE.ShaderMaterial to make a custom material in A-Frame. Apparently A-Frame doesn't compile the shader if it's not coming through the registerShader API. The wireframe property takes effect but the shader doesn't work. In particular, I wanted to have wireframe rendering besides my shader which simply changes the color of vertices based on their distance from a particular point (pos). Is there any way to either change this code to force A-Frame to compile the shader or to use the shader API and still achieve the wireframe and other properties of THREE.ShaderMaterial.

AFRAME.registerShader('shellmaterial', {

schema: {
    color: {default: {value: new THREE.Color(255, 255, 255)}},
    pos: {default: {value: {x: 132.89, y: 50.64, z: -106.52}}}
},

init: function (data) {
    let uniformsObj = {color: data.color, pos: data.pos};

    this.material = new THREE.ShaderMaterial({
        wireframe: true,
        shading: THREE.SmoothShading,
        uniforms: uniformsObj,
        vertexShader: this.vertexShader,
        fragmentShader: this.fragmentShader
    });
},

update: function (data) {
    let uniformsObj = {color: data.color, pos: data.pos};

    this.material = new THREE.ShaderMaterial({
        wireframe: true,
        shading: THREE.SmoothShading,
        uniforms: uniformsObj,
        vertexShader: this.vertexShader,
        fragmentShader: this.fragmentShader
    });
},

vertexShader:

 `
   uniform vec3 color;
   uniform vec3 pos;
   varying vec3 vColor;
   varying float dist;

   void main(){
        dist = distance(position,pos);
            if (dist<500.0){
                vColor = vec3(1.0,dist/500.0,dist/500.0);
            }
            else{
                vColor = vec3(1.0);
            }
        gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );}
    `,

fragmentShader: `
uniform vec3 color;
varying vec3 vColor;

void main(){
  gl_FragColor = vec4( color*vColor, 1.0 );
}
`
});


来源: stackexchange

问:
Reading subset of large data
I have a LARGE dataset with over 100 Million rows. I only want to read part of the data corresponds to one particular level of a factor, say column1 == A. How do I accomplish this in R using read.csv?

Thank you

答:
You can't filter rows using read.csv. You might try sqldf::read.csv.sql as outlined in answers to this question.

But I think most people would process the file using another tool first. For example, csvkit allows filtering by rows.

ContentLicense: CC BY-SA 3.0

Title: Reading subset of large data


问:
Add Alt text on Media Images while uploading - Umbraco
I am using Umbraco 7.5.3 and I want to add an alt text to media images while uploading or while selecting (On clicking submit) them using media picker. Is this possible?

I have added a property to Image Media Type. This way it is available for all the images I have in the CMS.

But another question I am getting stucked with. Is it good or bad to change inbuilt Umbraco data types?

Any help appreciated.

Thanks in advance!

答:
For this, I have added an alternative text property to the media Image type. (Settings -> Media Types -> Image).

You can see the below image.


问:
Python Flask SQLAlchemy Pagination
I am having trouble implementing pagination with Flask-SQLAlchemy or Flask-Pagination, either or. I am unsure how to initialize the pagination, setting pages, determining pages, offest, etc. I am coming from PHP, quite new to Python.

I am querying all the posts in my database

```<code>posts = Posts.query.order_by(Posts.time.desc()).all()
</code>```

I have been looking at the following examples:

http://www.ergo.io/tutorials/better-pagination-in-flask/better-pagination-in-flask/

https://pythonhosted.org/Flask-paginate/

sqlalchemy pagination

I am confused on really what to do, the information I am finding greatly differs between articles. It's left me with confusion and not knowing where to begin. I want to query all rows of the database table, limit the results to 20 and paginate. I'm not seeing this clearly.

答:
I recommend using Flask-SQLAlchemy's pagination: http://flask-sqlalchemy.pocoo.org/2.1/api/?highlight=pagination#flask.ext.sqlalchemy.Pagination

There's a well-written example here: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-ix-pagination

Here's the basic idea for the view:

```<code>@app.route('/myview/<int:page>',methods=['GET'])
def view(page=1):
    per_page = 10
    posts = Posts.query.order_by(Posts.time.desc()).paginate(page,per_page,error_out=False)
    return render_template('view.html',posts=posts)
</code>```

And then for the template (I don't know your posts model so I made something up):

```<code><html>
  <head>
    Posts
  </head>
  <body>

{% for post in posts.items %}
<p>
  {{ post.post_name }} post body: <b>{{ post.body }}</b>
</p>
{% endfor %}
{% if posts.has_prev %}<a href="{{ url_for('view', page=posts.prev_num) }}"><< Newer posts</a>{% else %}<< Newer posts{% endif %} |
{% if posts.has_next %}<a href="{{ url_for('view', page=posts.next_num) }}">Older posts >></a>{% else %}Older posts >>{% endif %}

  </body>
</html>
</code>```

Title: Python Flask SQLAlchemy Pagination

Body:
I am having trouble implementing pagination with Flask-SQLAlchemy or Flask-Pagination, either or. I am unsure how to initialize the pagination, setting pages, determining pages, offest, etc. I am coming from PHP, quite new to Python.

I am querying all the posts in my database

posts = Posts.query.order_by(Posts.time.desc()).all()

I have been looking at the following examples:

http://www.ergo.io/tutorials/better-pagination-in-flask/better-pagination-in-flask/

https://pythonhosted.org/Flask-paginate/

sqlalchemy pagination

I am confused on really what to do, the information I am finding greatly differs between articles. It's left me with confusion and not knowing where to begin. I want to query all rows of the database table, limit the results to 20 and paginate. I'm not seeing this clearly.

Body:
I recommend using Flask-SQLAlchemy's pagination: http://flask-sqlalchemy.pocoo.org/2.1/api/?highlight=pagination#flask.ext.sqlalchemy.Pagination

There's a well-written example here: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-ix-pagination

Here's the basic idea for the view:

@app.route('/myview/<int:page>',methods=['GET'])
def view(page=1):
    per_page = 10
    posts = Posts.query.order_by(Posts.time.desc()).paginate(page,per_page,error_out=False)
    return render_template('view.html',posts=posts)

And then for the template (I don't know your posts model so I made something up):

<html>
  <head>
    Posts
  </head>
  <body>

{% for post in posts.items %}
<p>
  {{ post.post_name }} post body: <b>{{ post.body }}</b>
</p>
{% endfor %}
{% if posts.has_prev %}<a href="{{ url_for('view', page=posts.prev_num) }}">&lt;&lt; Newer posts</a>{% else %}&lt;&lt; Newer posts{% endif %} |
{% if posts.has_next %}<a href="{{ url_for('view', page=posts.next_num) }}">Older posts &gt;&gt;</a>{% else %}Older posts &gt;&gt;{% endif %}

  </body>
</html>


问:
C# GUI Programming Starting
So....I've never really done much in the way of GUI programming apps. Namely because for school ive been stuck in C++ land. But since Im graduating in December I thought it'd be nice (while im looking for a job) to study something I've wanted to look into for awhile. And please dont mark this as "subjective" im just simply asking what I need to "know" to get started.

Namely GUI programming. Im not used to it....nor have I really ever been. It's not something they focus on in school (for instance my senior design was a webcam mouse thing, but had very little in the way of GUI)

I've seen alot about C# being the superior GUI programming tool for fast development.....but I dont really know whats out there. I know "of" QT, and Im used to C++. However Im not too familiar with what the "choice" GUI language is. I do like programming on Windows however most of my stuff has been in Unix here lately (Mostly because of my OS class).

I dont know anything about .net, and i've heard of something called WPF? Is that part of .net.....or.....what? Im just a bit confused at where to start.

Thanks

答:
WPF is pretty awesome. It is rather closely related to xml.

http://msdn.microsoft.com/en-us/library/aa663364.aspx

If you use the toolbox its mostly self explanatory for the basic components. Here are components of a basic page.

http://msdn.microsoft.com/en-us/library/bb531270(VS.90).aspx

ContentLicense: CC BY-SA 2.5

Title: C# GUI Programming Starting


问:
d3.js - Force-Layout boundary issue V4
Currently I am working one of FCC's project National Contiguity

Essentially I was able to figure it out how to render the flags sprites and connect the nodes and its links.

The only thing that I am having trouble is implementing is how to behave similar to FCC's example. Specifically I am trying ways to have the nodes to repel away from the boundries like in the example.

However, mine doesn't behave that way (in fact, it's very clustered but I don't know exactly what properties in the d3.js Force Documents V4 I should look into). Instead, it seems that though the node and the links stops near the boundary, it stops at that point

```<code>const width = w - (margin.left + margin.right);
const height = h - (margin.top + margin.bottom);

let flagNodes = d3.select("#canvas")
                  .append("div")
                  .classed("flag-nodes",true)

let svg = d3.select("#canvas")
              .append("svg")
              .attr("id","chart")
              .attr("width", w)
              .attr("height", h)

let chart = svg.append("g")
                .classed("display", true)
                .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

let simulation = d3.forceSimulation()
    .force("link", d3.forceLink().id(function(d,i) {
      return i;
    }))
    .force("charge", d3.forceManyBody().strength(-60).distanceMax(50).distanceMin(5))
    .force("center", d3.forceCenter(width/2, height/2))
    .force("collide", d3.forceCollide().radius(35))
    // .force("centering", d3.forceCenter(,height))
    // .force("position", d3.forceX(0).strength(.01))
    // .force("position", d3.forceY(-18))

let link = chart.append("g")
        .classed("links",true)
        .selectAll("line")
        .data(data.links)
        .enter()
          .append("line")

simulation
    .nodes(data.nodes)
    .on("tick", ticked);

simulation
    .force("link")
    .links(data.links);

let node = flagNodes.selectAll(".flag-nodes")
        .data(data.nodes)
        .enter()
          .append("div")
          .attr("class", function(d,i){
            return `flag flag-${d.code}`
          })
          .call(d3.drag()
          .on("start", dragstarted)
          .on("drag", dragged)
          .on("end", dragended)
        )

node.append("title")
.text(function(d) { return d.country; });

d3.forceX(width)

//functions provided by D3.js
//
function ticked() {
    node
        .style("left", function(d) {
          let xlimit = Math.max(radius, Math.min(width - radius, d.x))
          return (xlimit) + 'px'
        })
        .style("top", function(d) {
          let ylimit = Math.max(radius, Math.min(height - radius, d.y))
          return (ylimit - 2) + 'px'
        });
    link
        .attr("x1", function(d) {
          let x1 = Math.max(radius, Math.min(width - radius, d.source.x))
          return x1;
        })
        .attr("y1", function(d) {
          let y1 = Math.max(radius, Math.min(height - radius, d.source.y))
          return y1
        })
        .attr("x2", function(d) {
          let x2 = Math.max(radius, Math.min(width - radius, d.target.x))
          return x2;
        })
        .attr("y2", function(d) {
          let y2 = Math.max(radius, Math.min(height - radius, d.target.y))
          return y2
        });
  }

function dragstarted(d) {
  if (!d3.event.active) simulation.alphaTarget(0.3).restart();
  d.fx = d.x;
  d.fy = d.y;
}

function dragged(d) {
  d.fx = d3.event.x;
  d.fy = d3.event.y;
}

function dragended(d) {
  if (!d3.event.active) simulation.alphaTarget(0);
  d.fx = null;
  d.fy = null;
}
</code>```

Codepen

答:
On every tick, run this function on the simulation's nodes:

```<code>fixBounds() {
    const graphNodes = this.forceSimulation.nodes();

    graphNodes.forEach((node) => {
        if (node.x - this.nodeRadius < 0) {
            node.x = this.nodeRadius;
            node.vx = 0;
        }

        if (node.y - this.nodeRadius < 0) {
            node.y = this.nodeRadius;
            node.vy = 0;
        }

        if (this.width && node.x + this.nodeRadius > this.width) {
            node.x = this.width - this.nodeRadius;
            node.vx = 0;
        }

        if (this.height && node.y + this.nodeRadius > this.height) {
            node.y = this.height - this.nodeRadius;
            node.yx = 0;
        }
    })
}
</code>```

This will cause the nodes to get stuck on the border, and the forces between the nodes will cause them to move away from the border.

Title: d3.js - Force-Layout boundary issue V4

Body:
Currently I am working one of FCC's project National Contiguity

Essentially I was able to figure it out how to render the flags sprites and connect the nodes and its links.

The only thing that I am having trouble is implementing is how to behave similar to FCC's example. Specifically I am trying ways to have the nodes to repel away from the boundries like in the example.

However, mine doesn't behave that way (in fact, it's very clustered but I don't know exactly what properties in the d3.js Force Documents V4 I should look into). Instead, it seems that though the node and the links stops near the boundary, it stops at that point

const width = w - (margin.left + margin.right);
const height = h - (margin.top + margin.bottom);

let flagNodes = d3.select("#canvas")
                  .append("div")
                  .classed("flag-nodes",true)

let svg = d3.select("#canvas")
              .append("svg")
              .attr("id","chart")
              .attr("width", w)
              .attr("height", h)

let chart = svg.append("g")
                .classed("display", true)
                .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

let simulation = d3.forceSimulation()
    .force("link", d3.forceLink().id(function(d,i) {
      return i;
    }))
    .force("charge", d3.forceManyBody().strength(-60).distanceMax(50).distanceMin(5))
    .force("center", d3.forceCenter(width/2, height/2))
    .force("collide", d3.forceCollide().radius(35))
    // .force("centering", d3.forceCenter(,height))
    // .force("position", d3.forceX(0).strength(.01))
    // .force("position", d3.forceY(-18))

let link = chart.append("g")
        .classed("links",true)
        .selectAll("line")
        .data(data.links)
        .enter()
          .append("line")

simulation
    .nodes(data.nodes)
    .on("tick", ticked);

simulation
    .force("link")
    .links(data.links);

let node = flagNodes.selectAll(".flag-nodes")
        .data(data.nodes)
        .enter()
          .append("div")
          .attr("class", function(d,i){
            return `flag flag-${d.code}`
          })
          .call(d3.drag()
          .on("start", dragstarted)
          .on("drag", dragged)
          .on("end", dragended)
        )

node.append("title")
.text(function(d) { return d.country; });

d3.forceX(width)

//functions provided by D3.js
//
function ticked() {
    node
        .style("left", function(d) {
          let xlimit = Math.max(radius, Math.min(width - radius, d.x))
          return (xlimit) + 'px'
        })
        .style("top", function(d) {
          let ylimit = Math.max(radius, Math.min(height - radius, d.y))
          return (ylimit - 2) + 'px'
        });
    link
        .attr("x1", function(d) {
          let x1 = Math.max(radius, Math.min(width - radius, d.source.x))
          return x1;
        })
        .attr("y1", function(d) {
          let y1 = Math.max(radius, Math.min(height - radius, d.source.y))
          return y1
        })
        .attr("x2", function(d) {
          let x2 = Math.max(radius, Math.min(width - radius, d.target.x))
          return x2;
        })
        .attr("y2", function(d) {
          let y2 = Math.max(radius, Math.min(height - radius, d.target.y))
          return y2
        });
  }

function dragstarted(d) {
  if (!d3.event.active) simulation.alphaTarget(0.3).restart();
  d.fx = d.x;
  d.fy = d.y;
}

function dragged(d) {
  d.fx = d3.event.x;
  d.fy = d3.event.y;
}

function dragended(d) {
  if (!d3.event.active) simulation.alphaTarget(0);
  d.fx = null;
  d.fy = null;
}

Codepen

Body:
On every tick, run this function on the simulation's nodes:

fixBounds() {
    const graphNodes = this.forceSimulation.nodes();

    graphNodes.forEach((node) => {
        if (node.x - this.nodeRadius < 0) {
            node.x = this.nodeRadius;
            node.vx = 0;
        }

        if (node.y - this.nodeRadius < 0) {
            node.y = this.nodeRadius;
            node.vy = 0;
        }

        if (this.width && node.x + this.nodeRadius > this.width) {
            node.x = this.width - this.nodeRadius;
            node.vx = 0;
        }

        if (this.height && node.y + this.nodeRadius > this.height) {
            node.y = this.height - this.nodeRadius;
            node.yx = 0;
        }
    })
}

This will cause the nodes to get stuck on the border, and the forces between the nodes will cause them to move away from the border.


问:
Emacs - No tabbable suggestions for init.el
I am fairly new to Emacs.

After opening init.el I would expect tab completion, just like in the minibuffer when doing M-x and typing part of a command and pressing tab to get the *Completions* window.

However, after entering part of a line:

```<code>(add-to-
</code>```

and pressing tab, Emacs does nothing; it does not show the *Completions* window.

Is there a method of enabling tab completion when editing an .el file?

答:
You can get the TAB key to perform completion simply with

```<code>(setq tab-always-indent 'complete)
</code>```

it won't prevent TAB from reindenting, tho: instead, it refines the behavior of TAB so that if TAB's reindentation has no effect (i.e. the line is already properly indented), it then tries to perform completion.  It should work in most major modes (as long as they provide the needed completion data via completion-at-point-functions), not just in Elisp.

Body:
I am fairly new to Emacs.

After opening init.el I would expect tab completion, just like in the minibuffer when doing M-x and typing part of a command and pressing tab to get the *Completions* window.

However, after entering part of a line:

(add-to-

and pressing tab, Emacs does nothing; it does not show the *Completions* window.

Is there a method of enabling tab completion when editing an .el file?

Body:
You can get the TAB key to perform completion simply with

(setq tab-always-indent 'complete)

it won't prevent TAB from reindenting, tho: instead, it refines the behavior of TAB so that if TAB's reindentation has no effect (i.e. the line is already properly indented), it then tries to perform completion.  It should work in most major modes (as long as they provide the needed completion data via completion-at-point-functions), not just in Elisp.


问:
Bing Maps v8 and strange work of instanceof
Load map:

```<code>map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
    ...
});
</code>```

And it works fine (visually). But:

```<code>console.log(map instanceof Microsoft.Maps.Map);  // false
</code>```

Whaaat?! :) How can I check it? Is it a bug or my mistake?

You can try example in Bing Dev Center sandbox:

http://www.bing.com/api/maps/sdkrelease/mapcontrol/isdk#loadMapAsync+JS

Thanks

答:
Using the Bing Apps dev page, if you edit out the new it still works, and logging map.constructor just prints function n(). So it appears Microsoft has not been entirely accurate as to what the code does at the moment - which is to act as an object factory.

Microsoft may be reserving the right to make Maps.Map an object constructor in the future. At the moment instanceof returning false is correct.

Body:
Load map:

map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
    ...
});

And it works fine (visually). But:

console.log(map instanceof Microsoft.Maps.Map);  // false

Whaaat?! :) How can I check it? Is it a bug or my mistake?

You can try example in Bing Dev Center sandbox:

http://www.bing.com/api/maps/sdkrelease/mapcontrol/isdk#loadMapAsync+JS

Thanks


问:
Seggregation of Json Schema Validation and Json Validation
I have a use case where I will take a json-schema as input, validate it, then keep in my system. Later I will get json data which I need to validate with above mentioned json-schema. given the scenario, I need to do two level of validations:

```<code>1. provided json-schema is valid or not.
2. Json is valid or not.
</code>```

I am using json-schema-validator jar and could find only second level of validation, couldn't find json-schema validation in documentation. for example: lets say we have below sample json-schema:

```<code>{
"title": "Person",
"type": "object",
"properties": {
    "firstName": {
        "type": "string"
    },
    "lastName": {
        "type": "string"
    },
    "age": {
        "description": "Age in years",
        "type": "integer",
        "minimum": 0
    }
},
"required": ["firstName", "lastName"]
}
</code>```

so how to validate this json-schema itself is valid or not?

答:
There is a working example here with the everit-org/json-schema implementation (just in case you want to use a maintained library):
How to validate a json schema against the version spec it specifies in Java</p>

Body:
I have a use case where I will take a json-schema as input, validate it, then keep in my system. Later I will get json data which I need to validate with above mentioned json-schema. given the scenario, I need to do two level of validations:

1. provided json-schema is valid or not.
2. Json is valid or not.

I am using json-schema-validator jar and could find only second level of validation, couldn't find json-schema validation in documentation. for example: lets say we have below sample json-schema:

{
"title": "Person",
"type": "object",
"properties": {
    "firstName": {
        "type": "string"
    },
    "lastName": {
        "type": "string"
    },
    "age": {
        "description": "Age in years",
        "type": "integer",
        "minimum": 0
    }
},
"required": ["firstName", "lastName"]
}

so how to validate this json-schema itself is valid or not?


问:
NSContainerView with multiple child view controllers in Xcode 6
I'm trying to link two different view controllers in an Xcode 6 storyboard with a NSContainerView so that they can be switched conditionally. Unfortunately this tutorial here isn't of any help since things seem to have changed since in Xcode.

So I have two different view controllers and one of them is loaded into the container view by default but I want to be able to load the second view controller into the container view programmatically. Xcode 6 only allows to create embed Segues when I drag from one to the other so that's not much of a help.

Can somebody tell me how this is achieved with Xcode 6?

答:
First, here's a sample GitHub project of the solution: click. I wasn't sure whether you wanted to swap the views or simply push the 2nd view onto a proverbial stack, so I went with a push/pop scheme. If you want to swap the views instead, you should be able to do that fairly easily by just skipping the stack storage.

Essentially, we have our "host" NSViewController that holds a Container View (CV) inside of it. This host doesn't actually manually manage the view controller that the CV is showing at the moment. The way this is done is through, well, a sort of nested view controller that then manages all the other view controllers that you're going to show/hide/push/pop/swap/etc. (Note: you might be able to remove the layering a bit, but in iOS terms, I'm treating the 'Sub View Controller Manager' in the storyboard screenshot sort of like a UINavigationController).

We also take advantage of some custom segues/segue animators in order to be able to do more work in the storyboard.

You just have to tell the content view manager view controller to manipulate its subviews in such a way that the old views that you want to pop "back" to are retained (in this case, using an NSMutableArray) and such that the new views have the right frame or have their constraints set up properly.

Here is a screenshot of the storyboard:  Each segue you see on the storyboard of a custom type (looks like this -> { } ) is of type SegueBetweenEmbedded in the sample project. Buttons that push perform a segue, and buttons labeled 'Pop' perform dismissController: on the NSViewController (so that was done in the storyboard).

Here's some code (and there's a lot of it, so I suggest looking at the sample project instead):

ViewController.h

```<code>#import <Cocoa/Cocoa.h>
#import "ContentManagerViewController.h"

@class ContentManagerViewController;

@protocol ContentManagerViewControllerHolder <NSObject>

-(ContentManagerViewController*)retreiveContentManagerController;

@end

@interface ViewController : NSViewController <ContentManagerViewControllerHolder>

@end
</code>```

ViewController.m

```<code>#import "ViewController.h"
#import "ContentManagerViewController.h"
#import "BackForwardViewController.h"

@interface ViewController ()

@property ContentManagerViewController *vcController;

-(IBAction)pushViewController:(id)sender;
-(IBAction)popViewController:(id)sender;
-(IBAction)popToRootViewController:(id)sender;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

-(void)prepareForSegue:(NSStoryboardSegue *)segue sender:(id)sender {
    if ([[segue destinationController] class] == [ContentManagerViewController class]) {
        self.vcController = segue.destinationController;
    }
}

-(ContentManagerViewController*)retreiveContentManagerController {
    return self.vcController;
}

-(IBAction)pushViewController:(id)sender {
    // note: this works, but then pop is broken via dismissController: since it wasn't done with a segue.
    // Better way is to rig up a manual segue and execute the segue.
    //BackForwardViewController *viewController = [[NSStoryboard storyboardWithName:@"Main" bundle:nil] instantiateControllerWithIdentifier:@"BackForwardStoryboardID"];
    //[self.vcController push:viewController];

    [self performSegueWithIdentifier:@"CustomSegueToBackForward" sender:self];
}

-(IBAction)popViewController:(id)sender {
    [self.vcController pop];
}

-(IBAction)popToRootViewController:(id)sender {
    [self.vcController popToRoot];
}

@end
</code>```

SegueBetweenEmbedded.h

```<code>#import <Cocoa/Cocoa.h>

@interface SegueBetweenEmbedded : NSStoryboardSegue

@end
</code>```

SegueBetweenEmbedded.m (sorry not sorry for the nested class)

```<code>#import "SegueBetweenEmbedded.h"
#import "ContentManagerViewController.h"
#import "ViewController.h"

@interface SegueAnimator : NSObject <NSViewControllerPresentationAnimator>

- (void)animatePresentationOfViewController:(NSViewController *)viewController fromViewController:(NSViewController *)fromViewController;
- (void)animateDismissalOfViewController:(NSViewController *)viewController fromViewController:(NSViewController *)fromViewController;

@end

@implementation SegueAnimator

- (void)animatePresentationOfViewController:(NSViewController *)viewController fromViewController:(NSViewController *)fromViewController {
    NSViewController *parent = [fromViewController parentViewController];
    if (parent && [parent class] == [ContentManagerViewController class]) {
        ContentManagerViewController *manager = (ContentManagerViewController*)parent;
        [manager push:viewController];
    }
    else if ([fromViewController conformsToProtocol:@protocol(ContentManagerViewControllerHolder)]) {
        id<ContentManagerViewControllerHolder> holder = (id<ContentManagerViewControllerHolder>)fromViewController;
        [[holder retreiveContentManagerController] push:viewController];
    }
}

- (void)animateDismissalOfViewController:(NSViewController *)viewController fromViewController:(NSViewController *)fromViewController {
    NSViewController *parent = [viewController parentViewController];
    if ([parent class] == [ContentManagerViewController class]) {
        ContentManagerViewController *manager = (ContentManagerViewController*)parent;
        [manager pop];
    }
}

@end

@implementation SegueBetweenEmbedded

- (void)perform {
    SegueAnimator *animator = [[SegueAnimator alloc] init];
    [self.sourceController presentViewController:self.destinationController
                                        animator:(id<NSViewControllerPresentationAnimator>)animator];
}

@end
</code>```

ContentManagerViewController.h

```<code>#import <Cocoa/Cocoa.h>

@interface ContentManagerViewController : NSViewController

-(void)push:(NSViewController*)viewController;
-(void)pop;
-(void)popToRoot;

@end
</code>```

ContentManagerViewController.m

```<code>#import "ContentManagerViewController.h"
#import "BackForwardViewController.h"

@interface ContentManagerViewController ()

@property (weak) IBOutlet NSView *subViewControllerManager;

@property NSViewController *currentViewController;
@property NSMutableArray<NSViewController*> *viewControllerStack;

@end

@implementation ContentManagerViewController

-(instancetype)init {
    self = [super init];
    self.viewControllerStack = [NSMutableArray array];
    return self;
}

-(instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    self.viewControllerStack = [NSMutableArray array];
    return self;
}

-(instancetype)initWithNibName:(NSNibName)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    self.viewControllerStack = [NSMutableArray array];
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

-(void)showViewController:(NSViewController*)viewController {
    [self addChildViewController:viewController];
    viewController.view.frame = self.currentViewController.view.frame;
    [self.view addSubview:viewController.view];
    self.currentViewController = viewController;
}

-(void)removeCurrentViewControllerFromView {
    [self.currentViewController.view removeFromSuperview];
    [self.currentViewController removeFromParentViewController];
}

-(void)push:(NSViewController*)viewController {
    [self removeCurrentViewControllerFromView];
    [self.viewControllerStack addObject:viewController];
    [self showViewController:viewController];
}

-(void)pop {
    if (self.viewControllerStack.count > 1) {
        [self removeCurrentViewControllerFromView];
        [self.viewControllerStack removeLastObject];
        NSViewController *viewController = [self.viewControllerStack lastObject];
        [self showViewController:viewController];
    }
}

-(void)popToRoot {
    while (self.viewControllerStack.count > 1) {
        [self pop];
    }
}

-(void)prepareForSegue:(NSStoryboardSegue *)segue sender:(id)sender {
    // this will be called on the initial embed to set up the first view controller
    self.currentViewController = segue.destinationController;
    [self.viewControllerStack addObject:segue.destinationController];
}

@end
</code>```

BackForwardViewController.h

```<code>#import <Cocoa/Cocoa.h>

@interface BackForwardViewController : NSViewController

@end
</code>```

BackForwardViewController.m

```<code>#import "BackForwardViewController.h"

@interface BackForwardViewController ()

@end

@implementation BackForwardViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do view setup here.
}

@end
</code>```

Body:
First, here's a sample GitHub project of the solution: click. I wasn't sure whether you wanted to swap the views or simply push the 2nd view onto a proverbial stack, so I went with a push/pop scheme. If you want to swap the views instead, you should be able to do that fairly easily by just skipping the stack storage.

Essentially, we have our "host" NSViewController that holds a Container View (CV) inside of it. This host doesn't actually manually manage the view controller that the CV is showing at the moment. The way this is done is through, well, a sort of nested view controller that then manages all the other view controllers that you're going to show/hide/push/pop/swap/etc. (Note: you might be able to remove the layering a bit, but in iOS terms, I'm treating the 'Sub View Controller Manager' in the storyboard screenshot sort of like a UINavigationController).

We also take advantage of some custom segues/segue animators in order to be able to do more work in the storyboard.

You just have to tell the content view manager view controller to manipulate its subviews in such a way that the old views that you want to pop "back" to are retained (in this case, using an NSMutableArray) and such that the new views have the right frame or have their constraints set up properly.

Here is a screenshot of the storyboard:  Each segue you see on the storyboard of a custom type (looks like this -> { } ) is of type SegueBetweenEmbedded in the sample project. Buttons that push perform a segue, and buttons labeled 'Pop' perform dismissController: on the NSViewController (so that was done in the storyboard).

Here's some code (and there's a lot of it, so I suggest looking at the sample project instead):

ViewController.h

#import <Cocoa/Cocoa.h>
#import "ContentManagerViewController.h"

@class ContentManagerViewController;

@protocol ContentManagerViewControllerHolder <NSObject>

-(ContentManagerViewController*)retreiveContentManagerController;

@end

@interface ViewController : NSViewController <ContentManagerViewControllerHolder>

@end

ViewController.m

#import "ViewController.h"
#import "ContentManagerViewController.h"
#import "BackForwardViewController.h"

@interface ViewController ()

@property ContentManagerViewController *vcController;

-(IBAction)pushViewController:(id)sender;
-(IBAction)popViewController:(id)sender;
-(IBAction)popToRootViewController:(id)sender;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

-(void)prepareForSegue:(NSStoryboardSegue *)segue sender:(id)sender {
    if ([[segue destinationController] class] == [ContentManagerViewController class]) {
        self.vcController = segue.destinationController;
    }
}

-(ContentManagerViewController*)retreiveContentManagerController {
    return self.vcController;
}

-(IBAction)pushViewController:(id)sender {
    // note: this works, but then pop is broken via dismissController: since it wasn't done with a segue.
    // Better way is to rig up a manual segue and execute the segue.
    //BackForwardViewController *viewController = [[NSStoryboard storyboardWithName:@"Main" bundle:nil] instantiateControllerWithIdentifier:@"BackForwardStoryboardID"];
    //[self.vcController push:viewController];

    [self performSegueWithIdentifier:@"CustomSegueToBackForward" sender:self];
}

-(IBAction)popViewController:(id)sender {
    [self.vcController pop];
}

-(IBAction)popToRootViewController:(id)sender {
    [self.vcController popToRoot];
}

@end

SegueBetweenEmbedded.h

#import <Cocoa/Cocoa.h>

@interface SegueBetweenEmbedded : NSStoryboardSegue

@end

SegueBetweenEmbedded.m (sorry not sorry for the nested class)

#import "SegueBetweenEmbedded.h"
#import "ContentManagerViewController.h"
#import "ViewController.h"

@interface SegueAnimator : NSObject <NSViewControllerPresentationAnimator>

- (void)animatePresentationOfViewController:(NSViewController *)viewController fromViewController:(NSViewController *)fromViewController;
- (void)animateDismissalOfViewController:(NSViewController *)viewController fromViewController:(NSViewController *)fromViewController;

@end

@implementation SegueAnimator

- (void)animatePresentationOfViewController:(NSViewController *)viewController fromViewController:(NSViewController *)fromViewController {
    NSViewController *parent = [fromViewController parentViewController];
    if (parent && [parent class] == [ContentManagerViewController class]) {
        ContentManagerViewController *manager = (ContentManagerViewController*)parent;
        [manager push:viewController];
    }
    else if ([fromViewController conformsToProtocol:@protocol(ContentManagerViewControllerHolder)]) {
        id<ContentManagerViewControllerHolder> holder = (id<ContentManagerViewControllerHolder>)fromViewController;
        [[holder retreiveContentManagerController] push:viewController];
    }
}

- (void)animateDismissalOfViewController:(NSViewController *)viewController fromViewController:(NSViewController *)fromViewController {
    NSViewController *parent = [viewController parentViewController];
    if ([parent class] == [ContentManagerViewController class]) {
        ContentManagerViewController *manager = (ContentManagerViewController*)parent;
        [manager pop];
    }
}

@end

@implementation SegueBetweenEmbedded

- (void)perform {
    SegueAnimator *animator = [[SegueAnimator alloc] init];
    [self.sourceController presentViewController:self.destinationController
                                        animator:(id<NSViewControllerPresentationAnimator>)animator];
}

@end

ContentManagerViewController.h

#import <Cocoa/Cocoa.h>

@interface ContentManagerViewController : NSViewController

-(void)push:(NSViewController*)viewController;
-(void)pop;
-(void)popToRoot;

@end

ContentManagerViewController.m

#import "ContentManagerViewController.h"
#import "BackForwardViewController.h"

@interface ContentManagerViewController ()

@property (weak) IBOutlet NSView *subViewControllerManager;

@property NSViewController *currentViewController;
@property NSMutableArray<NSViewController*> *viewControllerStack;

@end

@implementation ContentManagerViewController

-(instancetype)init {
    self = [super init];
    self.viewControllerStack = [NSMutableArray array];
    return self;
}

-(instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    self.viewControllerStack = [NSMutableArray array];
    return self;
}

-(instancetype)initWithNibName:(NSNibName)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    self.viewControllerStack = [NSMutableArray array];
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

-(void)showViewController:(NSViewController*)viewController {
    [self addChildViewController:viewController];
    viewController.view.frame = self.currentViewController.view.frame;
    [self.view addSubview:viewController.view];
    self.currentViewController = viewController;
}

-(void)removeCurrentViewControllerFromView {
    [self.currentViewController.view removeFromSuperview];
    [self.currentViewController removeFromParentViewController];
}

-(void)push:(NSViewController*)viewController {
    [self removeCurrentViewControllerFromView];
    [self.viewControllerStack addObject:viewController];
    [self showViewController:viewController];
}

-(void)pop {
    if (self.viewControllerStack.count > 1) {
        [self removeCurrentViewControllerFromView];
        [self.viewControllerStack removeLastObject];
        NSViewController *viewController = [self.viewControllerStack lastObject];
        [self showViewController:viewController];
    }
}

-(void)popToRoot {
    while (self.viewControllerStack.count > 1) {
        [self pop];
    }
}

-(void)prepareForSegue:(NSStoryboardSegue *)segue sender:(id)sender {
    // this will be called on the initial embed to set up the first view controller
    self.currentViewController = segue.destinationController;
    [self.viewControllerStack addObject:segue.destinationController];
}

@end

BackForwardViewController.h

#import <Cocoa/Cocoa.h>

@interface BackForwardViewController : NSViewController

@end

BackForwardViewController.m

#import "BackForwardViewController.h"

@interface BackForwardViewController ()

@end

@implementation BackForwardViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do view setup here.
}

@end


问:
UWP page transitions applied to frame for all pages
I currently have a UWP page which acts as my main window and defines the common menu/header wrapper that goes around everything else.

I then have a <frame/>

```<code><Frame Name="ContentFrame" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Grid.Row="1"/>
</code>```

I have about 10 pages that i Navigate() to using the content frame, but i would like to add the UWP page transitions, but not be forced to add the transition to every single page (it feels messy, and i dont want to forget when i add new pages).

Is there a way to define the transition within the frame its self so that all child pages will transition?

I have tried this, but with no luck

```<code><Frame Name="ContentFrame" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Grid.Row="1">
    <TransitionCollection>
        <NavigationThemeTransition>
            <NavigationThemeTransition.DefaultNavigationTransitionInfo>
                <SlideNavigationTransitionInfo/>
            </NavigationThemeTransition.DefaultNavigationTransitionInfo>
        </NavigationThemeTransition>
    </TransitionCollection>
</Frame>
</code>```

答:
I discovered the answer by accident (intelisence):

I was missing the Frame.ContentTransitions tags to make the animation apply to the child pages.

```<code><Frame Name="ContentFrame" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Grid.Row="1">
    <Frame.ContentTransitions>
        <TransitionCollection>
            <NavigationThemeTransition>
                <NavigationThemeTransition.DefaultNavigationTransitionInfo>
                    <SlideNavigationTransitionInfo/>
                </NavigationThemeTransition.DefaultNavigationTransitionInfo>
            </NavigationThemeTransition>
        </TransitionCollection>
    </Frame.ContentTransitions>
</Frame>
</code>```

Body:
I currently have a UWP page which acts as my main window and defines the common menu/header wrapper that goes around everything else.

I then have a <frame/>

<Frame Name="ContentFrame" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Grid.Row="1"/>

I have about 10 pages that i Navigate() to using the content frame, but i would like to add the UWP page transitions, but not be forced to add the transition to every single page (it feels messy, and i dont want to forget when i add new pages).

Is there a way to define the transition within the frame its self so that all child pages will transition?

I have tried this, but with no luck

<Frame Name="ContentFrame" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Grid.Row="1">
    <TransitionCollection>
        <NavigationThemeTransition>
            <NavigationThemeTransition.DefaultNavigationTransitionInfo>
                <SlideNavigationTransitionInfo/>
            </NavigationThemeTransition.DefaultNavigationTransitionInfo>
        </NavigationThemeTransition>
    </TransitionCollection>
</Frame>

Body:
I discovered the answer by accident (intelisence):

I was missing the Frame.ContentTransitions tags to make the animation apply to the child pages.

<Frame Name="ContentFrame" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Grid.Row="1">
    <Frame.ContentTransitions>
        <TransitionCollection>
            <NavigationThemeTransition>
                <NavigationThemeTransition.DefaultNavigationTransitionInfo>
                    <SlideNavigationTransitionInfo/>
                </NavigationThemeTransition.DefaultNavigationTransitionInfo>
            </NavigationThemeTransition>
        </TransitionCollection>
    </Frame.ContentTransitions>
</Frame>


问:
opencv simpleblobdetector - get blob attributes for identified blobs
I'm using the simpleblobdetector from opencv with python to identify blobs in an image.

I'm able to get the simple blob detector to work and give me the locations of identified blobs. But can I also get the inertia/convexity/circularity/etc properties of identified blobs?

```<code>img = cv2.imread('image.png', cv2.IMREAD_GRAYSCALE)

# set up blob detector params
detector_params = cv2.SimpleBlobDetector_Params()
detector_params.filterByInertia = True
detector_params.minInertiaRatio = 0.001
detector_params.filterByArea = True
detector_params.maxArea = 10000000
detector_params.minArea = 1000
detector_params.filterByCircularity = True
detector_params.minCircularity = 0.0001
detector_params.filterByConvexity = True
detector_params.minConvexity = 0.01

detector = cv2.SimpleBlobDetector_create(detector_params)

# Detect blobs.
keypoints = detector.detect(img)

# print properties of identified blobs
for p in keypoints:
    print(p.pt) # locations of blobs
    # circularity???
    # inertia???
    # area???
    # convexity???
    # etc...
</code>```

Thanks

答:
The keypoints returned by the detector do not contain any information about the algorithm that found them, as per opencv.org:

cv::KeyPoint: Data structure for salient point detectors.

The class instance stores a keypoint, i.e. a point feature found by
one of     many available keypoint detectors, such as Harris corner
detector, cv::FAST, cv::StarDetector, cv::SURF, cv::SIFT,
cv::LDetector etc.

The keypoint is characterized by the 2D position, scale (proportional
to the diameter of the neighborhood that needs to be taken into
account), orientation and some other parameters.

You can draw the keypoints, showing size and rotation:

```<code>img = cv2.drawKeypoints(img, keypoints, None, color=(0,255,0), flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
</code>```

Body:
I'm using the simpleblobdetector from opencv with python to identify blobs in an image.

I'm able to get the simple blob detector to work and give me the locations of identified blobs. But can I also get the inertia/convexity/circularity/etc properties of identified blobs?

img = cv2.imread('image.png', cv2.IMREAD_GRAYSCALE)

# set up blob detector params
detector_params = cv2.SimpleBlobDetector_Params()
detector_params.filterByInertia = True
detector_params.minInertiaRatio = 0.001
detector_params.filterByArea = True
detector_params.maxArea = 10000000
detector_params.minArea = 1000
detector_params.filterByCircularity = True
detector_params.minCircularity = 0.0001
detector_params.filterByConvexity = True
detector_params.minConvexity = 0.01

detector = cv2.SimpleBlobDetector_create(detector_params)

# Detect blobs.
keypoints = detector.detect(img)

# print properties of identified blobs
for p in keypoints:
    print(p.pt) # locations of blobs
    # circularity???
    # inertia???
    # area???
    # convexity???
    # etc...

Thanks

Body:
The keypoints returned by the detector do not contain any information about the algorithm that found them, as per opencv.org:

cv::KeyPoint: Data structure for salient point detectors.

The class instance stores a keypoint, i.e. a point feature found by
one of     many available keypoint detectors, such as Harris corner
detector, cv::FAST, cv::StarDetector, cv::SURF, cv::SIFT,
cv::LDetector etc.

The keypoint is characterized by the 2D position, scale (proportional
to the diameter of the neighborhood that needs to be taken into
account), orientation and some other parameters.

You can draw the keypoints, showing size and rotation:

img = cv2.drawKeypoints(img, keypoints, None, color=(0,255,0), flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)


问:
Best way of handling Screen Orientation Changing when working with dynamically created views?
When starting a certain activity of my app, the user is "welcomed" with a dialog that he must fill with some data in order to proceed. Then, in the activity per se, the user has 2 buttons that enable him to dynamically create and delete an infinite number of fields (that are composed by several views)

As you know, when the screen orientation changes, the activity is restarted so every information is lost. Obviously, this can be problematic.

In order to handle the screen orientation, android documentation advises developers to use onRetainNonConfigurationInstance(). The only problem is that if you use it to save objects in a context all the views tied will leak. This is further problematic in my case, since the data in that activity is inherently tied to its view, which, in turn, is tied with its context.

Android Documentation does not recommend developers to handle configuration changes themselves. They state (and I quote) "in general, a short-term solution that will only complicate their lives later"

I can bypass the initial dialog easily, creating a hasBeenShown Boolean and set it to true, for instance. I can even bypass the "dynamically created views" problem by saving their metadata: in this case the number of fields generated, their type, their relative position to each other, their text or selection, and so on... (with some minor bugs, but nothing serious).

But since fields(views) are generated dynamically with layoutInflate(and thus we can have an infinite number of views), when re-generating those same fields after screen orientation change, the application gets really really slow even on emulator. With 20 fields (approximately 120 views) on a real device (Samsung Galaxy S) it took almost 1 minute to complete.

Strangely, when I passed views directly (and thus, leaking all that stuff), it took my Samsumg Galaxy S less than 10 seconds to complete.

With this information, what do you think its the best approach?

(1) - Let the fields reset? (not really an option, I bet anyone would get pissed if they inadvertently tilt their screen =P)

(2) - Add a loading screen while android takes care of changing screen orientation?

(3) - Block screen orientation change

(4) - Handle screen orientation change myself, and hope the impeding Doom Android docs talk about never comes.

P.S: A bit offtopic, but when my activity finishes, all memory is released right?

答:
Your situation is different from mine, but a similar solution may be in order.

Again, because Android will destroy and recreate on an orientation change I initially had issues with Async tasks doing network communication. Obviously I shouldn't be creating new requests on every orientation change when the first one is still executing.

To save some network usage and headaches I just 'handle' the orientation change myself. By placing this code in your AndroidManifest.xml

```<code><activity android:name=".whatever" android:configChanges="keyboardHidden|orientation"/>
</code>```

you allow Android to keep the current context, with views and variables etc. What happens is the layouts will resize themselves but if you designed correctly then you should be ok.

AFAIK the only thing I am preventing Android from doing is using specialized layouts based on the orientation of the device (which I don't need) and so far I have not been hit by the forewarned impending doom.

Body:
Your situation is different from mine, but a similar solution may be in order.

Again, because Android will destroy and recreate on an orientation change I initially had issues with Async tasks doing network communication. Obviously I shouldn't be creating new requests on every orientation change when the first one is still executing.

To save some network usage and headaches I just 'handle' the orientation change myself. By placing this code in your AndroidManifest.xml

<activity android:name=".whatever" android:configChanges="keyboardHidden|orientation"/>

you allow Android to keep the current context, with views and variables etc. What happens is the layouts will resize themselves but if you designed correctly then you should be ok.

AFAIK the only thing I am preventing Android from doing is using specialized layouts based on the orientation of the device (which I don't need) and so far I have not been hit by the forewarned impending doom.


问:
Execute Pick Point from Windows Form in ArcGIS
I have a windows form which is launched with an ESRI AddIn button (ArcGIS 10.2 and Windows 7). On my form I have a button to pick a point from the Map. I have added an ESRI BaseTool class to the project, which has an OnMouseDown event.

The problem is that I cannot get the Tool to run. Note that the tool is not on the ArcGIS Command Bar (like the button is) but the tool is still found by the Find(uid) process.

When the Tool was added to the project (using the ArcGIS Add BaseTool process) it didn't update the .esriaddinx file. I had to do that manually.

My Addin file is:

```<code><AddIn language="CLR4.0" library="HVLR_Processing.dll" namespace="HVLR_Processing">
<ArcMap>
  <Commands>
    <Button id="RMS_HVLR_Processing_clsHVLR_Processing" class="clsHVLR_Processing" ...
    <Tool id="HVLR_PickTool" class="clsMapPick" category="Add-In Controls" caption="" message="" tip="" image="" />
  </Commands>
</ArcMap>
</code>```

The clsMapClick code contains the OnMouseDown event.

To start the process I have tried many methods. I can retrieve the Tool but when I execute it (or assign it to the CurrentTool) nothing happens.

```<code>UID pUID;
ICommandItem pCmdItem;
ICommand pCmd;
clsMapPick pPick;
ITool pTool;

try
{
   this.WindowState = FormWindowState.Minimized;

   m_pApp.CurrentTool = null;

   pUID = new UIDClass();
   pUID.Value = "HVLR_PickTool";

   pCmdItem = m_pApp.Document.CommandBars.Find(pUID, false, false);

   if (pCmdItem != null)
   {
       m_pApp.CurrentTool = pCmdItem; // Nothing happens
       m_pApp.CurrentTool.Execute(); // Nothing happens
       m_pApp.CurrentTool.Refresh();
   }
}
catch (Exception ex)
</code>```

Can anyone tell me how to get this tool to execute?

答:
OK. Big stuff-up. You can't add a BaseTool to an ESRI AddIn; it's a COM object. What has to be done is:

Create a new ESRI Tool class.

Add a boolean variable to the class to indicate the mousedown event has fired.

In the OnUpdate method put some code to continue until the mousedown event has fired.

Create an OnMouseDown event handler by starting to type protected void On... and itellisense will allow you to select the event you want to track.

Put the code you want to run in the OnMouseDown event handler and also set the boolean value to true.

Code:

```<code>public class clsMapPick : ESRI.ArcGIS.Desktop.AddIns.Tool
{
    private bool m_bIsFinished = false;
    private int m_iXPixel = -1;
    private int m_iYPixel = -1;
    //private string m_sError = "";
    //private bool m_bSuccess = true;

    public clsMapPick()
    {
    }

    protected override void OnActivate()
    {
        base.OnActivate();
        return;
    }

    protected override void OnUpdate()
    {
        if (m_bIsFinished)
        {

            m_bIsFinished = false;
            frmHVLR.m_dX = m_iXPixel;
            frmHVLR.m_dX = m_iYPixel;

        }
    }

    protected override void OnMouseDown(MouseEventArgs arg)
    {
        base.OnMouseDown(arg);

        m_iXPixel = arg.X;
        m_iYPixel = arg.Y;
        m_bIsFinished = true;
    }
}
</code>```

In the form where the button for clicking on the map is fired:

```<code>        string sError = "";
        dPickedX = 0;
        dPickedY = 0;
        UID pUID;
        ICommandItem pCmdItem;
        ICommandBars pCmdBars;
        ICommand pCmd;
        ITool pTool;

        try
        {
            this.WindowState = FormWindowState.Minimized;

            pCmdBars = m_pApp.Document.CommandBars;

            pUID = new UIDClass();
            pUID.Value = HVLR_Processing.ThisAddIn.IDs.clsMapPick;
            pCmdItem = pCmdBars.Find(pUID);

            if (pCmdItem != null)
            {
                m_pApp.CurrentTool = pCmdItem;
                //pCmdItem.Execute();

                dPickedX = m_pMxDoc.CurrentLocation.X;
                dPickedY = m_pMxDoc.CurrentLocation.Y;
            }

            return sError;
        }
</code>```

This is working fine for me now, the Tool class is being called but the OnMouseDown event isn't being fired.

If you know why I'd appreciate it.

Body:
I have a windows form which is launched with an ESRI AddIn button (ArcGIS 10.2 and Windows 7). On my form I have a button to pick a point from the Map. I have added an ESRI BaseTool class to the project, which has an OnMouseDown event.

The problem is that I cannot get the Tool to run. Note that the tool is not on the ArcGIS Command Bar (like the button is) but the tool is still found by the Find(uid) process.

When the Tool was added to the project (using the ArcGIS Add BaseTool process) it didn't update the .esriaddinx file. I had to do that manually.

My Addin file is:

<AddIn language="CLR4.0" library="HVLR_Processing.dll" namespace="HVLR_Processing">
<ArcMap>
  <Commands>
    <Button id="RMS_HVLR_Processing_clsHVLR_Processing" class="clsHVLR_Processing" ...
    <Tool id="HVLR_PickTool" class="clsMapPick" category="Add-In Controls" caption="" message="" tip="" image="" />
  </Commands>
</ArcMap>

The clsMapClick code contains the OnMouseDown event.

To start the process I have tried many methods. I can retrieve the Tool but when I execute it (or assign it to the CurrentTool) nothing happens.

UID pUID;
ICommandItem pCmdItem;
ICommand pCmd;
clsMapPick pPick;
ITool pTool;

try
{
   this.WindowState = FormWindowState.Minimized;

   m_pApp.CurrentTool = null;

   pUID = new UIDClass();
   pUID.Value = "HVLR_PickTool";

   pCmdItem = m_pApp.Document.CommandBars.Find(pUID, false, false);

   if (pCmdItem != null)
   {
       m_pApp.CurrentTool = pCmdItem; // Nothing happens
       m_pApp.CurrentTool.Execute(); // Nothing happens
       m_pApp.CurrentTool.Refresh();
   }
}
catch (Exception ex)

Can anyone tell me how to get this tool to execute?

Body:
OK. Big stuff-up. You can't add a BaseTool to an ESRI AddIn; it's a COM object. What has to be done is:

Create a new ESRI Tool class.

Add a boolean variable to the class to indicate the mousedown event has fired.

In the OnUpdate method put some code to continue until the mousedown event has fired.

Create an OnMouseDown event handler by starting to type protected void On... and itellisense will allow you to select the event you want to track.

Put the code you want to run in the OnMouseDown event handler and also set the boolean value to true.

Code:

public class clsMapPick : ESRI.ArcGIS.Desktop.AddIns.Tool
{
    private bool m_bIsFinished = false;
    private int m_iXPixel = -1;
    private int m_iYPixel = -1;
    //private string m_sError = "";
    //private bool m_bSuccess = true;

    public clsMapPick()
    {
    }

    protected override void OnActivate()
    {
        base.OnActivate();
        return;
    }

    protected override void OnUpdate()
    {
        if (m_bIsFinished)
        {

            m_bIsFinished = false;
            frmHVLR.m_dX = m_iXPixel;
            frmHVLR.m_dX = m_iYPixel;

        }
    }

    protected override void OnMouseDown(MouseEventArgs arg)
    {
        base.OnMouseDown(arg);

        m_iXPixel = arg.X;
        m_iYPixel = arg.Y;
        m_bIsFinished = true;
    }
}

In the form where the button for clicking on the map is fired:

        string sError = "";
        dPickedX = 0;
        dPickedY = 0;
        UID pUID;
        ICommandItem pCmdItem;
        ICommandBars pCmdBars;
        ICommand pCmd;
        ITool pTool;

        try
        {
            this.WindowState = FormWindowState.Minimized;

            pCmdBars = m_pApp.Document.CommandBars;

            pUID = new UIDClass();
            pUID.Value = HVLR_Processing.ThisAddIn.IDs.clsMapPick;
            pCmdItem = pCmdBars.Find(pUID);

            if (pCmdItem != null)
            {
                m_pApp.CurrentTool = pCmdItem;
                //pCmdItem.Execute();

                dPickedX = m_pMxDoc.CurrentLocation.X;
                dPickedY = m_pMxDoc.CurrentLocation.Y;
            }

            return sError;
        }

This is working fine for me now, the Tool class is being called but the OnMouseDown event isn't being fired.

If you know why I'd appreciate it.


问:
If Lisp source code is basically an AST, does that mean Lisp macros are language agnostic?
Can macros (or reader macros even) walk a nonLisp language's AST and transform them somehow? I'd want to run the nonLisp language in its own compiler, not a Lisp compiler </p>

答:
Firstly, most Lisp macros walk a "non-Lisp" language: the language of the macro. :)

Secondly, Lisp macros can indeed be used for expanding structures which ultimately generate some entirely non-Lisp language which is processed somewhere else.

A very common (nowadays) example of this is any one of the available HTML-generation systems, many of which use macros, which ultimately produce textual textual HTML (a structured computer language) that is then ultimately processed in the user's browser.

If you want a code-generating system to be able to use Lisp macros, all you have to do, in a nutshell, is implement it in such a way that it is driven by the evaluation of Lisp forms.

For instance, if you make a Lisp-based assembler for X86, have it so that an expression like (movl eax ebx) is processed by means of it being evaluated as a form, such that there is actually a movl function or macro that is called. This evaluation could require some context, like a stream where the output is supposed to go, and that could be set up by some setup macro:

```<code>(with-x86-assembler (:output-file "foo.asm")
  (movl eax ebx))  ;; just evaluated!
</code>```

This movl thing is aware of the environment set up by the with-x86-assembler, such as some dynamically scoped variable that holds the destination stream and other context.

Since the interior of the with-x86-assembler macro is just some forms to be evluated, we can use macros there:

```<code>(defmacro save-basic-regs (base-reg)
  ^(progn (movl (ind ,base-reg) eax)     ;; movl [<reg>], eax
          (movl (ind ,base-reg 4) ebx)   ;; movl [<reg> + 4], ebx
          ...))
</code>```

Now we can use (save-basic-regs edi) inside with-x86-assembler. Effectively we have a macro assembler supporting a macro instruction.

Lisp macros can be used to process the AST of some entirely non-Lisp language which is parsed by a custom parser having nothing to do with read macros. Nothing prevents you from writing Lisp code that parsers, say, JavaScript syntax, and produces Lisp which is then evaluated. That Lisp then relies on various run-time support, which may include macros. Some JavaScript loop can turn into a (loop ...) form, which is a macro. The Lisp is that code's AST, and the loop macro is expanded during the macro-expanding AST walk.

Body:
Firstly, most Lisp macros walk a "non-Lisp" language: the language of the macro. :)

Secondly, Lisp macros can indeed be used for expanding structures which ultimately generate some entirely non-Lisp language which is processed somewhere else.

A very common (nowadays) example of this is any one of the available HTML-generation systems, many of which use macros, which ultimately produce textual textual HTML (a structured computer language) that is then ultimately processed in the user's browser.

If you want a code-generating system to be able to use Lisp macros, all you have to do, in a nutshell, is implement it in such a way that it is driven by the evaluation of Lisp forms.

For instance, if you make a Lisp-based assembler for X86, have it so that an expression like (movl eax ebx) is processed by means of it being evaluated as a form, such that there is actually a movl function or macro that is called. This evaluation could require some context, like a stream where the output is supposed to go, and that could be set up by some setup macro:

(with-x86-assembler (:output-file "foo.asm")
  (movl eax ebx))  ;; just evaluated!

This movl thing is aware of the environment set up by the with-x86-assembler, such as some dynamically scoped variable that holds the destination stream and other context.

Since the interior of the with-x86-assembler macro is just some forms to be evluated, we can use macros there:

(defmacro save-basic-regs (base-reg)
  ^(progn (movl (ind ,base-reg) eax)     ;; movl [<reg>], eax
          (movl (ind ,base-reg 4) ebx)   ;; movl [<reg> + 4], ebx
          ...))

Now we can use (save-basic-regs edi) inside with-x86-assembler. Effectively we have a macro assembler supporting a macro instruction.

Lisp macros can be used to process the AST of some entirely non-Lisp language which is parsed by a custom parser having nothing to do with read macros. Nothing prevents you from writing Lisp code that parsers, say, JavaScript syntax, and produces Lisp which is then evaluated. That Lisp then relies on various run-time support, which may include macros. Some JavaScript loop can turn into a (loop ...) form, which is a macro. The Lisp is that code's AST, and the loop macro is expanded during the macro-expanding AST walk.


问:
Vim autocmd error
I have this script to set variables when loading Python files

```<code>au BufNewFile,BufRead *.py
    \ set tabstop=4
    \ set softtabstop=4
    \ set shiftwidth=4
    \ set textwidth=79
    \ set expandtab
    \ set autoindent
    \ set fileformat=unix
</code>```

When I load a Python file I get this error:

```<code>Error detected while processing BufRead Auto commands for "*.py":
E518: Unknown option: set
</code>```

答:
You can do .  instead of *.test and it works for me.
(Astrix . Astrix )

Example:
au BufNewFile,BufRead . set tabstop=4

Title: Vim autocmd error

Body:
I have this script to set variables when loading Python files

au BufNewFile,BufRead *.py
    \ set tabstop=4
    \ set softtabstop=4
    \ set shiftwidth=4
    \ set textwidth=79
    \ set expandtab
    \ set autoindent
    \ set fileformat=unix

When I load a Python file I get this error:

Error detected while processing BufRead Auto commands for "*.py":
E518: Unknown option: set


问:
How to set AND expand variables in a heredoc section
I have a heredoc that needs to call existing variables from the main script, and set its own variables to use later. Something like this:

```<code>count=0

ssh $other_host <<ENDSSH
  if [[ "${count}" == "0" ]]; then
    output="string1"
  else
    output="string2"
  fi
  echo output
ENDSSH
</code>```

That doesn't work because 'output' doesn't get set to anything.

I tried using the solution from this question:

```<code>count=0

ssh $other_host << \ENDSSH
  if [[ "${count}" == "0" ]]; then
    output="string1"
  else
    output="string2"
  fi
  echo output
ENDSSH
</code>```

It didn't work either. $output got set to "string2" because $count wasn't expanded.

How can I use a heredoc that expands variables from the parent script, and sets its own variables?

答:
It is better not to use stdin (such as by using here-docs) to pass commands to ssh.

If you use a command-line argument to pass your shell commands instead, you can better separate what is expanded locally and what will be executed remotely:

```<code># Use a *literal* here-doc to read the script into a *variable*.
# Note how the script references parameter $1 instead of
# local variable $count.
read -d '' -r script <<'EOF'
  [[ $1 == '0' ]] && output='zero' || output='nonzero'
  echo "$output"
EOF

# The variable whose value to pass as a parameter.
# With value 0, the script will echo 'zero', otherwise 'nonzero'.
count=0

# Use `set -- '$<local-var>'...;` to pass the local variables as
# positional parameters, followed by the script code.
ssh localhost "set -- '$count'; $script"
</code>```

Body:
I have a heredoc that needs to call existing variables from the main script, and set its own variables to use later. Something like this:

count=0

ssh $other_host <<ENDSSH
  if [[ "${count}" == "0" ]]; then
    output="string1"
  else
    output="string2"
  fi
  echo output
ENDSSH

That doesn't work because 'output' doesn't get set to anything.

I tried using the solution from this question:

count=0

ssh $other_host << \ENDSSH
  if [[ "${count}" == "0" ]]; then
    output="string1"
  else
    output="string2"
  fi
  echo output
ENDSSH

It didn't work either. $output got set to "string2" because $count wasn't expanded.

How can I use a heredoc that expands variables from the parent script, and sets its own variables?

Body:
It is better not to use stdin (such as by using here-docs) to pass commands to ssh.

If you use a command-line argument to pass your shell commands instead, you can better separate what is expanded locally and what will be executed remotely:

# Use a *literal* here-doc to read the script into a *variable*.
# Note how the script references parameter $1 instead of
# local variable $count.
read -d '' -r script <<'EOF'
  [[ $1 == '0' ]] && output='zero' || output='nonzero'
  echo "$output"
EOF

# The variable whose value to pass as a parameter.
# With value 0, the script will echo 'zero', otherwise 'nonzero'.
count=0

# Use `set -- '$<local-var>'...;` to pass the local variables as
# positional parameters, followed by the script code.
ssh localhost "set -- '$count'; $script"


问:
How can I hook into the explorer directory calls in windows to determine when a new directory is opened?
If you use a tool like Process Monitor, you can see that when a directory is opened, explorer.exe performs a DirectoryQuery. I don't know if DirectoryQuery is specific to procmon, but I'm trying to see if I can capture those calls within C#. Or determine if there are any Win32 APIs I can PInvoke to get this info.

There are other tools like Clover that also do this. The functionality I'm trying to replicate is basically the same as Clover. Where I would redirect new directories to my application instead of Explorer.

If anyone can point me in the right direction, I would greatly appreciate it.

答:
If you want to write your own File Explorer application then you can use the IExplorerBrowser object to do 90% of the work for you. Register a new default verb for the Directory and Folder ProgIds.

If you want to hook into Explorers File Explorer windows then you must implement a browser helper object (C# if you must) and tweak it so it only loads in Explorer.

DWebBrowserEvents2 will tell you about navigation events.


问:
Big quantity of data with MySql
i have a question about Mass storage. Actually, i'm working with 5 sensors which sends a lot of datas with a different frequency for each one and i'm using MySQL DATABASE.

so here is my questions:

1) is MySQL the perfect solution.
2) if not, is there a solution to store this big quantity of data in a data base?
3) I'm using Threads in this and i'm using mutexs also, i'm afraid if this can cause problems, Actually,it seems to be.

i hope i will have an answer to this question.

答:
MySql is good solution for OLTP scenarios where you are storing transactions to serve web or mobile apps. But it does not scale well (despite of cluster abilities).

There are many options out there based on what is important to you:
File System: You can device your own write-ahead-log solution to solve multi-threading problems and achieve "eventual consistency". That way you don't have to lock data for one thread at a time. You can use schema-full files like CSV, Avro or Parquet. Also you can use S3 or WSB for cloud based block storage. Or HDFS for just block and replicated storage.

NoSql: You can store each entry as document in NoSql Document stores. If you want to keep data in memory for faster read, explore Memcached or Redis. If you want to perform searches on data, use Solr or ElasticSearch. MongoDB is popular but it has scalability issues similar to MySql, instead I would chose Cassandra or HBase if you need more scalability. With some of NoSql stores, you might have to parse your "documents" at read time which may impact analytics performance.

RDBMS: As MySql is not scalable enough, you might explore Teradata and Oracle. Latest version of Oracle offers petabyte query capabilities and in-memory caching.

Title: Big quantity of data with MySql


问:
SourceTree can't clone Repository but still can create new remote one
I have been using SourceTree for months in Windows but recently I turned to Mac. And I ran into a problem with it. I can create a new remote repository with SourceTree but I can't clone any Repositories from Bitbucket or Github. It said that This is not a valid source path / URL, I have tried so many ways and researches but It's not working.

PS: I have set Git version to System Git instead of Embedded Git but there is no change.

Do you have any idea to solve my issue. Thanks a lot!

答:
First, in the remote account add you account, for example, the login with google.

Cloning a remote repository, in the field Source URL, try changing

```<code>ssh://git@bitbucket.org/[project]/[repository].git
</code>```

for

```<code>https://[your-user]@bitbucket.org/[project]/[repository].git
</code>```

Using Sierra, and sourceTree 2.4.1 (97)

Body:
First, in the remote account add you account, for example, the login with google.

Cloning a remote repository, in the field Source URL, try changing

ssh://git@bitbucket.org/[project]/[repository].git

for

https://[your-user]@bitbucket.org/[project]/[repository].git

Using Sierra, and sourceTree 2.4.1 (97)


问:
How to change fragment with the Bottom Navigation Activity?
I created a new project with the "Bottom Navigation Activity":

This is the generated code:

```<code>package com.aaron.waller.mrpolitik;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView mTextMessage;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    mTextMessage.setText(R.string.title_home);
                case R.id.navigation_dashboard:
                    mTextMessage.setText(R.string.title_dashboard);
                case R.id.navigation_notifications:
                    mTextMessage.setText(R.string.title_notifications);
            }
            return true;
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextMessage = (TextView) findViewById(R.id.message);
        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    }

}
</code>```

How can I change to new Fragments with the Bottom Bar?
For example I have 3 Fragments:
Fragment1
Fragment2 and
Fragment3
And I want to change to them with the 3 buttons from the Bottom Bar.
Also I want that I can switch the Fragments by swiping my finger left and right how can I do that?

答:
The way I would do it is, I would first add three methods similar to this one (each for a single fragment. Replace the layout name and the fragment object to the appropriate fragment that is being switched to):

```<code>public void switchToFragment1() {
    FragmentManager manager = getSupportFragmentManager();
    manager.beginTransaction().replace(R.id.your_fragment_layout_name, new Fragment1()).commit();
}
</code>```

So your switch statement would end up looking like this:

```<code>        switch (item.getItemId()) {
            case R.id.navigation_home:
                mTextMessage.setText(R.string.title_home);
                switchToFragment1();
                break;

            case R.id.navigation_dashboard:
                mTextMessage.setText(R.string.title_dashboard);
                switchToFragment2();
                break;

            case R.id.navigation_notifications:
                mTextMessage.setText(R.string.title_notifications);
                switchToFragment3();
                break;
        }
</code>```

As for switching the fragments by swiping to the sides, I believe you would need a ViewPager.

ContentLicense: CC BY-SA 4.0

Body:
I created a new project with the "Bottom Navigation Activity":

This is the generated code:

package com.aaron.waller.mrpolitik;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView mTextMessage;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    mTextMessage.setText(R.string.title_home);
                case R.id.navigation_dashboard:
                    mTextMessage.setText(R.string.title_dashboard);
                case R.id.navigation_notifications:
                    mTextMessage.setText(R.string.title_notifications);
            }
            return true;
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextMessage = (TextView) findViewById(R.id.message);
        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    }

}

How can I change to new Fragments with the Bottom Bar?
For example I have 3 Fragments:
Fragment1
Fragment2 and
Fragment3
And I want to change to them with the 3 buttons from the Bottom Bar.
Also I want that I can switch the Fragments by swiping my finger left and right how can I do that?

Body:
The way I would do it is, I would first add three methods similar to this one (each for a single fragment. Replace the layout name and the fragment object to the appropriate fragment that is being switched to):

public void switchToFragment1() {
    FragmentManager manager = getSupportFragmentManager();
    manager.beginTransaction().replace(R.id.your_fragment_layout_name, new Fragment1()).commit();
}

So your switch statement would end up looking like this:

        switch (item.getItemId()) {
            case R.id.navigation_home:
                mTextMessage.setText(R.string.title_home);
                switchToFragment1();
                break;

            case R.id.navigation_dashboard:
                mTextMessage.setText(R.string.title_dashboard);
                switchToFragment2();
                break;

            case R.id.navigation_notifications:
                mTextMessage.setText(R.string.title_notifications);
                switchToFragment3();
                break;
        }

As for switching the fragments by swiping to the sides, I believe you would need a ViewPager.


问:
iOS framework to get audio in from dock connector
How would I go abouts playing an 'audio in' through the dock connector in an iOS app? I'm making an app just for myself and have no plans of putting it into the apple store. I have the 30pin breakout board, and on it there are pins for L/R audio in, but I can not find any info on how to use them?

Thanks

答: As far as I'm aware, your only officially supported option for any accessory using the dock connector would be to use the External Accessory Framework, which requires enrollment in the Made for iPod Program (overkill for your purposes). However, the iPhone and iPod both support line-in via the headphone jack, and there are plenty of apps that make use of audio input. At least it provides some possibilities.</p>


问:
android MVP - can I have multiple presenters for custom views and fragments
So I have an a presenter that is already tied to an activity. The book says that one presenter should be tied to one view. But now I am adding a few fragments and lots of custom views. I am considering a fragment to be a view as well.   The custom views will contain a little bit of logic in them. Both the fragments and custom views are contained in my activity of course.

My question is, should I re-use the same presenter in the fragment and custom views or should each view get its own presenter? I realize this is all opinion based but I want the best approach for testing and keeping code clean.

If i do have one presenter for all these fews then then interface the presenter uses will have many callback methods in it.  Meanwhile if i did the opposite and created one presenter for each view it might be easier to read but how would i test it ?

答: Best practice is to create a basepresenter , then create presenter for each view implementing basepresenter</p>


问:
How to create a fade in effect on the selection?
Regarding macros, there's very few done with Impress (no record of macros, no Python scripting, only Basic etc.), and very few samples.

There's no sample how to create "manually" a text animation. I've found one here (6 years old) and there's a lot of information.

So far I've managed to (1) scan for a text animation "fadein" that is already there (2) scan for all other text animations, and then remove them an replace them by a clone of the "fadein" animation:

```<code>sub MyFunction
    ' --------------------------------------------------------------------
    ' (1) scan for a text animation "fadein" that is already there
    effectNodeFadeIn = Null
    doc = ThisComponent
    numSlides = doc.getDrawPages().getCount()
    slide = doc.drawPages(numSlides-1)

    mainSequence = getMainSequence(slide)
    clickNodes = mainSequence.createEnumeration()
    while clickNodes.hasMoreElements() and IsNull(effectNodeFadeIn)
        clickNode = clickNodes.nextElement()

        groupNodes = clickNode.createEnumeration()
        while groupNodes.hasMoreElements() and IsNull(effectNodeFadeIn)
            groupNode = groupNodes.nextElement()

            effectNodes = groupNode.createEnumeration()
            while effectNodes.hasMoreElements() and IsNull(effectNodeFadeIn)
                effectNode = effectNodes.nextElement()
                ' ICIC

                if effectNode.ImplementationName = "animcore::ParallelTimeContainer" then
                    if hasUserDataKey(effectNode, "preset-id") then
                        v = getUserDataValue(effectNode, "preset-id")
                        if v = "ooo-entrance-fade-in" then ' ooo-entrance-appear
                            effectNodeFadeIn = effectNode
                        end if
                    end if
                end if
                ' useless loop just in case I need it:
                animNodes = effectNode.createEnumeration()
                while animNodes.hasMoreElements()
                    animNode = animNodes.nextElement()
                wend
            wend
        wend
    wend
    ' --------------------------------------------------------------------
    ' (2) scan for all other text animations,
    ' and then remove them an replace them by a clone of the "fadein" animation
    if not IsNull(effectNodeFadeIn) then

        clickNodes = mainSequence.createEnumeration()
        while clickNodes.hasMoreElements()
            clickNode = clickNodes.nextElement()

            groupNodes = clickNode.createEnumeration()
            while groupNodes.hasMoreElements()
                groupNode = groupNodes.nextElement()

                effectNodes = groupNode.createEnumeration()
                while effectNodes.hasMoreElements()
                    effectNode = effectNodes.nextElement()
                    ' ICIC

                    if effectNode.ImplementationName = "animcore::ParallelTimeContainer" then
                        if hasUserDataKey(effectNode, "preset-id") then
                            v = getUserDataValue(effectNode, "preset-id")
                            if v <> "ooo-entrance-fade-in" then ' ooo-entrance-appear
                                groupNode.removeChild(effectNode)
                                n = effectNodeFadeIn.createClone()
                                groupNode.appendChild(n)

                                ' useless loop just in case I need it:
                                animNodes = effectNode.createEnumeration()
                                while animNodes.hasMoreElements()
                                    animNode = animNodes.nextElement()
                                wend
                            end if
                        end if

                    end if
                wend
            wend
        wend
    end if
end sub

function hasUserDataKey(node as Object, key as String) as Boolean
    for each data in node.UserData
        if data.Name = "node-type" then
            hasUserDataKey = True
            exit function
        end if
    next data
    hasUserDataKey = False
end function

function getUserDataValue(node as Object, key as String) as Variant
    for each data in node.UserData
        if data.Name = key then
            getUserDataValue = data.Value
            exit function
        end if
    next data
end function
</code>```

When I clone the effect, it's still "linked" to the original text and then the parent is removed and replaced by the "fadein" text. Any idea how to correct this?

答:
It sounds like you have selected text inside of a shape, so use Basic code as follows:

Sub AddAnimation
    xTextCursor = ThisComponent.CurrentController.Selection(0)
    xText = xTextCursor.getText()
    xText.TextEffect = com.sun.star.presentation.AnimationEffect.FADE_FROM_BOTTOM
End Sub
```

<p>Or in python:</p>

<pre class="lang-py prettyprint-override"><code>import uno
from com.sun.star.presentation.AnimationEffect import FADE_FROM_BOTTOM

def add_animation():
    oDoc = XSCRIPTCONTEXT.getDocument()
    xTextCursor = oDoc.CurrentController.Selection.getByIndex(0)
    xText = xTextCursor.getText()
    xText.TextEffect = FADE_FROM_BOTTOM
</code>```

For reasons not entirely clear to me, the result is Wipe rather than Fade In.

Documentation is at https://wiki.openoffice.org/wiki/Documentation/DevGuide/Drawings/Animations_and_Interactions.  The ShapeHelper class from that page is defined in ShapeHelper.java.

Body:
Regarding macros, there's very few done with Impress (no record of macros, no Python scripting, only Basic etc.), and very few samples.

There's no sample how to create "manually" a text animation. I've found one here (6 years old) and there's a lot of information.

So far I've managed to (1) scan for a text animation "fadein" that is already there (2) scan for all other text animations, and then remove them an replace them by a clone of the "fadein" animation:

sub MyFunction
    ' --------------------------------------------------------------------
    ' (1) scan for a text animation "fadein" that is already there
    effectNodeFadeIn = Null
    doc = ThisComponent
    numSlides = doc.getDrawPages().getCount()
    slide = doc.drawPages(numSlides-1)

    mainSequence = getMainSequence(slide)
    clickNodes = mainSequence.createEnumeration()
    while clickNodes.hasMoreElements() and IsNull(effectNodeFadeIn)
        clickNode = clickNodes.nextElement()

        groupNodes = clickNode.createEnumeration()
        while groupNodes.hasMoreElements() and IsNull(effectNodeFadeIn)
            groupNode = groupNodes.nextElement()

            effectNodes = groupNode.createEnumeration()
            while effectNodes.hasMoreElements() and IsNull(effectNodeFadeIn)
                effectNode = effectNodes.nextElement()
                ' ICIC

                if effectNode.ImplementationName = "animcore::ParallelTimeContainer" then
                    if hasUserDataKey(effectNode, "preset-id") then
                        v = getUserDataValue(effectNode, "preset-id")
                        if v = "ooo-entrance-fade-in" then ' ooo-entrance-appear
                            effectNodeFadeIn = effectNode
                        end if
                    end if
                end if
                ' useless loop just in case I need it:
                animNodes = effectNode.createEnumeration()
                while animNodes.hasMoreElements()
                    animNode = animNodes.nextElement()
                wend
            wend
        wend
    wend
    ' --------------------------------------------------------------------
    ' (2) scan for all other text animations,
    ' and then remove them an replace them by a clone of the "fadein" animation
    if not IsNull(effectNodeFadeIn) then

        clickNodes = mainSequence.createEnumeration()
        while clickNodes.hasMoreElements()
            clickNode = clickNodes.nextElement()

            groupNodes = clickNode.createEnumeration()
            while groupNodes.hasMoreElements()
                groupNode = groupNodes.nextElement()

                effectNodes = groupNode.createEnumeration()
                while effectNodes.hasMoreElements()
                    effectNode = effectNodes.nextElement()
                    ' ICIC

                    if effectNode.ImplementationName = "animcore::ParallelTimeContainer" then
                        if hasUserDataKey(effectNode, "preset-id") then
                            v = getUserDataValue(effectNode, "preset-id")
                            if v <> "ooo-entrance-fade-in" then ' ooo-entrance-appear
                                groupNode.removeChild(effectNode)
                                n = effectNodeFadeIn.createClone()
                                groupNode.appendChild(n)

                                ' useless loop just in case I need it:
                                animNodes = effectNode.createEnumeration()
                                while animNodes.hasMoreElements()
                                    animNode = animNodes.nextElement()
                                wend
                            end if
                        end if

                    end if
                wend
            wend
        wend
    end if
end sub

function hasUserDataKey(node as Object, key as String) as Boolean
    for each data in node.UserData
        if data.Name = "node-type" then
            hasUserDataKey = True
            exit function
        end if
    next data
    hasUserDataKey = False
end function

function getUserDataValue(node as Object, key as String) as Variant
    for each data in node.UserData
        if data.Name = key then
            getUserDataValue = data.Value
            exit function
        end if
    next data
end function

When I clone the effect, it's still "linked" to the original text and then the parent is removed and replaced by the "fadein" text. Any idea how to correct this?

Body:
It sounds like you have selected text inside of a shape, so use Basic code as follows:

Sub AddAnimation
    xTextCursor = ThisComponent.CurrentController.Selection(0)
    xText = xTextCursor.getText()
    xText.TextEffect = com.sun.star.presentation.AnimationEffect.FADE_FROM_BOTTOM
End Sub

Or in python:

import uno
from com.sun.star.presentation.AnimationEffect import FADE_FROM_BOTTOM

def add_animation():
    oDoc = XSCRIPTCONTEXT.getDocument()
    xTextCursor = oDoc.CurrentController.Selection.getByIndex(0)
    xText = xTextCursor.getText()
    xText.TextEffect = FADE_FROM_BOTTOM

For reasons not entirely clear to me, the result is Wipe rather than Fade In.

Documentation is at https://wiki.openoffice.org/wiki/Documentation/DevGuide/Drawings/Animations_and_Interactions.  The ShapeHelper class from that page is defined in ShapeHelper.java.


问:
How to work multiple Hibernate Properties file for lazy loading?
I want to build an application where i use the same Hibernate Objects but using multiple Hibernate properties file. For example, person 1 might only want columns 1-3 on table 1 while person 2 want columns 1,5-6 on table 1.

How do i dynamically load different configurations (if person 1 is using the app or person 2) depending on the user? Is this possible?

thanks!

答:
You don't need different mapping files for this. You can handle this at the code level. You can introduce a Object to Entity and vice-versa conversion layer in your project.

Depending on which user logs in you can only get/set those fields.

For ex:

```<code>if (user.equals(user1)) {
        domainObj.setColumn1(entityObject.getColumbn1);
        domainObj.setColumn2(entityObject.getColumbn2);
        domainObj.setColumn3(entityObject.getColumbn2);

    }

    if (user.equals(user2)) {
        domainObj.setColumn1(entityObject.getColumbn1);
        domainObj.setColumn2(entityObject.getColumbn2);
        domainObj.setColumn3(entityObject.getColumbn3);
        domainObj.setColumn4(entityObject.getColumbn4);
        domainObj.setColumn5(entityObject.getColumbn5);
    }
</code>```

Body:
You don't need different mapping files for this. You can handle this at the code level. You can introduce a Object to Entity and vice-versa conversion layer in your project.

Depending on which user logs in you can only get/set those fields.

For ex:

if (user.equals(user1)) {
        domainObj.setColumn1(entityObject.getColumbn1);
        domainObj.setColumn2(entityObject.getColumbn2);
        domainObj.setColumn3(entityObject.getColumbn2);

    }

    if (user.equals(user2)) {
        domainObj.setColumn1(entityObject.getColumbn1);
        domainObj.setColumn2(entityObject.getColumbn2);
        domainObj.setColumn3(entityObject.getColumbn3);
        domainObj.setColumn4(entityObject.getColumbn4);
        domainObj.setColumn5(entityObject.getColumbn5);
    }


问:
DynamoDB: Remove old entries automatically
We want to have DynamoDb to automatically delete entries which is, like, more than a year old. Is there a setting or common practice to do it?</p>

答:
Dynamo DB has added TTL functionality  to delete items automatically .

https://aws.amazon.com/blogs/aws/new-manage-dynamodb-items-using-time-to-live-ttl/