问:
.NET Core and Swagger API generation
I am creating a barebones .NET Core web api project (Started from blank template below)
https://andrewlock.net/removing-the-mvc-razor-dependencies-from-the-web-api-template-in-asp-net-core/

The code below was working fine, untill I added Swashbuckle.AspNetCore (Along with the configuration code below), now we get this error

InvalidOperationException: No service for type 'Microsoft.AspNetCore.Mvc.ApiExplorer.IApiDescriptionGroupCollectionProvider' has been registered.

Any ideas?

Please note: We are not using "builder.AppMvc()" as we are trying to slim this api down as much as possible.

```<code>public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        var builder = services.AddMvcCore();

        builder.AddAuthorization();
        builder.AddFormatterMappings();
        builder.AddJsonFormatters();
        builder.AddCors();

        // Register the Swagger generator, defining one or more Swagger documents
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();

        if (env.IsDevelopment())
            app.UseDeveloperExceptionPage();

        app.UseMvc();

        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        });
    }
}

[Route("api/[controller]")]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    public IActionResult Get()
    {
        return Ok(new[] {"value1", "value2"});
    }
}
</code>```

答:
Solution: Use AddMvc() instead of AddMvcCore() in Startup.cs and it will work.

or write:

```<code>services.AddMvcCore().AddApiExplorer();
</code>```

These links can help:

No service for type 'Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionaryFactory' has been registered

https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/299

Title: .NET Core and Swagger API generation

Body:
I am creating a barebones .NET Core web api project (Started from blank template below)
https://andrewlock.net/removing-the-mvc-razor-dependencies-from-the-web-api-template-in-asp-net-core/

The code below was working fine, untill I added Swashbuckle.AspNetCore (Along with the configuration code below), now we get this error

InvalidOperationException: No service for type 'Microsoft.AspNetCore.Mvc.ApiExplorer.IApiDescriptionGroupCollectionProvider' has been registered.

Any ideas?

Please note: We are not using "builder.AppMvc()" as we are trying to slim this api down as much as possible.

public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        var builder = services.AddMvcCore();

        builder.AddAuthorization();
        builder.AddFormatterMappings();
        builder.AddJsonFormatters();
        builder.AddCors();

        // Register the Swagger generator, defining one or more Swagger documents
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();

        if (env.IsDevelopment())
            app.UseDeveloperExceptionPage();

        app.UseMvc();

        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        });
    }
}

[Route("api/[controller]")]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    public IActionResult Get()
    {
        return Ok(new[] {"value1", "value2"});
    }
}

Body:
Solution: Use AddMvc() instead of AddMvcCore() in Startup.cs and it will work.

or write:

services.AddMvcCore().AddApiExplorer();

These links can help:

No service for type 'Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionaryFactory' has been registered

https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/299


来源: stackexchange

问:
Forcing the Qt GUI to update
I am coding a boardgame in Qt where, after the player makes a move, the computer AI must pause and think for some time. However, while it is thinking, it seems the screen will not be updated until every line of code has been executed. Thus, the user would click on a square, see nothing happen for a few seconds, and then suddenly see the result of both his move and the computer's move.

In an attempt to fix this, I tried creating a new thread on which the AI runs its code, and then places its piece on the board. However, sometimes (and this is very inconsistent) the game crashes after the computer has made a move.

So can you guys either:

Tell me how force the MainWindow to update its contents

Help me try to debug the crashing problem (I'm totally new to threads)

EDIT--I tried setting breakpoints as suszterpatt suggested, and the program seems to crash consistently in the debugger (it wasn't before I set the breakpoints).

Anyways, as I step through the program, it seems to go through the run function fine, until it reaches the ending bracket, and then if I step through it jumps into line 317 on qthread_win.cpp, which just says

```<code>finish(arg); //line 317
return 0;
</code>```

If I step through that line, the debugger freezes up and Qt alerts me after 20 seconds. If I continue, I get the "This application has requested the Runtime to terminate it in an unusual way" message that I get when the program occasionally crashes when I'm not debugging.

What should I do now?

答:
The cause of the crash can be a variety of reasons but if I had to take a guess I'd say you're probably calling methods of a GUI object (label, textbox, your game board, etc.) from the AI thread.

The way threads communicate with one another in Qt is through a mechanism called signals and slots: the AI thread should expose a set of signals, i.e. 'beginThink', 'endThink', and the UI thread should register to those signals (with slots) and react accordingly. This is documented pretty throughly in the docs.

ContentLicense: CC BY-SA 2.5

Title: Forcing the Qt GUI to update

Body:
I am coding a boardgame in Qt where, after the player makes a move, the computer AI must pause and think for some time. However, while it is thinking, it seems the screen will not be updated until every line of code has been executed. Thus, the user would click on a square, see nothing happen for a few seconds, and then suddenly see the result of both his move and the computer's move.

In an attempt to fix this, I tried creating a new thread on which the AI runs its code, and then places its piece on the board. However, sometimes (and this is very inconsistent) the game crashes after the computer has made a move.

So can you guys either:

Tell me how force the MainWindow to update its contents

Help me try to debug the crashing problem (I'm totally new to threads)

EDIT--I tried setting breakpoints as suszterpatt suggested, and the program seems to crash consistently in the debugger (it wasn't before I set the breakpoints).

Anyways, as I step through the program, it seems to go through the run function fine, until it reaches the ending bracket, and then if I step through it jumps into line 317 on qthread_win.cpp, which just says

finish(arg); //line 317
return 0;

If I step through that line, the debugger freezes up and Qt alerts me after 20 seconds. If I continue, I get the "This application has requested the Runtime to terminate it in an unusual way" message that I get when the program occasionally crashes when I'm not debugging.

What should I do now?


问:
Way to reduce size of .ttf fonts?
Is there any way to reduce the size of the .ttf fonts? i.e. if we want to remove some glyps which we are not using.</p>

答:
I did the following to remove all Cyrillic glyphs (letters) from a font, hence cutting file size in half as I only needed the Latin letters.

get FontForge (https://fontforge.github.io/en-US/)

start FontForge and open your ttf font file

go to Edit -> Select -> Select By Script

on the pop up selection window chose Cyrillic from the drop down menu. As you might have guessed this will mark only the Cyrillic letters.

go to Encoding -> Detach & Remove Glyphs, confirm the question. See how the Cyrillic letters disappear?

go to Encoding -> Compact to get a better overview of the remaining letters which makes it easier to select more deleting candidates. (But I did not dare to manually delete/remove them.)

go to File -> Generate Fonts and don't forget to chose ttf as output format.

Please consider that I am not a pro in this. But I needed a fast solution.

Here you can read more on this topic: http://wiki.unity3d.com/index.php?title=Create_a_new_TrueType_font_using_a_subset_of_characters_from_an_existing_TrueType_font

Title: Way to reduce size of .ttf fonts?

ContentLicense: CC BY-SA 3.0


问:
How to associate two joining models in ActiveRecord?
Lets assume we have 2 AR models:

```<code>class User < ApplicationRecord
  has_many :proposals
  has_many :concerns
end

class Job < ApplicationRecord
  has_many :proposals
  has_many :concerns
end
</code>```

Proposal and Concern are both joining models between User and Job:

```<code>class Proposal < ApplicationRecord
  belongs_to :user
  belongs_to :job
end

class Concern < ApplicationRecord
  belongs_to :user
  belongs_to :job
end
</code>```

What I am trying to solve is how to associate proposals and concerns through both user and job. I.e. I want use eager loading etc:

```<code>proposals.preload(:concerns).map do |proposal|
  # proposal.concerns are preloaded here
  # and all concerns have same user and job
end
</code>```

My current solution is just simple concerns method which lookup over concerns - it's ineffective because do N + 1 queries.

I want to avoid adding redundant foreign key to one of joining models.

答:
This should avoid N+1 queries</p>

```<code>Proposal.includes(user: :concerns).where(condition: 123)
</code>```

Body:
Lets assume we have 2 AR models:

class User < ApplicationRecord
  has_many :proposals
  has_many :concerns
end

class Job < ApplicationRecord
  has_many :proposals
  has_many :concerns
end

Proposal and Concern are both joining models between User and Job:

class Proposal < ApplicationRecord
  belongs_to :user
  belongs_to :job
end

class Concern < ApplicationRecord
  belongs_to :user
  belongs_to :job
end

What I am trying to solve is how to associate proposals and concerns through both user and job. I.e. I want use eager loading etc:

proposals.preload(:concerns).map do |proposal|
  # proposal.concerns are preloaded here
  # and all concerns have same user and job
end

My current solution is just simple concerns method which lookup over concerns - it's ineffective because do N + 1 queries.

I want to avoid adding redundant foreign key to one of joining models.

Body:
This should avoid N+1 queries

Proposal.includes(user: :concerns).where(condition: 123)


问:
How to use methods to set a property in the default constructor in F#
I am trying to write a constructor that suppose to call method defined in the class and assign result to the member. In C# it would be something like:

```<code>public class Test
{
    public int Value { get; private set;}

    private static int SomeLogic(int a, int b)
    {
        return a + b;
    }

    public Test(int a, int b)
    {
        this.Value = SomeLogic(a,b);
    }
}
</code>```

But I have no idea how to do that it F#.

答:
You can use as binding at the beginning of the constructor:

```<code>type SomeClass() as this =

    do printfn this.Member1

    member this.Member1 = "s"
</code>```

You may call it whatever you like: x, etc. but I think using just this makes sense here.

You can read more about Self Identifiers here: https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/classes

EDIT: If you need to initialize any private fields of the type, you can define function in the constructor, use it in the initialization and then expose it as public member:

```<code>let func x = ...
let field = func 0
member this.Method(x) = func x
</code>```

Body:
I am trying to write a constructor that suppose to call method defined in the class and assign result to the member. In C# it would be something like:

public class Test
{
    public int Value { get; private set;}

    private static int SomeLogic(int a, int b)
    {
        return a + b;
    }

    public Test(int a, int b)
    {
        this.Value = SomeLogic(a,b);
    }
}

But I have no idea how to do that it F#.

Body:
You can use as binding at the beginning of the constructor:

type SomeClass() as this =

    do printfn this.Member1

    member this.Member1 = "s"

You may call it whatever you like: x, etc. but I think using just this makes sense here.

You can read more about Self Identifiers here: https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/classes

EDIT: If you need to initialize any private fields of the type, you can define function in the constructor, use it in the initialization and then expose it as public member:

let func x = ...
let field = func 0
member this.Method(x) = func x


问:
Looking at Sorts - Quicksort Iterative?
I'm looking at all different sorts. Note that this is not homework (I'm in the midst of finals) I'm just looking to be prepared if that sort of thing would pop up.
I was unable to find a reliable method of doing a quicksort iteratively. Is it possible and, if so, how?</p>

答:
```<code> I was unable to find a reliable method of doing a quicksort iteratively
</code>```

Have you tried google ?

It is just common quicksort, when recursion is realized with array.

Title: Looking at Sorts - Quicksort Iterative?

Body:
 I was unable to find a reliable method of doing a quicksort iteratively

Have you tried google ?

It is just common quicksort, when recursion is realized with array.


问:
How to pass a variable value to another server using ssh
```<code>#!/bin/ksh

CTN=1
ssh -q user@host 'exec bash -s' << 'ENDSSH'
cd abc/def
./scriptname \$CTN
ENDSSH

exit;
</code>```

However in the remote server, value of variable CTN is not getting passed.
Please help.

答:
It should be:

```<code>CTN=1
ssh -q user@host 'exec bash -s' << ENDSSH
cd abc/def
./scriptname "$CTN"
ENDSSH
</code>```

Since you want $CTN to expanded locally you must not escape the $ and must not put ENDSSH between single quotes.

Body:
#!/bin/ksh

CTN=1
ssh -q user@host 'exec bash -s' << 'ENDSSH'
cd abc/def
./scriptname \$CTN
ENDSSH

exit;

However in the remote server, value of variable CTN is not getting passed.
Please help.

Body:
It should be:

CTN=1
ssh -q user@host 'exec bash -s' << ENDSSH
cd abc/def
./scriptname "$CTN"
ENDSSH

Since you want $CTN to expanded locally you must not escape the $ and must not put ENDSSH between single quotes.


问:
three.js memory management shader material
I'm trying to create textual labels. I need to use shader material to better control the label during rendering.

I've noticed that the memory keeps increasing even though I clean up old labels.

I've created a jsfiddle example that is not unlike: https://threejs.org/examples/#webgl_test_memory

The following code uses a canvas object to generate a texture, which contains the text to be depicted as a label:

Please be careful, these computations are heavy and make the tab quite unresponsive.

var container;

var camera, scene, renderer;

var labels;

var canvas;

init();
animate();

function init() {

  container = document.createElement( 'div' );
  document.body.appendChild( container );

  camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 10000 );
  camera.position.z = 200;

  scene = new THREE.Scene();

  renderer = new THREE.WebGLRenderer();
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );
  container.appendChild( renderer.domElement );

  labels = new THREE.Object3D();

  canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');

  // get text metrics
  var fontface = 'Arial';
  var fontSize = 60;
  context.font = fontSize + "px " + fontface;

  var width = context.measureText(text).width;

  // add text
  var text = 'abcdef';
  canvas.width = width;
  canvas.height = fontSize*1.3;
  context.textAlign = "center";
  context.font = fontSize + "px " + fontface;
  context.fillStyle = "white";
  context.fillText(text, canvas.width / 2, canvas.height / 2);
}

function createLabels() {
  for(var i = 0; i < 10000 ; i++) {
    createTextMesh();
  }

  scene.add( labels );
}

function createTextMesh() {
  // canvas contents will be used for a texture
  var texture = new THREE.Texture(canvas);
  texture.needsUpdate = true;

  var uniforms = {
    text: {
      type: 't',
      value: texture
    }
  };

  var material = new THREE.ShaderMaterial( {
    uniforms: uniforms,
    vertexShader: document.getElementById( 'vertex-shader' ).textContent,
    fragmentShader: document.getElementById( 'fragment-shader' ).textContent
  } );

  var geometry = new THREE.PlaneBufferGeometry(15, 15);

  var label = new THREE.Mesh( geometry, material );

  labels.add(label);
}

function clearLabels() {
  for(var i = 0; i < labels.children.length; i++) {
    var label = labels.children[i];

    if(label.material.uniforms) {
      label.material.uniforms.text.value.dispose();
    }
    label.material.dispose();
    label.geometry.dispose();

    labels.remove(label);
  }

  scene.remove( labels );
}

function animate() {
  requestAnimationFrame( animate );
  render();
}

function render() {
  // build GL objects
  createLabels();

  renderer.render( scene, camera );

  // clean up
  clearLabels();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin:0;
}</code>```

<canvas></canvas>```

You can use's chromes dev tools to evaluate the perceptual memory utilisation increase.

I'd recommend using something like Window's own task manager to see the memory increase.

You can decrease the label creation speed, although this will naturally mean that it will take longer for the tab do run out of memory.

Am I doing the resource clean-up wrongly?

Cheers

答:
Don't create a new mesh 1000 times every tick, pool them.
Don't create a 1000 geometries that are all the same plane. This is probably the biggest culprit here. Create just one, ever, and pass it to meshes.
Textures, im not so sure about that one. I think you're not supposed to create a new texture from the canvas context, create once and update canvas.

This will go away with the changes, but it's good to note that for performance you'd want to avoid creating that uniforms object in the loop as well.

EDIT

You do create a lot of stuff. Width of the label comes in as 263, and if three's console log is to be trusted, it's resized to 256x64. So you end up with 480mb of data, although, with the alpha channel it could be 600mb. I assume that your demo never even gets to the disposal part. It just crashed the browser on my end.

Three also complains about the textures being NPOT, so it attempts to write out ten thousand console logs.

Body:
I'm trying to create textual labels. I need to use shader material to better control the label during rendering.

I've noticed that the memory keeps increasing even though I clean up old labels.

I've created a jsfiddle example that is not unlike: https://threejs.org/examples/#webgl_test_memory

The following code uses a canvas object to generate a texture, which contains the text to be depicted as a label:

Please be careful, these computations are heavy and make the tab quite unresponsive.

var container;

var camera, scene, renderer;

var labels;

var canvas;

init();
animate();

function init() {

  container = document.createElement( 'div' );
  document.body.appendChild( container );

  camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 10000 );
  camera.position.z = 200;

  scene = new THREE.Scene();

  renderer = new THREE.WebGLRenderer();
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );
  container.appendChild( renderer.domElement );

  labels = new THREE.Object3D();

  canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');

  // get text metrics
  var fontface = 'Arial';
  var fontSize = 60;
  context.font = fontSize + "px " + fontface;

  var width = context.measureText(text).width;

  // add text
  var text = 'abcdef';
  canvas.width = width;
  canvas.height = fontSize*1.3;
  context.textAlign = "center";
  context.font = fontSize + "px " + fontface;
  context.fillStyle = "white";
  context.fillText(text, canvas.width / 2, canvas.height / 2);
}

function createLabels() {
  for(var i = 0; i < 10000 ; i++) {
    createTextMesh();
  }

  scene.add( labels );
}

function createTextMesh() {
  // canvas contents will be used for a texture
  var texture = new THREE.Texture(canvas);
  texture.needsUpdate = true;

  var uniforms = {
    text: {
      type: 't',
      value: texture
    }
  };

  var material = new THREE.ShaderMaterial( {
    uniforms: uniforms,
    vertexShader: document.getElementById( 'vertex-shader' ).textContent,
    fragmentShader: document.getElementById( 'fragment-shader' ).textContent
  } );

  var geometry = new THREE.PlaneBufferGeometry(15, 15);

  var label = new THREE.Mesh( geometry, material );

  labels.add(label);
}

function clearLabels() {
  for(var i = 0; i < labels.children.length; i++) {
    var label = labels.children[i];

    if(label.material.uniforms) {
      label.material.uniforms.text.value.dispose();
    }
    label.material.dispose();
    label.geometry.dispose();

    labels.remove(label);
  }

  scene.remove( labels );
}

function animate() {
  requestAnimationFrame( animate );
  render();
}

function render() {
  // build GL objects
  createLabels();

  renderer.render( scene, camera );

  // clean up
  clearLabels();
}

body {
  margin:0;
}

<canvas></canvas>

You can use's chromes dev tools to evaluate the perceptual memory utilisation increase.

I'd recommend using something like Window's own task manager to see the memory increase.

You can decrease the label creation speed, although this will naturally mean that it will take longer for the tab do run out of memory.

Am I doing the resource clean-up wrongly?

Cheers


问:
H2OServerError: HTTP 500 Server Error: Server error water.util.DistributedException:
I am having trouble loading in a data set to h2o. I keep getting the same H2o server error when I was able to run this same code without issue yesterday.

```<code>import h2o
h2o.init()

h2o.import_file('train_csv')
</code>```

The train_csv is in the same directory and the is saved in the lines above from a spark dataframe. I continue to get the same error:

```<code>H2OServerError                            Traceback (most recent call last)
<ipython-input-3-d9a5a8533622> in <module>()
----> 1 h2o.import_file('train_csv')

/home/.local/lib/python3.5/site-packages/h2o/h2o.py in import_file(path,
destination_frame, parse, header, sep, col_names, col_types, na_strings,
pattern)
    405         return lazy_import(path, pattern)
    406     else:
--> 407         return H2OFrame()._import_parse(path, pattern,
destination_frame, header, sep, col_names, col_types, na_strings)
    408
    409

/home/.local/lib/python3.5/site-packages/h2o/frame.py in _import_parse(self,
path, pattern, destination_frame, header, separator, column_names,
column_types, na_strings)
    306             path = os.path.abspath(path)
    307         rawkey = h2o.lazy_import(path, pattern)
--> 308         self._parse(rawkey, destination_frame, header, separator,
column_names, column_types, na_strings)
    309         return self
    310

/home/.local/lib/python3.5/site-packages/h2o/frame.py in _parse(self,
rawkey, destination_frame, header, separator, column_names, column_types,
na_strings)
    319     def _parse(self, rawkey, destination_frame="", header=None,
separator=None, column_names=None, column_types=None,
    320                na_strings=None):
--> 321         setup = h2o.parse_setup(rawkey, destination_frame, header,
separator, column_names, column_types, na_strings)
    322         return self._parse_raw(setup)
    323

/home/.local/lib/python3.5/site-packages/h2o/h2o.py in
parse_setup(raw_frames, destination_frame, header, separator, column_names,
column_types, na_strings)
    550         kwargs["separator"] = ord(separator)
    551
--> 552     j = api("POST /3/ParseSetup", data=kwargs)
    553     if "warnings" in j and j["warnings"]:
    554         for w in j["warnings"]:

/home/.local/lib/python3.5/site-packages/h2o/h2o.py in api(endpoint, data,
json, filename, save_to)
     97     # type checks are performed in H2OConnection class
     98     _check_connection()
---> 99     return h2oconn.request(endpoint, data=data, json=json,
filename=filename, save_to=save_to)
    100
    101

/home/.local/lib/python3.5/site-packages/h2o/backend/connection.py in
request(self, endpoint, data, json, filename, save_to)
   400                                     auth=self._auth,
verify=self._verify_ssl_cert, proxies=self._proxies)
    401             self._log_end_transaction(start_time, resp)
--> 402             return self._process_response(resp, save_to)
    403
    404         except (requests.exceptions.ConnectionError,
requests.exceptions.HTTPError) as e:

/home/.local/lib/python3.5/site-packages/h2o/backend/connection.py in
_process_response(response, save_to)
    728         # Note that it is possible to receive valid H2OErrorV3
object in this case, however it merely means the server
    729         # did not provide the correct status code.
--> 730         raise H2OServerError("HTTP %d %s:\n%r" % (status_code,
response.reason, data))
    731
    732

H2OServerError: HTTP 500 Server Error:
Server error water.util.DistributedException:
  Error: DistributedException from /127.0.0.1:54321
  Request: None
</code>```

答: Thank you for your help. It turns out my error was coming from the fact that my train_csv was empty due to a variable that I hadn't changed above. It is back to working.</p>

Body:
I am having trouble loading in a data set to h2o. I keep getting the same H2o server error when I was able to run this same code without issue yesterday.

import h2o
h2o.init()

h2o.import_file('train_csv')

The train_csv is in the same directory and the is saved in the lines above from a spark dataframe. I continue to get the same error:

H2OServerError                            Traceback (most recent call last)
<ipython-input-3-d9a5a8533622> in <module>()
----> 1 h2o.import_file('train_csv')

/home/.local/lib/python3.5/site-packages/h2o/h2o.py in import_file(path,
destination_frame, parse, header, sep, col_names, col_types, na_strings,
pattern)
    405         return lazy_import(path, pattern)
    406     else:
--> 407         return H2OFrame()._import_parse(path, pattern,
destination_frame, header, sep, col_names, col_types, na_strings)
    408
    409

/home/.local/lib/python3.5/site-packages/h2o/frame.py in _import_parse(self,
path, pattern, destination_frame, header, separator, column_names,
column_types, na_strings)
    306             path = os.path.abspath(path)
    307         rawkey = h2o.lazy_import(path, pattern)
--> 308         self._parse(rawkey, destination_frame, header, separator,
column_names, column_types, na_strings)
    309         return self
    310

/home/.local/lib/python3.5/site-packages/h2o/frame.py in _parse(self,
rawkey, destination_frame, header, separator, column_names, column_types,
na_strings)
    319     def _parse(self, rawkey, destination_frame="", header=None,
separator=None, column_names=None, column_types=None,
    320                na_strings=None):
--> 321         setup = h2o.parse_setup(rawkey, destination_frame, header,
separator, column_names, column_types, na_strings)
    322         return self._parse_raw(setup)
    323

/home/.local/lib/python3.5/site-packages/h2o/h2o.py in
parse_setup(raw_frames, destination_frame, header, separator, column_names,
column_types, na_strings)
    550         kwargs["separator"] = ord(separator)
    551
--> 552     j = api("POST /3/ParseSetup", data=kwargs)
    553     if "warnings" in j and j["warnings"]:
    554         for w in j["warnings"]:

/home/.local/lib/python3.5/site-packages/h2o/h2o.py in api(endpoint, data,
json, filename, save_to)
     97     # type checks are performed in H2OConnection class
     98     _check_connection()
---> 99     return h2oconn.request(endpoint, data=data, json=json,
filename=filename, save_to=save_to)
    100
    101

/home/.local/lib/python3.5/site-packages/h2o/backend/connection.py in
request(self, endpoint, data, json, filename, save_to)
   400                                     auth=self._auth,
verify=self._verify_ssl_cert, proxies=self._proxies)
    401             self._log_end_transaction(start_time, resp)
--> 402             return self._process_response(resp, save_to)
    403
    404         except (requests.exceptions.ConnectionError,
requests.exceptions.HTTPError) as e:

/home/.local/lib/python3.5/site-packages/h2o/backend/connection.py in
_process_response(response, save_to)
    728         # Note that it is possible to receive valid H2OErrorV3
object in this case, however it merely means the server
    729         # did not provide the correct status code.
--> 730         raise H2OServerError("HTTP %d %s:\n%r" % (status_code,
response.reason, data))
    731
    732

H2OServerError: HTTP 500 Server Error:
Server error water.util.DistributedException:
  Error: DistributedException from /127.0.0.1:54321
  Request: None


问:
Is there a method like JavaScript's substr in Rust?
I looked at the Rust docs for String but I can't find a way to extract a substring.

Is there a method like JavaScript's substr in Rust? If not, how would you implement it?

```<code>str.substr(start[, length])
</code>```

The closest is probably slice_unchecked but it uses byte offsets instead of character indexes and is marked unsafe.

答:
For my_string.substring(start, len)-like syntax, you can write a custom trait:

```<code>trait StringUtils {
    fn substring(&self, start: usize, len: usize) -> Self;
}

impl StringUtils for String {
    fn substring(&self, start: usize, len: usize) -> Self {
        self.chars().skip(start).take(len).collect()
    }
}

// Usage:
fn main() {
    let phrase: String = "this is a string".to_string();
    println!("{}", phrase.substring(5, 8)); // prints "is a str"
}
</code>```

Body:
I looked at the Rust docs for String but I can't find a way to extract a substring.

Is there a method like JavaScript's substr in Rust? If not, how would you implement it?

str.substr(start[, length])

The closest is probably slice_unchecked but it uses byte offsets instead of character indexes and is marked unsafe.

Body:
For my_string.substring(start, len)-like syntax, you can write a custom trait:

trait StringUtils {
    fn substring(&self, start: usize, len: usize) -> Self;
}

impl StringUtils for String {
    fn substring(&self, start: usize, len: usize) -> Self {
        self.chars().skip(start).take(len).collect()
    }
}

// Usage:
fn main() {
    let phrase: String = "this is a string".to_string();
    println!("{}", phrase.substring(5, 8)); // prints "is a str"
}


问:
Try-Catch with fluent expressions
This LINQ query expression fails with Win32Exception "Access is denied":

```<code>Process.GetProcesses().Select(p => p.MainModule.FileName)
</code>```

And this fails with IOException "The device is not ready":

```<code>DriveInfo.GetDrives().Select(d => d.VolumeLabel)
</code>```

What is the best way to filter out inaccessible objects and avoid exceptions?

答:
I would try for the first scenario:

```<code>//Declare logger type
private readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

Process.GetProcesses()
.Where(p => {
    try {
        var x = p.MainModule;
        return true;
    }
    catch(Win32Exception e2)
    { IgnoreError(); }
    })
.Select(p => p.MainModule.FileName)

public static void IgnoreError(Exception e)
{
    #if DEBUG
    throw e2;
    //Save the error track, I prefer log4net
    _log.Info("Something bad happened!");
    #end if
}
</code>```

And for the second scenario, I'd rather prefer to use an IF and save the log:

```<code>//Somewhere in the begging of your class, in a place whose name I do not care to remember ...
//Declare logger type
private readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

public List<string> VolumenLabels()
{
    //Return the List<T>
    List<string> myVolumeLabels = new List<string>();
    //Getting the info
    DriveInfo[] allDrives = DriveInfo.GetDrives();

    foreach(DriveInfo drive in allDrives)
    {
        if (drive.IsReady == true)
        {
            myVolumeLabels.Add(drive.VolumeLabel.ToString());
        }
        else
        {
            _log.Info("Check the Drive: " + drive.Name + " the device is not ready.");
        }
    }
    return myVolumeLabels;
}
</code>```

I hope, I helped a little bit... Have a nice day!

Title: Try-Catch with fluent expressions

Body:
This LINQ query expression fails with Win32Exception "Access is denied":

Process.GetProcesses().Select(p => p.MainModule.FileName)

And this fails with IOException "The device is not ready":

DriveInfo.GetDrives().Select(d => d.VolumeLabel)

What is the best way to filter out inaccessible objects and avoid exceptions?

Body:
I would try for the first scenario:

//Declare logger type
private readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

Process.GetProcesses()
.Where(p => {
    try {
        var x = p.MainModule;
        return true;
    }
    catch(Win32Exception e2)
    { IgnoreError(); }
    })
.Select(p => p.MainModule.FileName)

public static void IgnoreError(Exception e)
{
    #if DEBUG
    throw e2;
    //Save the error track, I prefer log4net
    _log.Info("Something bad happened!");
    #end if
}

And for the second scenario, I'd rather prefer to use an IF and save the log:

//Somewhere in the begging of your class, in a place whose name I do not care to remember ...
//Declare logger type
private readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

public List<string> VolumenLabels()
{
    //Return the List<T>
    List<string> myVolumeLabels = new List<string>();
    //Getting the info
    DriveInfo[] allDrives = DriveInfo.GetDrives();

    foreach(DriveInfo drive in allDrives)
    {
        if (drive.IsReady == true)
        {
            myVolumeLabels.Add(drive.VolumeLabel.ToString());
        }
        else
        {
            _log.Info("Check the Drive: " + drive.Name + " the device is not ready.");
        }
    }
    return myVolumeLabels;
}

I hope, I helped a little bit... Have a nice day!


问:
How to Escape Double Quotes from Ruby Page Object text
In using the Page Object gem, I'm trying to pull text from a page to verify error messages. One of these error messages contains double-quotes, but when the page object pulls the text from the page, it pulls some other characters.

```<code>expected ["Please select a category other than the Default â?oEMSâ?? before saving."]
to include "Please select a category other than the Default \"EMS\" before saving."
(RSpec::Expectations::ExpectationNotMetError)
</code>```

I'm not quite sure how to escape these - I'm not sure where I could use Regexs and be able to escape these odd characters.

答:
Honestly you are over complicating your validation.

I would recommend simplifying what you are trying to do, start by asking yourself: Is the part in quotes a critical part of your validation?

If it is, isolate it by doing a String.contains("EMS")

If it is not, then you are probably doing too much work, only check for exactly what you need in validation:

String.beginsWith("Please select a category other than the Default")

With respect to the actual issue you are having, on a technical level you have an encoding issue. Encode your result string with utf-8 before you pass it to your validation and you will be fine.

Good luck

Body:
In using the Page Object gem, I'm trying to pull text from a page to verify error messages. One of these error messages contains double-quotes, but when the page object pulls the text from the page, it pulls some other characters.

expected ["Please select a category other than the Default â?oEMSâ?? before saving."]
to include "Please select a category other than the Default \"EMS\" before saving."
(RSpec::Expectations::ExpectationNotMetError)

I'm not quite sure how to escape these - I'm not sure where I could use Regexs and be able to escape these odd characters.


问:
Android - Delete item from custom ListView
Does anyone know how to delete an item from a custom ListView? I'm currently working on an Android bar code scanner that stores a scanned item name into an inventory, together with its price. I also want it to be removed when the user clicks on it (but it doesn't works).

This is my code, which might seem messy because I'm still a beginner in Android.

XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="in.aurora.android_barcode_scanner.Inventory"
    android:focusableInTouchMode="false"
    android:clickable="false"
    android:focusable="false">

    <ListView
        android:id="@+id/listView"
        android:layout_width="365dp"
        android:layout_height="495dp"
        tools:layout_editor_absoluteX="10dp"
        tools:layout_editor_absoluteY="8dp"
        android:focusableInTouchMode="false"
        android:clickable="false"
        android:focusable="false"/>
</android.support.constraint.ConstraintLayout>
</code>```

Implementation:

```<code>public void display() {
    ShoppingListAdapter adapter = new ShoppingListAdapter(this,
        R.layout.adapter_view_layout, shoppingList);
    lv = (ListView) findViewById(R.id.listView);

    lv.setAdapter(adapter);
}

@Override
public void onItemClick(AdapterView parent, View view, final int position, long id) {

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Remove this item?");
    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            shoppingList.remove(position);

            display();
        }
    });
    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });
    builder.show();
}
</code>```

Adapter:

```<code>public class ShoppingListAdapter extends ArrayAdapter<Product> {

    private static final String TAG = "ShoppingListAdapter";

    private Context mContext;
    int mResource;

    public ShoppingListAdapter(Context context, int resource, ArrayList<Product> objects)
    {
        super(context, resource, objects);
        mContext = context;
        mResource = resource;
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        String name = getItem(position).getName();
        double price = getItem(position).getPrice();
        String convertPrice = Double.toString(price);

        Product product = new Product(name, price);

        LayoutInflater inflater  = LayoutInflater.from(mContext);
        convertView = inflater.inflate(mResource, parent, false);

        TextView productName = (TextView)
        convertView.findViewById(R.id.textView1);
        TextView productPrice = (TextView)
        convertView.findViewById(R.id.textView2);

        productName.setText(name);
        productPrice.setText(convertPrice);

        return convertView;
    }

}
</code>```

答:
Put this method in your adapter:

```<code>public void remove(Product product) {
    objects.remove(product);
    notifyDataSetChanged();
}
</code>```

Then call it like this:

```<code>Product product = shoppingList.get(position);
adapter.remove(product);
adapter.notifyDataSetChanged();
</code>```

Also make sure your adapter class has getCount and getItem methods:

```<code>@Override
public int getCount() {
    if(objects== null){
        return 0;
    }else {
        return objects.isEmpty()? 0 : objects.size();
    }
}

@Override
public Product getItem(int position) {
    return objects.get(position);
}
</code>```

Body:
Does anyone know how to delete an item from a custom ListView? I'm currently working on an Android bar code scanner that stores a scanned item name into an inventory, together with its price. I also want it to be removed when the user clicks on it (but it doesn't works).

This is my code, which might seem messy because I'm still a beginner in Android.

XML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="in.aurora.android_barcode_scanner.Inventory"
    android:focusableInTouchMode="false"
    android:clickable="false"
    android:focusable="false">

    <ListView
        android:id="@+id/listView"
        android:layout_width="365dp"
        android:layout_height="495dp"
        tools:layout_editor_absoluteX="10dp"
        tools:layout_editor_absoluteY="8dp"
        android:focusableInTouchMode="false"
        android:clickable="false"
        android:focusable="false"/>
</android.support.constraint.ConstraintLayout>

Implementation:

public void display() {
    ShoppingListAdapter adapter = new ShoppingListAdapter(this,
        R.layout.adapter_view_layout, shoppingList);
    lv = (ListView) findViewById(R.id.listView);

    lv.setAdapter(adapter);
}

@Override
public void onItemClick(AdapterView parent, View view, final int position, long id) {

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Remove this item?");
    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            shoppingList.remove(position);

            display();
        }
    });
    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });
    builder.show();
}

Adapter:

public class ShoppingListAdapter extends ArrayAdapter<Product> {

    private static final String TAG = "ShoppingListAdapter";

    private Context mContext;
    int mResource;

    public ShoppingListAdapter(Context context, int resource, ArrayList<Product> objects)
    {
        super(context, resource, objects);
        mContext = context;
        mResource = resource;
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        String name = getItem(position).getName();
        double price = getItem(position).getPrice();
        String convertPrice = Double.toString(price);

        Product product = new Product(name, price);

        LayoutInflater inflater  = LayoutInflater.from(mContext);
        convertView = inflater.inflate(mResource, parent, false);

        TextView productName = (TextView)
        convertView.findViewById(R.id.textView1);
        TextView productPrice = (TextView)
        convertView.findViewById(R.id.textView2);

        productName.setText(name);
        productPrice.setText(convertPrice);

        return convertView;
    }

}

Body:
Put this method in your adapter:

public void remove(Product product) {
    objects.remove(product);
    notifyDataSetChanged();
}

Then call it like this:

Product product = shoppingList.get(position);
adapter.remove(product);
adapter.notifyDataSetChanged();

Also make sure your adapter class has getCount and getItem methods:

@Override
public int getCount() {
    if(objects== null){
        return 0;
    }else {
        return objects.isEmpty()? 0 : objects.size();
    }
}

@Override
public Product getItem(int position) {
    return objects.get(position);
}


问:
Measuring time with a resolution of microseconds in C++?
I'm looking for a way to measure microsecs in C++/Windows.

I read about the "clock" function, but it returns only milliseconds...

Is there a way to do it?

答:
Use QueryPerformanceCounter and QueryPerformanceFrequency for finest grain timing on Windows.

MSDN article on code timing with these APIs here (sample code is in VB - sorry).


问:
Issues running Airflow DAG
I have been working on Apache Airflow for a while now to schedule my workflow. I seem to be having issues scheduling my DAG. I have been using this SO question for reference : Airflow not scheduling Correctly Python

```<code>from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import datetime
from datetime import timedelta

default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
'start_date': datetime.now() - timedelta(minutes=5),
'email': ['airflow@airflow.com'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(minutes=5),
}

 dag = DAG('dag_mkdir_folder', default_args=default_args,
      schedule_interval=timedelta(minutes=5))

 task_hello = BashOperator(task_id='print_hello',
                      bash_command='mkdir test_airflow', dag=dag)
</code>```

I'm trying to run the task using the following list of commands :

```<code> airflow scheduler
 airflow trigger_dag dag_mkdir_folder
</code>```

I keep getting this as an error :

```
[2017-05-15 13:49:06,688] {models.py:322} DagFileProcessor406 INFO -      Finding 'running' jobs without a recent heartbeat
[2017-05-15 13:49:06,689] {models.py:328} DagFileProcessor406 INFO -   Failing jobs without heartbeat after 2017-05-15 13:44:06.689284
```

The bash command is just supposed to create a new directory. The test version works fine.

答:
Your current bash_command is telling Airflow to create a directory inside of the temporary directory that the DAG uses when it is running, which it blows away along with all of its contents after the DAG is run.

Consider changing directories to the directory you want to create it in.

A bash_command with that would look something like:

```<code>"cd <path_to_directory>; mkdir test_airflow"
</code>```

Title: Issues running Airflow DAG

Body:
I have been working on Apache Airflow for a while now to schedule my workflow. I seem to be having issues scheduling my DAG. I have been using this SO question for reference : Airflow not scheduling Correctly Python

from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import datetime
from datetime import timedelta

default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
'start_date': datetime.now() - timedelta(minutes=5),
'email': ['airflow@airflow.com'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(minutes=5),
}

 dag = DAG('dag_mkdir_folder', default_args=default_args,
      schedule_interval=timedelta(minutes=5))

 task_hello = BashOperator(task_id='print_hello',
                      bash_command='mkdir test_airflow', dag=dag)

I'm trying to run the task using the following list of commands :

 airflow scheduler
 airflow trigger_dag dag_mkdir_folder

I keep getting this as an error :

[2017-05-15 13:49:06,688] {models.py:322} DagFileProcessor406 INFO -      Finding 'running' jobs without a recent heartbeat
[2017-05-15 13:49:06,689] {models.py:328} DagFileProcessor406 INFO -   Failing jobs without heartbeat after 2017-05-15 13:44:06.689284

The bash command is just supposed to create a new directory. The test version works fine.

Body:
Your current bash_command is telling Airflow to create a directory inside of the temporary directory that the DAG uses when it is running, which it blows away along with all of its contents after the DAG is run.

Consider changing directories to the directory you want to create it in.

A bash_command with that would look something like:

"cd <path_to_directory>; mkdir test_airflow"


问:
Relation between HTTP.sys request queue and IIS app pool
I read this from < IIS 7.0 resource kit >

HTTP.sys maintains a request queue for each worker process. It sends the HTTP requests to the request queue for the worker process that serves the application pool where the requested application is located.
  For each application, HTTP.sys maintains the URI namespace routing table with one entry. The routing table data is used to determine which application pool responds to requests from what parts of the namespace. Each request queue corresponds to  one application pool. And application pool corresponds to one request queues within HTTP.sys and one or more worker processes.

The bold parts confused me.
My understanding is: HTTP.sys matain a request queue for each worker process. An application pool can have one or more worker processes. So an application pool should also corresponds to one or more request queues. Why only one in the bold sentence?

And btw, could anyone give a more clear explanation about the URI namespace routing table? Some examples would be better.

Thanks.

答:
To discuss a paragraph in a book, you should give more info.

This paragraph comes from "IIS 7.0 Core Components" section, and the version at Safari Books Online is different from what you pasted,

HTTP.sys maintains a request queue for each worker process. It sends
  the HTTP requests it receives to the request queue for the worker
  process that serves the application pool where the requested
  application is located. For each application, HTTP.sys maintains the
  URI namespace routing table with one entry. The routing table data is
  used to determine which application pool responds to requests from
  what parts of the namespace. Each request queue corresponds to one
  application pool. An application pool corresponds to one request queue
  within HTTP.sys and one or more worker processes.

So the last sentence should be understood as,

An application pool corresponds to one request queue within http.sys.

An application pool corresponds to one or more worker processes.

Thus, your understanding of "HTTP.sys maintains a request queue for each worker process" is not correct. The correct one should be "HTTP.sys maintains a request queue for each application pool". So no matter how many worker processes are there for a single application pool, they only serve requests from a single request queue in http.sys.

"For each application, HTTP.sys maintains the URI namespace routing
  table with one entry"

I think it should be "for each application pool, HTTP.sys maintains the URI namespace routing table with one entry". This routing table makes it easier to dispatch requests (whose URL is clear) to the pools. Very similar to a hash table.

The table can be constructed from <sites> tag in applicationHost.config, by combining sites, their bindings, applications, and their application pool association. There is no further information from Microsoft on the exact table structure.


问:
VisualStudio Code marks error in React code to close html tag
I am trying to run basic React helloworld application under VisualStudio Code

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import './index.css';

ReactDOM.render( < App / > , document.getElementById('root'));
registerServiceWorker();

var element = < h1 > abcd < /h1>;

ReactDOM.render(element, document.getElementById('root'));
</code>```

When I run it in commandline everything works fine, but I wonder why VisualStudio Code marks error at line: (after save)

```<code>var element = < h1 > abcd < /h1>;
</code>```

And claims, that opened tag should be closed.

Here is my configuration (as I suppose it is IDE specific issue)

```<code>{
    "workbench.colorTheme": "Visual Studio Dark",
    "workbench.iconTheme": "vscode-icons",
    "terminal.integrated.shell.windows": "C:\\windows\\Sysnative\\WindowsPowerShell\\v1.0\\powershell.exe",
    "emmet.syntaxProfiles": { "javascript": "jsx" }
}
</code>```

When I google for solution, all answers just say to only add closing html tag.

答:
Quite simply you are adding unnecessary white space:

```<code>var element = < h1 > abcd < /h1>; // BAD
var element = <h1>abcd</h1>; // GOOD :)
</code>```

I strongly recommend to keep it as a good practice to avoid adding those extra spaces, it makes it hard for your editor to parse it as actual HTML/JSX. I am using VSCode as well and it doesn't even recognize it as proper JSX if I use spaces like in your example.

Body:
I am trying to run basic React helloworld application under VisualStudio Code

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import './index.css';

ReactDOM.render( < App / > , document.getElementById('root'));
registerServiceWorker();

var element =
 abcd
;

ReactDOM.render(element, document.getElementById('root'));

When I run it in commandline everything works fine, but I wonder why VisualStudio Code marks error at line: (after save)

var element =
 abcd
;

And claims, that opened tag should be closed.

Here is my configuration (as I suppose it is IDE specific issue)

{
    "workbench.colorTheme": "Visual Studio Dark",
    "workbench.iconTheme": "vscode-icons",
    "terminal.integrated.shell.windows": "C:\\windows\\Sysnative\\WindowsPowerShell\\v1.0\\powershell.exe",
    "emmet.syntaxProfiles": { "javascript": "jsx" }
}

When I google for solution, all answers just say to only add closing html tag.

Body:
Quite simply you are adding unnecessary white space:

var element = < h1 > abcd < /h1>; // BAD
var element = <h1>abcd</h1>; // GOOD :)

I strongly recommend to keep it as a good practice to avoid adding those extra spaces, it makes it hard for your editor to parse it as actual HTML/JSX. I am using VSCode as well and it doesn't even recognize it as proper JSX if I use spaces like in your example.


问:
Is there a way to convert Trac Wiki pages to HTML?
I see the suggestion of using Mylyn WikiText to convert wiki pages to html from this question except I'm not sure if its what I'm looking for from reading the front page of the site alone. I'll look into it further. Though I would prefer it being a Trac plug-in so I could initiate the conversion from within the wiki options but all the plugins at Trac-Hacks export single pages only whereas I want to dump all formatted pages in one go.

So is there an existing Trac plug-in or stand-alone application that'll meet my requirements? If not where would you point me to start looking at implementing that functionality myself?

答:
You may find some useful information in the comments for this ticket on trac-hacks.  One user reports using the wget utility to create a mirror copy of the wiki as if it was a normal website.  Another user reports using the XmlRpc plugin to extract HTML versions of any given wiki page, but this method would probably require you to create a script to interface with the plugin.  The poster didn't provide any example code, unfortunately, but the XmlRpc Plugin page includes a decent amount of documentation and samples to get you started.

If you have access to a command line on the server hosting Trac, you can use the trac-admin command like:

```<code>trac-admin /path/to/trac wiki export <wiki page name>
</code>```

to retrieve a plain-text version of the specified wiki page.  You would then have to parse the wiki syntax to HTML, but there are tools available to do that.

Body:
You may find some useful information in the comments for this ticket on trac-hacks.  One user reports using the wget utility to create a mirror copy of the wiki as if it was a normal website.  Another user reports using the XmlRpc plugin to extract HTML versions of any given wiki page, but this method would probably require you to create a script to interface with the plugin.  The poster didn't provide any example code, unfortunately, but the XmlRpc Plugin page includes a decent amount of documentation and samples to get you started.

If you have access to a command line on the server hosting Trac, you can use the trac-admin command like:

trac-admin /path/to/trac wiki export <wiki page name>

to retrieve a plain-text version of the specified wiki page.  You would then have to parse the wiki syntax to HTML, but there are tools available to do that.


问:
C#: Returning Javascript Object Collection vs Array of Objects
I'm using a 3rd party map for some charting functionality within our intranet.  To populate the regions, I need to pass it an Object Collection (javascript) formatted thusly:

```<code>            simplemaps_usmap_mapdata.state_specific = {
            AZ: {
                name: "Arizona",
                description: "The best state in the whole got damn union",
                color: "#cecece",
                hover_color: "default",
                url: "",
              },
            NH: {
                name: "New Hampshire",
                description: "Small and insignificant",
                color: "#f68831",
                hover_color: "default",
                url: "",
              }
        }
</code>```

Obviously, it'd be much better if it were an array of objects, then it'd be simple enough to return via my C# controller a List, but since it's an object collection, what is the best way to return JSON formatted this way via my C# controller?

答:
I am going to assume you have already configured your controller to return JSON, meaning your object type is the only thing that needs to be setup.

The problem with this format, as you are likely already aware of, is that you will need to define an object that has all of the states on it's root level.  This is tedious and likely overkill when you don't need every single state to be returned.

To solve this, utilize either the dynamic type or an anonymous object in C#.  This will allow you to define just what you need at that time:

Pseudocode for your controller method:

```<code>public dynamic MyAction() // Dynamic
public object MyAction() // Object
{
    return new {
        AZ = new StateObj(), // Insert your state type here
        NH = new StateObj()
    }
}
</code>```

Body:
I'm using a 3rd party map for some charting functionality within our intranet.  To populate the regions, I need to pass it an Object Collection (javascript) formatted thusly:

            simplemaps_usmap_mapdata.state_specific = {
            AZ: {
                name: "Arizona",
                description: "The best state in the whole got damn union",
                color: "#cecece",
                hover_color: "default",
                url: "",
              },
            NH: {
                name: "New Hampshire",
                description: "Small and insignificant",
                color: "#f68831",
                hover_color: "default",
                url: "",
              }
        }

Obviously, it'd be much better if it were an array of objects, then it'd be simple enough to return via my C# controller a List, but since it's an object collection, what is the best way to return JSON formatted this way via my C# controller?

Body:
I am going to assume you have already configured your controller to return JSON, meaning your object type is the only thing that needs to be setup.

The problem with this format, as you are likely already aware of, is that you will need to define an object that has all of the states on it's root level.  This is tedious and likely overkill when you don't need every single state to be returned.

To solve this, utilize either the dynamic type or an anonymous object in C#.  This will allow you to define just what you need at that time:

Pseudocode for your controller method:

public dynamic MyAction() // Dynamic
public object MyAction() // Object
{
    return new {
        AZ = new StateObj(), // Insert your state type here
        NH = new StateObj()
    }
}


问:
JavaFx Controller: detect when stage is closing
I have a javaFx project and I would like to implement a method inside the Controller that is invoked every time the stage(window) is closing this to be able to perform some actions before closing it.
The desire to have the method placed inside the controller is because the actions to be taken depend on the choices that the user has made while using the scene.

My goal is every time the user closes the stage, to have a print and then an user related action.

I try inside the controller class:

```<code>@FXML
    public void exitApplication(ActionEvent event) {
        System.out.println("stop");
        action();
        Platform.exit();
    }
</code>```

but it's no effective.

答:
Just from a design perspective, it doesn't really make sense in the controller to associate a handler with the stage, as the stage is typically not part of the view to which the controller is connected.

A more natural approach is to define a method in the controller, and then invoke that method from a handler which you associate with the stage at the point where the stage is created.

So you would do something like this in the controller:

```<code>public class Controller {

    // fields and event handler methods...

    public void shutdown() {
        // cleanup code here...
        System.out.println("Stop");
        action();
        // note that typically (i.e. if Platform.isImplicitExit() is true, which is the default)
        // closing the last open window will invoke Platform.exit() anyway
        Platform.exit();
    }
}
</code>```

and then at the point where you load the FXML you would do

```<code>FXMLLoader loader = new FXMLLoader(getClass().getResource("/path/to/file.fxml"));
Parent root = loader.load();
Controller controller = loader.getController();
Scene scene = new Scene(root);
Stage stage = new Stage();
stage.setScene(scene);
stage.setOnHidden(e -> controller.shutdown());
stage.show();
</code>```

Again, exiting the application is probably not (or probably should not be) the responsibility of the controller (it's the responsibility of the class that creates the window or manages application life-cycle), so if you really needed to force an exit when the window closed, you would probably move that to the onHidden handler:

```<code>public class Controller {

    // fields and event handler methods...

    public void shutdown() {
        // cleanup code here...
        System.out.println("Stop");
        action();
    }
}
</code>```

and

```<code>FXMLLoader loader = new FXMLLoader(getClass().getResource("/path/to/file.fxml"));
Parent root = loader.load();
Controller controller = loader.getController();
Scene scene = new Scene(root);
Stage stage = new Stage();
stage.setScene(scene);
stage.setOnHidden(e -> {
    controller.shutdown();
    Platform.exit();
});
stage.show();
</code>```

Body:
I have a javaFx project and I would like to implement a method inside the Controller that is invoked every time the stage(window) is closing this to be able to perform some actions before closing it.
The desire to have the method placed inside the controller is because the actions to be taken depend on the choices that the user has made while using the scene.

My goal is every time the user closes the stage, to have a print and then an user related action.

I try inside the controller class:

@FXML
    public void exitApplication(ActionEvent event) {
        System.out.println("stop");
        action();
        Platform.exit();
    }

but it's no effective.

Body:
Just from a design perspective, it doesn't really make sense in the controller to associate a handler with the stage, as the stage is typically not part of the view to which the controller is connected.

A more natural approach is to define a method in the controller, and then invoke that method from a handler which you associate with the stage at the point where the stage is created.

So you would do something like this in the controller:

public class Controller {

    // fields and event handler methods...

    public void shutdown() {
        // cleanup code here...
        System.out.println("Stop");
        action();
        // note that typically (i.e. if Platform.isImplicitExit() is true, which is the default)
        // closing the last open window will invoke Platform.exit() anyway
        Platform.exit();
    }
}

and then at the point where you load the FXML you would do

FXMLLoader loader = new FXMLLoader(getClass().getResource("/path/to/file.fxml"));
Parent root = loader.load();
Controller controller = loader.getController();
Scene scene = new Scene(root);
Stage stage = new Stage();
stage.setScene(scene);
stage.setOnHidden(e -> controller.shutdown());
stage.show();

Again, exiting the application is probably not (or probably should not be) the responsibility of the controller (it's the responsibility of the class that creates the window or manages application life-cycle), so if you really needed to force an exit when the window closed, you would probably move that to the onHidden handler:

public class Controller {

    // fields and event handler methods...

    public void shutdown() {
        // cleanup code here...
        System.out.println("Stop");
        action();
    }
}

and

FXMLLoader loader = new FXMLLoader(getClass().getResource("/path/to/file.fxml"));
Parent root = loader.load();
Controller controller = loader.getController();
Scene scene = new Scene(root);
Stage stage = new Stage();
stage.setScene(scene);
stage.setOnHidden(e -> {
    controller.shutdown();
    Platform.exit();
});
stage.show();


问:
Measure distance from an iPhone to an Object using proximity sensor
I have read many Forums on this topic but I still haven't found an exact answer. Is the iPhone's proximity sensor only a trigger that turns the display on or off or can one get a distance from the sensor to an object?

Thank you!

答: The proximity sensor won't be precise enough to give you distances, it's basically a light sensor...</p>


问:
How to setup Git on local network?
I downloaded Git setup and trying to setup for computers in my network. I searched for the process but I found it for to host code on line on github.com. I found a few links but there is not the whole process.

I am aware for how to push and pull.

答:
If you're asking about how to connect to a repository hosted by another computer on the same network, take a look at this StackOverflow thread.

Basically, you'll want to use git daemon. If you just need to set up a single repository, that's one line from each machine:

Server:

```<code>git daemon --base-path=/path/to/repo --export-all
</code>```

Client:

```<code>git remote add LocalServerName git://<serveraddress>/
</code>```

or

```<code>git clone git://<serveraddress>/
</code>```

where <serveraddress> is some reference to that machine (IPv4, IPv6, .local, etc.). You can also specify --verbose for the daemon command for more detailed output.

I think, also, you could have --base-path point to a folder with many repositories, and that would let you specify which project you wanted on the client-side like so:

```<code>git daemon --base-path=/path/to/all/repos

git remote add ServerName git://<serveraddress>/MyProject/
</code>```

Be advised: using --export-all will let any computer on the network pull from your repo.

Title: How to setup Git on local network?

Body:
If you're asking about how to connect to a repository hosted by another computer on the same network, take a look at this StackOverflow thread.

Basically, you'll want to use git daemon. If you just need to set up a single repository, that's one line from each machine:

Server:

git daemon --base-path=/path/to/repo --export-all

Client:

git remote add LocalServerName git://<serveraddress>/

or

git clone git://<serveraddress>/

where <serveraddress> is some reference to that machine (IPv4, IPv6, .local, etc.). You can also specify --verbose for the daemon command for more detailed output.

I think, also, you could have --base-path point to a folder with many repositories, and that would let you specify which project you wanted on the client-side like so:

git daemon --base-path=/path/to/all/repos

git remote add ServerName git://<serveraddress>/MyProject/

Be advised: using --export-all will let any computer on the network pull from your repo.

ContentLicense: CC BY-SA 4.0


问:
Vue.js - "SyntaxError: Unexpected token <" when testing component
I am trying to create a component with Vue.js. My component is currently defined like this:

MyComponent.vue

```<code><template id="my-template">
    <div>
        <button class="btn" v-on:click="increment">increment</button>
    </div>
</template>

<script type="text/javascript">
    Vue.component('incrementer', {
        template: '#my-template',
        props: {
            i: {
                type: Number,
                default: 1,
            }
        },

        data: function() {
            return {
                count: 0
            }
        },

        methods: {
            increment: function() {
              this.count = this.count + this.i;
            }
        }
    });
</script>
</code>```

I am trying to create some automated tests for this component. In an attempt to do this, I have the following:

my-component.spec.js

```<code>const MyComponent = require('../src/MyComponent.vue');

describe('my-component', function() {
    // Inspect the raw component options
    it('has a created hook', () => {
        expect(typeof MyComponent .created).toBe('function')
    });
});
</code>```

I am trying to run this test via Jasmine through Gulp. In Gulp, my test task looks like this:

gulpfile.js

```<code>gulp.task('test', ['build'], function() {
    return gulp.src(['test/**/*spec.js'])
        .pipe(jasmine({
            timeout: 10000,
            includeStackTrace: false,
            color: false
         }))
    ;
});
</code>```

When this task gets executed, I receive the following error:

```<code>(function (exports, require, module, __filename, __dirname) { <template id="my-template">
                                                              ^
SyntaxError: Unexpected token <
</code>```

I don't understand why I'm receiving this error. What do I need to do to test a component in Vue.js via Jasmine?

Thank you!

答:
According to Vue Docs:

In terms of code structure for testing, you don’t have to do anything special in your components to make them testable. Just export the raw options

When you test that component, all you have to do is import the object along with Vue to make many common assertions

So in you MyComponent.vue file:

```<code><template>
<div>
    <button class="btn" v-on:click="increment">increment</button>
</div>
</template>

<script type="text/javascript">
export default {
    props: {
        i: {
            type: Number,
            default: 1,
        }
    },

    data: function() {
        return {
            count: 0
        }
    },

    methods: {
        increment: function() {
          this.count = this.count + this.i;
        }
    }
}
</script>
</code>```

Then in your my-component.spec.js:

```<code>const Vue = reuqire("vue")
const MyComponent = require('../src/MyComponent.vue');

describe('my-component', function() {
    // Inspect the raw component options
    it('has a created hook', () => {
        expect(typeof MyComponent.created).toBe('function')
    });
});
</code>```

Body:
I am trying to create a component with Vue.js. My component is currently defined like this:

MyComponent.vue

<template id="my-template">

        <button class="btn" v-on:click="increment">increment</button>

</template>

I am trying to create some automated tests for this component. In an attempt to do this, I have the following:

my-component.spec.js

const MyComponent = require('../src/MyComponent.vue');

describe('my-component', function() {
    // Inspect the raw component options
    it('has a created hook', () => {
        expect(typeof MyComponent .created).toBe('function')
    });
});

I am trying to run this test via Jasmine through Gulp. In Gulp, my test task looks like this:

gulpfile.js

gulp.task('test', ['build'], function() {
    return gulp.src(['test/**/*spec.js'])
        .pipe(jasmine({
            timeout: 10000,
            includeStackTrace: false,
            color: false
         }))
    ;
});

When this task gets executed, I receive the following error:

(function (exports, require, module, __filename, __dirname) { <template id="my-template">
                                                              ^
SyntaxError: Unexpected token <

I don't understand why I'm receiving this error. What do I need to do to test a component in Vue.js via Jasmine?

Thank you!

Body:
According to Vue Docs:

In terms of code structure for testing, you don’t have to do anything special in your components to make them testable. Just export the raw options

When you test that component, all you have to do is import the object along with Vue to make many common assertions

So in you MyComponent.vue file:

<template>
<div>
    <button class="btn" v-on:click="increment">increment</button>
</div>
</template>

<script type="text/javascript">
export default {
    props: {
        i: {
            type: Number,
            default: 1,
        }
    },

    data: function() {
        return {
            count: 0
        }
    },

    methods: {
        increment: function() {
          this.count = this.count + this.i;
        }
    }
}
</script>

Then in your my-component.spec.js:

const Vue = reuqire("vue")
const MyComponent = require('../src/MyComponent.vue');

describe('my-component', function() {
    // Inspect the raw component options
    it('has a created hook', () => {
        expect(typeof MyComponent.created).toBe('function')
    });
});


问:
How to use babel-runtime transform without an external dependency?
If I use the babel-plugin-transform-runtime plugin, then my code will import/require babel-runtime instead of including all those helper functions inline. This is nice, but it makes my library have a dependency babel-runtime. What I would rather do is have Babel extract one extra file (./babel-runtime) and drop that in with the other output files so that I don't have to include it as an external dependency. i.e., I won't have to add that to package.json everywhere my library is used. Is this possible?

答:
The only solution I found was to not use the babel-plugin-transform-runtime plugin and add exclude: ['transform-regenerator'] to your config. This will prevent Babel from adding a dependency on regenerator. It also means your code won't run in older browsers.

If you need support for older browsers, you can try fast-async. It says there's a way to inline the dependency in just your index file, but I haven't tried it yet. I believe this assumes the browser supports Promises but not async/await.


问:
How to detect ENTER keypress/ or the "GO" button in the Address Bar?
I want to detect the ENTER keypress of the Address Bar and also, the "Go(to the specified URL)" button using Javascript.
As per my previous efforts using "keycode==13" did not work as required.
say, in the following code:

```<code>window.onkeypress = testKeyEvent;

function testKeyEvent(e) {
    if (e.keyCode == 13) //We are using Enter key press event for test purpose.
    {
        alert('Enter key pressed');
    }
    else //If any other button pressed.
    {
        alert('Not Enter key pressed');
    }
}    </script>
</code>```

I want first the Alert box to be displayed,after I have typed any URL(valid or not) in the address box and Pressed ENTER/ Clicked GO button and then go to specified URL.

Is it Possible? I know I am missing out on a lot of things, Please mention about them.

答: If I am interpreting your question correctly, I don't think you can do this, because the context in which the JavaScript runs stops at the Document (meaning, JavaScript doesn't even quite know that the browser itself exists).</p>

Body:
I want to detect the ENTER keypress of the Address Bar and also, the "Go(to the specified URL)" button using Javascript.
As per my previous efforts using "keycode==13" did not work as required.
say, in the following code:

window.onkeypress = testKeyEvent;

function testKeyEvent(e) {
    if (e.keyCode == 13) //We are using Enter key press event for test purpose.
    {
        alert('Enter key pressed');
    }
    else //If any other button pressed.
    {
        alert('Not Enter key pressed');
    }
}    </script>

I want first the Alert box to be displayed,after I have typed any URL(valid or not) in the address box and Pressed ENTER/ Clicked GO button and then go to specified URL.

Is it Possible? I know I am missing out on a lot of things, Please mention about them.


问:
border-spacing for inside borders only
I want my table cells to have a margin between them within same row, so I tried setting border-spacing: smth, but it also forces the left-most and right-most to have that same margin from table's outside border. Is it possible to avoid such scenario and apply spacing only between cells?

答:
You can select the first and last td and reset their margins to 0.

```<code>td {
  margin: 0 5px;
}
td:first-of-type, td:last-of-type {
  margin: 0;
}
</code>```

Title: border-spacing for inside borders only

Body:
You can select the first and last td and reset their margins to 0.

td {
  margin: 0 5px;
}
td:first-of-type, td:last-of-type {
  margin: 0;
}


问:
Android: service for gps / sensor logging
I m looking for the best practice to implement a service for logging gps- or other sensor-values periodically (every 10-60 sec). The service should deal with the standby mode, when the phone goes asleep.

Any help (pseudo-code or tutorials) is very much appreciated!

答:
Here's a link to a tutorial on how to use Android Services. LINK
Here's a link to a tutorial on how to read data from sensors.  LINK</p>


问:
Numericupdown box line width
```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MiniPaint
{
    public partial class Form1 : Form
    {
        Graphics g;
        Pen p = new Pen(Color.Black, 1);
        Point sp = new Point(0, 0);
        Point ep = new Point(0, 0);
        int k = 0;
        public Form1()
        {
            InitializeComponent();
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void red_Click(object sender, EventArgs e)
        {
            p.Color = red.BackColor;
            default1.BackColor = red.BackColor;
        }

        private void green_Click(object sender, EventArgs e)
        {
            p.Color = green.BackColor;
            default1.BackColor = green.BackColor;
        }

        private void blue_Click(object sender, EventArgs e)
        {
            p.Color = blue.BackColor;
            default1.BackColor = blue.BackColor;
        }

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            sp = e.Location;
            if (e.Button == MouseButtons.Left);
            k = 1;

        }

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            k = 0;

        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            if (k == 1)
            {
                ep = e.Location;
                g = this.CreateGraphics();
                g.DrawLine(p, sp, ep);
            }

            sp = ep;

        }

        private void del1_Click(object sender, EventArgs e)
        {
            g.Clear(Color.White);

        }

        private void yellow_Click(object sender, EventArgs e)
        {
            p.Color = yellow.BackColor;
            default1.BackColor = yellow.BackColor;
        }

        private void purple_Click(object sender, EventArgs e)
        {
            p.Color = purple.BackColor;
            default1.BackColor = purple.BackColor;
        }

        private void brown_Click(object sender, EventArgs e)
        {
            p.Color = brown.BackColor;
            default1.BackColor = brown.BackColor;
        }

        private void black_Click(object sender, EventArgs e)
        {
            p.Color = black.BackColor;
            default1.BackColor = black.BackColor;
        }

        private void nud1_ValueChanged(object sender, EventArgs e)
        {

        }

        private void white_Click(object sender, EventArgs e)
        {
            p.Color = white.BackColor;
            default1.BackColor = white.BackColor;
        }
    }
}
</code>```

I'm almost done with my minipaint code in c#. I wanted to add one more thing to it and it's that I can change the thickness(width) of the line im going to draw via numericupadown box and I'm trying to make it work for over an hour. Can someone help me with it please and is there a simple way of doing it? ( nud1 is  the numereric updown box)

答:
On numeric up down value changed event, change the thickness of the pen you're using, I would recommend storing the current color in a variable that you can assign back to your pen on the value changed event when you re-initialize.

This MSDN link shows details on the Pen class from System.Drawing.

```<code>p = new Pen(Color, (float)nud1.Value);
</code>```

Title: Numericupdown box line width

Body:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MiniPaint
{
    public partial class Form1 : Form
    {
        Graphics g;
        Pen p = new Pen(Color.Black, 1);
        Point sp = new Point(0, 0);
        Point ep = new Point(0, 0);
        int k = 0;
        public Form1()
        {
            InitializeComponent();
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void red_Click(object sender, EventArgs e)
        {
            p.Color = red.BackColor;
            default1.BackColor = red.BackColor;
        }

        private void green_Click(object sender, EventArgs e)
        {
            p.Color = green.BackColor;
            default1.BackColor = green.BackColor;
        }

        private void blue_Click(object sender, EventArgs e)
        {
            p.Color = blue.BackColor;
            default1.BackColor = blue.BackColor;
        }

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            sp = e.Location;
            if (e.Button == MouseButtons.Left);
            k = 1;

        }

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            k = 0;

        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            if (k == 1)
            {
                ep = e.Location;
                g = this.CreateGraphics();
                g.DrawLine(p, sp, ep);
            }

            sp = ep;

        }

        private void del1_Click(object sender, EventArgs e)
        {
            g.Clear(Color.White);

        }

        private void yellow_Click(object sender, EventArgs e)
        {
            p.Color = yellow.BackColor;
            default1.BackColor = yellow.BackColor;
        }

        private void purple_Click(object sender, EventArgs e)
        {
            p.Color = purple.BackColor;
            default1.BackColor = purple.BackColor;
        }

        private void brown_Click(object sender, EventArgs e)
        {
            p.Color = brown.BackColor;
            default1.BackColor = brown.BackColor;
        }

        private void black_Click(object sender, EventArgs e)
        {
            p.Color = black.BackColor;
            default1.BackColor = black.BackColor;
        }

        private void nud1_ValueChanged(object sender, EventArgs e)
        {

        }

        private void white_Click(object sender, EventArgs e)
        {
            p.Color = white.BackColor;
            default1.BackColor = white.BackColor;
        }
    }
}

I'm almost done with my minipaint code in c#. I wanted to add one more thing to it and it's that I can change the thickness(width) of the line im going to draw via numericupadown box and I'm trying to make it work for over an hour. Can someone help me with it please and is there a simple way of doing it? ( nud1 is  the numereric updown box)

Body:
On numeric up down value changed event, change the thickness of the pen you're using, I would recommend storing the current color in a variable that you can assign back to your pen on the value changed event when you re-initialize.

This MSDN link shows details on the Pen class from System.Drawing.

p = new Pen(Color, (float)nud1.Value);


问:
How to get price of Chart HLine objects and calculate Fibonacci levels
Three part question:

How to find 2 user created horizontal lines on a chart by name and return the price of each.

Then determine which HLine was crossed by the price most recently to determine trend direction.

Calculate Fibonacci levels based on prices and direction

答:
```<code>double value = ObjectGetDouble(0,nameOfHLine,OBJPROP_PRICE1);
</code>```

<p>this is your value if you have name of the object, if you dont have it - need to loop over all objects: </p>

```<code> string name;
 for(int i=ObjectsTotal()-1;i>=0;i--){
    name = ObjectName(i);
    if(ObjectType(name)!=OBJ_HLINE) continue;
 }
</code>```

Body:
double value = ObjectGetDouble(0,nameOfHLine,OBJPROP_PRICE1);

this is your value if you have name of the object, if you dont have it - need to loop over all objects:

 string name;
 for(int i=ObjectsTotal()-1;i>=0;i--){
    name = ObjectName(i);
    if(ObjectType(name)!=OBJ_HLINE) continue;
 }


问:
Angular2+ How can I switch locale at runtime?
I have looked at the i18n stuff in Angular2+ and I really like it. However, my requirement is to allow the user to select their language at runtime.

In some cases more than one person will be using the same terminal so it will be necessary to switch languages at different points in the day, or perhaps even during a task (English manager handing control over to a non-English worker to complete some input).

Is there a way to do this in Angular2+ (currently using Angular 4) or will I need to roll my own solution?

答:
You need some i18n libraries.

Like ngx-translate or angular-l10n

I suggest ngx-translate.


答:
First, a class:

```<code>class MyClass {
    public string name {get;set;}
    public string description {get;set;}
    public string color {get;set;}
    public string hover_color {get;set;}
    public string url {get;set;}
}
</code>```

Then, a dictionary:

```<code>var result = new Dictionary<string, MyClass>();
</code>```

Add to the dictionary:

```<code>result["AZ"] = new MyClass { name="xyz"... };
</code>```

Finally, return the dictionary via the JSON method:

```<code>return JSON(result);
</code>```

Title: C#: Returning Javascript Object Collection vs Array of Objects

Body:
First, a class:

class MyClass {
    public string name {get;set;}
    public string description {get;set;}
    public string color {get;set;}
    public string hover_color {get;set;}
    public string url {get;set;}
}

Then, a dictionary:

var result = new Dictionary<string, MyClass>();

Add to the dictionary:

result["AZ"] = new MyClass { name="xyz"... };

Finally, return the dictionary via the JSON method:

return JSON(result);


问:
How can I change TelemetryChannel properties for Application Insights?
Microsoft provides documentation of many settings that can be set for the TelemetryChannel class in Application Insights.

But I can't find any explanation of how these settings can be set.

Setting them in the ApplicationInsights.config file like this does not work for my web application:

```<code><TelemetryChannel Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel, Microsoft.AI.ServerTelemetryChannel">
  <DataUploadIntervalInSeconds>1</DataUploadIntervalInSeconds>
  <MaxTelemetryBufferCapacity>1</MaxTelemetryBufferCapacity>
</TelemetryChannel>
</code>```

I simply cannot seem to influence my web app to honor these settings.

How can these settings be adjusted?

答:
The sample config in below git spark the idea of usage. You have to use Profiles & set these settings.

```<code><ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
 <ActiveProfile>Production</ActiveProfile>
<Profiles>
<Profile name="Production">
      <!-- <ServerAnalytics> controls Application Insights Telemetry SDK settings. -->
      <ServerAnalytics enabled="true">
        <!-- The frequency in seconds with which the SDK uploads data to Application Insights. -->
        <DataUploadIntervalInSeconds>60</DataUploadIntervalInSeconds>
</Profile>
  </Profiles>
</ApplicationInsights>
</code>```

https://github.com/postsharp/ApplicationInsightsExample/blob/master/ApplicationInsightsExample/ApplicationInsights.config

Body:
Microsoft provides documentation of many settings that can be set for the TelemetryChannel class in Application Insights.

But I can't find any explanation of how these settings can be set.

Setting them in the ApplicationInsights.config file like this does not work for my web application:

<TelemetryChannel Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel, Microsoft.AI.ServerTelemetryChannel">
  <DataUploadIntervalInSeconds>1</DataUploadIntervalInSeconds>
  <MaxTelemetryBufferCapacity>1</MaxTelemetryBufferCapacity>
</TelemetryChannel>

I simply cannot seem to influence my web app to honor these settings.

How can these settings be adjusted?

Body:
The sample config in below git spark the idea of usage. You have to use Profiles & set these settings.

<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
 <ActiveProfile>Production</ActiveProfile>
<Profiles>
<Profile name="Production">
      <!-- <ServerAnalytics> controls Application Insights Telemetry SDK settings. -->
      <ServerAnalytics enabled="true">
        <!-- The frequency in seconds with which the SDK uploads data to Application Insights. -->
        <DataUploadIntervalInSeconds>60</DataUploadIntervalInSeconds>
</Profile>
  </Profiles>
</ApplicationInsights>

https://github.com/postsharp/ApplicationInsightsExample/blob/master/ApplicationInsightsExample/ApplicationInsights.config


问:
Using GNSDK within a Video Camera Mobile Application
Is it possible to use the GNSDK recognition feature within a video camera application? Ie, starting to record a video would concurrently trigger the GNSDK recognition function.</p>

答: GNSDK does not work with video. You need to feed decoded audio stream to GNSDK. As long as you provide the correct audio data, when or how you start the recognition is totally up to you, the developer.</p>


问:
angujar js 2 Owl Carousel Responsive options not working
i am using Angular 2
i want to make it responsive carousel

```<code><owl-carousel [options]="{nav : true, slideBy : 2 ,margin :14  }"

</owl-carousel>
</code>```

this is working fine without responsive

but when i want to add responsive options in  its shows me error

but when i add Responsive code in options is show error

but at a time of run Project Browser show this Below error
can any one help me out ,to create  Responsive ng2-owl-carousel

答:
This should be the JSON structure as it is a string you have to differentiate the items with quotes</p>

```<code>{
  responsive:{
    '320':{
        items:1

    },
    '720':{
        items:3

    }
  }
}
</code>```

Body:
i am using Angular 2
i want to make it responsive carousel

<owl-carousel [options]="{nav : true, slideBy : 2 ,margin :14  }"

</owl-carousel>

this is working fine without responsive

but when i want to add responsive options in  its shows me error

but when i add Responsive code in options is show error

but at a time of run Project Browser show this Below error
can any one help me out ,to create  Responsive ng2-owl-carousel

Body:
This should be the JSON structure as it is a string you have to differentiate the items with quotes

{
  responsive:{
    '320':{
        items:1

    },
    '720':{
        items:3

    }
  }
}


问:
Run DELETE cleanup query after a Solr dataimport
I'm working on a Solr dataimport from an Oracle database.  The database system has a set of tables dedicated to storing references to changes in other tables.
 For example, I might have a table named PERSON, and when records are added to this table, their IDs are added to the PERSON_CHANGED table.  I'd like to use this PERSON_CHANGED table when defining my deltaQuery so that Solr only indexes the changed records in subsequent indexes.  As part of this process, I need to remove records that I've read from the PERSON_CHANGED table after Solr finishes its import (either delta or full), so that I don't process them again later.

What's the best way to run this kind of "cleanup" SQL query after a dataimport?

I've tried combining both of the queries like this (simplified for brevity):

```<code><dataConfig>
    <dataSource ... >
    <document>
        <entity name="person"
                query="
                    SELECT ID, FIRST_NAME, LAST_NAME
                    FROM PERSON
                    WHERE '${dataimporter.request.clean}' != 'false'
                        OR PERSON_ID IN (
                            SELECT ID FROM CHANGED_PERSON
                        );

                    DELETE * (
                        SELECT * FROM CHANGED_PERSON
                    );
        " />
    </document>
</dataConfig>
</code>```

But this results in a SQL command not properly ended error.  Does Solr provide a way to do this kind of cleanup?

答:
I found a way to accomplish this cleanup task, but I'm not super happy with it.  I can define a separate entity whose query runs a DELETE:

```<code><dataConfig>
    <dataSource ... >
    <document>
        <entity name="person"
                query="
                    SELECT ID, FIRST_NAME, LAST_NAME
                    FROM PERSON
                    WHERE '${dataimporter.request.clean}' != 'false'
                        OR PERSON_ID IN (
                            SELECT ID FROM CHANGED_PERSON
                        )" />

        <entity name="deleteChangedPersonRecords"
                query="DELETE FROM CHANGED_PERSON" />
    </document>
</dataConfig>
</code>```

This seems to work, but it's a bit of a hack, and it relies on the assumption that Solr executes its entity queries in the same order that they are specified in the file.  If anyone has a better solution, please feel free to add your answer to this question.

Body:
I'm working on a Solr dataimport from an Oracle database.  The database system has a set of tables dedicated to storing references to changes in other tables.
 For example, I might have a table named PERSON, and when records are added to this table, their IDs are added to the PERSON_CHANGED table.  I'd like to use this PERSON_CHANGED table when defining my deltaQuery so that Solr only indexes the changed records in subsequent indexes.  As part of this process, I need to remove records that I've read from the PERSON_CHANGED table after Solr finishes its import (either delta or full), so that I don't process them again later.

What's the best way to run this kind of "cleanup" SQL query after a dataimport?

I've tried combining both of the queries like this (simplified for brevity):

<dataConfig>
    <dataSource ... >
    <document>
        <entity name="person"
                query="
                    SELECT ID, FIRST_NAME, LAST_NAME
                    FROM PERSON
                    WHERE '${dataimporter.request.clean}' != 'false'
                        OR PERSON_ID IN (
                            SELECT ID FROM CHANGED_PERSON
                        );

                    DELETE * (
                        SELECT * FROM CHANGED_PERSON
                    );
        " />
    </document>
</dataConfig>

But this results in a SQL command not properly ended error.  Does Solr provide a way to do this kind of cleanup?

Body:
I found a way to accomplish this cleanup task, but I'm not super happy with it.  I can define a separate entity whose query runs a DELETE:

<dataConfig>
    <dataSource ... >
    <document>
        <entity name="person"
                query="
                    SELECT ID, FIRST_NAME, LAST_NAME
                    FROM PERSON
                    WHERE '${dataimporter.request.clean}' != 'false'
                        OR PERSON_ID IN (
                            SELECT ID FROM CHANGED_PERSON
                        )" />

        <entity name="deleteChangedPersonRecords"
                query="DELETE FROM CHANGED_PERSON" />
    </document>
</dataConfig>

This seems to work, but it's a bit of a hack, and it relies on the assumption that Solr executes its entity queries in the same order that they are specified in the file.  If anyone has a better solution, please feel free to add your answer to this question.