问:
Camera2 Library not giving default capture sound on picture taken in android
everyone !
I have searched about the capture sound in new Camera2 Library but i did't find it. I need to play capture sound when image is taken. As in old hardware.camera there is shutterCallBack which we can use to play sound. if any one know how to do that please thanks in advance!</p>

答:
In Camera2 api still exist a callback method that you can use for play shutter sound

https://developer.android.com/reference/android/hardware/camera2/CameraCaptureSession.CaptureCallback.html

CameraCaptureSession.CaptureCallback.onCaptureStarted

added in API level 21
void onCaptureStarted (CameraCaptureSession session,
                CaptureRequest request,
                long timestamp,
                long frameNumber)
This method is called when the camera device has started capturing the output image for the request, at the beginning of image exposure, or when the camera device has started processing an input image for a reprocess request.

For a regular capture request, this callback is invoked right as the capture of a frame begins, so it is the most appropriate time for playing a shutter sound, or triggering UI indicators of capture.

The request that is being used for this capture is provided, along with the actual timestamp for the start of exposure. For a reprocess request, this timestamp will be the input image's start of exposure which matches the result timestamp field of the TotalCaptureResult that was used to create the reprocess request. This timestamp matches the timestamps that will be included in the result timestamp field, and in the buffers sent to each output Surface. These buffer timestamps are accessible through, for example, Image.getTimestamp() or getTimestamp(). The frame number included is equal to the frame number that will be included in getFrameNumber().

For the simplest way to play a shutter sound camera shutter or a video recording start/stop sound, see the MediaActionSound class.

The default implementation of this method does nothing.


来源: stackexchange

问:
$scope variable in function
I  have to take a few pictures in an app, I'm making it with Ionic and Angular.

I have 3 buttons and each has to take a picture.
This is the HTML side:

```<code><img ng-src="{{srcImage1 || 'img/foto_defecto.png'}}" id="takeImage1"
 height="40" width="40" style="margin-right: 7px;" ng-click="Take">

<img ng-src="{{srcImage2 || 'img/foto_defecto.png'}}" id="srcImage2"
height="40" width="40" style="margin-right: 7px;" ng-click="takeImage2">

<img ng-src="{{srcImage3 || 'img/foto_defecto.png'}}" id="srcImage3"
height="40" width="40" style="margin-right: 7px;" ng-click="takeImage3">
</code>```

Doesn't matter I have inline css, it's a test.

And these are the functions: 3 of them, one for each button.

```<code>    $scope.takeImage1 = function() {
      var options = {
        quality: 100,
        destinationType: Camera.DestinationType.DATA_URL,
        sourceType: Camera.PictureSourceType.CAMERA,
        allowEdit: false,
        encodingType: Camera.EncodingType.PNG,
        targetWidth: 250,
        targetHeight: 250,
        popoverOptions: CameraPopoverOptions,
        saveToPhotoAlbum: true
      };

      $cordovaCamera.getPicture(options).then(function(imageData) {
        $scope.srcImage1 = "data:image/PNG;base64," + imageData;

      }, function(err) {
        // error
      });
    }
</code>```

What the function does is: takes the picture, saves it and it'll show a thumbnail under the srcImage1/2/3/etc.

However I want to have just ONE function and call it from each button.

For that I changed the code to this:

the call:

```<code><img ng-src="{{srcImage1 || 'img/foto_defecto.png'}}" id="srcImage1"
height="40" width="40" style="margin-right: 7px;" ng-click="hacerFoto(1)">
</code>```

the function:

```<code> $scope.hacerFoto = function(numero) {
    var options = {
        quality: 100,
        destinationType: Camera.DestinationType.DATA_URL,
        sourceType: Camera.PictureSourceType.CAMERA,
        allowEdit: false,
        encodingType: Camera.EncodingType.PNG,
        targetWidth: 250,
        targetHeight: 250,
        popoverOptions: CameraPopoverOptions,
        saveToPhotoAlbum: true
    };
  var buscar = "srcImage".concat(numero);
  alert(buscar);
  $cordovaCamera.getPicture(options).then(function(imageData) {
        $scope.buscar = "data:image/PNG;base64," + imageData;
  }, function() {
        alert("error al hacer la foto");
  });
}
</code>```

However the $scope.buscar in my intent to make a general function won't update the thumbnail.

The alert(buscar); shows exactly what I'm expecting, however $scope.buscar won't update the image. I don't know why it wouldn't work.

I found a solution to this, which is the next one:

```<code>  $cordovaCamera.getPicture(options).then(function(imageData) {
        var image = document.getElementById('srcImage'+numero);
        image.src = "data:image/PNG;base64," + imageData;
  }, function() {
        alert("error al hacer la foto");
  });
</code>```

Just take the ID with JS and replace the src.
However, the answer from @Vladimir Zdenek is much more elegant and in Angular - so I changed my code to that. I accepted his answear as the correct one.

答:
You have to change the reference to the image in your template from:

```<code><img ng-src="{{srcImage1 || 'img/foto_defecto.png'}}" id="srcImage1" height="40" width="40" style="margin-right: 7px;" ng-click="hacerFoto(1)">
</code>```

to

```<code><img ng-src="{{buscar1 || 'img/foto_defecto.png'}}" id="buscar1" height="40" width="40" style="margin-right: 7px;" ng-click="hacerFoto(1)">
</code>```

Then in your function, change the following line

```<code>$scope.buscar = "data:image/PNG;base64," + imageData;
</code>```

to this

```<code>$scope['buscar' + numero] = "data:image/PNG;base64," + imageData;
</code>```

Also make sure to change your other images in the template as well.

ContentLicense: CC BY-SA 3.0

Title: $scope variable in function

Body:
I  have to take a few pictures in an app, I'm making it with Ionic and Angular.

I have 3 buttons and each has to take a picture.
This is the HTML side:

Doesn't matter I have inline css, it's a test.

And these are the functions: 3 of them, one for each button.

    $scope.takeImage1 = function() {
      var options = {
        quality: 100,
        destinationType: Camera.DestinationType.DATA_URL,
        sourceType: Camera.PictureSourceType.CAMERA,
        allowEdit: false,
        encodingType: Camera.EncodingType.PNG,
        targetWidth: 250,
        targetHeight: 250,
        popoverOptions: CameraPopoverOptions,
        saveToPhotoAlbum: true
      };

      $cordovaCamera.getPicture(options).then(function(imageData) {
        $scope.srcImage1 = "data:image/PNG;base64," + imageData;

      }, function(err) {
        // error
      });
    }

What the function does is: takes the picture, saves it and it'll show a thumbnail under the srcImage1/2/3/etc.

However I want to have just ONE function and call it from each button.

For that I changed the code to this:

the call:

the function:

 $scope.hacerFoto = function(numero) {
    var options = {
        quality: 100,
        destinationType: Camera.DestinationType.DATA_URL,
        sourceType: Camera.PictureSourceType.CAMERA,
        allowEdit: false,
        encodingType: Camera.EncodingType.PNG,
        targetWidth: 250,
        targetHeight: 250,
        popoverOptions: CameraPopoverOptions,
        saveToPhotoAlbum: true
    };
  var buscar = "srcImage".concat(numero);
  alert(buscar);
  $cordovaCamera.getPicture(options).then(function(imageData) {
        $scope.buscar = "data:image/PNG;base64," + imageData;
  }, function() {
        alert("error al hacer la foto");
  });
}

However the $scope.buscar in my intent to make a general function won't update the thumbnail.

The alert(buscar); shows exactly what I'm expecting, however $scope.buscar won't update the image. I don't know why it wouldn't work.

I found a solution to this, which is the next one:

  $cordovaCamera.getPicture(options).then(function(imageData) {
        var image = document.getElementById('srcImage'+numero);
        image.src = "data:image/PNG;base64," + imageData;
  }, function() {
        alert("error al hacer la foto");
  });

Just take the ID with JS and replace the src.
However, the answer from @Vladimir Zdenek is much more elegant and in Angular - so I changed my code to that. I accepted his answear as the correct one.

Body:
You have to change the reference to the image in your template from:

<img ng-src="{{srcImage1 || 'img/foto_defecto.png'}}" id="srcImage1" height="40" width="40" style="margin-right: 7px;" ng-click="hacerFoto(1)">

to

<img ng-src="{{buscar1 || 'img/foto_defecto.png'}}" id="buscar1" height="40" width="40" style="margin-right: 7px;" ng-click="hacerFoto(1)">

Then in your function, change the following line

$scope.buscar = "data:image/PNG;base64," + imageData;

to this

$scope['buscar' + numero] = "data:image/PNG;base64," + imageData;

Also make sure to change your other images in the template as well.


问:
Combining two Microsoft Access Databases into one with a form to choose between them
So I've been assigned to work on two identical databases which are very poorly made.  Both are split up into front/back ends, but that have different data.

Is it possible to combine both databases into one and create a form to allow the user to choose which "database" they will interact with?

To clarify, the school that utilizes these databases has a database for the Fall semester and Spring semester.  Both contain the exact same forms/queries/tables, but the specific data differs. e.g. Maybe a teacher teaches 3 classes in the fall, but 4 classes in the Spring (the database is way more complicated that this though).  The structure of the data remains the same, but the specific data changes depending on the database.

So, if they need to access data, they need to open the corresponding database.  As a result, they are constantly open/closing different databases.  What they want to do is be able to just use one database and switch between Fall/Spring.

Is this at all possible?

答:
Without knowing the exact structure of your data it's hard to give specific answers, but my gut feeling is most definitely these two databases could be combined. Combine all the data in tables of the same name, but add a "Semester" column to any table that would result in duplicated data. Then simply create the application frontend so wherever necessary the user would select the Semester they want to view, and pass it to your queries retrieving the data. You could even carry the "Semester" value from the beginning as you point out, and pass it from screen to screen (w/ a global application-level variable).

It's been a while since I've had to code in Access in my professional life, but I'm sure there's a way to accomplish your goal. Maybe post more details of your specific data structure, and we can all jump in and give pointers!

ContentLicense: CC BY-SA 2.5


问:
Elastic Search: Get Exact Match first the other match
In Elastic Search we have function: setDefaultOperator.

```<code>$query->setDefaultOperator('AND')->setFields(array('keyword'));
</code>```

Above gives only exact match.

```<code>$query->setDefaultOperator('OR')->setFields(array('keyword'));
</code>```

Above gives all matches.(But not exact match first)

I need exact match first then other match. Any idea?

I am using Elastic Search for the first time. Any help will be appreciated.

答:
If you would like to do it using query_string
then you have to define the default operator in order to change the default one which is OR.

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html

have a look full example below using Kibana

```<code>PUT /phone/brand/1
{
  "color" : "black",
  "name" : "Samsung"
}

PUT /phone/brand/2
{
  "color" : "black",
  "name" : "Iphone"
}

PUT /phone/brand/3
{
  "color" : "white",
  "name" : "Samsung"
}

//query string
GET /phone/brand/_search
{
  "query": {
    "query_string": {
      "fields": ["color","name"],
      "default_operator": "AND",
      "query": "Samsung black"
    }
  }
}
</code>```

Body:
In Elastic Search we have function: setDefaultOperator.

$query->setDefaultOperator('AND')->setFields(array('keyword'));

Above gives only exact match.

$query->setDefaultOperator('OR')->setFields(array('keyword'));

Above gives all matches.(But not exact match first)

I need exact match first then other match. Any idea?

I am using Elastic Search for the first time. Any help will be appreciated.

Body:
If you would like to do it using query_string
then you have to define the default operator in order to change the default one which is OR.

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html

have a look full example below using Kibana

PUT /phone/brand/1
{
  "color" : "black",
  "name" : "Samsung"
}

PUT /phone/brand/2
{
  "color" : "black",
  "name" : "Iphone"
}

PUT /phone/brand/3
{
  "color" : "white",
  "name" : "Samsung"
}

//query string
GET /phone/brand/_search
{
  "query": {
    "query_string": {
      "fields": ["color","name"],
      "default_operator": "AND",
      "query": "Samsung black"
    }
  }
}


问:
Can't get sockets to work in ASP.NET Core
I'm trying to use sockets to send/receive data in ASP.NET Core. I followed a few tutorial I found but I can't seem to get any working. No matter what I try in my website, the socket connector stays in the "Connecting/Opening" state.

These are the tutorials I tried:

http://zbrad.github.io/tools/wscore/ -> this is the one I currently used in my code below

https://radu-matei.github.io/blog/aspnet-core-websockets-middleware/

http://dotnetthoughts.net/using-websockets-in-aspnet-core/

My startup.cs file looks like this:

```<code>using System;
using System.Text;
using arnvanhoutte.Data;
using arnvanhoutte.Models;
using arnvanhoutte.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;

namespace arnvanhoutte
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            Console.WriteLine(env.EnvironmentName);
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", true, true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true);

            Console.WriteLine(Configuration.GetConnectionString("DefaultConnection"));
            if (env.IsDevelopment())
            {
                builder.AddUserSecrets("aspnet-arnvanhoutte-8942961e-3f9b-48f6-a54d-907858e0ad3a");
            }

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        private IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(_ => Configuration);

            // Add framework services.
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc();

            services.Configure<IdentityOptions>(opt =>
            {
                opt.Cookies.ApplicationCookie.LoginPath = new PathString("/Admin/User/Login");
            });

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();
            services.AddTransient<Seed>();
        }

        // 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, IServiceProvider serviceProvider, Seed seeder)
        {

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            loggerFactory.AddAzureWebAppDiagnostics();

            seeder.SeedRoles().ConfigureAwait(false);
            seeder.SeedAdminUser().ConfigureAwait(false);
            seeder.SeedTestUser().ConfigureAwait(false);

            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.Map("/ws", SocketHandler.Map);

          if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            if (env.IsDevelopment())
            {
                app.Use(async (context, next) =>
                {
                    var request = context.Request;
                    if (request.IsHttps)
                    {
                        await next();
                    }
                    else
                    {
                        var devPort = Configuration.GetValue<int>("iisSettings:iisExpress:sslPort");

                        var host = new HostString(request.Host.Host, devPort);

                        string newUrl = $"https://{host}{request.PathBase}{request.Path}{request.QueryString}";
                        context.Response.Redirect(newUrl, true);
                    }
                });
            }

            app.UseIdentity();

            // secretKey contains a secret passphrase only your server knows
            var secretKey = Configuration.GetSection("AppSettings")["SecretKey"];
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));

            var options = new TokenProviderOptions
            {
                Path = "/token",
                Audience = "User",
                Issuer = "arnvanhoutte",
                SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
                IdentityResolver = (username, password) =>
                {
                    using (
                        var serviceScope =
                            app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
                    {
                        var userManager = serviceScope.ServiceProvider.GetService<UserManager<ApplicationUser>>();

                        var user = userManager.FindByNameAsync(username).Result;

                        if (user != null && userManager.CheckPasswordAsync(user, password).Result)
                        {
                            return user;
                        }

                        // Credentials are invalid, or account doesn't exist
                        return null;
                    }
                }
            };

            var tokenValidationParameters = new TokenValidationParameters
            {
                // The signing key must match!
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,

                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer = "arnvanhoutte",

                // Validate the JWT Audience (aud) claim
                ValidateAudience = true,
                ValidAudience = "User",

                // Validate the token expiry
                ValidateLifetime = true,

                // If you want to allow a certain amount of clock drift, set that here:
                ClockSkew = TimeSpan.Zero
            };

            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                TokenValidationParameters = tokenValidationParameters
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                AuthenticationScheme = "Cookie",
                LoginPath = new PathString("/login"),
                AccessDeniedPath = new PathString("/login"),
                ReturnUrlParameter = "redirect",
                CookieName = "access_token",
                TicketDataFormat = new CustomJwtDataFormat(
                    SecurityAlgorithms.HmacSha256,
                    tokenValidationParameters)
            });

            app.UseMiddleware<TokenProviderMiddleware>(Options.Create(options));

            app.UseMvc(routes =>
            {
                routes.MapRoute("myProjects",
                    "{area:exists}/{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute(
                    "default",
                    "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
</code>```

This is the sockethandler.cs file:

```<code>using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

namespace arnvanhoutte.Services
{
    public class SocketHandler
    {
        public const int BufferSize = 4096;

        private readonly WebSocket _socket;

        private SocketHandler(WebSocket socket)
        {
            _socket = socket;
        }

        private async Task EchoLoop()
        {
            var buffer = new byte[BufferSize];
            var seg = new ArraySegment<byte>(buffer);

            while (_socket.State == WebSocketState.Open)
            {
                var incoming = await _socket.ReceiveAsync(seg, CancellationToken.None);
                var outgoing = new ArraySegment<byte>(buffer, 0, incoming.Count);
                await _socket.SendAsync(outgoing, WebSocketMessageType.Text, true, CancellationToken.None);
            }
        }

        private static async Task Acceptor(HttpContext hc, Func<Task> n)
        {
            if (!hc.WebSockets.IsWebSocketRequest)
                return;

            var socket = await hc.WebSockets.AcceptWebSocketAsync();
            var h = new SocketHandler(socket);
            await h.EchoLoop();
        }
        public static void Map(IApplicationBuilder app)
        {
            app.UseWebSockets();
            app.Use(Acceptor);
        }
    }
}
</code>```

And this is the html file I serve:

```<code>@{
    Layout = null;
}
<div id="output"></div>

<script language="javascript" type="text/javascript">

    var socket;
    var uri = "ws://" + window.location.host + "/ws";
    var output;
    var text = "test echo";

    function write(s) {
        var p = document.createElement("p");
        p.innerHTML = s;
        output.appendChild(p);
    }

    function doConnect() {
        socket = new WebSocket(uri);
        socket.onopen = function (e) { write("opened " + uri); doSend(); };
        socket.onclose = function (e) { write("closed"); };
        socket.onmessage = function (e) { write("Received: " + e.data); socket.close(); };
        socket.onerror = function (e) { write("Error: " + e.data); };
    }

    function doSend() {
        write("Sending: " + text);
        socket.send(text);
    }

    function onInit() {
        output = document.getElementById("output");
        doConnect();
    }

    window.onload = onInit;

</script>
</code>```

When I run this and navigate to the file, nothing initially appears. After a while do I get this error in the console: sockettest:17 WebSocket connection to 'ws://localhost:44399/ws' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET

答:
I found a solution! The problem was that google chrome was blocking my websockets I think because of an unsafe certificate. The fix was to generate a legit certificate with a script found here: https://github.com/webpack/webpack-dev-server/issues/854

Then I also had to change the uri to wss:// instead of ws://. Then everything worked

Body:
I'm trying to use sockets to send/receive data in ASP.NET Core. I followed a few tutorial I found but I can't seem to get any working. No matter what I try in my website, the socket connector stays in the "Connecting/Opening" state.

These are the tutorials I tried:

http://zbrad.github.io/tools/wscore/ -> this is the one I currently used in my code below

https://radu-matei.github.io/blog/aspnet-core-websockets-middleware/

http://dotnetthoughts.net/using-websockets-in-aspnet-core/

My startup.cs file looks like this:

using System;
using System.Text;
using arnvanhoutte.Data;
using arnvanhoutte.Models;
using arnvanhoutte.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;

namespace arnvanhoutte
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            Console.WriteLine(env.EnvironmentName);
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", true, true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true);

            Console.WriteLine(Configuration.GetConnectionString("DefaultConnection"));
            if (env.IsDevelopment())
            {
                builder.AddUserSecrets("aspnet-arnvanhoutte-8942961e-3f9b-48f6-a54d-907858e0ad3a");
            }

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        private IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(_ => Configuration);

            // Add framework services.
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc();

            services.Configure<IdentityOptions>(opt =>
            {
                opt.Cookies.ApplicationCookie.LoginPath = new PathString("/Admin/User/Login");
            });

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();
            services.AddTransient<Seed>();
        }

        // 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, IServiceProvider serviceProvider, Seed seeder)
        {

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            loggerFactory.AddAzureWebAppDiagnostics();

            seeder.SeedRoles().ConfigureAwait(false);
            seeder.SeedAdminUser().ConfigureAwait(false);
            seeder.SeedTestUser().ConfigureAwait(false);

            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.Map("/ws", SocketHandler.Map);

          if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            if (env.IsDevelopment())
            {
                app.Use(async (context, next) =>
                {
                    var request = context.Request;
                    if (request.IsHttps)
                    {
                        await next();
                    }
                    else
                    {
                        var devPort = Configuration.GetValue<int>("iisSettings:iisExpress:sslPort");

                        var host = new HostString(request.Host.Host, devPort);

                        string newUrl = $"https://{host}{request.PathBase}{request.Path}{request.QueryString}";
                        context.Response.Redirect(newUrl, true);
                    }
                });
            }

            app.UseIdentity();

            // secretKey contains a secret passphrase only your server knows
            var secretKey = Configuration.GetSection("AppSettings")["SecretKey"];
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));

            var options = new TokenProviderOptions
            {
                Path = "/token",
                Audience = "User",
                Issuer = "arnvanhoutte",
                SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
                IdentityResolver = (username, password) =>
                {
                    using (
                        var serviceScope =
                            app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
                    {
                        var userManager = serviceScope.ServiceProvider.GetService<UserManager<ApplicationUser>>();

                        var user = userManager.FindByNameAsync(username).Result;

                        if (user != null && userManager.CheckPasswordAsync(user, password).Result)
                        {
                            return user;
                        }

                        // Credentials are invalid, or account doesn't exist
                        return null;
                    }
                }
            };

            var tokenValidationParameters = new TokenValidationParameters
            {
                // The signing key must match!
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,

                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer = "arnvanhoutte",

                // Validate the JWT Audience (aud) claim
                ValidateAudience = true,
                ValidAudience = "User",

                // Validate the token expiry
                ValidateLifetime = true,

                // If you want to allow a certain amount of clock drift, set that here:
                ClockSkew = TimeSpan.Zero
            };

            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                TokenValidationParameters = tokenValidationParameters
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                AuthenticationScheme = "Cookie",
                LoginPath = new PathString("/login"),
                AccessDeniedPath = new PathString("/login"),
                ReturnUrlParameter = "redirect",
                CookieName = "access_token",
                TicketDataFormat = new CustomJwtDataFormat(
                    SecurityAlgorithms.HmacSha256,
                    tokenValidationParameters)
            });

            app.UseMiddleware<TokenProviderMiddleware>(Options.Create(options));

            app.UseMvc(routes =>
            {
                routes.MapRoute("myProjects",
                    "{area:exists}/{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute(
                    "default",
                    "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

This is the sockethandler.cs file:

using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

namespace arnvanhoutte.Services
{
    public class SocketHandler
    {
        public const int BufferSize = 4096;

        private readonly WebSocket _socket;

        private SocketHandler(WebSocket socket)
        {
            _socket = socket;
        }

        private async Task EchoLoop()
        {
            var buffer = new byte[BufferSize];
            var seg = new ArraySegment<byte>(buffer);

            while (_socket.State == WebSocketState.Open)
            {
                var incoming = await _socket.ReceiveAsync(seg, CancellationToken.None);
                var outgoing = new ArraySegment<byte>(buffer, 0, incoming.Count);
                await _socket.SendAsync(outgoing, WebSocketMessageType.Text, true, CancellationToken.None);
            }
        }

        private static async Task Acceptor(HttpContext hc, Func<Task> n)
        {
            if (!hc.WebSockets.IsWebSocketRequest)
                return;

            var socket = await hc.WebSockets.AcceptWebSocketAsync();
            var h = new SocketHandler(socket);
            await h.EchoLoop();
        }
        public static void Map(IApplicationBuilder app)
        {
            app.UseWebSockets();
            app.Use(Acceptor);
        }
    }
}

And this is the html file I serve:

@{
    Layout = null;
}

When I run this and navigate to the file, nothing initially appears. After a while do I get this error in the console: sockettest:17 WebSocket connection to 'ws://localhost:44399/ws' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET


问:
purrr::map equivalent to dplyr::do
Reading https://twitter.com/hadleywickham/status/719542847045636096 I understand that the purrr approach should basically replace do.

Hence, I was wondering how I would use purrr to do this:

```<code>library(dplyr)
d <- data_frame(n = 1:3)
d %>% rowwise() %>% do(data_frame(x = seq_len(.$n))) %>% ungroup()
# # tibble [6 x 1]
#       x
# * <int>
# 1     1
# 2     1
# 3     2
# 4     1
# 5     2
# 6     3
</code>```

The closest I could get was something like:

```<code>library(purrrr)
d %>% mutate(x = map(n, seq_len))
# # A tibble: 3 x 2
#       n         x
#   <int>    <list>
# 1     1 <int [1]>
# 2     2 <int [2]>
# 3     3 <int [3]>
</code>```

map_int would not work. So what is the purrrr way of doing it?

答:
You could do the following:

```<code>library(tidyverse)
library(purrr)
d %>% by_row(~data_frame(x = seq_len(.$n))) %>% unnest()
</code>```

by_row applies a function to each row, storing the result in nested tibbles.
unnest is then used to remove the nesting and to concatenate the tibbles.

Title: purrr::map equivalent to dplyr::do

Body:
Reading https://twitter.com/hadleywickham/status/719542847045636096 I understand that the purrr approach should basically replace do.

Hence, I was wondering how I would use purrr to do this:

library(dplyr)
d <- data_frame(n = 1:3)
d %>% rowwise() %>% do(data_frame(x = seq_len(.$n))) %>% ungroup()
# # tibble [6 x 1]
#       x
# * <int>
# 1     1
# 2     1
# 3     2
# 4     1
# 5     2
# 6     3

The closest I could get was something like:

library(purrrr)
d %>% mutate(x = map(n, seq_len))
# # A tibble: 3 x 2
#       n         x
#   <int>    <list>
# 1     1 <int [1]>
# 2     2 <int [2]>
# 3     3 <int [3]>

map_int would not work. So what is the purrrr way of doing it?

Body:
You could do the following:

library(tidyverse)
library(purrr)
d %>% by_row(~data_frame(x = seq_len(.$n))) %>% unnest()

by_row applies a function to each row, storing the result in nested tibbles.
unnest is then used to remove the nesting and to concatenate the tibbles.


问:
How to throw errors in a lib
I am currently building a small lib for reading / writing / moving files around concurrently.
While doing this i ran into the problem of error handling which lead me to think:

should i throw an error inside the lib and have the user's entire app crash, or return an error message for the user to handle ?

I would like to know which is best for the given situation and why.

答:
I recommend reading over The Go Blog article Error Handling and Go and Effective Go on errors, which take a look at the power of Go's error type.

In general panics are okay to use within a library/package, but they should not propagate outside of the package unless there is a fatal error. In other words, developers should never have to write code that expects panics form your library.

You can use panics internally if managing the propagation of errors is tedious. In that case you can wrap your public functions with a defer/recover handler which passes the error

```<code>func Function() (err error) {
    defer func() {
        if r := recover(); r != nil {
            err = r.(error)
        }
    }()
    // Do stuff
    panic(errors.New("Error Message"))
}
</code>```

This sample is adapted from the json package of the standard library, where internal panics are used to clean up complicated nested error handling.

Title: How to throw errors in a lib

Body:
I recommend reading over The Go Blog article Error Handling and Go and Effective Go on errors, which take a look at the power of Go's error type.

In general panics are okay to use within a library/package, but they should not propagate outside of the package unless there is a fatal error. In other words, developers should never have to write code that expects panics form your library.

You can use panics internally if managing the propagation of errors is tedious. In that case you can wrap your public functions with a defer/recover handler which passes the error

func Function() (err error) {
    defer func() {
        if r := recover(); r != nil {
            err = r.(error)
        }
    }()
    // Do stuff
    panic(errors.New("Error Message"))
}

This sample is adapted from the json package of the standard library, where internal panics are used to clean up complicated nested error handling.


问:
linq nested query conditional order by
I have a parent query with sub query return child ,
what i need to sort child query according to one property in parent.
here is sudo code:

```<code>from menu in db.Menus
                     orderby menu.Order
                     select new
                     {
                         Title= menu.Title,
                         OrderNumber = menu.Order,
                         data = (from menuItem in menu.Items
                                  let g = Guid.NewGuid()
                                  orderby g
                                 select new
                                 {
                                     id = worker.ID,
                                     Title = worker.JobTitle
                                  })
                                 .Take(4)

                     };
</code>```

that works ok,But what i need to sort some menu in random(NewGuid) and sort others with their item priority some thing like it:

```<code>  let g = Guid.NewGuid()
orderby menu.ISRandom ? g: menuItem.Order
</code>```

But it give error about mismatch guid and int.What's the soloution?
second:How can i replace take(4) with take(menu.size)?
thank's

答:
It seems you want to read four records from menu.Items at random.

I think you'd be way better off just reading all the items, and then doing the random selection later in code in memory.

Title: linq nested query conditional order by

Body:
I have a parent query with sub query return child ,
what i need to sort child query according to one property in parent.
here is sudo code:

from menu in db.Menus
                     orderby menu.Order
                     select new
                     {
                         Title= menu.Title,
                         OrderNumber = menu.Order,
                         data = (from menuItem in menu.Items
                                  let g = Guid.NewGuid()
                                  orderby g
                                 select new
                                 {
                                     id = worker.ID,
                                     Title = worker.JobTitle
                                  })
                                 .Take(4)

                     };

that works ok,But what i need to sort some menu in random(NewGuid) and sort others with their item priority some thing like it:

  let g = Guid.NewGuid()
orderby menu.ISRandom ? g: menuItem.Order

But it give error about mismatch guid and int.What's the soloution?
second:How can i replace take(4) with take(menu.size)?
thank's


问:
Change Parameter Group of AWS RDS instance
How to change the parameter group of an AWS RDS instance?

I've created a new parameter group. So now I have default and my new one.

In RDS Dashboard > Instances, on my instance under configuration details I see that default group is selected.

But don't see anywhere to edit the group on the instance. Clicking the group under configuration details loads the parameter group page.

This entire article never actually mentions how to change the group on the instance. http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithParamGroups.html

答:
To change anything like that you click on the RDS instance and then select "Modify". In the Modify screen you can select a different parameter group.

From @bitavoc's reply -
If the dropdown doesn't let you select a parameter group recently created, check that both the parameter group and the RDS instance use the same major version of the engine.

ContentLicense: CC BY-SA 4.0


问:
R error in renaming list of objects
I am working with R 3.4.0.

I have got multiple single-band rasters, gathered in one folder, which I want to stack together, in a multi-band raster. Following the instructions of other posts, I wrote these simple lines:

```<code>s2_list <- list.files(path="C:/Users/LAURA/Documents/S2", pattern=".tif$")
s2_stack <- stack(s2_list)
</code>```

This procedure gave me the following error:

Error in .local(.Object, ...) :

      Error in .rasterObjectFromFile(x, band = band, objecttype = "RasterLayer",  :
      Cannot create a RasterLayer object from this file. (file does not exist)

I read other posts with the same problem but without a clear solution; one of the alternatives is renaming the files of the list, which I'm trying to do with the following script:

```<code>s2_list <- list.files(path="C:/Users/LAURA/Documents/S2", pattern=".tif$")
names_list <- paste("ndvi_", 1:104)
file.rename(s2_list, names_list)
s2_stack <- stack(s2_list)
</code>```

The output is the following:

```<code>file.rename(s2_list, names_list)

[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[20] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[39] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[58] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[77] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[96] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
</code>```

Anyone has got any idea why this happens? I already checked the number of objects in the first list, and it's 104.

Sample of s2_list:

```<code>s2_list
  [1] "S2A_20150706T105351Z_31UFS_NDVI_10M_V008.tif" "S2A_20150716T105024Z_31UFS_NDVI_10M_V008.tif"
  [3] "S2A_20150726T105024Z_31UFS_NDVI_10M_V008.tif" "S2A_20150805T105026Z_31UFS_NDVI_10M_V008.tif"
  [5] "S2A_20150812T104021Z_31UFS_NDVI_10M_V008.tif" "S2A_20150815T105627Z_31UFS_NDVI_10M_V008.tif"
  [7] "S2A_20150822T104035Z_31UFS_NDVI_10M_V008.tif" "S2A_20150825T105041Z_31UFS_NDVI_10M_V008.tif"
  [9] "S2A_20150904T105042Z_31UFS_NDVI_10M_V008.tif" "S2A_20150911T104038Z_31UFS_NDVI_10M_V008.tif"
</code>```

答:
A more safe way is to avoid "hard coding" (<- root of all evil)
.</p>

```<code>    targetDir<-file.path("path","where","your","files","reside")
    s2_list <-list.files(path=targetDir,pattern=".tif$",full.names = T)
    names_list <- paste0(targetDir,"/ndvi_", 1:length(s2_list),".tif")
    file.rename(s2_list, names_list)
</code>```

Title: R error in renaming list of objects

Body:
I am working with R 3.4.0.

I have got multiple single-band rasters, gathered in one folder, which I want to stack together, in a multi-band raster. Following the instructions of other posts, I wrote these simple lines:

s2_list <- list.files(path="C:/Users/LAURA/Documents/S2", pattern=".tif$")
s2_stack <- stack(s2_list)

This procedure gave me the following error:

Error in .local(.Object, ...) :

      Error in .rasterObjectFromFile(x, band = band, objecttype = "RasterLayer",  :
      Cannot create a RasterLayer object from this file. (file does not exist)

I read other posts with the same problem but without a clear solution; one of the alternatives is renaming the files of the list, which I'm trying to do with the following script:

s2_list <- list.files(path="C:/Users/LAURA/Documents/S2", pattern=".tif$")
names_list <- paste("ndvi_", 1:104)
file.rename(s2_list, names_list)
s2_stack <- stack(s2_list)

The output is the following:

file.rename(s2_list, names_list)

[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[20] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[39] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[58] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[77] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[96] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

Anyone has got any idea why this happens? I already checked the number of objects in the first list, and it's 104.

Sample of s2_list:

s2_list
  [1] "S2A_20150706T105351Z_31UFS_NDVI_10M_V008.tif" "S2A_20150716T105024Z_31UFS_NDVI_10M_V008.tif"
  [3] "S2A_20150726T105024Z_31UFS_NDVI_10M_V008.tif" "S2A_20150805T105026Z_31UFS_NDVI_10M_V008.tif"
  [5] "S2A_20150812T104021Z_31UFS_NDVI_10M_V008.tif" "S2A_20150815T105627Z_31UFS_NDVI_10M_V008.tif"
  [7] "S2A_20150822T104035Z_31UFS_NDVI_10M_V008.tif" "S2A_20150825T105041Z_31UFS_NDVI_10M_V008.tif"
  [9] "S2A_20150904T105042Z_31UFS_NDVI_10M_V008.tif" "S2A_20150911T104038Z_31UFS_NDVI_10M_V008.tif"

Body:
A more safe way is to avoid "hard coding" (<- root of all evil)
.

    targetDir<-file.path("path","where","your","files","reside")
    s2_list <-list.files(path=targetDir,pattern=".tif$",full.names = T)
    names_list <- paste0(targetDir,"/ndvi_", 1:length(s2_list),".tif")
    file.rename(s2_list, names_list)


问:
How to build a swipable intro screen?
A lot of apps have swipable intro screens - You know - those with the dots below which indicate the page one is currently viewing.

What would be the best way to create one in Codename One - a Container with snapToGrid?

答:
I have my own implementation for this use case. There are two classes : TutoDialog which could be in your case the "intro screens" dialog and Caroussel with the dots indicator.
A tuto dialog has a title and some images in parameter. It automatically adjust the number of dots of the caroussel according to the number of images. For my use case, each image is a screenshot of my app with some advise. The tuto dialog contains 3 buttons to navigate between images (next/previous/finish).

```<code>public class Caroussel extends Container {
private final static Image CIRCLE = MainClass.getResources().getImage("circle-blue20.png");
private final static Image CIRCLE_EMPTY = MainClass.getResources().getImage("circle-empty-blue20.png");

private Label[] circles;
private int currentIndex = -1;

public Caroussel(int nbItems, boolean selectFirst) {
    if (nbItems < 2 || nbItems > 50) {
        throw new IllegalArgumentException("Can't create Caroussel component with nbItems<2 || nbItems>50 ! ");
    }
    this.circles = new Label[nbItems];
    setLayout(new BoxLayout(BoxLayout.X_AXIS));
    for (int i = 0; i < nbItems; i++) {
        circles[i] = new Label("", CIRCLE_EMPTY);
        add(circles[i]);
    }
    if (selectFirst) {
        select(0);
    }
}

public void select(int index) {
    if (index >= 0 && index <= circles.length) {
        if (currentIndex > -1) {
            circles[currentIndex].setIcon(CIRCLE_EMPTY);
        }
        circles[index].setIcon(CIRCLE);
        currentIndex = index;
        repaint();
    }
}

public void selectNext() {
    if (currentIndex <= circles.length) {
        select(currentIndex + 1);
    }
}

public void selectPrevious() {
    if (currentIndex >= 1) {
        select(currentIndex - 1);
    }
}}
</code>```

And

```<code>public class TutoDialog extends Dialog {
private Caroussel caroussel = null;

public TutoDialog(String title, Image... images) {
    if (images == null) {
        return;
    }
    this.caroussel = new Caroussel(images.length, true);
    setTitle(title);
    setAutoAdjustDialogSize(true);
    getTitleComponent().setUIID("DialogTitle2");
    setBlurBackgroundRadius(8.5f);
    Tabs tabs = new Tabs();
    tabs.setSwipeActivated(false);
    tabs.setAnimateTabSelection(false);
    int px1 = DisplayUtil.getScaledPixel(800), px2 = DisplayUtil.getScaledPixel(600);
    for (Image img : images) {
        tabs.addTab("", new Label("", img.scaled(px1, px2)));
    }
    Container cButtons = new Container(new BorderLayout());
    Button bSuivant = new Button("button.suivant");
    Button bPrecedent = new Button("button.precedent");
    Button bTerminer = new Button("button.terminer");
    bPrecedent.setVisible(false);
    bTerminer.setVisible(false);
    bSuivant.addActionListener(new ActionListener<ActionEvent>() {
        public void actionPerformed(ActionEvent evt) {
            int currentInd = tabs.getSelectedIndex();
            if (currentInd == 0) {
                bPrecedent.setVisible(true);
            }
            if (currentInd + 1 <= tabs.getTabCount() - 1) {
                if (caroussel != null)
                    caroussel.selectNext();
                tabs.setSelectedIndex(currentInd + 1);
                if (currentInd + 1 == tabs.getTabCount() - 1) {
                    bTerminer.setVisible(true);
                    bSuivant.setVisible(false);
                    cButtons.revalidate();
                }
            }

        };
    });
    bPrecedent.addActionListener(new ActionListener<ActionEvent>() {
        public void actionPerformed(ActionEvent evt) {
            int currentInd = tabs.getSelectedIndex();
            tabs.setSelectedIndex(currentInd - 1);

            bSuivant.setVisible(true);
            if (caroussel != null)
                caroussel.selectPrevious();
            if (currentInd - 1 == 0) {
                bPrecedent.setVisible(false);
                cButtons.revalidate();
            }
        };
    });
    bTerminer.addActionListener(new ActionListener<ActionEvent>() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            tabs.setSelectedIndex(0);
            bPrecedent.setVisible(false);
            bTerminer.setVisible(false);
            bSuivant.setVisible(true);
            if (caroussel != null)
                caroussel.select(0);
            TutoDialog.this.dispose();
        }
    });
    cButtons.add(BorderLayout.WEST, bPrecedent).add(BorderLayout.CENTER, bSuivant).add(BorderLayout.EAST, bTerminer);
    add(BoxLayout.encloseY(tabs, BoxLayout.encloseY(FlowLayout.encloseCenter(caroussel), cButtons)));
}

public static void showIfFirstTime(AbstractComponentController ctrl) {
    if (ctrl == null) {
        Log.p("Can't execute method showIfFirstTime(...) with null AbstractComponentController");
        return;
    }
    String key = getKey(ctrl);
    if (ctrl.getTutoDlg() != null && !Preferences.get(key, false)) {
        Display.getInstance().callSerially(new Runnable() {

            @Override
            public void run() {
                Preferences.set(key, true);
                ctrl.getTutoDlg().show();
            }
        });
    }

}

public static String getKey(AbstractComponentController ctrl) {
    String key = "tuto" + ctrl.getClass().getSimpleName();
    if (UserController.getCurrentUser() != null) {
        key += "-" + UserController.getCurrentUser().getId();
    }
    return key;
}

public static boolean isAlreadyShown(AbstractComponentController ctrl) {
    return Preferences.get(getKey(ctrl), false);
}
}
</code>```

It's look like this :

Title: How to build a swipable intro screen?

Body:
I have my own implementation for this use case. There are two classes : TutoDialog which could be in your case the "intro screens" dialog and Caroussel with the dots indicator.
A tuto dialog has a title and some images in parameter. It automatically adjust the number of dots of the caroussel according to the number of images. For my use case, each image is a screenshot of my app with some advise. The tuto dialog contains 3 buttons to navigate between images (next/previous/finish).

public class Caroussel extends Container {
private final static Image CIRCLE = MainClass.getResources().getImage("circle-blue20.png");
private final static Image CIRCLE_EMPTY = MainClass.getResources().getImage("circle-empty-blue20.png");

private Label[] circles;
private int currentIndex = -1;

public Caroussel(int nbItems, boolean selectFirst) {
    if (nbItems < 2 || nbItems > 50) {
        throw new IllegalArgumentException("Can't create Caroussel component with nbItems<2 || nbItems>50 ! ");
    }
    this.circles = new Label[nbItems];
    setLayout(new BoxLayout(BoxLayout.X_AXIS));
    for (int i = 0; i < nbItems; i++) {
        circles[i] = new Label("", CIRCLE_EMPTY);
        add(circles[i]);
    }
    if (selectFirst) {
        select(0);
    }
}

public void select(int index) {
    if (index >= 0 && index <= circles.length) {
        if (currentIndex > -1) {
            circles[currentIndex].setIcon(CIRCLE_EMPTY);
        }
        circles[index].setIcon(CIRCLE);
        currentIndex = index;
        repaint();
    }
}

public void selectNext() {
    if (currentIndex <= circles.length) {
        select(currentIndex + 1);
    }
}

public void selectPrevious() {
    if (currentIndex >= 1) {
        select(currentIndex - 1);
    }
}}

And

public class TutoDialog extends Dialog {
private Caroussel caroussel = null;

public TutoDialog(String title, Image... images) {
    if (images == null) {
        return;
    }
    this.caroussel = new Caroussel(images.length, true);
    setTitle(title);
    setAutoAdjustDialogSize(true);
    getTitleComponent().setUIID("DialogTitle2");
    setBlurBackgroundRadius(8.5f);
    Tabs tabs = new Tabs();
    tabs.setSwipeActivated(false);
    tabs.setAnimateTabSelection(false);
    int px1 = DisplayUtil.getScaledPixel(800), px2 = DisplayUtil.getScaledPixel(600);
    for (Image img : images) {
        tabs.addTab("", new Label("", img.scaled(px1, px2)));
    }
    Container cButtons = new Container(new BorderLayout());
    Button bSuivant = new Button("button.suivant");
    Button bPrecedent = new Button("button.precedent");
    Button bTerminer = new Button("button.terminer");
    bPrecedent.setVisible(false);
    bTerminer.setVisible(false);
    bSuivant.addActionListener(new ActionListener<ActionEvent>() {
        public void actionPerformed(ActionEvent evt) {
            int currentInd = tabs.getSelectedIndex();
            if (currentInd == 0) {
                bPrecedent.setVisible(true);
            }
            if (currentInd + 1 <= tabs.getTabCount() - 1) {
                if (caroussel != null)
                    caroussel.selectNext();
                tabs.setSelectedIndex(currentInd + 1);
                if (currentInd + 1 == tabs.getTabCount() - 1) {
                    bTerminer.setVisible(true);
                    bSuivant.setVisible(false);
                    cButtons.revalidate();
                }
            }

        };
    });
    bPrecedent.addActionListener(new ActionListener<ActionEvent>() {
        public void actionPerformed(ActionEvent evt) {
            int currentInd = tabs.getSelectedIndex();
            tabs.setSelectedIndex(currentInd - 1);

            bSuivant.setVisible(true);
            if (caroussel != null)
                caroussel.selectPrevious();
            if (currentInd - 1 == 0) {
                bPrecedent.setVisible(false);
                cButtons.revalidate();
            }
        };
    });
    bTerminer.addActionListener(new ActionListener<ActionEvent>() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            tabs.setSelectedIndex(0);
            bPrecedent.setVisible(false);
            bTerminer.setVisible(false);
            bSuivant.setVisible(true);
            if (caroussel != null)
                caroussel.select(0);
            TutoDialog.this.dispose();
        }
    });
    cButtons.add(BorderLayout.WEST, bPrecedent).add(BorderLayout.CENTER, bSuivant).add(BorderLayout.EAST, bTerminer);
    add(BoxLayout.encloseY(tabs, BoxLayout.encloseY(FlowLayout.encloseCenter(caroussel), cButtons)));
}

public static void showIfFirstTime(AbstractComponentController ctrl) {
    if (ctrl == null) {
        Log.p("Can't execute method showIfFirstTime(...) with null AbstractComponentController");
        return;
    }
    String key = getKey(ctrl);
    if (ctrl.getTutoDlg() != null && !Preferences.get(key, false)) {
        Display.getInstance().callSerially(new Runnable() {

            @Override
            public void run() {
                Preferences.set(key, true);
                ctrl.getTutoDlg().show();
            }
        });
    }

}

public static String getKey(AbstractComponentController ctrl) {
    String key = "tuto" + ctrl.getClass().getSimpleName();
    if (UserController.getCurrentUser() != null) {
        key += "-" + UserController.getCurrentUser().getId();
    }
    return key;
}

public static boolean isAlreadyShown(AbstractComponentController ctrl) {
    return Preferences.get(getKey(ctrl), false);
}
}

It's look like this :


问:
How to check if data exists in firebase using angularfire?
I would like to register users manually in firebase. How can i check if the user is registered already or if his ( USERID ) exists? If it exists it should not let him register otherwise if his userid is not yet on the database then his info should be saved. Here is my current code wherein only saving userinfo is still available.</p>

```<code>$scope.details={};

$scope.registerme= function() {
var someDate = new Date();
var ref = firebase.database().ref('/Users/');
$scope.submitme = $firebaseArray(ref);

            $scope.submitme.$add({
            facebookid: $scope.details.userid,
            firstname: $scope.details.firstname,
            lastname: $scope.details.lastname,
            timestamp: someDate.toString(),
            }).then(function(ref) {
            alert('Registration success.');
            }).catch(function(error) {
            alert('Registration Failed.');
            });

};
</code>```

答:
If you set up a link to your db entity as FirebaseObjectObservable, then you can use exists() to check if your entity exists.
That how I check if my table exists and if not, I'll fill it with initial data:

vehicle.service.ts:

```<code>...
public vehicles$$: FirebaseObjectObservable<any>; // link to '/vehicles' as object
public vehicles$ FirebaseListObservable<Vehicle[]>; // link to '/vehicles' as list
...
constructor(
  private _http: Http,
  private _db: AngularFireDatabase,

) {
  this.vehicles$$ = _db.object('/vehicles');
  this.vehicles$ = _db.list('/vehicles');
}

public getVehicles(){
  this.vehicles$$.subscribe(table => {
    if(!table.$exists()){
      this.getVehiclesFromFile().subscribe(vehicles(vehicles: Vehicle[]) =>
        this.vehicles$$.set(vehicles).catch(err=>console.error(err))
      )
    }
  })
  return this.vehicles$;
}
</code>```

Body:
I would like to register users manually in firebase. How can i check if the user is registered already or if his ( USERID ) exists? If it exists it should not let him register otherwise if his userid is not yet on the database then his info should be saved. Here is my current code wherein only saving userinfo is still available.

$scope.details={};

$scope.registerme= function() {
var someDate = new Date();
var ref = firebase.database().ref('/Users/');
$scope.submitme = $firebaseArray(ref);

            $scope.submitme.$add({
            facebookid: $scope.details.userid,
            firstname: $scope.details.firstname,
            lastname: $scope.details.lastname,
            timestamp: someDate.toString(),
            }).then(function(ref) {
            alert('Registration success.');
            }).catch(function(error) {
            alert('Registration Failed.');
            });

};

Body:
If you set up a link to your db entity as FirebaseObjectObservable, then you can use exists() to check if your entity exists.
That how I check if my table exists and if not, I'll fill it with initial data:

vehicle.service.ts:

...
public vehicles$$: FirebaseObjectObservable<any>; // link to '/vehicles' as object
public vehicles$ FirebaseListObservable<Vehicle[]>; // link to '/vehicles' as list
...
constructor(
  private _http: Http,
  private _db: AngularFireDatabase,

) {
  this.vehicles$$ = _db.object('/vehicles');
  this.vehicles$ = _db.list('/vehicles');
}

public getVehicles(){
  this.vehicles$$.subscribe(table => {
    if(!table.$exists()){
      this.getVehiclesFromFile().subscribe(vehicles(vehicles: Vehicle[]) =>
        this.vehicles$$.set(vehicles).catch(err=>console.error(err))
      )
    }
  })
  return this.vehicles$;
}


问:
Spring Batch: What is the way to pass a huge Map Object across the Job in Spring Batch
Use case:
Step 1:
ItemReader : Reading Data from Database in chunk of 1000
ItemProcessor : Process those Data.
ItemWriter : Write the data in a Map for used in next step

Step 2:
ItemReader : Reading the Map
ItemProcessor : Process the Map data and get the new object.
ItemWriter : Persist the new process object in database.

Now I want the Map the should remain same across the job,
Currently I have created a different POJO class for Map and Autowired in the step to use it, but the problem is when ever I new chunk of data loading my Map is reseting but I want to keep the Map object with all its value as it is across the Job execution.

答: Try with StepExecutionListener.</p>

Body: Try with StepExecutionListener.


问:
MySQL Query Browser alternatives
I usually use MySQL Query Browser for my queries, but I always run into issues with the connections timing out and the Query Browser locking up, so I'm looking into alternatives.  The new MySQL Workbench is much too slow and heavyweight, I prefer that the Administrative tools and the Query tools are separate (although it wouldn't be as much of a problem if the application wasn't so slow).  I run on Ubuntu 10.04 x64.  I'd like to avoid Windows/Wine-based solutions as much as possible.  I also have had bad experiences (slow, buggy) with JVM-based MySQL applications, although perhaps other people know more lightweight ones.

I want something lightweight that can show me the schemas, tables, and column tree, and present a decent UI for editing tables.

Any suggestions would be appreciated.

答:
I realize you want to avoid wine, but this might be a good suggestion for you as a free tool.

http://www.heidisql.com/

Title: MySQL Query Browser alternatives


问:
Write Once, Test Everywhere - Selenium and Python's unittest on desktop and mobile
I'm working with Selenium and Python's unittest and I'm creating test cases for desktop, tablet and mobile websites. However, it's not ideal to have three test cases that test on same things.

At the moment, I put self.driver.set_window_size(1366, 768) in the desktop's test method and self.driver.set_window_size(414, 736) in the mobile's test method. So I have two test methods that do the same job mostly.

I am looking for some ways to encapsulate the set_window_size() and to have one test method, maybe with the if loop to test on some elements that may only appear on mobile or desktop websites.

答:
With a solution from e4c5, I was able to run one test case on desktop and mobile.

I would need to have a if loop to test an element that may be on mobile but not on desktop and vice versa.

So my solution was:

```<code>if self.driver.get_window_size() == {'height': 736, 'width': 414}:
</code>```

Body:
With a solution from e4c5, I was able to run one test case on desktop and mobile.

I would need to have a if loop to test an element that may be on mobile but not on desktop and vice versa.

So my solution was:

if self.driver.get_window_size() == {'height': 736, 'width': 414}:


问:
Make Wordpress theme Underscores dropdown menu close when clicking outside of it
I'm working with the WordPress starter theme Underscores and the dropdown menu can be opened and closed by clicking the 'menu' button. I'd also like it to close when I click somewhere else on the page though, and I can't for the life of me figure out how to do it. :(

I've tried stuff like:

```<code>$(document).click(function(){
  $(".toggled").hide();
});
</code>```

But that doesn't work.

This is the navigation.js file:

```<code>( function() {
var container, button, menu, links, subMenus, i, len;

container = document.getElementById( 'site-navigation' );
if ( ! container ) {
    return;
}

button = container.getElementsByTagName( 'button' )[0];
if ( 'undefined' === typeof button ) {
    return;
}

menu = container.getElementsByTagName( 'ul' )[0];

// Hide menu toggle button if menu is empty and return early.
if ( 'undefined' === typeof menu ) {
    button.style.display = 'none';
    return;
}

menu.setAttribute( 'aria-expanded', 'false' );
if ( -1 === menu.className.indexOf( 'nav-menu' ) ) {
    menu.className += ' nav-menu';
}

button.onclick = function() {
    if ( -1 !== container.className.indexOf( 'toggled' ) ) {
        container.className = container.className.replace( ' toggled', '' );
        button.setAttribute( 'aria-expanded', 'false' );
        menu.setAttribute( 'aria-expanded', 'false' );
    } else {
        container.className += ' toggled';
        button.setAttribute( 'aria-expanded', 'true' );
        menu.setAttribute( 'aria-expanded', 'true' );
    }
};

// Get all the link elements within the menu.
links    = menu.getElementsByTagName( 'a' );
subMenus = menu.getElementsByTagName( 'ul' );

// Set menu items with submenus to aria-haspopup="true".
for ( i = 0, len = subMenus.length; i < len; i++ ) {
    subMenus[i].parentNode.setAttribute( 'aria-haspopup', 'true' );
}

// Each time a menu link is focused or blurred, toggle focus.
for ( i = 0, len = links.length; i < len; i++ ) {
    links[i].addEventListener( 'focus', toggleFocus, true );
    links[i].addEventListener( 'blur', toggleFocus, true );
}

/**
 * Sets or removes .focus class on an element.
 */
function toggleFocus() {
    var self = this;

    // Move up through the ancestors of the current link until we hit .nav-menu.
    while ( -1 === self.className.indexOf( 'nav-menu' ) ) {

        // On li elements toggle the class .focus.
        if ( 'li' === self.tagName.toLowerCase() ) {
            if ( -1 !== self.className.indexOf( 'focus' ) ) {
                self.className = self.className.replace( ' focus', '' );
            } else {
                self.className += ' focus';
            }
        }

        self = self.parentElement;
    }
}
} )();
</code>```

答:
Assuming the ul has the class .toggled, the following should do it

```<code>$(document).on("click", "body" function(){
  $('.toggled').not(':hidden').toggle();
});
</code>```

Body:
I'm working with the WordPress starter theme Underscores and the dropdown menu can be opened and closed by clicking the 'menu' button. I'd also like it to close when I click somewhere else on the page though, and I can't for the life of me figure out how to do it. :(

I've tried stuff like:

$(document).click(function(){
  $(".toggled").hide();
});

But that doesn't work.

This is the navigation.js file:

( function() {
var container, button, menu, links, subMenus, i, len;

container = document.getElementById( 'site-navigation' );
if ( ! container ) {
    return;
}

button = container.getElementsByTagName( 'button' )[0];
if ( 'undefined' === typeof button ) {
    return;
}

menu = container.getElementsByTagName( 'ul' )[0];

// Hide menu toggle button if menu is empty and return early.
if ( 'undefined' === typeof menu ) {
    button.style.display = 'none';
    return;
}

menu.setAttribute( 'aria-expanded', 'false' );
if ( -1 === menu.className.indexOf( 'nav-menu' ) ) {
    menu.className += ' nav-menu';
}

button.onclick = function() {
    if ( -1 !== container.className.indexOf( 'toggled' ) ) {
        container.className = container.className.replace( ' toggled', '' );
        button.setAttribute( 'aria-expanded', 'false' );
        menu.setAttribute( 'aria-expanded', 'false' );
    } else {
        container.className += ' toggled';
        button.setAttribute( 'aria-expanded', 'true' );
        menu.setAttribute( 'aria-expanded', 'true' );
    }
};

// Get all the link elements within the menu.
links    = menu.getElementsByTagName( 'a' );
subMenus = menu.getElementsByTagName( 'ul' );

// Set menu items with submenus to aria-haspopup="true".
for ( i = 0, len = subMenus.length; i < len; i++ ) {
    subMenus[i].parentNode.setAttribute( 'aria-haspopup', 'true' );
}

// Each time a menu link is focused or blurred, toggle focus.
for ( i = 0, len = links.length; i < len; i++ ) {
    links[i].addEventListener( 'focus', toggleFocus, true );
    links[i].addEventListener( 'blur', toggleFocus, true );
}

/**
 * Sets or removes .focus class on an element.
 */
function toggleFocus() {
    var self = this;

    // Move up through the ancestors of the current link until we hit .nav-menu.
    while ( -1 === self.className.indexOf( 'nav-menu' ) ) {

        // On li elements toggle the class .focus.
        if ( 'li' === self.tagName.toLowerCase() ) {
            if ( -1 !== self.className.indexOf( 'focus' ) ) {
                self.className = self.className.replace( ' focus', '' );
            } else {
                self.className += ' focus';
            }
        }

        self = self.parentElement;
    }
}
} )();

Body:
Assuming the ul has the class .toggled, the following should do it

$(document).on("click", "body" function(){
  $('.toggled').not(':hidden').toggle();
});


问:
The name 'Drawline' does not exist in the current context
```<code>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;

        }
    }
}
</code>```

Hello guys! Im having a problem with this code and the title is my error. Im pretty new with c# and graphics too, I understand this code,(partially wrote it myself but this error is driving me crazy). Can anyone tell me where im mistaken and explain it to me? Thanks in advance! And btw is there an easy way for example via button to delete everything thats going to be painted on the form and how can i do that?

答:
You are using the DrawLine method wrong. It draws a line on Graphics instance. You should use something like this:

```<code>g.DrawLine(p, sp, ep);
</code>```

Body:
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;

        }
    }
}

Hello guys! Im having a problem with this code and the title is my error. Im pretty new with c# and graphics too, I understand this code,(partially wrote it myself but this error is driving me crazy). Can anyone tell me where im mistaken and explain it to me? Thanks in advance! And btw is there an easy way for example via button to delete everything thats going to be painted on the form and how can i do that?

Body:
You are using the DrawLine method wrong. It draws a line on Graphics instance. You should use something like this:

g.DrawLine(p, sp, ep);


问:
ERROR:ssl_client_socket_openssl.cc(1158)] handshake failed with ChromeDriver Chrome browser and Selenium
When running my python selenium script with Chrome driver I get about three of the below error messages every time a page loads even though everything works fine. Is there a way to suppress these messages?

[24412:18772:0617/090708:ERROR:ssl_client_socket_openssl.cc(1158)]
handshake failed; returned -1, SSL error code 1, net_error -100

答:
For me it got resolved after writing code as below in chrome options, change from above answer was to include spki-list.</p>

```<code>options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors-spki-list')
options.add_argument('--ignore-ssl-errors')
driver = webdriver.Chrome(chrome_options=options)
</code>```

Body:
For me it got resolved after writing code as below in chrome options, change from above answer was to include spki-list.

options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors-spki-list')
options.add_argument('--ignore-ssl-errors')
driver = webdriver.Chrome(chrome_options=options)


答:
Here is something that I used when I ran into the same problem:

It also checks whether you click on it to cancel the event.

```<code>$(document).click(function() {
    $(".dropdown-content").hide();
    // $(".dropdown-content").removeClass("show");
});

$(".dropdown-content").click(function(e) {
    e.stopPropagation(); // if you click on the div itself it will cancel the click event.
});
</code>```

Title: Make Wordpress theme Underscores dropdown menu close when clicking outside of it

Body:
Here is something that I used when I ran into the same problem:

It also checks whether you click on it to cancel the event.

$(document).click(function() {
    $(".dropdown-content").hide();
    // $(".dropdown-content").removeClass("show");
});

$(".dropdown-content").click(function(e) {
    e.stopPropagation(); // if you click on the div itself it will cancel the click event.
});


问:
how to represent graphs /trees in python and how to detect cycles?
i want to implement kruskal's algorithm in python how can i go about representing the tree/graph and what approach should i follow to detect the cycles ?</p>

答:
Python Graph API is a good place to start.

For example, NetworkX has a Kruskal's algorithm implementation to find the minimum spanning tree.

If you want to re-invent the wheel and do it yourself, that is also possible.


问:
Android Studio Gradle OutofMemory Error
Ive been trying to import my android project into a new computer with Android Studio 0.5.2 after each gradle build i get:

```<code>Out of memory: Java heap space. Configure Gradle memory settings using '-Xmx' JVM option (e.g. '-Xmx2048m'.)
    Please fix the project's Gradle settings.
    Gradle settings
</code>```

The project isnt very big,only thing im using is google play services and i dont believe it requires alot of memory.For this has a head scratcher and i dont know what to do.

答:
You can also got to:
Help > Edit Custom VM Options...

custom Android Studio VM options, see http://tools.android.com/tech-docs/configuration

```<code>-server
-Xms512m
-Xmx2048m
-XX:ReservedCodeCacheSize=720m
-XX:+UseConcMarkSweepGC
-XX:SoftRefLRUPolicyMSPerMB=100
-ea
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-XX:+HeapDumpOnOutOfMemoryError
-XX:-OmitStackTraceInFastThrow
-XX:MaxJavaStackTraceDepth=-1
</code>```

Title: Android Studio Gradle OutofMemory Error

Body:
Ive been trying to import my android project into a new computer with Android Studio 0.5.2 after each gradle build i get:

Out of memory: Java heap space. Configure Gradle memory settings using '-Xmx' JVM option (e.g. '-Xmx2048m'.)
    Please fix the project's Gradle settings.
    Gradle settings

The project isnt very big,only thing im using is google play services and i dont believe it requires alot of memory.For this has a head scratcher and i dont know what to do.

Body:
You can also got to:
Help > Edit Custom VM Options...

custom Android Studio VM options, see http://tools.android.com/tech-docs/configuration

-server
-Xms512m
-Xmx2048m
-XX:ReservedCodeCacheSize=720m
-XX:+UseConcMarkSweepGC
-XX:SoftRefLRUPolicyMSPerMB=100
-ea
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-XX:+HeapDumpOnOutOfMemoryError
-XX:-OmitStackTraceInFastThrow
-XX:MaxJavaStackTraceDepth=-1


问:
Modify "tf history" command to yield only unmerged changesets
I have two branches, Apple and Banana. Out of all the unmerged changesets in Apple, I only want to merge those that contain the term MergeToBanana in their check-in comments.

So far this is what I have in my PowerShell script:

```<code>Param (
       [Parameter(Mandatory=$true)]
       [String]$ChangesetComment
       )

$tf = get-item "c:\program files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\TF.EXE"

if ($ChangesetComment) {
    echo "*** Looking for all changesets containing '$ChangesetComment' in their check-in comments. This might take a while. ***"
    $changesetsToMerge = & $tf history $/TeamProject/Server/Apple /noprompt /recursive | findstr $ChangesetComment
    $changesetNumbers = $changesetsToMerge | % $_.changesetnumber

    echo "*** Now merging filtered changesets. ***"
    Foreach ($c in $changesetNumbers) {
        & $tf merge /version $_.c $/IMSDev/Closed/$ScdVersion . /r /noprompt
    }
}
</code>```

Given my example, ChangesetComment will be set to MergeToBanana when I run the script.

I would like to modify my tf history command so that it only yields information about changesets in Apple that are not yet merged into Banana, so that I don't have to search through the entire history for changesets that contain ChangesetComment in their check-in comments. How can I do so?

Any other advice on how to improve my script is also welcome.

答:
Instead of using the  tf history command, you could try to use  /candidate option in TF merge command

tf merge /candidate SOURCE_BRANCH TARGET_BRANCH

Example:

tf merge /candidate Apple Banana

More detai ways please refer the answers in this question: TFS: List changesets that have not been merged

Body:
I have two branches, Apple and Banana. Out of all the unmerged changesets in Apple, I only want to merge those that contain the term MergeToBanana in their check-in comments.

So far this is what I have in my PowerShell script:

Param (
       [Parameter(Mandatory=$true)]
       [String]$ChangesetComment
       )

$tf = get-item "c:\program files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\TF.EXE"

if ($ChangesetComment) {
    echo "*** Looking for all changesets containing '$ChangesetComment' in their check-in comments. This might take a while. ***"
    $changesetsToMerge = & $tf history $/TeamProject/Server/Apple /noprompt /recursive | findstr $ChangesetComment
    $changesetNumbers = $changesetsToMerge | % $_.changesetnumber

    echo "*** Now merging filtered changesets. ***"
    Foreach ($c in $changesetNumbers) {
        & $tf merge /version $_.c $/IMSDev/Closed/$ScdVersion . /r /noprompt
    }
}

Given my example, ChangesetComment will be set to MergeToBanana when I run the script.

I would like to modify my tf history command so that it only yields information about changesets in Apple that are not yet merged into Banana, so that I don't have to search through the entire history for changesets that contain ChangesetComment in their check-in comments. How can I do so?

Any other advice on how to improve my script is also welcome.


问:
Working with EventListener in Firebase for Android
Consider, I store the following Key-Value pair in Firebase Database.

Key: "CarBrand" and Value: "Audi"

I read the Value for this Key from Firebase Database and display the Value in TextView. For this, I use an EventListener.

The problem I face with an EventListsner is since it runs on a separate thread, the TextView returns a NullPointerException even before the Value is fetched from Firebase.

To overcome the issue I have been using this dirty trick (using a Handler with 500 to 1000 ms delay). Can someone guide me the right way to fetch and display the Value in TextView or any other Views

PS: Apologies for this codeless Question

Thanks

EDIT: More the Code, better the question. The sample code is as follows

```<code>String CardBrand;

private ValueEventListener contentListener() {
    contentListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //Pull Values for all available Keys
            CarBrand = dataSnapshot.child("CarBrand").getValue(String.class);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    };
    return contentListener;
}

dbContent.addListenerForSingleValueEvent(contentListener());
mTextView.setText(CarBrand);
</code>```

The above code results in error. To avoid this, I replaced the last line of code with

```<code>    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            mTextView.setText(CarBrand);
        }
    }, 1000);
</code>```

So this is what I have been doing. What would be the right way to display the Text in TextView in my Case?

答:
Let me show you small example:

This class responsible for retreiving the link for you, and it doesn't know what will you do with it, so it takes Callback and pass the result to your callback, where you can do anything you want.
public class SomeDataSource {

```<code>void getData(Callback callback) {
    String url = Backend.GetUrl();
    callback.onDownloadUrlReceived(url);
}
</code>```

}

this is description of callback. Which you can implement to handle data from SomeDataSource

```<code>public interface Callback {
    void onDownloadUrlReceived(String url)
}
</code>```

usage

```<code>void onCreate(Bundle savedInstanceState) {
    SomeDataSource downloader = new SomeDataSource();
    //here callback is implemented, and you can handle data from SomeDataSource like you want.
    downloader.getData(new Callback() {
        @Override
        public void onDownloadUrlReceived(String url) {
            do wat you want with url
        }
    });
}
</code>```

Body:
Consider, I store the following Key-Value pair in Firebase Database.

Key: "CarBrand" and Value: "Audi"

I read the Value for this Key from Firebase Database and display the Value in TextView. For this, I use an EventListener.

The problem I face with an EventListsner is since it runs on a separate thread, the TextView returns a NullPointerException even before the Value is fetched from Firebase.

To overcome the issue I have been using this dirty trick (using a Handler with 500 to 1000 ms delay). Can someone guide me the right way to fetch and display the Value in TextView or any other Views

PS: Apologies for this codeless Question

Thanks

EDIT: More the Code, better the question. The sample code is as follows

String CardBrand;

private ValueEventListener contentListener() {
    contentListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //Pull Values for all available Keys
            CarBrand = dataSnapshot.child("CarBrand").getValue(String.class);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    };
    return contentListener;
}

dbContent.addListenerForSingleValueEvent(contentListener());
mTextView.setText(CarBrand);

The above code results in error. To avoid this, I replaced the last line of code with

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            mTextView.setText(CarBrand);
        }
    }, 1000);

So this is what I have been doing. What would be the right way to display the Text in TextView in my Case?

Body:
Let me show you small example:

This class responsible for retreiving the link for you, and it doesn't know what will you do with it, so it takes Callback and pass the result to your callback, where you can do anything you want.
public class SomeDataSource {

void getData(Callback callback) {
    String url = Backend.GetUrl();
    callback.onDownloadUrlReceived(url);
}

}

this is description of callback. Which you can implement to handle data from SomeDataSource

public interface Callback {
    void onDownloadUrlReceived(String url)
}

usage

void onCreate(Bundle savedInstanceState) {
    SomeDataSource downloader = new SomeDataSource();
    //here callback is implemented, and you can handle data from SomeDataSource like you want.
    downloader.getData(new Callback() {
        @Override
        public void onDownloadUrlReceived(String url) {
            do wat you want with url
        }
    });
}


问:
gwmi Win32_TSAccount -namespace root\cimv2\terminalservices r
gwmi Win32_TSAccount -namespace root\cimv2\terminalservices

resulting permission allowed in a bit wise format.

How can we covert to reaabale format?

答:
Try this:</p>

```<code>function Get-PermissionStrings {

    param([int]$Bits)

    $Permissions = @{
        0x001 = "WINSTATION_QUERY"
        0x002 = "WINSTATION_SET"
        0x004 = "WINSTATION_LOGOFF"
        0x010 = "WINSTATION_SHADOW"
        0x020 = "WINSTATION_LOGON"
        0x040 = "WINSTATION_RESET"
        0x080 = "WINSTATION_MSG"
        0x100 = "WINSTATION_CONNECT"
        0x200 = "WINSTATION_DISCONNECT"
        0xF0008 = "WINSTATION_VIRTUAL | STANDARD_RIGHTS_REQUIRED"
    }

    foreach($Bitmask in $Permissions.Keys | Sort-Object){
        if(($Bits -band $Bitmask) -eq $Bitmask){
            $Permissions[$Bitmask]
        }
    }
}
</code>```

Body:
Try this:

function Get-PermissionStrings {

    param([int]$Bits)

    $Permissions = @{
        0x001 = "WINSTATION_QUERY"
        0x002 = "WINSTATION_SET"
        0x004 = "WINSTATION_LOGOFF"
        0x010 = "WINSTATION_SHADOW"
        0x020 = "WINSTATION_LOGON"
        0x040 = "WINSTATION_RESET"
        0x080 = "WINSTATION_MSG"
        0x100 = "WINSTATION_CONNECT"
        0x200 = "WINSTATION_DISCONNECT"
        0xF0008 = "WINSTATION_VIRTUAL | STANDARD_RIGHTS_REQUIRED"
    }

    foreach($Bitmask in $Permissions.Keys | Sort-Object){
        if(($Bits -band $Bitmask) -eq $Bitmask){
            $Permissions[$Bitmask]
        }
    }
}


问:
Node: How to fix routing?
I need to use a router to integrate applications. To define an application I use app.use ('/ chat'. The application works separately, but it does not work together with the routing file.

How to fix routing?

/app.js

```<code>let express = require('express'),
    sqlite3 = require('sqlite3'),
    app = express(),
    http = require('http').Server(app),
    io = require('socket.io')(http),
    iconv = require('iconv-lite'),
    path = require('path'),
    sassMiddleware = require('node-sass-middleware'),
    fs = require('fs'),
    db = new sqlite3.Database('./chat/history.db');
    var routes = require('./chat');
    app.use('/chat', routes);
http.listen(3000);
</code>```

chat/index.js

```<code>let express = require('express'),
    router = express.Router(),
    sqlite3 = require('sqlite3'),
    app = express(),
    http = require('http').Server(app),
    io = require('socket.io')(http),
    iconv = require('iconv-lite'),
    path = require('path'),
    sassMiddleware = require('node-sass-middleware'),
    fs = require('fs'),
    db = new sqlite3.Database('./history.db');

// DB
if (!fs.existsSync(__dirname + '/history.db'))
    db.run("CREATE TABLE message (id INTEGER PRIMARY KEY AUTOINCREMENT,txt TEXT)");

// VIEWS SETTINGS
app.set('views', __dirname + '/tpl');
app.set('view engine', 'jade');
app.use(sassMiddleware({
    src: path.join(__dirname, '/tpl'),
    dest: path.join(__dirname, '/tpl'),
    debug: true,
    indentedSyntax: true,
    outputStyle: 'compressed',
}));
app.use(express.static(__dirname + '/tpl'));

// ROUTER
router.get("/", function (req, res) {
    res.render('page', {"name": "Виталий"})
});

// DOP FUNC
function addMesToDB(txt) {
    var stmt = db.prepare("INSERT INTO message (txt) VALUES (?)");
    stmt.run(txt);
    stmt.finalize();
}
function loadLast10() {
    db.each("SELECT * FROM message LIMIT 10", function(err, row) {
        io.emit('new message show', row.txt);
    });
}
function loadAll() {
    db.each("SELECT * FROM message", function(err, row) {
        io.emit('new message show', row.txt);
    });
}
function getDateTime() {
    var date = new Date();
    var hour = date.getHours();
    hour = (hour < 10 ? "0" : "") + hour;
    var min  = date.getMinutes();
    min = (min < 10 ? "0" : "") + min;
    var sec  = date.getSeconds();
    sec = (sec < 10 ? "0" : "") + sec;
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    month = (month < 10 ? "0" : "") + month;
    var day  = date.getDate();
    day = (day < 10 ? "0" : "") + day;
    return year + ":" + month + ":" + day + ":" + hour + ":" + min + ":" + sec;
}

// EMIT
let name = '';
io.on('connection', function(socket){
    io.sockets.on('connection', function (client) {});
    socket.on('login', function(msg){
        if(msg == '888') name = 'Оксана';
        else if(msg == '8888') name = 'Виталий';
        if(msg == '888' || msg == '8888') {
            addMesToDB(getDateTime() + ' <span class="name">Вошел пользователь: ' + name + '</span>');
            loadLast10();
        }
    });
    socket.on('loadAll', function(msg){
        loadAll();
    });
    socket.on('new message send', function(msg){
        io.emit('new message show', getDateTime() + ' <span class="name">' + name + ':</span> <span class="msg">' + msg + '</span>');
        addMesToDB(getDateTime() + ' <span class="name">' + name + ':</span> ' + msg);
    });
    socket.on('disconnect', function () {
        io.emit('new message show', getDateTime() + '  <span class="name">Вышел пользователь: ' + name + '</span>');
        addMesToDB(getDateTime() + '  <span class="name">Вышел пользователь: ' + name + '</span>');
    });
});

module.exports = router;
</code>```

err:

```<code>Error: No default engine was specified and no extension was provided.
    at new View (C:\chat2\chat2\node_modules\express\lib\view.js:62:11)
    at Function.render (C:\chat2\chat2\node_modules\express\lib\application.js:570:12)
    at ServerResponse.render (C:\chat2\chat2\node_modules\express\lib\response.js:971:7)
    at C:\chat2\chat2\chat\index.js:41:9
    at Layer.handle [as handle_request] (C:\chat2\chat2\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\chat2\chat2\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\chat2\chat2\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\chat2\chat2\node_modules\express\lib\router\layer.js:95:5)
    at C:\chat2\chat2\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\chat2\chat2\node_modules\express\lib\router\index.js:335:12)
</code>```

答:
When using res.render, you have to specify a view engine on root app:

```<code>app.set('view engine', 'jade')
</code>```

More details you could refer this document

Title: Node: How to fix routing?

Body:
I need to use a router to integrate applications. To define an application I use app.use ('/ chat'. The application works separately, but it does not work together with the routing file.

How to fix routing?

/app.js

let express = require('express'),
    sqlite3 = require('sqlite3'),
    app = express(),
    http = require('http').Server(app),
    io = require('socket.io')(http),
    iconv = require('iconv-lite'),
    path = require('path'),
    sassMiddleware = require('node-sass-middleware'),
    fs = require('fs'),
    db = new sqlite3.Database('./chat/history.db');
    var routes = require('./chat');
    app.use('/chat', routes);
http.listen(3000);

chat/index.js

let express = require('express'),
    router = express.Router(),
    sqlite3 = require('sqlite3'),
    app = express(),
    http = require('http').Server(app),
    io = require('socket.io')(http),
    iconv = require('iconv-lite'),
    path = require('path'),
    sassMiddleware = require('node-sass-middleware'),
    fs = require('fs'),
    db = new sqlite3.Database('./history.db');

// DB
if (!fs.existsSync(__dirname + '/history.db'))
    db.run("CREATE TABLE message (id INTEGER PRIMARY KEY AUTOINCREMENT,txt TEXT)");

// VIEWS SETTINGS
app.set('views', __dirname + '/tpl');
app.set('view engine', 'jade');
app.use(sassMiddleware({
    src: path.join(__dirname, '/tpl'),
    dest: path.join(__dirname, '/tpl'),
    debug: true,
    indentedSyntax: true,
    outputStyle: 'compressed',
}));
app.use(express.static(__dirname + '/tpl'));

// ROUTER
router.get("/", function (req, res) {
    res.render('page', {"name": "Виталий"})
});

// DOP FUNC
function addMesToDB(txt) {
    var stmt = db.prepare("INSERT INTO message (txt) VALUES (?)");
    stmt.run(txt);
    stmt.finalize();
}
function loadLast10() {
    db.each("SELECT * FROM message LIMIT 10", function(err, row) {
        io.emit('new message show', row.txt);
    });
}
function loadAll() {
    db.each("SELECT * FROM message", function(err, row) {
        io.emit('new message show', row.txt);
    });
}
function getDateTime() {
    var date = new Date();
    var hour = date.getHours();
    hour = (hour < 10 ? "0" : "") + hour;
    var min  = date.getMinutes();
    min = (min < 10 ? "0" : "") + min;
    var sec  = date.getSeconds();
    sec = (sec < 10 ? "0" : "") + sec;
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    month = (month < 10 ? "0" : "") + month;
    var day  = date.getDate();
    day = (day < 10 ? "0" : "") + day;
    return year + ":" + month + ":" + day + ":" + hour + ":" + min + ":" + sec;
}

// EMIT
let name = '';
io.on('connection', function(socket){
    io.sockets.on('connection', function (client) {});
    socket.on('login', function(msg){
        if(msg == '888') name = 'Оксана';
        else if(msg == '8888') name = 'Виталий';
        if(msg == '888' || msg == '8888') {
            addMesToDB(getDateTime() + ' Вошел пользователь: ' + name + '');
            loadLast10();
        }
    });
    socket.on('loadAll', function(msg){
        loadAll();
    });
    socket.on('new message send', function(msg){
        io.emit('new message show', getDateTime() + ' ' + name + ': ' + msg + '');
        addMesToDB(getDateTime() + ' ' + name + ': ' + msg);
    });
    socket.on('disconnect', function () {
        io.emit('new message show', getDateTime() + '  Вышел пользователь: ' + name + '');
        addMesToDB(getDateTime() + '  Вышел пользователь: ' + name + '');
    });
});

module.exports = router;

err:

Error: No default engine was specified and no extension was provided.
    at new View (C:\chat2\chat2\node_modules\express\lib\view.js:62:11)
    at Function.render (C:\chat2\chat2\node_modules\express\lib\application.js:570:12)
    at ServerResponse.render (C:\chat2\chat2\node_modules\express\lib\response.js:971:7)
    at C:\chat2\chat2\chat\index.js:41:9
    at Layer.handle [as handle_request] (C:\chat2\chat2\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\chat2\chat2\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\chat2\chat2\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\chat2\chat2\node_modules\express\lib\router\layer.js:95:5)
    at C:\chat2\chat2\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\chat2\chat2\node_modules\express\lib\router\index.js:335:12)

Body:
When using res.render, you have to specify a view engine on root app:

app.set('view engine', 'jade')

More details you could refer this document