问:
Team Foundation 2015 Environment variable PATH not recognized
I have a TFS 2015 build in which I want to run command 'dotnet restore'. On my build machine, the path to dotnet.exe is part of my environment variable 'Path'. When running the command from command prompt window, it works fine. When trying to run it via a TFS build step of type 'Command line' dotnet is not recognized. My path variable containing dotnet.exe path is at system level, so every users, including the one on which my build agent is running, should see it.</p>

答: FYI, this is still an issue with TFS 2017 as well. From my tests, it appears TFS doesn't like when the PATH variable is over 900 characters. After shortening the PATH variable and closing the dialog windows, restart the VSO/VSTS agent services and you should see the Path variable appear as a capability for the agent.    Hopefully this helps someone else.


来源: stackexchange

问:
How to horizontally flip images already on the canvas?
Before you throw me out - I am aware of this answer, but it does not seem to work for me. It is also different in that the source of the image data in my case is a WebGL canvas - not an img node.

I am trying to put ImageData onto a canvas like so:

```<code>var c = document.createElement('canvas');
c.setAttribute('width', size.width);
c.setAttribute('height', size.height);

$('body').append(c)

// p contains a Uint8ClampedArray with imagedata coming from a WebGL canvas

var i = new ImageData(p, size.width, size.height);
var ctx = c.getContext('2d');
ctx.putImageData(i, 0, 0);
</code>```

and then to flip it like so:

```<code>var d = document.createElement('canvas');
d.width = c.width; d.height = c.height;
d.getContext('2d').drawImage(c, 0, 0);

ctx.clearRect(0, 0, c.width, c.height);
ctx.scale(-1, 1);
ctx.translate(c.width, 0);

ctx.drawImage(d, 0, 0);
</code>```

but this fails miserably.

The data comes from a WebGL canvas like this:

```<code>var gl = renderer.domElement.getContext("webgl")
var pixels = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4);
gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
</code>```

so I've considered low-level operations on the pixel array as a solution, but before I get into that I thought I'd ask.

I have a hunch that drawImage is insensitive to transforms, but that would be funny. Please please don't make me use toDataURL()

答:
Works for me when translating using the negative width
ctx.translate(-c.width, 0);

var webglReadPixelsData;

// draw some webgl
(function(){
var
  ctx=webgl.getContext('webgl',{preserveDrawingBuffer:true}),
  p=ctx.createProgram(),
  vs=ctx.createShader(ctx.VERTEX_SHADER),
  fs=ctx.createShader(ctx.FRAGMENT_SHADER),
  vb=ctx.createBuffer()
;
ctx.shaderSource(vs,"attribute vec2 p;void main(){gl_Position=vec4(p*2.-1.,0,1);}");
ctx.compileShader(vs);
ctx.shaderSource(fs,"void main(){gl_FragColor=vec4(sin(gl_FragCoord.x*.2+gl_FragCoord.y*.2),0,0,1);}");
ctx.compileShader(fs);
ctx.attachShader(p,vs);
ctx.attachShader(p,fs);
ctx.linkProgram(p);
ctx.useProgram(p);

ctx.bindBuffer(ctx.ARRAY_BUFFER,vb);
ctx.bufferData(ctx.ARRAY_BUFFER,new Float32Array([0,0,1,0,1,1,0,1]),ctx.STATIC_DRAW);
ctx.enableVertexAttribArray(0);
ctx.vertexAttribPointer(0,2,ctx.FLOAT,false,0,0);
ctx.viewport(0,0,ctx.canvas.clientWidth,ctx.canvas.clientHeight);
ctx.drawArrays(ctx.TRIANGLE_FAN,0,4);

webglReadPixelsData = new Uint8Array(ctx.drawingBufferWidth * ctx.drawingBufferHeight * 4);

ctx.readPixels(0, 0, ctx.drawingBufferWidth,ctx.drawingBufferHeight, ctx.RGBA, ctx.UNSIGNED_BYTE, webglReadPixelsData);
})();

// Flip image data
(function(){
var ctx=canvas2d.getContext('2d');
var id=new ImageData(webgl.clientWidth, webgl.clientHeight);
id.data.set(webglReadPixelsData);
ctx.putImageData(id,0,0);

var d = intermediate;
d.getContext('2d').drawImage(canvas2d, 0, 0);
ctx.clearRect(0,0,ctx.canvas.clientWidth,ctx.canvas.clientHeight);

ctx.scale(-1, 1);
ctx.translate(-ctx.canvas.clientWidth, 0);

ctx.drawImage(d, 0, 0);
})();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#webgl {display:block;outline:1px solid #f00;}
#canvas2d{display:block;outline:1px solid #0f0;}
#intermediate{outline:1px solid #00f;}</code>```

WebGL Canvas

<canvas id="webgl"></canvas>

Intermediate Canvas

<canvas id="intermediate"></canvas>

2D Canvas

<canvas id="canvas2d"></canvas>```

ContentLicense: CC BY-SA 3.0

Body:
Before you throw me out - I am aware of this answer, but it does not seem to work for me. It is also different in that the source of the image data in my case is a WebGL canvas - not an img node.

I am trying to put ImageData onto a canvas like so:

var c = document.createElement('canvas');
c.setAttribute('width', size.width);
c.setAttribute('height', size.height);

$('body').append(c)

// p contains a Uint8ClampedArray with imagedata coming from a WebGL canvas

var i = new ImageData(p, size.width, size.height);
var ctx = c.getContext('2d');
ctx.putImageData(i, 0, 0);

and then to flip it like so:

var d = document.createElement('canvas');
d.width = c.width; d.height = c.height;
d.getContext('2d').drawImage(c, 0, 0);

ctx.clearRect(0, 0, c.width, c.height);
ctx.scale(-1, 1);
ctx.translate(c.width, 0);

ctx.drawImage(d, 0, 0);

but this fails miserably.

The data comes from a WebGL canvas like this:

var gl = renderer.domElement.getContext("webgl")
var pixels = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4);
gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, pixels);

so I've considered low-level operations on the pixel array as a solution, but before I get into that I thought I'd ask.

I have a hunch that drawImage is insensitive to transforms, but that would be funny. Please please don't make me use toDataURL()

Body:
Works for me when translating using the negative width
ctx.translate(-c.width, 0);

var webglReadPixelsData;

// draw some webgl
(function(){
var
  ctx=webgl.getContext('webgl',{preserveDrawingBuffer:true}),
  p=ctx.createProgram(),
  vs=ctx.createShader(ctx.VERTEX_SHADER),
  fs=ctx.createShader(ctx.FRAGMENT_SHADER),
  vb=ctx.createBuffer()
;
ctx.shaderSource(vs,"attribute vec2 p;void main(){gl_Position=vec4(p*2.-1.,0,1);}");
ctx.compileShader(vs);
ctx.shaderSource(fs,"void main(){gl_FragColor=vec4(sin(gl_FragCoord.x*.2+gl_FragCoord.y*.2),0,0,1);}");
ctx.compileShader(fs);
ctx.attachShader(p,vs);
ctx.attachShader(p,fs);
ctx.linkProgram(p);
ctx.useProgram(p);

ctx.bindBuffer(ctx.ARRAY_BUFFER,vb);
ctx.bufferData(ctx.ARRAY_BUFFER,new Float32Array([0,0,1,0,1,1,0,1]),ctx.STATIC_DRAW);
ctx.enableVertexAttribArray(0);
ctx.vertexAttribPointer(0,2,ctx.FLOAT,false,0,0);
ctx.viewport(0,0,ctx.canvas.clientWidth,ctx.canvas.clientHeight);
ctx.drawArrays(ctx.TRIANGLE_FAN,0,4);

webglReadPixelsData = new Uint8Array(ctx.drawingBufferWidth * ctx.drawingBufferHeight * 4);

ctx.readPixels(0, 0, ctx.drawingBufferWidth,ctx.drawingBufferHeight, ctx.RGBA, ctx.UNSIGNED_BYTE, webglReadPixelsData);
})();

// Flip image data
(function(){
var ctx=canvas2d.getContext('2d');
var id=new ImageData(webgl.clientWidth, webgl.clientHeight);
id.data.set(webglReadPixelsData);
ctx.putImageData(id,0,0);

var d = intermediate;
d.getContext('2d').drawImage(canvas2d, 0, 0);
ctx.clearRect(0,0,ctx.canvas.clientWidth,ctx.canvas.clientHeight);

ctx.scale(-1, 1);
ctx.translate(-ctx.canvas.clientWidth, 0);

ctx.drawImage(d, 0, 0);
})();

#webgl {display:block;outline:1px solid #f00;}
#canvas2d{display:block;outline:1px solid #0f0;}
#intermediate{outline:1px solid #00f;}

<h1>WebGL Canvas</h1>
<canvas id="webgl"></canvas>
<h1>Intermediate Canvas</h1>
<canvas id="intermediate"></canvas>
<h1>2D Canvas</h1>
<canvas id="canvas2d"></canvas>


问:
FIND_IN_SET problem
I have this MySql query:

```<code>SELECT * FROM `tbl_prods`
WHERE `id` IN ('58', '169', '166', '496', '24', '28')
ORDER BY FIND_IN_SET(`id`, '58, 169, 166, 496, 24, 28')
</code>```

the result is weird:

```<code>24
28
166
169
496
58
</code>```

I can't figure out how to return the exact order by my FIND_IN_SET

any ideas where I am doing wrong?

ContentLicense: CC BY-SA 2.5

Title: FIND_IN_SET problem

Body:
I have this MySql query:

SELECT * FROM `tbl_prods`
WHERE `id` IN ('58', '169', '166', '496', '24', '28')
ORDER BY FIND_IN_SET(`id`, '58, 169, 166, 496, 24, 28')

the result is weird:

24
28
166
169
496
58

I can't figure out how to return the exact order by my FIND_IN_SET

any ideas where I am doing wrong?

Body:
Use FIELD instead of FIND_IN_SET:

SELECT * FROM `tbl_prods`
WHERE `id` IN ('58', '169', '166', '496', '24', '28')
ORDER BY FIELD(`id`, '58', '169', '166', '496', '24', '28')


问:
Scala: map just first element in tuple
I want to use some function on tuple, which returns tuple with only first element transformed and other elements unchanged.

This is naive version for Tuple2:

```<code>def mapFirst[T, U, R](tuple: (T, U))(f: T => R): (R, U) = tuple match {
     |   case (x, y) => f(x) -> y
     | }

mapFirst((1, 2))(_ * 5) // returns (5, 2)
</code>```

Though, it doesn't feel native, what I want is to write it this way:

```<code>(1, 2).mapFirst(_ * 5)
</code>```

I wrote implicit conversion then:

```<code>class RichTuple[T, U](tuple: (T, U)) {
  def mapFirst[R](f: T => R): (R, U) = tuple match {
    case (x, y) => f(x) -> y
  }
}

implicit def tuple2RichTuple[T, U](tuple: (T, U)): RichTuple[T, U] = new RichTuple(tuple)

(1, 2).mapFirst(_ * 5)
</code>```

Then, when I'll want to map just second element or first element on Tuple3, I'll have to write same boilerplate again. Is there some library which has such methods built-in?

答:
You could use case classes rather than tuples (this is good style) then use the named elements, e.g. </p>

```<code>case class Pie(filling: String, weight: Double, servings: Int)
val p = Pie("cheese", 500.0, 2)
val q = p.copy(filling = "potato")
val r = p.copy(weight = 750.0, servings = 3)
</code>```

Title: Scala: map just first element in tuple

Body:
I want to use some function on tuple, which returns tuple with only first element transformed and other elements unchanged.

This is naive version for Tuple2:

def mapFirst[T, U, R](tuple: (T, U))(f: T => R): (R, U) = tuple match {
     |   case (x, y) => f(x) -> y
     | }

mapFirst((1, 2))(_ * 5) // returns (5, 2)

Though, it doesn't feel native, what I want is to write it this way:

(1, 2).mapFirst(_ * 5)

I wrote implicit conversion then:

class RichTuple[T, U](tuple: (T, U)) {
  def mapFirst[R](f: T => R): (R, U) = tuple match {
    case (x, y) => f(x) -> y
  }
}

implicit def tuple2RichTuple[T, U](tuple: (T, U)): RichTuple[T, U] = new RichTuple(tuple)

(1, 2).mapFirst(_ * 5)

Then, when I'll want to map just second element or first element on Tuple3, I'll have to write same boilerplate again. Is there some library which has such methods built-in?

Body:
You could use case classes rather than tuples (this is good style) then use the named elements, e.g.

case class Pie(filling: String, weight: Double, servings: Int)
val p = Pie("cheese", 500.0, 2)
val q = p.copy(filling = "potato")
val r = p.copy(weight = 750.0, servings = 3)


问:
XPath 2.0: how to select the current node - current() no longer available
In XPath 1.0 there's a function current() that comes in handy when I refer to a node somewhere else in the XML based on the node I'm in at the moment.
My XML has a structure like this:

```<code><root>
    <book>
        <chapter>
            <section>
                <para>
                    <image id="1">1.png</image>
                </para>
            </section>
        </chapter>
    </book>
    <objects>
        <Object>
            <ID>1</ID>
        </Object>
    </objects>
</root>
</code>```

When I process the para nodes in book, I sometimes use XPath expressions like this one to look up information in the objects nodes:

```<code>Object[ID=current()/descendant::image[1]/@id]
</code>```

When I switch my parser to XPath 2.0, this expression gives an error (function current is not available).

I've done some searching, but haven't been able to find a straight replacement for this function. Is there one?

答:
The current() function is only available in XSLT (all versions). It's not available in XPath (any version).

See the current() function description in the "Additional Functions" section of the spec.

Body:
In XPath 1.0 there's a function current() that comes in handy when I refer to a node somewhere else in the XML based on the node I'm in at the moment.
My XML has a structure like this:

<root>
    <book>
        <chapter>

                <para>
                    <image id="1">1.png</image>
                </para>

        </chapter>
    </book>
    <objects>
        <Object>
            <ID>1</ID>
        </Object>
    </objects>
</root>

When I process the para nodes in book, I sometimes use XPath expressions like this one to look up information in the objects nodes:

Object[ID=current()/descendant::image[1]/@id]

When I switch my parser to XPath 2.0, this expression gives an error (function current is not available).

I've done some searching, but haven't been able to find a straight replacement for this function. Is there one?


问:
Rotating a grid of div's through center
I am trying to make a grid of div elements rotate around it's center. I googled and found out that transform-origin property can be used to anchor rotation. But somehow it's rotating with one of the corner as anchor. What I need to do to make it work and rotate around grid's center?

var n = 20;

for( var i=0; i<n; ++i){
  for(var j =0; j<n; ++j)
    {
        var div = document.createElement("div");
        div.style.width = "9px";
        div.style.height = "9px";
        div.style.position = "absolute";
        div.style.left = i*10 + "px";
        div.style.top = j*10 + "px";
        div.style.background = "black";

        document.getElementById("top-div").appendChild(div);

    }
}

var d = 0;
setInterval( function(e) {
  d  = (d +  1)%360;
  document.getElementById("top-div").style.transform = "rotate("+ d  + "deg)";
}, 1);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#top-div{
  transform-origin: center center;
  -ms-transform-origin: center center;
  -webkit-transform-origin: center center;
  -moz-transform-origin: center center;
  -o-transform-origin: center center;

}</code>```

```

Using Google Chrome Version 57.0.2987.98 (64-bit)

答:
The problem is that you didn't set a width and / or height to the rotating div; It needs a width and height to calculate where the anchor is.

var n = 20;

for (var i = 0; i < n; ++i) {
  for (var j = 0; j < n; ++j) {
    var div = document.createElement("div");
    div.style.width = "9px";
    div.style.height = "9px";
    div.style.position = "absolute";
    div.style.left = i * 10 + "px";
    div.style.top = j * 10 + "px";
    div.style.background = "black";

    document.getElementById("top-div").appendChild(div);

  }
}

var d = 0;
setInterval(function(e) {
  d = (d + 1) % 360;
  document.getElementById("top-div").style.transform = "rotate(" + d + "deg)";
}, 1);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#top-div {
  transform-origin: center center;
  -ms-transform-origin: center center;
  -webkit-transform-origin: center center;
  -moz-transform-origin: center center;
  -o-transform-origin: center center;
  height: 200px;
  width: 200px;
}</code>```

```

Title: Rotating a grid of div's through center

Body:
I am trying to make a grid of div elements rotate around it's center. I googled and found out that transform-origin property can be used to anchor rotation. But somehow it's rotating with one of the corner as anchor. What I need to do to make it work and rotate around grid's center?

var n = 20;

for( var i=0; i<n; ++i){
  for(var j =0; j<n; ++j)
    {
        var div = document.createElement("div");
        div.style.width = "9px";
        div.style.height = "9px";
        div.style.position = "absolute";
        div.style.left = i*10 + "px";
        div.style.top = j*10 + "px";
        div.style.background = "black";

        document.getElementById("top-div").appendChild(div);

    }
}

var d = 0;
setInterval( function(e) {
  d  = (d +  1)%360;
  document.getElementById("top-div").style.transform = "rotate("+ d  + "deg)";
}, 1);

#top-div{
  transform-origin: center center;
  -ms-transform-origin: center center;
  -webkit-transform-origin: center center;
  -moz-transform-origin: center center;
  -o-transform-origin: center center;

}

Using Google Chrome Version 57.0.2987.98 (64-bit)

Body:
The problem is that you didn't set a width and / or height to the rotating div; It needs a width and height to calculate where the anchor is.

var n = 20;

for (var i = 0; i < n; ++i) {
  for (var j = 0; j < n; ++j) {
    var div = document.createElement("div");
    div.style.width = "9px";
    div.style.height = "9px";
    div.style.position = "absolute";
    div.style.left = i * 10 + "px";
    div.style.top = j * 10 + "px";
    div.style.background = "black";

    document.getElementById("top-div").appendChild(div);

  }
}

var d = 0;
setInterval(function(e) {
  d = (d + 1) % 360;
  document.getElementById("top-div").style.transform = "rotate(" + d + "deg)";
}, 1);

#top-div {
  transform-origin: center center;
  -ms-transform-origin: center center;
  -webkit-transform-origin: center center;
  -moz-transform-origin: center center;
  -o-transform-origin: center center;
  height: 200px;
  width: 200px;
}

<div id='top-div'></div>


问:
laravel - rss display
Welcome ! Can someone tell me how to display rss from another site on mine? Exactly this rss  link http://awiacja.imgw.pl/rss/metar00.php?airport=EPWA I'm using laravel 5.3

Regards and thank You for help

答:
Searching for Laravel RSS readers provides a number of Laravel 5-compatible packages to do RSS parsing for you. For instance, https://packagist.org/packages/willvincent/feeds provides you a full example of working with the reader.

If, for some reason, you don't want to work with a Laravel package, there are non-Laravel RSS parsers or generic markup parsers for PHP that can do the same thing.

Or you could do your own parsing by using something like file_get_contents() or a curl call to grab the RSS feed and then use a basic regex or substr to grab the tags you care about.

In any case, you then have to pass that extracted data to your view for display. Presumably, your data would be in an array so you could just use a @foreach directive in the view and then display the items in a list or table or whatever you want.

```<code><ul>
@foreach($data as $datum)
    <li>{{$datum['title']}}</li>
@endforeach
</ul>
</code>```

The pre-made packages will save you a lot of time, though.

Title: laravel - rss display

Body:
Searching for Laravel RSS readers provides a number of Laravel 5-compatible packages to do RSS parsing for you. For instance, https://packagist.org/packages/willvincent/feeds provides you a full example of working with the reader.

If, for some reason, you don't want to work with a Laravel package, there are non-Laravel RSS parsers or generic markup parsers for PHP that can do the same thing.

Or you could do your own parsing by using something like file_get_contents() or a curl call to grab the RSS feed and then use a basic regex or substr to grab the tags you care about.

In any case, you then have to pass that extracted data to your view for display. Presumably, your data would be in an array so you could just use a @foreach directive in the view and then display the items in a list or table or whatever you want.

<ul>
@foreach($data as $datum)
    <li>{{$datum['title']}}</li>
@endforeach
</ul>

The pre-made packages will save you a lot of time, though.


问:
Why python datetime replace timezone is returning different timezone?
I am working on Python/Django project. I am trying to let user select date and time using jQuery plugin datetimepicker add-on. So when I select now option and post data django is saving the time in UTC offset. This is what is saved in database, 2017-03-30 13:38:00+00:00. I need to convert this time from user's timezone and save it in system as utc. Because later I will have script running which will look for data in database which is less than the utc time.

Actually the script is to let user post information on website and let them chose the publish date and time. So for example, If use posted an article which will be published on April 2nd 1pm Chicago time, I don't want other users to read the article before this time. So people around the world can read article as soon as it is April 2nd and 1PM in Chicago. So how can I make this functionality work?

My solution was to get the time and remove it's timezone information using replace(tzinfo=pytz.timezone('America/Chicago')) and when I print the time, I am getting 2017-03-30 13:38:00-05:51. The actual offset right now is -05:00. Can anyone help me to and tell me what I am doing wrong?

What I am doing for form is that I have publish_date object in my model and I am using django forms to create form. I have added class as an attribute in it and using jquery plugin,

```<code>$('.datepicker').datetimepicker({
                timeFormat: 'HH:mm',
                stepHour: 1,
                stepMinute: 1,
            });
</code>```

So when User submits the form, on post method this my code,

```<code>form = PublishForm(request.POST)

if form.is_valid():

                f = form.save(commit=False)
                f.created_by_user_id = request.user.id
                f.save()
</code>```

and than to get the date all I am doing is f.publish_date and the other  options I have used lice replace and localize are pretty standard.

Thanks

答:
The naming of the datetime replace(tzinfo = ...) function is unfortunate. In fact, its behaviour is random. Do not use this!

Mark's answer is the way to go. Use localize.

Body:
I am working on Python/Django project. I am trying to let user select date and time using jQuery plugin datetimepicker add-on. So when I select now option and post data django is saving the time in UTC offset. This is what is saved in database, 2017-03-30 13:38:00+00:00. I need to convert this time from user's timezone and save it in system as utc. Because later I will have script running which will look for data in database which is less than the utc time.

Actually the script is to let user post information on website and let them chose the publish date and time. So for example, If use posted an article which will be published on April 2nd 1pm Chicago time, I don't want other users to read the article before this time. So people around the world can read article as soon as it is April 2nd and 1PM in Chicago. So how can I make this functionality work?

My solution was to get the time and remove it's timezone information using replace(tzinfo=pytz.timezone('America/Chicago')) and when I print the time, I am getting 2017-03-30 13:38:00-05:51. The actual offset right now is -05:00. Can anyone help me to and tell me what I am doing wrong?

What I am doing for form is that I have publish_date object in my model and I am using django forms to create form. I have added class as an attribute in it and using jquery plugin,

$('.datepicker').datetimepicker({
                timeFormat: 'HH:mm',
                stepHour: 1,
                stepMinute: 1,
            });

So when User submits the form, on post method this my code,

form = PublishForm(request.POST)

if form.is_valid():

                f = form.save(commit=False)
                f.created_by_user_id = request.user.id
                f.save()

and than to get the date all I am doing is f.publish_date and the other  options I have used lice replace and localize are pretty standard.

Thanks


问:
Can my Service Fabric StatefulService have both memory-only and disk-persisted data?
I am designing a Service Fabric application that includes a stateful partitioned microservice. Some of the data must be persisted to disk however some related data is very ephemeral and I would like keep it only in memory. During a failover I do want the secondary instances to have the ephemeral data.

From what I can tell the StatefulService has only one StateManager and all collections created via that StateManager share the same behavior. In other words I can't have one reliable dictionary that is persisted to disk and a second reliable dictionary that is only in memory.

Is there any way to do this within a single StatefulService instance?

答:
No, Reliable Collections always persist all data to disk.

But if that related data can be generated on the fly from the data that's being inserted into a Reliable Collection, then you might be able to use Reliable Collection notifications to generate that related data and keep it in memory whenever you perform an operation on a Reliable Collection. Those notifications are fired on primary and secondary replicas.


问:
Compare two column values and get distinct values from first column
I want to compare column1 and column2 and get the unique values from column1 (ignoring NaN). So in this case, I should get test1, test4.

Also, can we create and store the result in another column?

```<code>    Column1 column2
0   test1   test2
1   test2   test3
2   test3   hello
3   test4   world
4     NaN     how
5     NaN     are
6     NaN     you
</code>```

答:
Without referencing the column names

explanation

I stack because it is a convenient way to drop nan's and not force a rectangular shape.

grouping by level=1 is the same as by columns prior to stacking.

applying set will allow me to use subtraction or diff which is interpreted as set.difference which is what we want.

[::-1] just reverses the order so I get the correct difference.

```<code>np.diff(df.stack().groupby(level=1).apply(set).values[::-1])

array([{'test4', 'test1'}], dtype=object)
</code>```

Body:
I want to compare column1 and column2 and get the unique values from column1 (ignoring NaN). So in this case, I should get test1, test4.

Also, can we create and store the result in another column?

    Column1 column2
0   test1   test2
1   test2   test3
2   test3   hello
3   test4   world
4     NaN     how
5     NaN     are
6     NaN     you

Body:
Without referencing the column names

explanation

I stack because it is a convenient way to drop nan's and not force a rectangular shape.

grouping by level=1 is the same as by columns prior to stacking.

applying set will allow me to use subtraction or diff which is interpreted as set.difference which is what we want.

[::-1] just reverses the order so I get the correct difference.

np.diff(df.stack().groupby(level=1).apply(set).values[::-1])

array([{'test4', 'test1'}], dtype=object)


问:
Android: Storing large fixed arrays in android studio
I am trying to use a 2d array to do some mapping in android. Basically the task is to convert polar coordinates to cartesian coordinates(both coordinates have to be integers). This conversion is used to pick a value at the calculated X and Y coordinates.

I have an r and that input that needs to return x and y. (int)(R + rcostheta) and (int)(R - rsintheta) will give me the required values (since my original cartesian matrix is 2R * 2R). But calculating them repeatedly is causing a lot of overhead. So i decided to pre-calculate the values of these so that i can avoid calculations. (And these calculations do take around 2-3 second overhead when I run my code)

i.e., instead of using Value[x][y], I can use

Value  [  X[r][theta]  ]    [  Y[r][theta]  ]

However this conversion matrix/2d array is pretty large. It has 128 x 960 elements (my applications has 128 radius and 960 segments). I keep getting a "code too large" error.

Can you suggest an easy way to implement this? i.e, to store this mapping matrix somewhere where it can be referenced without too much overhead.

Some people suggest using a database. But since I am new to android programming it looks a little bit scary. Surely it can be done a lot simpler?

Currently I am storing my two mapping matrices as

```<code>int[][] X = new int[][]{
                 {229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356},

{next line},
.
.
.
{last line};
</code>```

And using it as

getBinary(tempBitmap, X[j][i],Y[j][i]);

This should work if the X and Y matrices were smaller. But since they are gigantic, I cant do it. Please suggest a way to go about doing this.

答:
The computation doesn't look like it should take a long time - is it because you are you doing a large number of these calculations?

If a typical run of your application only uses a relatively small number of points, but does the conversion on them many times, then it would probably be best to do the calculation the first time that it's needed, and cache the result (in memory, if there isn't going to be a huge number of them).

If that's not going to work, then the next logical thing to do would indeed be to put the values into the database. This is a very common thing to do in an Android application, and there are a large number of tutorials available on the internet, in books, etc.

Body:
I am trying to use a 2d array to do some mapping in android. Basically the task is to convert polar coordinates to cartesian coordinates(both coordinates have to be integers). This conversion is used to pick a value at the calculated X and Y coordinates.

I have an r and that input that needs to return x and y. (int)(R + rcostheta) and (int)(R - rsintheta) will give me the required values (since my original cartesian matrix is 2R * 2R). But calculating them repeatedly is causing a lot of overhead. So i decided to pre-calculate the values of these so that i can avoid calculations. (And these calculations do take around 2-3 second overhead when I run my code)

i.e., instead of using Value[x][y], I can use

Value  [  X[r][theta]  ]    [  Y[r][theta]  ]

However this conversion matrix/2d array is pretty large. It has 128 x 960 elements (my applications has 128 radius and 960 segments). I keep getting a "code too large" error.

Can you suggest an easy way to implement this? i.e, to store this mapping matrix somewhere where it can be referenced without too much overhead.

Some people suggest using a database. But since I am new to android programming it looks a little bit scary. Surely it can be done a lot simpler?

Currently I am storing my two mapping matrices as

int[][] X = new int[][]{
                 {229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356},

{next line},
.
.
.
{last line};

And using it as

getBinary(tempBitmap, X[j][i],Y[j][i]);

This should work if the X and Y matrices were smaller. But since they are gigantic, I cant do it. Please suggest a way to go about doing this.


问:
Secondary index missing records after migration (add/remove node)
I have noticed that whenever i add/remove nodes from my cluster, secondary index query returns empty result for some records even after migration completes. However they can be successfully retrieved using PK. I am using version 3.8.1 with RAM+HDD model. Currently i have to drop and create each secondary index manually every time. Is there better solution available for this?</p>

答:
You are likely hitting the following bug:

[AER-4930] - (SINDEX) Replica-creates not updating sindex entry, cause missing records in query.

This got addressed in version 3.9.0.1: http://www.aerospike.com/download/server/notes.html#3.9.0.1


问:
Coinbase API Python client.get_historic_prices()
I'm new to Python and API and am trying to start with some basics like making a list/plot of old BTC prices. I imported the Coinbase Wallet Client and used client.get_historic_prices(), which gave me a list of the price at midnight UTC for 365 days.

How can I adjust the parameters to get different date ranges and data resolution, for example each minute for two years? Is there a way to search the historic values of buy, sell, and spot separately?

```<code>from coinbase.wallet.client import Client
hist_price = client.get_historic_prices()

xx=[]
yy=[]
for ii in range(365):
    xx.append(ii*-1) # x coordinate being "days ago"
    yy.append(float(hist_price['prices'][ii]['price']))
</code>```

Returns (this is just from a print statement of print(hist_price['prices'][0:3]). So it's midnight once a day.

```<code>prices
length = 365
{
  "price": "974.39",
  "time": "2017-02-01T00:00:00Z"
}
{
  "price": "944.29",
  "time": "2017-01-31T00:00:00Z"
}
{
  "price": "920.47",
  "time": "2017-01-30T00:00:00Z"
}
</code>```

答:
Get_historic_prices is not clearly documented anywhere. This is a mini guide of what I have managed to discover about it and its usage. It's not much but it should be somewhere.

get_historic_prices supports one argument called period which can take the following values:

hour

day

week

month

year

all

Each of them except all returns approximately a list of 360 price points distributed more or less uniformly in the previous hour (day, week, month, year respectively).

all returns a list of price points one for each day at 00:00:00 UTC (i think).

get_historic_prices should also support a currency_pair argument as do the get_buy_price, get_sell_price, and get_spot_price do. Unfortunately, although I have submitted a PR, it has not been merged yet.

Body:
I'm new to Python and API and am trying to start with some basics like making a list/plot of old BTC prices. I imported the Coinbase Wallet Client and used client.get_historic_prices(), which gave me a list of the price at midnight UTC for 365 days.

How can I adjust the parameters to get different date ranges and data resolution, for example each minute for two years? Is there a way to search the historic values of buy, sell, and spot separately?

from coinbase.wallet.client import Client
hist_price = client.get_historic_prices()

xx=[]
yy=[]
for ii in range(365):
    xx.append(ii*-1) # x coordinate being "days ago"
    yy.append(float(hist_price['prices'][ii]['price']))

Returns (this is just from a print statement of print(hist_price['prices'][0:3]). So it's midnight once a day.

prices
length = 365
{
  "price": "974.39",
  "time": "2017-02-01T00:00:00Z"
}
{
  "price": "944.29",
  "time": "2017-01-31T00:00:00Z"
}
{
  "price": "920.47",
  "time": "2017-01-30T00:00:00Z"
}


问:
Get AD Group Names from List and Group Members Properties with Powershell
I'm trying to Get-Content from a text file which includes AD group names.  Then from this group list get the AD user properties for each member samaccountname, name, enabled properties of the user.  The output I'd like to see would look something like this for each group in the text file.

```<code>Group Name
samaccountname  name  enabled
</code>```

I managed to get the correct output but cannot get it output properly as the Write-Host result cannot be output to a file.  Here is the script that gets what I want (well sort of - the first group name appears above the header).

```<code>$ErrorActionPreference = "SilentlyContinue"
Get-Content D:\ADGroups.txt | Where{$_ -ne $null -and $_.trim() -ne ""} |
    foreach{
        $Group = $_
        Write-Host "$Group"
        Get-ADGroup -Identity $Group -Properties members |
            Select-Object -ExpandProperty members |
            Get-ADUser -Properties samaccountname, enabled |
            Select samaccountname, name, Enabled
    }
</code>```

I've searched and found similar scripts but none of them produced the results I'm looking for.

答:
You should simply be able to do (with optimizations):

```<code># Apply Silent Errors to only the functions you trust
$SC = ${ErrorAction="SilentlyContinue"}
cat "D:\ADGroups.txt" @SC | ? {"$_".trim()} | % {
    $Group = $_
    "$Group"
    Get-ADGroup -Identity $Group -Properties members @SC |
        Select -ExpandProperty members |
        Get-ADUser -Properties samaccountname, enabled @SC |
        Select samaccountname,name,enabled
} | Out-File "D:\Final-Output.txt"
</code>```

This is because Write-Host writes directly to the shell and is ignored by PowerShell's stdout stream handling.

Body:
I'm trying to Get-Content from a text file which includes AD group names.  Then from this group list get the AD user properties for each member samaccountname, name, enabled properties of the user.  The output I'd like to see would look something like this for each group in the text file.

Group Name
samaccountname  name  enabled

I managed to get the correct output but cannot get it output properly as the Write-Host result cannot be output to a file.  Here is the script that gets what I want (well sort of - the first group name appears above the header).

$ErrorActionPreference = "SilentlyContinue"
Get-Content D:\ADGroups.txt | Where{$_ -ne $null -and $_.trim() -ne ""} |
    foreach{
        $Group = $_
        Write-Host "$Group"
        Get-ADGroup -Identity $Group -Properties members |
            Select-Object -ExpandProperty members |
            Get-ADUser -Properties samaccountname, enabled |
            Select samaccountname, name, Enabled
    }

I've searched and found similar scripts but none of them produced the results I'm looking for.

Body:
You should simply be able to do (with optimizations):

# Apply Silent Errors to only the functions you trust
$SC = ${ErrorAction="SilentlyContinue"}
cat "D:\ADGroups.txt" @SC | ? {"$_".trim()} | % {
    $Group = $_
    "$Group"
    Get-ADGroup -Identity $Group -Properties members @SC |
        Select -ExpandProperty members |
        Get-ADUser -Properties samaccountname, enabled @SC |
        Select samaccountname,name,enabled
} | Out-File "D:\Final-Output.txt"

This is because Write-Host writes directly to the shell and is ignored by PowerShell's stdout stream handling.


问:
Is there a way to report git contributions on the command line?
I see that github records the commit, add, and delete history for each contributor. You can check it on the graph tab.

However, it's not as granular as I would like.

Is it possible to get this information on the command line?

I'd like to save a more granular dataset in the form of a table.

What I'm thinking of is four arrays: Day/Date, Commits, Additions, Deletions

答:
You can start with using the GitHub Statistics API like:

Get contributors list with additions, deletions, and commit counts

It does return:

```<code>total
</code>```

The Total number of commits authored by the contributor.

And: Weekly Hash (weeks array):

```<code>w - Start of the week, given as a Unix timestamp.
a - Number of additions
d - Number of deletions
c - Number of commits
</code>```

For the command-line aspect, use curl.

See "A curl tutorial using GitHub's API "

The above was based on the tag "github", but yes, git itself can generate stats (even fancy ones like the git-stats project)

See this gist for instance, or use git log --stat, git diff --stat.

As seen here, some form of processing is needed, to use the result of a

```<code>git log --author=$USER --shortstat $BRANCH
</code>```

Body:
You can start with using the GitHub Statistics API like:

Get contributors list with additions, deletions, and commit counts

It does return:

total

The Total number of commits authored by the contributor.

And: Weekly Hash (weeks array):

w - Start of the week, given as a Unix timestamp.
a - Number of additions
d - Number of deletions
c - Number of commits

For the command-line aspect, use curl.

See "A curl tutorial using GitHub's API "

The above was based on the tag "github", but yes, git itself can generate stats (even fancy ones like the git-stats project)

See this gist for instance, or use git log --stat, git diff --stat.

As seen here, some form of processing is needed, to use the result of a

git log --author=$USER --shortstat $BRANCH


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

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

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

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

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

答:
To achieve your first goal

be able to drag the red square ONLY AFTER the blue square has been
  dragged to the other end of its parent

You just need to apply the draggable to the html element after the stop event is fired from the first draggable element. Sample code is:

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

See the JSFiddle working example here

EDIT: In case you want to disable the draggable when blue element is not in the right side, see this other JSFiddle

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

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

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

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

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

Body:
To achieve your first goal

be able to drag the red square ONLY AFTER the blue square has been
  dragged to the other end of its parent

You just need to apply the draggable to the html element after the stop event is fired from the first draggable element. Sample code is:

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

See the JSFiddle working example here

EDIT: In case you want to disable the draggable when blue element is not in the right side, see this other JSFiddle


问:
ffmpeg returned non-zero exit status. Check stdout Coldfusion
I have an coldfusion application. I am converting recorded video from mobile through ffmpeg and coldfusion. Here is the ffmpeg command which i am running.

ffmpegPath -i "inputfile" -vcodec libx264 -acodec aac "OutputFile"

Output file type is mp4. I want to convert my all videos to mp4 with h.264 and ACC sound. So that it will work on all platforms.

I am getting the following error:

```<code>java.io.IOException: ffmpeg returned non-zero exit status. Check stdout.
</code>```

Here is the CF code that i am running.

```<code><cfset resultLog        = "path\to\directory\testOuput_result.log">
<cfset errorLog         = "path\to\directory\testOuput_error.log">
<cfset results  = structNew()>
        <cfscript>
            try {
                runtime = createObject("java", "java.lang.Runtime").getRuntime();
                command = 'ffmpegPath -i "inputfile" -vcodec libx264 -acodec aac "OutputFile"';
                process = runtime.exec(#command#);
                results.errorLogSuccess = processStream(process.getErrorStream(), errorLog);
                results.resultLogSuccess = processStream(process.getInputStream(), resultLog);
                results.exitCode = process.waitFor();
            }
            catch(exception e) {
                results.status = e;
            }
        </cfscript>
<cffunction name="processStream" access="public" output="false" returntype="boolean" hint="Returns true if stream was successfully processed">
    <cfargument name="in" type="any" required="true" hint="java.io.InputStream object">
    <cfargument name="logPath" type="string" required="false" default="" hint="Full path to LogFile">
    <cfset var out = "">
    <cfset var writer = "">
    <cfset var reader = "">
    <cfset var buffered = "">
    <cfset var line = "">
    <cfset var sendToFile = false>
    <cfset var errorFound = false>

    <cfscript>
        if ( len(trim(arguments.logPath)) ) {
            out = createObject("java", "java.io.FileOutputStream").init(arguments.logPath);
            writer = createObject("java", "java.io.PrintWriter").init(out);
            sendToFile = true;
        }

        reader = createObject("java", "java.io.InputStreamReader").init(arguments.in);
        buffered = createObject("java", "java.io.BufferedReader").init(reader);
        line = buffered.readLine();
        while ( IsDefined("line") ) {
            if (sendToFile) {
                writer.println(line);
            }
            line = buffered.readLine();
        }
           if (sendToFile) {
           errorFound = writer.checkError();
           writer.flush();
           writer.close();
        }
    </cfscript>
    <!--- return true if no errors found. --->
    <cfreturn (NOT errorFound)>
</cffunction>
</code>```

I have also used different ffmpeg.exe but got same error. I have also used ffmpeg-cli-wrapper java wrapper in coldfusion. Still i got the same error. Can any one help me to sort out this issue.

答:
Nothing to do with the error, but are you sure you really need Runtime.exec()? It is usually overkill. Most applications can be invoked with <cfexecute>, which is basically a wrapper of Runtime.exec(), which does the same thing, only with less code.

There was an issue with cfexecute and ffmpeg.exe way back in CF8, caused by the fact that early versions of cfexecute did not capture StdErr. However, that was resolved in one of the CF8 updates. Assuming you are using a recent version of CF, it should work right out of the box. Not tested, but something along these lines:

NB: Note the use of absolute paths for all files

```<code><!--- change to the appropriate timeout --->
<cfexecute name="c:\path\to\ffmpeg.exe"
    arguments=' -i "c:\path\to\in.file" -vcodec libx264 -acodec aac "c:\path\to\out.file"'
    timeout="120"
    variable="result"
    errorVariable="errorMessage"
    />

<!--- Display results --->
<cfoutput>
   result = #result#
   errorVariable = #errorVariable #
</cfoutput>
</code>```

See the cfexecute documentation for more details on arguments and syntax.

Body:
I have an coldfusion application. I am converting recorded video from mobile through ffmpeg and coldfusion. Here is the ffmpeg command which i am running.

ffmpegPath -i "inputfile" -vcodec libx264 -acodec aac "OutputFile"

Output file type is mp4. I want to convert my all videos to mp4 with h.264 and ACC sound. So that it will work on all platforms.

I am getting the following error:

java.io.IOException: ffmpeg returned non-zero exit status. Check stdout.

Here is the CF code that i am running.

<cfset resultLog        = "path\to\directory\testOuput_result.log">
<cfset errorLog         = "path\to\directory\testOuput_error.log">
<cfset results  = structNew()>
        <cfscript>
            try {
                runtime = createObject("java", "java.lang.Runtime").getRuntime();
                command = 'ffmpegPath -i "inputfile" -vcodec libx264 -acodec aac "OutputFile"';
                process = runtime.exec(#command#);
                results.errorLogSuccess = processStream(process.getErrorStream(), errorLog);
                results.resultLogSuccess = processStream(process.getInputStream(), resultLog);
                results.exitCode = process.waitFor();
            }
            catch(exception e) {
                results.status = e;
            }
        </cfscript>
<cffunction name="processStream" access="public" output="false" returntype="boolean" hint="Returns true if stream was successfully processed">
    <cfargument name="in" type="any" required="true" hint="java.io.InputStream object">
    <cfargument name="logPath" type="string" required="false" default="" hint="Full path to LogFile">
    <cfset var out = "">
    <cfset var writer = "">
    <cfset var reader = "">
    <cfset var buffered = "">
    <cfset var line = "">
    <cfset var sendToFile = false>
    <cfset var errorFound = false>

    <cfscript>
        if ( len(trim(arguments.logPath)) ) {
            out = createObject("java", "java.io.FileOutputStream").init(arguments.logPath);
            writer = createObject("java", "java.io.PrintWriter").init(out);
            sendToFile = true;
        }

        reader = createObject("java", "java.io.InputStreamReader").init(arguments.in);
        buffered = createObject("java", "java.io.BufferedReader").init(reader);
        line = buffered.readLine();
        while ( IsDefined("line") ) {
            if (sendToFile) {
                writer.println(line);
            }
            line = buffered.readLine();
        }
           if (sendToFile) {
           errorFound = writer.checkError();
           writer.flush();
           writer.close();
        }
    </cfscript>

    <cfreturn (NOT errorFound)>
</cffunction>

I have also used different ffmpeg.exe but got same error. I have also used ffmpeg-cli-wrapper java wrapper in coldfusion. Still i got the same error. Can any one help me to sort out this issue.

Body:
Nothing to do with the error, but are you sure you really need Runtime.exec()? It is usually overkill. Most applications can be invoked with <cfexecute>, which is basically a wrapper of Runtime.exec(), which does the same thing, only with less code.

There was an issue with cfexecute and ffmpeg.exe way back in CF8, caused by the fact that early versions of cfexecute did not capture StdErr. However, that was resolved in one of the CF8 updates. Assuming you are using a recent version of CF, it should work right out of the box. Not tested, but something along these lines:

NB: Note the use of absolute paths for all files

<!--- change to the appropriate timeout --->
<cfexecute name="c:\path\to\ffmpeg.exe"
    arguments=' -i "c:\path\to\in.file" -vcodec libx264 -acodec aac "c:\path\to\out.file"'
    timeout="120"
    variable="result"
    errorVariable="errorMessage"
    />

<!--- Display results --->
<cfoutput>
   result = #result#
   errorVariable = #errorVariable #
</cfoutput>

See the cfexecute documentation for more details on arguments and syntax.


问:
Golang goroutine endless loop memory leak
I have encountered strange (as for a man who is new to golang) behaviour of my goroutine:

```<code>go func(...) {
  for {
    buffer := make([]byte, 1024)
     ...
  }
}
</code>```

It slowly eats RAM. I understand that it is caused by calling make in an endless loop; it just allocates new memory every time. But i don't quite get why this construction:

```<code>  var buffer []byte
  for {
    buffer = make([]byte, 1024)
     ...
    }
  }
</code>```

..works well, while the first one doesn't. Shouldn't garbage collector detect that memory which old buf was pointing at is unreachable in both cases? And maybe there are some other similar traps that a go-newbie should know?

Also, if i will return this goroutine, will leaked memory be freed?

UPD: full memory leaking routine code:

```<code>go func(dataChannel chan []byte, errorChannel chan error) {
  for {
    buf := make([]byte, 1024)
    _, err := conn.Read(buf)
    if err != nil {
      errorChannel<- err
      break
    }
    dataChannel<- buf
  }
} (dataChannel, errorChannel)
</code>```

答:
```<code>  for {
        var mem runtime.MemStats
        runtime.ReadMemStats(&mem)
        fmt.Printf("alloc [%v] \t heapAlloc [%v] \n", mem.Alloc, mem.HeapAlloc)
        time.Sleep(2000 * time.Millisecond)
    }
</code>```

added the above lines in your main function for loop (in the leaking code link given above)

new code : https://pastebin.com/UQbYuVN7

while running this shows that memory is being re-collected at regular intervals by gc

Body:
I have encountered strange (as for a man who is new to golang) behaviour of my goroutine:

go func(...) {
  for {
    buffer := make([]byte, 1024)
     ...
  }
}

It slowly eats RAM. I understand that it is caused by calling make in an endless loop; it just allocates new memory every time. But i don't quite get why this construction:

  var buffer []byte
  for {
    buffer = make([]byte, 1024)
     ...
    }
  }

..works well, while the first one doesn't. Shouldn't garbage collector detect that memory which old buf was pointing at is unreachable in both cases? And maybe there are some other similar traps that a go-newbie should know?

Also, if i will return this goroutine, will leaked memory be freed?

UPD: full memory leaking routine code:

go func(dataChannel chan []byte, errorChannel chan error) {
  for {
    buf := make([]byte, 1024)
    _, err := conn.Read(buf)
    if err != nil {
      errorChannel<- err
      break
    }
    dataChannel<- buf
  }
} (dataChannel, errorChannel)

Body:
  for {
        var mem runtime.MemStats
        runtime.ReadMemStats(&mem)
        fmt.Printf("alloc [%v] \t heapAlloc [%v] \n", mem.Alloc, mem.HeapAlloc)
        time.Sleep(2000 * time.Millisecond)
    }

added the above lines in your main function for loop (in the leaking code link given above)

new code : https://pastebin.com/UQbYuVN7

while running this shows that memory is being re-collected at regular intervals by gc


问:
Word VBA to extract Captions of Embedded Files
I'm trying to extract all the embedded Excel files in a Word docx. I know that I can do this quickly by changing filename of the docx to zip, and then find all the Excel files in word/embeddings folder.

The problem is that the Excel files in word/embeddings have very generic filenames (e.g., Microsoft_Excel_Macro-Enabled_Worksheet1.xlsm, Microsoft_Excel_Macro-Enabled_Worksheet2.xlsm) instead of the original filename. The original files, however, were actually csv not xlsm files.

I did not play any part in creating this document. I assume they used Insert -> Object -> Create From File. Also, I'm using Word 2010, but according to the Compatibility Checker the document was originally created with Word 97-2003, and the files were embedded later with Word 2007.

I can find the original filename if I go into the docx, right click on embedded file icon, and go to Macro-Enabled Worksheet Object -> Convert... -> Change Icon... -> Caption

However, I don't want to do this manually for a bunch of embedded Excel files.

So is there a way to use some vba code to extract a list of the original filenames for all embedded files? Then I can use this list as a key to rename the generically named files.

答:
Here is what I ended up doing:</p>

```<code>Sub Extract()

Dim num As Integer
Dim AD As Document
Set AD = ActiveDocument

Dim numObjects As Integer
numObjects = AD.InlineShapes.Count

Dim caption_names() as variant
ctr = 1
For num = 1 To numObjects
    If AD.InlineShapes(num).Type = 1 Then
        'it's an embedded OLE type so open it.
        Redim Preserve caption_names(1 to ctr)
        caption_names(ctr) = AD.InlineShapes(num).OLEFormat.IconLabel
        ctr=ctr+1
    End If
Next num

End Sub
</code>```

Body:
Here is what I ended up doing:

Sub Extract()

Dim num As Integer
Dim AD As Document
Set AD = ActiveDocument

Dim numObjects As Integer
numObjects = AD.InlineShapes.Count

Dim caption_names() as variant
ctr = 1
For num = 1 To numObjects
    If AD.InlineShapes(num).Type = 1 Then
        'it's an embedded OLE type so open it.
        Redim Preserve caption_names(1 to ctr)
        caption_names(ctr) = AD.InlineShapes(num).OLEFormat.IconLabel
        ctr=ctr+1
    End If
Next num

End Sub


问:
Extracting a graph from 2 dimension
Having this data:

```<code>       keyword1  keyword2  keyword3
  art1    0          1        0
  art2    1          1        0
  art3    0          0        1
</code>```

It is possible to extract a graph using this:

```<code>    library(igraph)
    df1<-data.frame(keyword1=c(0,1,0),keyword2=c(1,1,0),keyword3=c(0,0,1),row.names=c("art1","art2","art3"))
  df1.mt <- as.matrix(df1)
  df1.adj <- t(df1.mt) %*% df1.mt
    diag(df1.adj) <- 0
    g <- graph.adjacency(df1.adj)
    plot(g)
</code>```

if data have this format:

```<code>        keyword1  keyword2  keyword3
  artA      0          1        0
  artA      1          1        0
  artB      0          0        1
  artB      1          1        0
  artC      1          1        0
</code>```

How is it possible to extract the graph?

答:
Here is a function which takes a binary matrix and creates an adjacency matrix for the columns, where two columns are said to be adjacent if for some row, both of the entries in those columns are 1's:

```<code>adj.matrix <- function(B){
  n <- ncol(B)
  g <- expand.grid(1:n,1:n)
  adj <- apply(g,MARGIN = 1, FUN = function(v){max(pmin(B[,v[1]],B[,v[2]]))})
  dim(adj) <- c(n,n)
  diag(adj) <- 0
  colnames(adj) <- colnames(B)
  row.names(adj) <- colnames(B)
  graph.adjacency(adj)
}
</code>```

To test it:

```<code>B <- rbind(c(1,1,0,0,0),
          c(0,0,1,1,0),
          c(0,0,0,1,1),
          c(0,0,1,0,1))
colnames(B) <- c("A","B","C","D","E")

g <- adj.matrix(B)
plot(g)
</code>```

Resulting graph:

I am not 100% sure what you intend to do with the second format. It looks like your second format is a dataframe of the following form:

```<code>df <- data.frame(names=c("artA","artA","artB","artB","artC"),keyword1=c(0,1,0,1,1),keyword2=c(1,1,0,1,1),keyword3=c(0,0,1,0,0))
</code>```

which is:

```<code>  names keyword1 keyword2 keyword3
1  artA        0        1        0
2  artA        1        1        0
3  artB        0        0        1
4  artC        1        1        0
5  artC        1        1        0
</code>```

You can get it into a format using suitable for the above function by a suitable use of aggregate:

```<code>> df <- aggregate(. ~ names,data = df, max)
> row.names(df) <- as.character(df$names)
> df$names <- NULL
> df
     keyword1 keyword2 keyword3
artA        1        1        0
artB        1        1        1
artC        1        1        0
</code>```

At this stage, df looks like your first table, and as.matrix(df) could be fed to the function adj.matrix()

Title: Extracting a graph from 2 dimension

Body:
Having this data:

       keyword1  keyword2  keyword3
  art1    0          1        0
  art2    1          1        0
  art3    0          0        1

It is possible to extract a graph using this:

    library(igraph)
    df1<-data.frame(keyword1=c(0,1,0),keyword2=c(1,1,0),keyword3=c(0,0,1),row.names=c("art1","art2","art3"))
  df1.mt <- as.matrix(df1)
  df1.adj <- t(df1.mt) %*% df1.mt
    diag(df1.adj) <- 0
    g <- graph.adjacency(df1.adj)
    plot(g)

if data have this format:

        keyword1  keyword2  keyword3
  artA      0          1        0
  artA      1          1        0
  artB      0          0        1
  artB      1          1        0
  artC      1          1        0

How is it possible to extract the graph?

Body:
Here is a function which takes a binary matrix and creates an adjacency matrix for the columns, where two columns are said to be adjacent if for some row, both of the entries in those columns are 1's:

adj.matrix <- function(B){
  n <- ncol(B)
  g <- expand.grid(1:n,1:n)
  adj <- apply(g,MARGIN = 1, FUN = function(v){max(pmin(B[,v[1]],B[,v[2]]))})
  dim(adj) <- c(n,n)
  diag(adj) <- 0
  colnames(adj) <- colnames(B)
  row.names(adj) <- colnames(B)
  graph.adjacency(adj)
}

To test it:

B <- rbind(c(1,1,0,0,0),
          c(0,0,1,1,0),
          c(0,0,0,1,1),
          c(0,0,1,0,1))
colnames(B) <- c("A","B","C","D","E")

g <- adj.matrix(B)
plot(g)

Resulting graph:

I am not 100% sure what you intend to do with the second format. It looks like your second format is a dataframe of the following form:

df <- data.frame(names=c("artA","artA","artB","artB","artC"),keyword1=c(0,1,0,1,1),keyword2=c(1,1,0,1,1),keyword3=c(0,0,1,0,0))

which is:

  names keyword1 keyword2 keyword3
1  artA        0        1        0
2  artA        1        1        0
3  artB        0        0        1
4  artC        1        1        0
5  artC        1        1        0

You can get it into a format using suitable for the above function by a suitable use of aggregate:

> df <- aggregate(. ~ names,data = df, max)
> row.names(df) <- as.character(df$names)
> df$names <- NULL
> df
     keyword1 keyword2 keyword3
artA        1        1        0
artB        1        1        1
artC        1        1        0

At this stage, df looks like your first table, and as.matrix(df) could be fed to the function adj.matrix()


问:
Can't get jquery resize function to work properly
I'm trying to create a function that checks the browser window width and applies or removes classes depending on what the width is. However, I either can't seem to remove one of the classes and can't get the function based on the classes to work either.

The concept is:
On window resize, IF the window width exceeds 480px to have the class "deskop" applied to the figure ".grid-block", and the class "mobile" removed. ELSE, if the window width goes below 481px to have the class "desktop" removed and "mobile" applied.
Then, if a ".grid-block" has the class "desktop", allow this mousover effect to take place. If the figure has the class "mobile", prevent the mouseover.

My problems are:
I couldn't get the class applying/removing resize function to fire properly, so I borrowed and revised some code I found and it ended up looking like this...

```<code>$(window).load(function() {
  (function($) {
    var $window = $(window),
    $block = $('.grid-block');

    function resize() {
      if ($window.width() < 481) {
        return $block.addClass('mobile');
      }
      $block.removeClass('mobile');
      if ($window.width() > 480) {
        return $block.addClass('desktop');
      }
      $block.removeClass('desktop');
    }
    $window
    .resize(resize)
    .trigger('resize')
  })(jQuery);
});
</code>```

This function assigns the mobile class properly, but it always keeps the desktop class. So be it- I thought- so I revised the function to omit using the desktop class and to have my functions based entirely on the figure element having the mobile class or not, like so...

```<code>if (!$('.grid-block').hasClass("mobile")) {
  $('.grid-block').mouseover(function() {
    $(this).find("figcaption").removeClass("testopacity");
  });
  $('.grid-block').mouseout(function() {
    $(this).find("figcaption").addClass("testopacity");
  });
}
</code>```

Instead of checking to see if the ".grid-block" figure has the "mobile" class applied, it just goes ahead with the mouseover function no matter what the browser window width is.

What is wrong with my functions? Why doesn't the first one remove the desktop class, and why doesn't the second one check for the mobile class before performing it's function?

答:
You may want to try your first resize function with minor update. It appears that you never reach the code at this line $block.removeClass('desktop'); as you return before that! So move that line as shown below and try:

```<code>if ($window.width() < 481) {
  $block.removeClass('desktop');
  return $block.addClass('mobile');
}
</code>```

Body:
I'm trying to create a function that checks the browser window width and applies or removes classes depending on what the width is. However, I either can't seem to remove one of the classes and can't get the function based on the classes to work either.

The concept is:
On window resize, IF the window width exceeds 480px to have the class "deskop" applied to the figure ".grid-block", and the class "mobile" removed. ELSE, if the window width goes below 481px to have the class "desktop" removed and "mobile" applied.
Then, if a ".grid-block" has the class "desktop", allow this mousover effect to take place. If the figure has the class "mobile", prevent the mouseover.

My problems are:
I couldn't get the class applying/removing resize function to fire properly, so I borrowed and revised some code I found and it ended up looking like this...

$(window).load(function() {
  (function($) {
    var $window = $(window),
    $block = $('.grid-block');

    function resize() {
      if ($window.width() < 481) {
        return $block.addClass('mobile');
      }
      $block.removeClass('mobile');
      if ($window.width() > 480) {
        return $block.addClass('desktop');
      }
      $block.removeClass('desktop');
    }
    $window
    .resize(resize)
    .trigger('resize')
  })(jQuery);
});

This function assigns the mobile class properly, but it always keeps the desktop class. So be it- I thought- so I revised the function to omit using the desktop class and to have my functions based entirely on the figure element having the mobile class or not, like so...

if (!$('.grid-block').hasClass("mobile")) {
  $('.grid-block').mouseover(function() {
    $(this).find("figcaption").removeClass("testopacity");
  });
  $('.grid-block').mouseout(function() {
    $(this).find("figcaption").addClass("testopacity");
  });
}

Instead of checking to see if the ".grid-block" figure has the "mobile" class applied, it just goes ahead with the mouseover function no matter what the browser window width is.

What is wrong with my functions? Why doesn't the first one remove the desktop class, and why doesn't the second one check for the mobile class before performing it's function?

Body:
You may want to try your first resize function with minor update. It appears that you never reach the code at this line $block.removeClass('desktop'); as you return before that! So move that line as shown below and try:

if ($window.width() < 481) {
  $block.removeClass('desktop');
  return $block.addClass('mobile');
}


问:
Liferay 6.1 facebook SSO update
Facebook SSO is not working in Liferay 6.1.
Maybe is due the change to API Graph v2.3 But I don't know if there is a fix in Liferay to solve it.</p>

答:
I'm assuming that you refer to Liferay 6.1 CE. The last update to that version is from 2013 and it's been end-of-lifed back with that update and the release of Liferay 6.2. You don't even mention which exact 6.1 version you're running, but I assume that this happened recently.

6.1 EE still receives limited support, but if you would run that version, I'd assume that you'd rather have filed a ticket with the Enterprise Support Team than posting a question on stackoverflow.

That's a long way to say: The last update for Liferay 6.1 CE was in 2013 and there are and will be no further fixes for any issues of that versions under a 6.1.x version number. The updates that exist carry the version numbers 6.2 (end-of-lifed in 2016) and 7.0 (currently in GA3) and you should try out the latest version if the issue appears there as well.

Title: Liferay 6.1 facebook SSO update


问:
Php Basics Create Object
```<code><?php

$myClass = new MyClass;
$myClass->myFunc();

class MyClass
{
    public static function myFunc() {
        echo 'testcall';
    }
}

?>
</code>```

Does php go from top to bottom?

If so why does php know MyClass at the moment where I create an instance of it?

答:
In PHP there is no need of declaration previously, You can use it at the time of using it that variable.Your code is working as you included it in the same file

At the time of declaring class in another .php file you have to include it compulsory before initiating the object of that particular class.

Hope it is useful to you :)

Title: Php Basics Create Object

Body:
<?php

$myClass = new MyClass;
$myClass->myFunc();

class MyClass
{
    public static function myFunc() {
        echo 'testcall';
    }
}

?>

Does php go from top to bottom?

If so why does php know MyClass at the moment where I create an instance of it?


问:
TIME_FORMAT Returns NULL
I have a time stored in mysql, the column is set as time, so it reads 13:16:00. When I try to run

```<code>SELECT TIME_FORMAT ('alarm_time', '%H:%i) FROM `Alarm`;
</code>```

I get a NULL, I am trying to get a result of 13:06.

答:
The quotes around alarm_time are causing that to be interpreted as a string. If you remove them, or surround them with backticks,  it will be interpreted as the table's column, which contains a date.
These should both work

```<code>SELECT TIME_FORMAT (alarm_time, '%H:%i' ) FROM `Alarm`;
</code>```

or

```<code>SELECT TIME_FORMAT (`alarm_time`, '%H:%i' ) FROM `Alarm`;
</code>```

Regarding the question about comparison you asked in the comments, if I understood correctly you can do that with something like

```<code>yourDate between SUBTIME(yourOtherDate, '00:00:30') and ADDTIME(yourOtherDate, '00:00:30')
</code>```

or any other interval

Title: TIME_FORMAT Returns NULL

Body:
I have a time stored in mysql, the column is set as time, so it reads 13:16:00. When I try to run

SELECT TIME_FORMAT ('alarm_time', '%H:%i) FROM `Alarm`;

I get a NULL, I am trying to get a result of 13:06.

Body:
The quotes around alarm_time are causing that to be interpreted as a string. If you remove them, or surround them with backticks,  it will be interpreted as the table's column, which contains a date.
These should both work

SELECT TIME_FORMAT (alarm_time, '%H:%i' ) FROM `Alarm`;

or

SELECT TIME_FORMAT (`alarm_time`, '%H:%i' ) FROM `Alarm`;

Regarding the question about comparison you asked in the comments, if I understood correctly you can do that with something like

yourDate between SUBTIME(yourOtherDate, '00:00:30') and ADDTIME(yourOtherDate, '00:00:30')

or any other interval


问:
Kubernetes Services not reachable after introducing Ingress with nginx Ingress Controller
I have some services with external IP addresses in Kubernetes that I was able to reach by navigating to the IP. I then configured an Ingress with a nginx Ingress-Controller:

```<code>  annotations:
    kubernetes.io/ingress.class: "nginx"
</code>```

I can now reach the service over the static IP of the Ingress, as expected. But can no longer reach the service directly over its external IP, nor any other services in k8s... why can't I reach the services with Ingress configured?

答: The Ingress Controller needs to be configured to allow access via its rules. See the documentation here: https://kubernetes.io/docs/user-guide/ingress/

Body:
I have some services with external IP addresses in Kubernetes that I was able to reach by navigating to the IP. I then configured an Ingress with a nginx Ingress-Controller:

  annotations:
    kubernetes.io/ingress.class: "nginx"

I can now reach the service over the static IP of the Ingress, as expected. But can no longer reach the service directly over its external IP, nor any other services in k8s... why can't I reach the services with Ingress configured?


问:
c++ graphical programming
I'm new to c++ 3D, so I may just be missing something obvious, but how do I convert from 3D to 2D and (for a given z location) from 2D to 3D?</p>

答:
One lame solution:

```<code>^ y
|
|
|  /z
| /
+/--------->x
</code>```

Angle is the angle between the Ox and Oz axes (

```<code>#include <cmath>

typedef struct {
  double x,y,z;
} Point3D;

typedef struct {
  double x,y;
} Point2D

const double angle = M_PI/4; //can be changed

Point2D* projection(Point3D& point) {
  Point2D* p = new Point2D();
  p->x = point.x + point.z * sin(angle);
  p->y = point.y + point.z * cos(angle);
  return p;
}
</code>```

However there are lots of tutorials on this on the net... Have you googled for it?

Title: c++ graphical programming

Body:
One lame solution:

^ y
|
|
|  /z
| /
+/--------->x

Angle is the angle between the Ox and Oz axes (

#include <cmath>

typedef struct {
  double x,y,z;
} Point3D;

typedef struct {
  double x,y;
} Point2D

const double angle = M_PI/4; //can be changed

Point2D* projection(Point3D& point) {
  Point2D* p = new Point2D();
  p->x = point.x + point.z * sin(angle);
  p->y = point.y + point.z * cos(angle);
  return p;
}

However there are lots of tutorials on this on the net... Have you googled for it?


答:
This should do the trick.</p>

```<code>select time_format(alarm_time,'%h:%m') as alarm_time
  from alarm;
</code>```

Title: TIME_FORMAT Returns NULL

Body:
This should do the trick.

select time_format(alarm_time,'%h:%m') as alarm_time
  from alarm;


问:
The type 'Expression<>' is defined in an assembly that is not referenced
In ASP.NET MVC 4.5.2 Framework, after typing @Html.LabelFor() or @Html.EditorFor() in a view, I'm getting this error:

The type 'Expression<>' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

I have added assembly reference System.Core.dll, Version 4.0.0.0, Runtime Version v4.0.30319, and also I did in web.config.

答: This can be caused if you have multiple projects in your solution that don't all target the same version of the .NET Framework. For example, if your web app project targets .NET 4.5 and you have an assembly reference to another project in the solution that targets .NET 4.5.2. To fix this you need to change your projects to all target the same version of the .NET Framework.</p>

ContentLicense: CC BY-SA 4.0


问:
Adding comma separators to numbers, asp.net
I'm trying to add comma separators to a number. I've tried the advice here: add commas using String.Format for number and and here: .NET String.Format() to add commas in thousands place for a number but I can't get it to work - they just return the number without commas. The code I'm using is here:

 public static string addCommas(string cash) {
 return string.Format("{0:n0}", cash).ToString();

 }

Where am I going wrong?

Thanks.

Update: Hi all, thanks for your help, but all of those methods are returning the same error: "error CS1502: The best overloaded method match for 'BishopFlemingFunctions.addCommas(int)' has some invalid arguments" (or variations therof depending on what number type I'm using.) Any ideas?

答:
Well, you are sending in a string. it looks like you want a currency back

Why are you passing in a string to the method if it is a numeric value?

String.Format will return a string so there is not need to .ToString() it again.

{0:c} = Currency format if you do not want the $ then use {0:n}

Not sure you have to but you may need to do an explicit conversion if you pass it in as a string to (decimal)cash

return String.Format("{0:c}", (decimal)cash);

or

return String.Format("{0:n}", (decimal)cash);

but i think it should be something like:

```<code>public static string addCommas(decimal cash)
{
return String.Format("{0:c}", cash);
}
</code>```

but this is such a simple statement i do not see the logic in making it a method, if you method is one line, in most cases, its not a method.

Body:
Well, you are sending in a string. it looks like you want a currency back

Why are you passing in a string to the method if it is a numeric value?

String.Format will return a string so there is not need to .ToString() it again.

{0:c} = Currency format if you do not want the $ then use {0:n}

Not sure you have to but you may need to do an explicit conversion if you pass it in as a string to (decimal)cash

return String.Format("{0:c}", (decimal)cash);

or

return String.Format("{0:n}", (decimal)cash);

but i think it should be something like:

public static string addCommas(decimal cash)
{
return String.Format("{0:c}", cash);
}

but this is such a simple statement i do not see the logic in making it a method, if you method is one line, in most cases, its not a method.


问:
Can't run Play app on heroku
I deploy a Play 2.2.1 app on Heroku with this following Procfile :

web: target/universal/stage/bin/{MY-APP-NAME} -Dhttp.port=${PORT} -DapplyEvolutions.default=true

And I don't understand, I have always the same error :

bash: target/universal/stage/bin/{MY-APP-NAME}: No such file or directory

Here my heroku config :

```<code>JAVA_OPTS:                  -Xmx384m -Xss512k -XX:+UseCompressedOops
PATH:                       .jdk/bin:.sbt_home/bin:/usr/local/bin:/usr/bin:/bin
REPO:                       /app/.sbt_home/.ivy2/cache
SBT_OPTS:                   -Xmx384m -Xss512k -XX:+UseCompressedOops
</code>```

I have no idea what to do, anyone have an idea please ?

Thanks for your response.

答:
As I had the same issue, I just wanted to share how I solved it.

So if you are using sub-projects like me, you have to adjust your Procfile. If you have a sub-project called server in a folder server, your Procfile should look like this :

```<code>web: server/target/universal/stage/bin/server -Dhttp.port=${PORT}
</code>```

Title: Can't run Play app on heroku

Body:
I deploy a Play 2.2.1 app on Heroku with this following Procfile :

web: target/universal/stage/bin/{MY-APP-NAME} -Dhttp.port=${PORT} -DapplyEvolutions.default=true

And I don't understand, I have always the same error :

bash: target/universal/stage/bin/{MY-APP-NAME}: No such file or directory

Here my heroku config :

JAVA_OPTS:                  -Xmx384m -Xss512k -XX:+UseCompressedOops
PATH:                       .jdk/bin:.sbt_home/bin:/usr/local/bin:/usr/bin:/bin
REPO:                       /app/.sbt_home/.ivy2/cache
SBT_OPTS:                   -Xmx384m -Xss512k -XX:+UseCompressedOops

I have no idea what to do, anyone have an idea please ?

Thanks for your response.

Body:
As I had the same issue, I just wanted to share how I solved it.

So if you are using sub-projects like me, you have to adjust your Procfile. If you have a sub-project called server in a folder server, your Procfile should look like this :

web: server/target/universal/stage/bin/server -Dhttp.port=${PORT}


问:
Allow PHP function to be called dynamically and statically
I'm building an application, and I need to be able to chain methods, so I will need to be able to call methods dynamically and statically.

For example:

```<code>$results = Class::where('something')
                ->where('something else');
</code>```

In this case, the method 'where' needs to be called statically and dynamically, and still be allowed to be chained.

I know Laravel has something like this with Eloquent, but I do not know how to implement something like this.

答:
I just surprised myself by proving that this is indeed possible:

```<code><?php
class Test {
    private static $myself;
    public function do() {
        echo isset($this) ? 'd' : 's';
        if (!isset(self::$myself)) {
            self::$myself = new self;
        }
        return self::$myself;
    }
    public static function done() {
        echo PHP_EOL;
    }
}
Test::do()->do()->do()->done();
$myTest = new Test;
$myTest->do()->do()->do()->done();
$myTest::do()->do()->do()->done();
$myTest::do()->do()::do()->done();
Test::do()->do()->do()->done();
</code>```

The output is:

```<code>sdd
ddd
sdd
sds
sdd
</code>```

But it is unbelievable bad style in my eyes...

Body:
I'm building an application, and I need to be able to chain methods, so I will need to be able to call methods dynamically and statically.

For example:

$results = Class::where('something')
                ->where('something else');

In this case, the method 'where' needs to be called statically and dynamically, and still be allowed to be chained.

I know Laravel has something like this with Eloquent, but I do not know how to implement something like this.

Body:
I just surprised myself by proving that this is indeed possible:

<?php
class Test {
    private static $myself;
    public function do() {
        echo isset($this) ? 'd' : 's';
        if (!isset(self::$myself)) {
            self::$myself = new self;
        }
        return self::$myself;
    }
    public static function done() {
        echo PHP_EOL;
    }
}
Test::do()->do()->do()->done();
$myTest = new Test;
$myTest->do()->do()->do()->done();
$myTest::do()->do()->do()->done();
$myTest::do()->do()::do()->done();
Test::do()->do()->do()->done();

The output is:

sdd
ddd
sdd
sds
sdd

But it is unbelievable bad style in my eyes...


问:
How to share arrays between 2 php files?
I've this php file (textMessages.php) where I'd like to define some php arrays ...

```<code><?php
  /*
  -----------------
  Language: Italian
  -----------------
  */
  $langIT = array();
  $langIT['LANG__CHOICE'] = 'Seleziona la lingua';
 /*
  -----------------
  Language: English
  -----------------
  */
  $langEN = array();
  $langEN['LANG__CHOICE'] = 'Select the language';
?>
</code>```

In a second php file (myFile.php) I'd like to use the two php array above for example (this code DOES NOT work ...)

```<code><?php
 include("textMessages.php");
 ....
 ....
 ....
     function myFunction($var1, $var2, ...)
    {
     ....
     $langCurrent = array();
     $langCurrent = $langEN;
     .....
    }
?>
</code>```

when  I try to execute I obtain this error ...

```<code>PHP Notice:  Undefined variable: langEN
</code>```

How may I to share the array defined in the first file to using them in the second one?

答:
Your code is correct. To double check I copied it to my local environment. What error do you get? Did you try to print_r($langEN)?

Another common approach is to return the array in "textMessages.php" and then use $langCurrent = include("textMessages.php");

However you should use one file per language then.

Body:
I've this php file (textMessages.php) where I'd like to define some php arrays ...

<?php
  /*
  -----------------
  Language: Italian
  -----------------
  */
  $langIT = array();
  $langIT['LANG__CHOICE'] = 'Seleziona la lingua';
 /*
  -----------------
  Language: English
  -----------------
  */
  $langEN = array();
  $langEN['LANG__CHOICE'] = 'Select the language';
?>

In a second php file (myFile.php) I'd like to use the two php array above for example (this code DOES NOT work ...)

<?php
 include("textMessages.php");
 ....
 ....
 ....
     function myFunction($var1, $var2, ...)
    {
     ....
     $langCurrent = array();
     $langCurrent = $langEN;
     .....
    }
?>

when  I try to execute I obtain this error ...

PHP Notice:  Undefined variable: langEN

How may I to share the array defined in the first file to using them in the second one?


问:
struct default values in c
I came across this problem in C using structs.I'm not sure of what is really happening here
Thanks

```<code>#include<stdio.h>
int main()
{
 struct num1
 {
  int n1:2;
  int n2:3;
  int n3:4;
 };
 struct  num1 num={3,4,5};
 printf("%d %d %d\n",num.n1,num.n2,num.n3);
 return 0;
}
</code>```

The obtained output is

-1 -4 5

答:
These are bit fields, the number after the : specifies how many bits are in that member.

```<code>int n1:2
</code>```

means a signed integer with 2 bits. In two's complement notation, this allows for values from -2 to 1; in sign+magnitude notation it allows for -1 to 1. When you try to assign 3 to this member, you get overflow, which results in undefined behavior.

Similarly

```<code>int n2:3
</code>```

means a signied integer with 3 bits, whose range is -4 to 3 in two's complement, -3 to 3 in sign+magnitude, so assigning 4 causes overflow.

```<code>int n3:4
</code>```

has a range from -8 to 7 or -7 to 7, so assigning 5 fits into it, so there's no overflow.

Title: struct default values in c

Body:
I came across this problem in C using structs.I'm not sure of what is really happening here
Thanks

#include<stdio.h>
int main()
{
 struct num1
 {
  int n1:2;
  int n2:3;
  int n3:4;
 };
 struct  num1 num={3,4,5};
 printf("%d %d %d\n",num.n1,num.n2,num.n3);
 return 0;
}

The obtained output is

-1 -4 5

Body:
These are bit fields, the number after the : specifies how many bits are in that member.

int n1:2

means a signed integer with 2 bits. In two's complement notation, this allows for values from -2 to 1; in sign+magnitude notation it allows for -1 to 1. When you try to assign 3 to this member, you get overflow, which results in undefined behavior.

Similarly

int n2:3

means a signied integer with 3 bits, whose range is -4 to 3 in two's complement, -3 to 3 in sign+magnitude, so assigning 4 causes overflow.

int n3:4

has a range from -8 to 7 or -7 to 7, so assigning 5 fits into it, so there's no overflow.


问:
XPath 2.0: how to select the current node - current() no longer available
In XPath 1.0 there's a function current() that comes in handy when I refer to a node somewhere else in the XML based on the node I'm in at the moment.
My XML has a structure like this:

```<code><root>
    <book>
        <chapter>
            <section>
                <para>
                    <image id="1">1.png</image>
                </para>
            </section>
        </chapter>
    </book>
    <objects>
        <Object>
            <ID>1</ID>
        </Object>
    </objects>
</root>
</code>```

When I process the para nodes in book, I sometimes use XPath expressions like this one to look up information in the objects nodes:

```<code>Object[ID=current()/descendant::image[1]/@id]
</code>```

When I switch my parser to XPath 2.0, this expression gives an error (function current is not available).

I've done some searching, but haven't been able to find a straight replacement for this function. Is there one?

答:
The current() function is defined in XSLT, not in XPath. It's available in XPath expressions within XSLT 1.0, 2.0, and 3.0 stylesheets, but it's not available in free-standing XPath (in any version, except perhaps as a non-conformant extension).

In XPath 2.0 there's a workaround using variables:

```<code>Object[ID=current()/descendant::image[1]/@id]
</code>```

becomes

```<code>for $x in descendant::image[1]/@id return Object[ID=$x]
</code>```

Body:
In XPath 1.0 there's a function current() that comes in handy when I refer to a node somewhere else in the XML based on the node I'm in at the moment.
My XML has a structure like this:

<root>
    <book>
        <chapter>

                <para>
                    <image id="1">1.png</image>
                </para>

        </chapter>
    </book>
    <objects>
        <Object>
            <ID>1</ID>
        </Object>
    </objects>
</root>

When I process the para nodes in book, I sometimes use XPath expressions like this one to look up information in the objects nodes:

Object[ID=current()/descendant::image[1]/@id]

When I switch my parser to XPath 2.0, this expression gives an error (function current is not available).

I've done some searching, but haven't been able to find a straight replacement for this function. Is there one?

Body:
The current() function is defined in XSLT, not in XPath. It's available in XPath expressions within XSLT 1.0, 2.0, and 3.0 stylesheets, but it's not available in free-standing XPath (in any version, except perhaps as a non-conformant extension).

In XPath 2.0 there's a workaround using variables:

Object[ID=current()/descendant::image[1]/@id]

becomes

for $x in descendant::image[1]/@id return Object[ID=$x]


问:
Simplify two filters in Scala
Is there a way to simplify this scala code into a for comprehension?

```<code>val selectedNames = names filter {setOfNames}
val selectedPersons = persons filter {p => seletectedNames contains p.name}
</code>```

Here I'm assuming that persons have a name attribute.

Edit

Of course the value names is obtained as

```<code>val names = persons map _.name
</code>```

答:
I'm not sure this is much of a simplification. It's just doing the same thing via a for comprehension as requested.

```<code>val selectedPersons = for {
  p <- persons
  if setOfNames(p.name)
} yield p
</code>```

Title: Simplify two filters in Scala

Body:
Is there a way to simplify this scala code into a for comprehension?

val selectedNames = names filter {setOfNames}
val selectedPersons = persons filter {p => seletectedNames contains p.name}

Here I'm assuming that persons have a name attribute.

Edit

Of course the value names is obtained as

val names = persons map _.name

Body:
I'm not sure this is much of a simplification. It's just doing the same thing via a for comprehension as requested.

val selectedPersons = for {
  p <- persons
  if setOfNames(p.name)
} yield p


问:
Why can't Excel update some of the links in my workbook
I have a Master workbook in MS Excel that references data in 4 other workbooks.

When it opens I get the following message:

```<code>We can't update some of the links in your workbook right now.
You can continue without updating their values, or edit the links you think are wrong.
[Continue] [Edit Links...]
</code>```

Each referenced workbook contains a N row, 365 column rectangular range that I have named 'DataRange'

My master workbook contains 4 lots of N row, 365 column ranges with Array Formula linked to these named ranges:

```<code>{='C:\Path\[Workbook1Name.xlsx]Sheet'![DataRange]}
</code>```

It feels like i've come across an Excel bug.. Anyone know what I'm doing wrong?

答:
I finally solved this issue after going on a scavenger hunt. In my case, the reference was to an old file that no longer exists, and removing the reference was all that was needed. Unfortunately Excel does not pinpoint where the reference is, so it was a pain to look for the cell that was making the reference.

In my workbook, it was a reference as a part of a Data Validation. For others seeing the same error, I recommend using the Find & Select -> Go To Special feature (Home ribbon tab) then searching by Formula errors and and Data validation.

Body:
I have a Master workbook in MS Excel that references data in 4 other workbooks.

When it opens I get the following message:

We can't update some of the links in your workbook right now.
You can continue without updating their values, or edit the links you think are wrong.
[Continue] [Edit Links...]

Each referenced workbook contains a N row, 365 column rectangular range that I have named 'DataRange'

My master workbook contains 4 lots of N row, 365 column ranges with Array Formula linked to these named ranges:

{='C:\Path\[Workbook1Name.xlsx]Sheet'![DataRange]}

It feels like i've come across an Excel bug.. Anyone know what I'm doing wrong?


问:
setting up routes with navigation menu angular 2
I have a tab menu and i set up my routes in my app.module.ts but i am not sure how to bridge between my tabs and my routes appropriately.

here is my tab html:

```<code><tabs>
    <tab [tabTitle]="'Home Page'">
    </tab>
    <tab tabTitle="Feedback"> </tab>
    <tab tabTitle="Background"> </tab>
    <tab tabTitle="What we do"> </tab>
</tabs>
</code>```

my routes in app.module.ts:

```<code>const appRoutes: Routes = [
  { path: './app/homepage/homepage.component.html', component: AppComponent },
  { path: './app/feedback/feedback.component.html', component: FeedbackComponent },
  { path: './app/background/background.component.html', component: BackgroundComponent },
  { path: './app/whatwedo/whatwedo.component.html', component: WhatwedoComponent}
];
</code>```

What are the steps i need to take to link the tabs with the correct route link.

答:
In your tab yo need to provide link on lcick of which it will show the licked component in the router outlet.

Make sure to add a tag <router-outlet></router-outlet> in your index.html so that routing component will be loaded there

below will be your tab navigation

```<code><tabs>
    <tab [tabTitle]="'Home Page'">
    </tab>
    <tab tabTitle="Feedback"><a [routerLink]="['./app/homepage/homepage.component.html]"
         routerLinkActive="css-class-for-active-link">
        Home
      </a></tab>
    <tab tabTitle="Background"> </tab>
    <tab tabTitle="What we do"> </tab>
</tabs>
</code>```

Then on click of the Home link, it will load the home component inside <router-outlet></router-outlet> tag

Body:
I have a tab menu and i set up my routes in my app.module.ts but i am not sure how to bridge between my tabs and my routes appropriately.

here is my tab html:

<tabs>
    <tab [tabTitle]="'Home Page'">
    </tab>
    <tab tabTitle="Feedback"> </tab>
    <tab tabTitle="Background"> </tab>
    <tab tabTitle="What we do"> </tab>
</tabs>

my routes in app.module.ts:

const appRoutes: Routes = [
  { path: './app/homepage/homepage.component.html', component: AppComponent },
  { path: './app/feedback/feedback.component.html', component: FeedbackComponent },
  { path: './app/background/background.component.html', component: BackgroundComponent },
  { path: './app/whatwedo/whatwedo.component.html', component: WhatwedoComponent}
];

What are the steps i need to take to link the tabs with the correct route link.

Body:
In your tab yo need to provide link on lcick of which it will show the licked component in the router outlet.

Make sure to add a tag <router-outlet></router-outlet> in your index.html so that routing component will be loaded there

below will be your tab navigation

<tabs>
    <tab [tabTitle]="'Home Page'">
    </tab>
    <tab tabTitle="Feedback"><a [routerLink]="['./app/homepage/homepage.component.html]"
         routerLinkActive="css-class-for-active-link">
        Home
      </a></tab>
    <tab tabTitle="Background"> </tab>
    <tab tabTitle="What we do"> </tab>
</tabs>

Then on click of the Home link, it will load the home component inside <router-outlet></router-outlet> tag


问:
Why I can't access remote Jupyter Notebook server?
I have started a Jupyter Notebook server on my centos6.5 server.And jupyter is running like

```<code>[I 17:40:59.649 NotebookApp] Serving notebooks from local directory: /root
[I 17:40:59.649 NotebookApp] 0 active kernels
[I 17:40:59.649 NotebookApp] The Jupyter Notebook is running at:https://[all ip addresses on your system]:8045/
[I 17:40:59.649 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
</code>```

When I want to access Jupyter remotely in the same local area network, say open http://192.168.1.111:8045/, I can't open a Jupyter page at all. By the way, I can access remote centos server successfully.

What's the possible reason?

答: Is that your private IP address? If so you'll need to use your public one. Go to ipchicken to find out what it is. I know you are in the same LAN, but try this to see if it resolves any issues.</p>

Body:
I have started a Jupyter Notebook server on my centos6.5 server.And jupyter is running like

[I 17:40:59.649 NotebookApp] Serving notebooks from local directory: /root
[I 17:40:59.649 NotebookApp] 0 active kernels
[I 17:40:59.649 NotebookApp] The Jupyter Notebook is running at:https://[all ip addresses on your system]:8045/
[I 17:40:59.649 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).

When I want to access Jupyter remotely in the same local area network, say open http://192.168.1.111:8045/, I can't open a Jupyter page at all. By the way, I can access remote centos server successfully.

What's the possible reason?


问:
link to local disk
Is it possible to put a html link on a page that opens a file in local disk?

Like c:/myFolder/myfile.xls

This page is not actually going to be on web, but this feature would be needed for demostration purposes only. When the page is on web, the file is too, and link has url value.

答:
You want to use the file: scheme.

```<code>file://C|/myFolder/myfile.xls
</code>```

Title: link to local disk

Body:
You want to use the file: scheme.

file://C|/myFolder/myfile.xls


问:
Wrong output in mySQL query
I'm relatively new to mySQL and phpMyAdmin and I am having problems with a query I am trying to put in. I want the "Units Sold" to be a number, but the whole column prints out "Units Sold" for some reason. I already tried removing both "Units Sold" and i've tried removing just one, but I am not sure what is going wrong here. Sorry if I am not clear enough, but here is my query:

```<code>SELECT brand_name, brand_type, Round(avgprice,2) AS "Average Price", "Units Sold"
FROM lgbrand b JOIN (SELECT brand_id, Avg(prod_price) AS avgprice
            FROM lgproduct
            GROUP BY brand_id) sub1
ON b.brand_id = sub1.brand_id
    JOIN (SELECT brand_id, Sum(line_qty) AS "Units Sold"
    FROM lgproduct p JOIN lgline l ON p.prod_sku = l.prod_sku
GROUP BY brand_id) sub2
    ON b.brand_id = sub2.brand_id
ORDER BY brand_name;
</code>```

And here is a picture to go along with what the output looks like:

答:
if you want to keep the space in the name of you column use :

```<code>  SELECT brand_name, brand_type, Round(avgprice,2) AS "Average Price", `Units Sold`
FROM lgbrand b JOIN (SELECT brand_id, Avg(prod_price) AS avgprice
            FROM lgproduct
            GROUP BY brand_id) sub1
ON b.brand_id = sub1.brand_id
    JOIN (SELECT brand_id, Sum(line_qty) AS "Units Sold"
    FROM lgproduct p JOIN lgline l ON p.prod_sku = l.prod_sku
GROUP BY brand_id) sub2
    ON b.brand_id = sub2.brand_id
ORDER BY brand_name;
</code>```

in postgres and Oracle you can do "fieldname" by in Mysql use

Title: Wrong output in mySQL query

Body:
I'm relatively new to mySQL and phpMyAdmin and I am having problems with a query I am trying to put in. I want the "Units Sold" to be a number, but the whole column prints out "Units Sold" for some reason. I already tried removing both "Units Sold" and i've tried removing just one, but I am not sure what is going wrong here. Sorry if I am not clear enough, but here is my query:

SELECT brand_name, brand_type, Round(avgprice,2) AS "Average Price", "Units Sold"
FROM lgbrand b JOIN (SELECT brand_id, Avg(prod_price) AS avgprice
            FROM lgproduct
            GROUP BY brand_id) sub1
ON b.brand_id = sub1.brand_id
    JOIN (SELECT brand_id, Sum(line_qty) AS "Units Sold"
    FROM lgproduct p JOIN lgline l ON p.prod_sku = l.prod_sku
GROUP BY brand_id) sub2
    ON b.brand_id = sub2.brand_id
ORDER BY brand_name;

And here is a picture to go along with what the output looks like:

Body:
if you want to keep the space in the name of you column use :

  SELECT brand_name, brand_type, Round(avgprice,2) AS "Average Price", `Units Sold`
FROM lgbrand b JOIN (SELECT brand_id, Avg(prod_price) AS avgprice
            FROM lgproduct
            GROUP BY brand_id) sub1
ON b.brand_id = sub1.brand_id
    JOIN (SELECT brand_id, Sum(line_qty) AS "Units Sold"
    FROM lgproduct p JOIN lgline l ON p.prod_sku = l.prod_sku
GROUP BY brand_id) sub2
    ON b.brand_id = sub2.brand_id
ORDER BY brand_name;

in postgres and Oracle you can do "fieldname" by in Mysql use


答:
How about </p>

```<code>val selectedPersons = persons filter { person => setOfNames contains person.name }
</code>```

Title: Simplify two filters in Scala

Body:
How about

val selectedPersons = persons filter { person => setOfNames contains person.name }