问:
Google App Engine: DuplicateFileException
Been using my backend for over a year without a problem. Today I made a deployment from a new computer and all of a sudden I got a duplicatefileexception.

Full error:

```<code>Error:Execution failed for task ':android:transformResourcesWithMergeJavaResForDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK com/google/appengine/repackaged/org/apache/commons/codec/language/bm/sep_approx_spanish.txt
    File1: C:\Users\\.gradle\caches\modules-2\files-2.1\com.google.appengine\appengine-api-1.0-sdk\1.9.42\c972bc847992e5512eb4338a38cc2392e56760f6\appengine-api-1.0-sdk-1.9.42.jar
    File2: C:\Users\\.gradle\caches\modules-2\files-2.1\com.google.appengine\appengine-endpoints\1.9.42\5c25efed254f8f9846d04b156e68283055efd320\appengine-endpoints-1.9.42.jar
</code>```

There is an answer on Stack that says all you need to do is add this to your gradle:

```<code>dependencies {
    appengineSdk 'com.google.appengine:appengine-java-sdk:1.9.42'
    compile 'com.google.appengine:appengine-endpoints:1.9.42'
    compile ('com.google.appengine:appengine-endpoints-deps:1.9.42'){
        exclude "sep_approx_spanish.txt" //added
    }
    compile 'javax.servlet:servlet-api:2.5'
    compile files('src/main/webapp/WEB-INF/lib/objectify-5.1.12.jar')
    compile files('src/main/webapp/WEB-INF/lib/guava-19.0.jar')
    compile files('src/main/webapp/WEB-INF/lib/gcm-server-1.0.2.jar')
}
</code>```

However this gives me another error:

```<code>Error:Could not find method exclude() for arguments [sep_approx_spanish.txt] on DefaultExternalModuleDependency{group='com.google.appengine', name='appengine-endpoints-deps', version='1.9.42', configuration='default'} of type org.gradle.api.internal.artifacts.dependencies.DefaultExternalModuleDependency.
</code>```

I've looked through my client gradle and server, I can't find anywhere I am calling the same library twice or anything like that. Not sure what has happened.

Adding Android Client and Backend Gradle below:

Android:

```<code>android {
    buildToolsVersion '25.0.0'
    compileSdkVersion 23
    defaultConfig {
        multiDexEnabled = true
    }
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
            jniLibs.srcDirs = ['libs']
        }

        instrumentTest.setRoot('tests')
    }
}

dependencies {
    compile 'com.google.android.gms:play-services-gcm:9.4.0'
    compile 'com.google.android.gms:play-services-ads:9.4.0'
    compile 'com.google.code.findbugs:jsr305:2.0.1'
    compile project(path: ':backend', configuration: 'android-endpoints')
}

// called every time gradle gets executed, takes the native dependencies of
// the natives configuration, and extracts them to the proper libs/ folders
// so they get packed with the APK.
task copyAndroidNatives() {
    file("libs/armeabi/").mkdirs();
    file("libs/armeabi-v7a/").mkdirs();
    file("libs/x86/").mkdirs();

    configurations.natives.files.each { jar ->
        def outputDir = null
        if (jar.name.endsWith("natives-armeabi-v7a.jar")) outputDir = file("libs/armeabi-v7a")
        if (jar.name.endsWith("natives-armeabi.jar")) outputDir = file("libs/armeabi")
        if (jar.name.endsWith("natives-x86.jar")) outputDir = file("libs/x86")
        if (outputDir != null) {
            copy {
                from zipTree(jar)
                into outputDir
                include "*.so"
            }
        }
    }
}
task run(type: Exec) {
    def path
    def localProperties = project.file("../local.properties")
    if (localProperties.exists()) {
        Properties properties = new Properties()
        localProperties.withInputStream { instr ->
            properties.load(instr)
        }
        def sdkDir = properties.getProperty('sdk.dir')
        if (sdkDir) {
            path = sdkDir
        } else {
            path = "$System.env.ANDROID_HOME"
        }
    } else {
        path = "$System.env.ANDROID_HOME"
    }

    def adb = path + "/platform-tools/adb"
    commandLine "$adb", 'shell', 'am', 'start', '-n', '.android/AndroidLauncher'
}
// sets up the Android Eclipse project, using the old Ant based build.
eclipse {
    // need to specify Java source sets explicitely, SpringSource Gradle Eclipse plugin
    // ignores any nodes added in classpath.file.withXml
    sourceSets {
        main {
            java.srcDirs "src", 'gen'
        }
    }

    jdt {
        sourceCompatibility = 1.6
        targetCompatibility = 1.6
    }

    classpath {
        plusConfigurations += [project.configurations.compile]
        containers 'com.android.ide.eclipse.adt.ANDROID_FRAMEWORK', 'com.android.ide.eclipse.adt.LIBRARIES'
    }

    project {
        name = appName + "-android"
        natures 'com.android.ide.eclipse.adt.AndroidNature'
        buildCommands.clear();
        buildCommand "com.android.ide.eclipse.adt.ResourceManagerBuilder"
        buildCommand "com.android.ide.eclipse.adt.PreCompilerBuilder"
        buildCommand "org.eclipse.jdt.core.javabuilder"
        buildCommand "com.android.ide.eclipse.adt.ApkBuilder"
    }
}
// sets up the Android Idea project, using the old Ant based build.
idea {
    module {
        sourceDirs += file("src");
        scopes = [COMPILE: [plus: [project.configurations.compile]]]

        iml {
            withXml {
                def node = it.asNode()
                def builder = NodeBuilder.newInstance();
                builder.current = node;
                builder.component(name: "FacetManager") {
                    facet(type: "android", name: "Android") {
                        configuration {
                            option(name: "UPDATE_PROPERTY_FILES", value: "true")
                        }
                    }
                }
            }
        }
    }
}
</code>```

Backend:

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.google.appengine:gradle-appengine-plugin:1.9.42'
    }
}

repositories {
    jcenter();
}

apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'appengine'

sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7

dependencies {
    appengineSdk 'com.google.appengine:appengine-java-sdk:1.9.42'
    compile 'com.google.appengine:appengine-endpoints:1.9.42'
    compile 'com.google.appengine:appengine-endpoints-deps:1.9.42'
    compile 'javax.servlet:servlet-api:2.5'
    compile files('src/main/webapp/WEB-INF/lib/objectify-5.1.12.jar')
    compile files('src/main/webapp/WEB-INF/lib/guava-19.0.jar')
    compile files('src/main/webapp/WEB-INF/lib/gcm-server-1.0.2.jar')
}

appengine {
    downloadSdk = true
    appcfg {
        oauth2 = true
    }
    endpoints {
        getClientLibsOnBuild = true
        getDiscoveryDocsOnBuild = true
    }
}
</code>```

答:
Try to add the following in your 'app' build.gradle file:

```<code>android {
    ...
    packagingOptions {
        ...
        exclude 'com/google/appengine/repackaged/org/apache/commons/codec/language/bm/sep_approx_spanish.txt'
    }
}
</code>```

Body:
Been using my backend for over a year without a problem. Today I made a deployment from a new computer and all of a sudden I got a duplicatefileexception.

Full error:

Error:Execution failed for task ':android:transformResourcesWithMergeJavaResForDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK com/google/appengine/repackaged/org/apache/commons/codec/language/bm/sep_approx_spanish.txt
    File1: C:\Users\\.gradle\caches\modules-2\files-2.1\com.google.appengine\appengine-api-1.0-sdk\1.9.42\c972bc847992e5512eb4338a38cc2392e56760f6\appengine-api-1.0-sdk-1.9.42.jar
    File2: C:\Users\\.gradle\caches\modules-2\files-2.1\com.google.appengine\appengine-endpoints\1.9.42\5c25efed254f8f9846d04b156e68283055efd320\appengine-endpoints-1.9.42.jar

There is an answer on Stack that says all you need to do is add this to your gradle:

dependencies {
    appengineSdk 'com.google.appengine:appengine-java-sdk:1.9.42'
    compile 'com.google.appengine:appengine-endpoints:1.9.42'
    compile ('com.google.appengine:appengine-endpoints-deps:1.9.42'){
        exclude "sep_approx_spanish.txt" //added
    }
    compile 'javax.servlet:servlet-api:2.5'
    compile files('src/main/webapp/WEB-INF/lib/objectify-5.1.12.jar')
    compile files('src/main/webapp/WEB-INF/lib/guava-19.0.jar')
    compile files('src/main/webapp/WEB-INF/lib/gcm-server-1.0.2.jar')
}

However this gives me another error:

Error:Could not find method exclude() for arguments [sep_approx_spanish.txt] on DefaultExternalModuleDependency{group='com.google.appengine', name='appengine-endpoints-deps', version='1.9.42', configuration='default'} of type org.gradle.api.internal.artifacts.dependencies.DefaultExternalModuleDependency.

I've looked through my client gradle and server, I can't find anywhere I am calling the same library twice or anything like that. Not sure what has happened.

Adding Android Client and Backend Gradle below:

Android:

android {
    buildToolsVersion '25.0.0'
    compileSdkVersion 23
    defaultConfig {
        multiDexEnabled = true
    }
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
            jniLibs.srcDirs = ['libs']
        }

        instrumentTest.setRoot('tests')
    }
}

dependencies {
    compile 'com.google.android.gms:play-services-gcm:9.4.0'
    compile 'com.google.android.gms:play-services-ads:9.4.0'
    compile 'com.google.code.findbugs:jsr305:2.0.1'
    compile project(path: ':backend', configuration: 'android-endpoints')
}

// called every time gradle gets executed, takes the native dependencies of
// the natives configuration, and extracts them to the proper libs/ folders
// so they get packed with the APK.
task copyAndroidNatives() {
    file("libs/armeabi/").mkdirs();
    file("libs/armeabi-v7a/").mkdirs();
    file("libs/x86/").mkdirs();

    configurations.natives.files.each { jar ->
        def outputDir = null
        if (jar.name.endsWith("natives-armeabi-v7a.jar")) outputDir = file("libs/armeabi-v7a")
        if (jar.name.endsWith("natives-armeabi.jar")) outputDir = file("libs/armeabi")
        if (jar.name.endsWith("natives-x86.jar")) outputDir = file("libs/x86")
        if (outputDir != null) {
            copy {
                from zipTree(jar)
                into outputDir
                include "*.so"
            }
        }
    }
}
task run(type: Exec) {
    def path
    def localProperties = project.file("../local.properties")
    if (localProperties.exists()) {
        Properties properties = new Properties()
        localProperties.withInputStream { instr ->
            properties.load(instr)
        }
        def sdkDir = properties.getProperty('sdk.dir')
        if (sdkDir) {
            path = sdkDir
        } else {
            path = "$System.env.ANDROID_HOME"
        }
    } else {
        path = "$System.env.ANDROID_HOME"
    }

    def adb = path + "/platform-tools/adb"
    commandLine "$adb", 'shell', 'am', 'start', '-n', '.android/AndroidLauncher'
}
// sets up the Android Eclipse project, using the old Ant based build.
eclipse {
    // need to specify Java source sets explicitely, SpringSource Gradle Eclipse plugin
    // ignores any nodes added in classpath.file.withXml
    sourceSets {
        main {
            java.srcDirs "src", 'gen'
        }
    }

    jdt {
        sourceCompatibility = 1.6
        targetCompatibility = 1.6
    }

    classpath {
        plusConfigurations += [project.configurations.compile]
        containers 'com.android.ide.eclipse.adt.ANDROID_FRAMEWORK', 'com.android.ide.eclipse.adt.LIBRARIES'
    }

    project {
        name = appName + "-android"
        natures 'com.android.ide.eclipse.adt.AndroidNature'
        buildCommands.clear();
        buildCommand "com.android.ide.eclipse.adt.ResourceManagerBuilder"
        buildCommand "com.android.ide.eclipse.adt.PreCompilerBuilder"
        buildCommand "org.eclipse.jdt.core.javabuilder"
        buildCommand "com.android.ide.eclipse.adt.ApkBuilder"
    }
}
// sets up the Android Idea project, using the old Ant based build.
idea {
    module {
        sourceDirs += file("src");
        scopes = [COMPILE: [plus: [project.configurations.compile]]]

        iml {
            withXml {
                def node = it.asNode()
                def builder = NodeBuilder.newInstance();
                builder.current = node;
                builder.component(name: "FacetManager") {
                    facet(type: "android", name: "Android") {
                        configuration {
                            option(name: "UPDATE_PROPERTY_FILES", value: "true")
                        }
                    }
                }
            }
        }
    }
}

Backend:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.google.appengine:gradle-appengine-plugin:1.9.42'
    }
}

repositories {
    jcenter();
}

apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'appengine'

sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7

dependencies {
    appengineSdk 'com.google.appengine:appengine-java-sdk:1.9.42'
    compile 'com.google.appengine:appengine-endpoints:1.9.42'
    compile 'com.google.appengine:appengine-endpoints-deps:1.9.42'
    compile 'javax.servlet:servlet-api:2.5'
    compile files('src/main/webapp/WEB-INF/lib/objectify-5.1.12.jar')
    compile files('src/main/webapp/WEB-INF/lib/guava-19.0.jar')
    compile files('src/main/webapp/WEB-INF/lib/gcm-server-1.0.2.jar')
}

appengine {
    downloadSdk = true
    appcfg {
        oauth2 = true
    }
    endpoints {
        getClientLibsOnBuild = true
        getDiscoveryDocsOnBuild = true
    }
}

Body:
Try to add the following in your 'app' build.gradle file:

android {
    ...
    packagingOptions {
        ...
        exclude 'com/google/appengine/repackaged/org/apache/commons/codec/language/bm/sep_approx_spanish.txt'
    }
}


来源: stackexchange

问:
Error while trying to rebuild the solution of windows forms
Everytime I open the database from visual studio 2017 and then try to rebuild the solution of windows form I get those errors:

Severity  Code    Description Project File    Line    Suppression State
  Error   MSB3021 Unable to copy file "C:\Users\bsuro\documents\visual studio 2017\Projects\WindowsFormsApp2\WindowsFormsApp2\App_Data\Database.mdf" to "bin\Debug\App_Data\Database.mdf". The process cannot access the file 'C:\Users\bsuro\documents\visual studio 2017\Projects\WindowsFormsApp2\WindowsFormsApp2\App_Data\Database.mdf' because it is being used by another process.     C:\Users\bsuro\documents\visual studio 2017\Projects\WindowsFormsApp2\WindowsFormsApp2\WindowsFormsApp2.csproj  C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets  4353

Severity  Code    Description Project File    Line    Suppression State
  Error   MSB3027 Could not copy "C:\Users\bsuro\documents\visual studio 2017\Projects\WindowsFormsApp2\WindowsFormsApp2\App_Data\Database.mdf" to "bin\Debug\App_Data\Database.mdf". Exceeded retry count of 10. Failed.     C:\Users\bsuro\documents\visual studio 2017\Projects\WindowsFormsApp2\WindowsFormsApp2\WindowsFormsApp2.csproj  C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets  4353

How can I fix it?

答:
This happens because another process is using your project's resources, or you have insufficiant privilages to modify them.

Try the following actions:

"As soon as I open again my database the problem repeats herself" - Do not open your database while trying to build - you are locking the mdf file.

Open your task manager and look for a process of your application, it might be running in the background. If it does, kill it.

Make sure you are building in "Debug" mode and not in "Release" mode. If you are, there could be a production EXE running somewhere.

Close and reopen Visual Studio.

Start Visual Studio as administrator.

ContentLicense: CC BY-SA 3.0


问:
DocuSign auto place do not anchor the tab on the right place
I have c# application that is using DocuSign APIService to sign up documents created in the application.

This is my code for the tab:

```<code>Tab tab = new Tab();
tab.DocumentID = "1";
tab.RecipientID = "1";
tab.Type = TabTypeCode.SignHere;
tab.AnchorTabItem = new AnchorTab();
//tab.AnchorTabItem.AnchorTabString = "Sign Here (Signer):";
tab.AnchorTabItem.AnchorTabString = string.Format("Sign Here ({0}):", signerName);
tab.AnchorTabItem.IgnoreIfNotPresent = true;
tab.AnchorTabItem.Unit = UnitTypeCode.Pixels;
tab.AnchorTabItem.UnitSpecified = true;
tab.AnchorTabItem.XOffset = 0;
tab.AnchorTabItem.YOffset = 0;
</code>```

This is from DocuSign documentation:

It does this by finding the bounding box of the anchor text (basically the rectangle containing the text) and using the Lower Right corner of the bounding box as the Lower Left corner of the Tab.

Unfortunately the signature box appears over the anchor text, not after.

I tried the auto place with template - same problem.

Is this a bug or do I do something wrong?

答:
The documentation link you mentioned is quite old and might not be accurate. If no offsets are specified signature box will appear over the anchor text.

See the following for Official Documentation

Anchoring Tabs

Tab Positioning

You have couple of options

Option 1 : Using Anchor Offsets :

Set the following properties to adjust the location of the anchor tab.

```<code>tab.AnchorTabItem.Unit = UnitTypeCode.Pixels;
tab.AnchorTabItem.UnitSpecified = true;
tab.AnchorTabItem.XOffset = 0;
tab.AnchorTabItem.YOffset = 0;
</code>```

From Documentation :

anchorXOffset : Specifies the X axis location of the tab, in achorUnits, relative to the anchorString.

anchorYOffset : Specifies the Y axis location of the tab, in achorUnits, relative to the anchorString.

Option 2: Using Static Anchor Text

Another option is add a static anchor text to the document and change the color of the anchor text to white or to the background color of the document.  This way the anchor text does not appear when the document is viewed, making the anchor text invisible to the recipients of the document. More Info here

See more tips and tricks for Anchor Tabs here

Body:
I have c# application that is using DocuSign APIService to sign up documents created in the application.

This is my code for the tab:

Tab tab = new Tab();
tab.DocumentID = "1";
tab.RecipientID = "1";
tab.Type = TabTypeCode.SignHere;
tab.AnchorTabItem = new AnchorTab();
//tab.AnchorTabItem.AnchorTabString = "Sign Here (Signer):";
tab.AnchorTabItem.AnchorTabString = string.Format("Sign Here ({0}):", signerName);
tab.AnchorTabItem.IgnoreIfNotPresent = true;
tab.AnchorTabItem.Unit = UnitTypeCode.Pixels;
tab.AnchorTabItem.UnitSpecified = true;
tab.AnchorTabItem.XOffset = 0;
tab.AnchorTabItem.YOffset = 0;

This is from DocuSign documentation:

It does this by finding the bounding box of the anchor text (basically the rectangle containing the text) and using the Lower Right corner of the bounding box as the Lower Left corner of the Tab.

Unfortunately the signature box appears over the anchor text, not after.

I tried the auto place with template - same problem.

Is this a bug or do I do something wrong?

Body:
The documentation link you mentioned is quite old and might not be accurate. If no offsets are specified signature box will appear over the anchor text.

See the following for Official Documentation

Anchoring Tabs

Tab Positioning

You have couple of options

Option 1 : Using Anchor Offsets :

Set the following properties to adjust the location of the anchor tab.

tab.AnchorTabItem.Unit = UnitTypeCode.Pixels;
tab.AnchorTabItem.UnitSpecified = true;
tab.AnchorTabItem.XOffset = 0;
tab.AnchorTabItem.YOffset = 0;

From Documentation :

anchorXOffset : Specifies the X axis location of the tab, in achorUnits, relative to the anchorString.

anchorYOffset : Specifies the Y axis location of the tab, in achorUnits, relative to the anchorString.

Option 2: Using Static Anchor Text

Another option is add a static anchor text to the document and change the color of the anchor text to white or to the background color of the document.  This way the anchor text does not appear when the document is viewed, making the anchor text invisible to the recipients of the document. More Info here

See more tips and tricks for Anchor Tabs here


问:
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 would recommend you to try SignalR. Please follow below link to know more about it.

https://learn.microsoft.com/en-us/aspnet/signalr/overview/getting-started/introduction-to-signalr

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


问:
java.lang.NoSuchMethodError: org.apache.fop.apps.FopFactory.newInstance(Ljava/io/File;)Lorg/apache/fop/apps/FopFactory;
I 've used  apache FOP 2.0 jar and below code

```<code>  FopFactory fopFactory = FopFactory.newInstance(new File("."));
</code>```

and getting below error So what is the reason and solution on it?

I've also used xmlgraphics-commons 1.5

but of no use

```<code>java.lang.NoSuchMethodError:  org.apache.fop.apps.FopFactory.newInstance(Ljava/io/File;)Lorg/apache/fop/apps/FopFactory;
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
            at java.lang.reflect.Method.invoke(Method.java:606)
            at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214)
            at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
            at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
            at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
            at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)
            at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
            at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
            at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
            at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
            at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
            at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
            at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
            at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
            at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
            at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
            at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
            at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
            at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
            at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
            at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:442)
            at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1083)
            at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:640)
            at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
            at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
            at java.lang.Thread.run(Thread.java:724)
</code>```

答:
Try to do this:</p>

```<code>FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI());
</code>```

Body:
I 've used  apache FOP 2.0 jar and below code

  FopFactory fopFactory = FopFactory.newInstance(new File("."));

and getting below error So what is the reason and solution on it?

I've also used xmlgraphics-commons 1.5

but of no use

java.lang.NoSuchMethodError:  org.apache.fop.apps.FopFactory.newInstance(Ljava/io/File;)Lorg/apache/fop/apps/FopFactory;
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
            at java.lang.reflect.Method.invoke(Method.java:606)
            at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214)
            at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
            at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
            at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
            at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)
            at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
            at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
            at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
            at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
            at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
            at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
            at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
            at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
            at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
            at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
            at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
            at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
            at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
            at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
            at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:442)
            at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1083)
            at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:640)
            at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
            at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
            at java.lang.Thread.run(Thread.java:724)

Body:
Try to do this:

FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI());


问:
How to pass user-defined data to a worker thread using IOCP?
Hey... I created a small test server using I/O completion ports and winsock.
I can successfully connect and associate a socket handle with the completion port.
But I don´t know how to pass user-defined data-structures into the wroker thread...

What I´ve tried so far was passing a user-structure as (ULONG_PTR)&structure as the Completion Key in the association-call of CreateIoCompletionPort()
But that did not work.

Now I tried defining my own OVERLAPPED-structure and using CONTAINING_RECORD() as described here http://msdn.microsoft.com/en-us/magazine/cc302334.aspx and http://msdn.microsoft.com/en-us/magazine/bb985148.aspx.
 But that does not work, too. (I get freaky values for the contents of pHelper)

So my Question is: How can I pass data to the worker thread using WSARecv(), GetQueuedCompletionStatus() and the Completion packet or the OVERLAPPED-strucutre?

EDIT: How can I successfully transmit "per-connection-data"?... It seems like I got the art of doing it (like explained in the two links above) wrong.

Here goes my code: (Yes, its ugly and its only TEST-code)

```<code>struct helper
    {
        SOCKET m_sock;
        unsigned int m_key;
        OVERLAPPED over;
    };

///////

SOCKET newSock = INVALID_SOCKET;
    WSABUF wsabuffer;
    char cbuf[250];
    wsabuffer.buf = cbuf;
    wsabuffer.len = 250;
    DWORD flags, bytesrecvd;

    while(true)
    {
        newSock = accept(AcceptorSock, NULL, NULL);
        if(newSock == INVALID_SOCKET)
            ErrorAbort("could not accept a connection");

        //associate socket with the CP
        if(CreateIoCompletionPort((HANDLE)newSock, hCompletionPort, 3,0) != hCompletionPort)
            ErrorAbort("Wrong port associated with the connection");
        else
            cout << "New Connection made and associated\n";

        helper* pHelper = new helper;
        pHelper->m_key = 3;
        pHelper->m_sock = newSock;
        memset(&(pHelper->over), 0, sizeof(OVERLAPPED));
        flags = 0;
        bytesrecvd = 0;

        if(WSARecv(newSock, &wsabuffer, 1, NULL, &flags, (OVERLAPPED*)pHelper, NULL) != 0)
        {
            if(WSAGetLastError() != WSA_IO_PENDING)
                ErrorAbort("WSARecv didnt work");
        }
    }

    //Cleanup
    CloseHandle(hCompletionPort);
    cin.get();
    return 0;
}

DWORD WINAPI ThreadProc(HANDLE h)
{
    DWORD dwNumberOfBytes = 0;
    OVERLAPPED* pOver = nullptr;
    helper* pHelper = nullptr;
    WSABUF RecvBuf;
    char cBuffer[250];
    RecvBuf.buf = cBuffer;
    RecvBuf.len = 250;
    DWORD dwRecvBytes = 0;
    DWORD dwFlags = 0;
    ULONG_PTR Key = 0;

    GetQueuedCompletionStatus(h, &dwNumberOfBytes, &Key, &pOver, INFINITE);

    //Extract helper
    pHelper = (helper*)CONTAINING_RECORD(pOver, helper, over);

    cout << "Received Overlapped item" << endl;
    if(WSARecv(pHelper->m_sock, &RecvBuf, 1, &dwRecvBytes, &dwFlags, pOver, NULL) != 0)
        cout << "Could not receive data\n";
    else
        cout << "Data Received: " << RecvBuf.buf << endl;

    ExitThread(0);
}
</code>```

答:
I use the standard socket routines (socket, closesocket, bind, accept, connect ...) for creating/destroying and ReadFile/WriteFile for I/O as they allow use of the OVERLAPPED structure.

After your socket has accepted or connected you should associate it with the session context that it services. Then you associate your socket to an IOCP and (in the third parameter) provide it with a reference to the session context. The IOCP does not know what this reference is and doesn't care either for that matter. The reference is for YOUR use so that when you get an IOC through GetQueuedCompletionStatus the variable pointed to by parameter 3 will be filled in with the reference so that you immediately find the context associated with the socket event and can begin servicing the event. I usually use an indexed structure containing (among other things) the socket declaration, the overlapped structure as well as other session-specific data. The reference I pass to CreateIoCompletionPort in parameter 3 will be the index to the structure member containing the socket.

You need to check if GetQueuedCompletionStatus returned a completion or a timeout. With a timeout you can run through your indexed structure and see (for example) if one of them has timed out or something else and take appropriate house-keeping actions.

The overlapped structure also needs to be checked to see that the I/O completed correctly.

The function servicing the IOCP should be a separate, multi-threaded entity. Use the same number of threads that you have cores in your system, or at least no more than that as it wastes system resources (you don't have more resources for servicing the event than the number of cores in your system, right?).

IOCPs really are the best of all worlds (too good to be true) and anyone who says "one thread per socket" or "wait on multiple-socket list in one function" don't know what they are talking about. The former stresses your scheduler and the latter is polling and polling is ALWAYS extremely wasteful.

ContentLicense: CC BY-SA 2.5

Body:
Hey... I created a small test server using I/O completion ports and winsock.
I can successfully connect and associate a socket handle with the completion port.
But I don´t know how to pass user-defined data-structures into the wroker thread...

What I´ve tried so far was passing a user-structure as (ULONG_PTR)&structure as the Completion Key in the association-call of CreateIoCompletionPort()
But that did not work.

Now I tried defining my own OVERLAPPED-structure and using CONTAINING_RECORD() as described here http://msdn.microsoft.com/en-us/magazine/cc302334.aspx and http://msdn.microsoft.com/en-us/magazine/bb985148.aspx.
 But that does not work, too. (I get freaky values for the contents of pHelper)

So my Question is: How can I pass data to the worker thread using WSARecv(), GetQueuedCompletionStatus() and the Completion packet or the OVERLAPPED-strucutre?

EDIT: How can I successfully transmit "per-connection-data"?... It seems like I got the art of doing it (like explained in the two links above) wrong.

Here goes my code: (Yes, its ugly and its only TEST-code)

struct helper
    {
        SOCKET m_sock;
        unsigned int m_key;
        OVERLAPPED over;
    };

///////

SOCKET newSock = INVALID_SOCKET;
    WSABUF wsabuffer;
    char cbuf[250];
    wsabuffer.buf = cbuf;
    wsabuffer.len = 250;
    DWORD flags, bytesrecvd;

    while(true)
    {
        newSock = accept(AcceptorSock, NULL, NULL);
        if(newSock == INVALID_SOCKET)
            ErrorAbort("could not accept a connection");

        //associate socket with the CP
        if(CreateIoCompletionPort((HANDLE)newSock, hCompletionPort, 3,0) != hCompletionPort)
            ErrorAbort("Wrong port associated with the connection");
        else
            cout << "New Connection made and associated\n";

        helper* pHelper = new helper;
        pHelper->m_key = 3;
        pHelper->m_sock = newSock;
        memset(&(pHelper->over), 0, sizeof(OVERLAPPED));
        flags = 0;
        bytesrecvd = 0;

        if(WSARecv(newSock, &wsabuffer, 1, NULL, &flags, (OVERLAPPED*)pHelper, NULL) != 0)
        {
            if(WSAGetLastError() != WSA_IO_PENDING)
                ErrorAbort("WSARecv didnt work");
        }
    }

    //Cleanup
    CloseHandle(hCompletionPort);
    cin.get();
    return 0;
}

DWORD WINAPI ThreadProc(HANDLE h)
{
    DWORD dwNumberOfBytes = 0;
    OVERLAPPED* pOver = nullptr;
    helper* pHelper = nullptr;
    WSABUF RecvBuf;
    char cBuffer[250];
    RecvBuf.buf = cBuffer;
    RecvBuf.len = 250;
    DWORD dwRecvBytes = 0;
    DWORD dwFlags = 0;
    ULONG_PTR Key = 0;

    GetQueuedCompletionStatus(h, &dwNumberOfBytes, &Key, &pOver, INFINITE);

    //Extract helper
    pHelper = (helper*)CONTAINING_RECORD(pOver, helper, over);

    cout << "Received Overlapped item" << endl;
    if(WSARecv(pHelper->m_sock, &RecvBuf, 1, &dwRecvBytes, &dwFlags, pOver, NULL) != 0)
        cout << "Could not receive data\n";
    else
        cout << "Data Received: " << RecvBuf.buf << endl;

    ExitThread(0);
}


问:
Force button to reload page after opening new window
I have a button delivered by outside company (Telerik) and It does contain some events, like one opening new window.

The thing I also want it to do is to refresh the window:

button got clicked

some built-in events fire (including open window)

the page button is on refresh itself

I tried to add a new event, but page refreshes itself and the new window is not appearing.

```<code>if (Button.addEventListener) {
    Button.addEventListener("click", ReloadPage, false);
} else {
    Button.attachEvent("onclick", ReloadPage);
}
</code>```

In some other place:

```<code>function ReloadPage() {
    Location.Reload();
}
</code>```

I tried to Google topics like "force event to fire as last" or "interval still going after changing the window" but I couldn't find something that might work ON IE8 without jQuery.

What event can I add that will refresh the page without touching existing events without jQuery on IE8?

Edit:

I also tried to reload some part of window, but then I got an error from button producers script.

```<code>var TempContainer = ElementsContainer.innerHTML;
        ElementsContainer.innerHTML = TempContainer;
</code>```

Edit2:

It looks like vicious circle:
-if window with button refreshes, all the other events (like open new window) are being canceled
-if new window appears, old one looses its focus (I think) and reload event is canceled.

答:
```<code>function ReloadPage() {
setTimeout(function(){
 location.reload();
},0);
}
</code>```

Use setTimeout to append to qeue...

Body:
I have a button delivered by outside company (Telerik) and It does contain some events, like one opening new window.

The thing I also want it to do is to refresh the window:

button got clicked

some built-in events fire (including open window)

the page button is on refresh itself

I tried to add a new event, but page refreshes itself and the new window is not appearing.

if (Button.addEventListener) {
    Button.addEventListener("click", ReloadPage, false);
} else {
    Button.attachEvent("onclick", ReloadPage);
}

In some other place:

function ReloadPage() {
    Location.Reload();
}

I tried to Google topics like "force event to fire as last" or "interval still going after changing the window" but I couldn't find something that might work ON IE8 without jQuery.

What event can I add that will refresh the page without touching existing events without jQuery on IE8?

Edit:

I also tried to reload some part of window, but then I got an error from button producers script.

var TempContainer = ElementsContainer.innerHTML;
        ElementsContainer.innerHTML = TempContainer;

Edit2:

It looks like vicious circle:
-if window with button refreshes, all the other events (like open new window) are being canceled
-if new window appears, old one looses its focus (I think) and reload event is canceled.

Body:
function ReloadPage() {
setTimeout(function(){
 location.reload();
},0);
}

Use setTimeout to append to qeue...


问:
Algorithm for ordering the order of responders at election hustings
For our local election hustings, someone from the audience asks a question and then the candidates take it in turns to answer it. The host decides which order the candidates should answer for each question.

There will probably be 5 candidates at the hustings, though it could be up to 7 or as few as 4.

The host wants to produce the fairest possible order for candidates to answer questions, so that one candidate doesn't answer first or last more frequently than other candidates. Also, he wants candidates to talk before and after each other with a roughly equal distribution.

(I have assigned each candidate a letter between A - E, and then candidates will draw from a hat on the night to choose their letter.)

So, for example:

ABCDE followed by ADCBE would be bad because A starts and E finishes both times.

ABCDE followed by ABECD would be bad because B follows A and D follows C both times.

ABCDE followed by DCEBA would satisfy all requirements.

The number of questions is variable - could be anywhere between 4 and 15.

The host wants a reproducible process that could be audited by the electoral commission if necessary, to establish that the selection process was fair. This rules out my initial approach of "produce a random list, and then edit it manually".  Performance doesn't really matter - it can take up to 10 minutes to run, on a quad-core machine with 16GB RAM.

So far I have tried:

Just producing a random list. This tends to fail on the constraints - if I keep running it until I get a list that feels right, it fails the 'reproducible' requirement.

Calling the levenshtein algorithm recursively for all combinations, and taking the ones that give the highest overall score. But with so many possible combinations, it's not possible to try all of them. It also doesn't produce great results - it lets a lot of the 'B follows A 3 times in a row' type problems.

I realise that I'm probably over-engineering the solution, but I'm interested in how I would solve this if it needed to be rock solid.

答:
Very good question, got me thinking for 10 minutes before I can arrive at some solution.

I have an approach in mind that, I would like to discuss here.

So let's take an example to understand the approach I have in mind.

```<code>Input: Candidates - [A,B,C,D,E] and 3 questions.

Step1. Let's generate all the possible combinations of the candidates,
       ex:- A,B,C,D,E | A,C,B,D,E ..... D,E,B,C,A etc.

Step2. Take first string A,B,C,D,E and make use of two pointers, one
       starting at beginning and other starting at the end, like this

       A B C D E
       ^       ^
       |       |

Step3. So for first question our order will be like this - A,B,C,D,E
Step4. For the next question increment beginning pointer and decrement ending pointer.

Step5. So for the next question our pointers look like this

       A B C D E
         ^   ^
         |   |

Step6. So out of the calculated permutations select that permutation which
       has B in the starting and D in the ending.
       So for the second question, our configuration would look like this
       B,A,C,E,D

Step7. Increment the same starting pointer and decrement the ending pointer
       in the same fashion for the next questions also.

Step8. Now when increment pointer reaches the end or decrement pointer
       reaches the start then reverse them and we took A,B,C,D,E as our
       string to move pointers.
       Now take another string to move pointers on.
</code>```

According to me this flow could give a more equal distribution of opportunities for answering the questions.

This algorithm could be a starting point and we can update some parts of it to randomly select pointers or string etc.

Hope this helps!

Body:
Very good question, got me thinking for 10 minutes before I can arrive at some solution.

I have an approach in mind that, I would like to discuss here.

So let's take an example to understand the approach I have in mind.

Input: Candidates - [A,B,C,D,E] and 3 questions.

Step1. Let's generate all the possible combinations of the candidates,
       ex:- A,B,C,D,E | A,C,B,D,E ..... D,E,B,C,A etc.

Step2. Take first string A,B,C,D,E and make use of two pointers, one
       starting at beginning and other starting at the end, like this

       A B C D E
       ^       ^
       |       |

Step3. So for first question our order will be like this - A,B,C,D,E
Step4. For the next question increment beginning pointer and decrement ending pointer.

Step5. So for the next question our pointers look like this

       A B C D E
         ^   ^
         |   |

Step6. So out of the calculated permutations select that permutation which
       has B in the starting and D in the ending.
       So for the second question, our configuration would look like this
       B,A,C,E,D

Step7. Increment the same starting pointer and decrement the ending pointer
       in the same fashion for the next questions also.

Step8. Now when increment pointer reaches the end or decrement pointer
       reaches the start then reverse them and we took A,B,C,D,E as our
       string to move pointers.
       Now take another string to move pointers on.

According to me this flow could give a more equal distribution of opportunities for answering the questions.

This algorithm could be a starting point and we can update some parts of it to randomly select pointers or string etc.

Hope this helps!


问:
Using byte arrays as parameters for constructor: compiler error due to not found arguments
I have a specific problem regarding constructor and parameters.

I used byte[] arrays as parameters for my object constructor. My object class compiles just fine, but the test class has an error which i cannot figure out.
I use the right parameters in the test class, but the compiler says there aren't any arguments in the constructor. It's propably just me not seeing the flaw, but i am pretty despirate over this one.

Thank you in advance!

Compiler-Error:

```<code>CubeTest.java:6: error: constructor Cube in class Cube cannot be applied to given types;
    Cube test = new Cube();
                ^
required: byte[],byte[],byte[],byte[],byte[],byte[]
found: no arguments
reason: actual and formal argument lists differ in length
1 error
</code>```

The Cube class:

```<code>class Cube{
//declare arrays
private byte[] f;
private byte[] r;
private byte[] u;
private byte[] b;
private byte[] l;
private byte[] d;
//
//
//
//constructor
public Cube(byte[] f, byte[] r, byte[] u, byte[] b, byte[] l, byte[] d){

    this.f = new byte[9];
    this.r = new byte[9];
    this.u = new byte[9];
    this.b = new byte[9];
    this.l = new byte[9];
    this.d = new byte[9];

    //fill this.f
    for(int i = 0, n = 0; i < 9 && n < 9; i++, n++){
        this.f[i] = f[n];
    }
    //fill this.r
    for(int i = 0, n = 0; i < 9 && n < 9; i++, n++){
        this.r[i] = r[n];
    }
    //fill this.u
    for(int i = 0, n = 0; i < 9 && n < 9; i++, n++){
        this.u[i] = u[n];
    }
    //fill this.b
    for(int i = 0, n = 0; i < 9 && n < 9; i++, n++){
        this.b[i] = b[n];
    }
    //fill this.l
    for(int i = 0, n = 0; i < 9 && n < 9; i++, n++){
        this.l[i] = l[n];
    }
    //fill this.d
    for(int i = 0, n = 0; i < 9 && n < 9; i++, n++){
        this.d[i] = d[n];
    }
}
}
</code>```

The test class:

```<code>class CubeTest{
public static void main(String args[]){
    //f, r, u, b, l, d
    //1, 2, 3, 4, 5, 6
    //create such arrays
    byte[] f = new byte[9];
    byte[] r = new byte[9];
    byte[] u = new byte[9];
    byte[] b = new byte[9];
    byte[] l = new byte[9];
    byte[] d = new byte[9];
    //fill arrays
    for(int i = 0; i < 9; i++){
        f[i] = 1;
        r[i] = 2;
        u[i] = 3;
        b[i] = 4;
        l[i] = 5;
        d[i] = 6;
    }
    //create Cube named test
    Cube test = new Cube(f, r, u, b, l, d);
    //
}
}
</code>```

答:
You have to provide a default constructor too in your class Cube.
When you declare a custom constructor Java compiler doesn't create a default one.</p>

Body:
I have a specific problem regarding constructor and parameters.

I used byte[] arrays as parameters for my object constructor. My object class compiles just fine, but the test class has an error which i cannot figure out.
I use the right parameters in the test class, but the compiler says there aren't any arguments in the constructor. It's propably just me not seeing the flaw, but i am pretty despirate over this one.

Thank you in advance!

Compiler-Error:

CubeTest.java:6: error: constructor Cube in class Cube cannot be applied to given types;
    Cube test = new Cube();
                ^
required: byte[],byte[],byte[],byte[],byte[],byte[]
found: no arguments
reason: actual and formal argument lists differ in length
1 error

The Cube class:

class Cube{
//declare arrays
private byte[] f;
private byte[] r;
private byte[] u;
private byte[] b;
private byte[] l;
private byte[] d;
//
//
//
//constructor
public Cube(byte[] f, byte[] r, byte[] u, byte[] b, byte[] l, byte[] d){

    this.f = new byte[9];
    this.r = new byte[9];
    this.u = new byte[9];
    this.b = new byte[9];
    this.l = new byte[9];
    this.d = new byte[9];

    //fill this.f
    for(int i = 0, n = 0; i < 9 && n < 9; i++, n++){
        this.f[i] = f[n];
    }
    //fill this.r
    for(int i = 0, n = 0; i < 9 && n < 9; i++, n++){
        this.r[i] = r[n];
    }
    //fill this.u
    for(int i = 0, n = 0; i < 9 && n < 9; i++, n++){
        this.u[i] = u[n];
    }
    //fill this.b
    for(int i = 0, n = 0; i < 9 && n < 9; i++, n++){
        this.b[i] = b[n];
    }
    //fill this.l
    for(int i = 0, n = 0; i < 9 && n < 9; i++, n++){
        this.l[i] = l[n];
    }
    //fill this.d
    for(int i = 0, n = 0; i < 9 && n < 9; i++, n++){
        this.d[i] = d[n];
    }
}
}

The test class:

class CubeTest{
public static void main(String args[]){
    //f, r, u, b, l, d
    //1, 2, 3, 4, 5, 6
    //create such arrays
    byte[] f = new byte[9];
    byte[] r = new byte[9];
    byte[] u = new byte[9];
    byte[] b = new byte[9];
    byte[] l = new byte[9];
    byte[] d = new byte[9];
    //fill arrays
    for(int i = 0; i < 9; i++){
        f[i] = 1;
        r[i] = 2;
        u[i] = 3;
        b[i] = 4;
        l[i] = 5;
        d[i] = 6;
    }
    //create Cube named test
    Cube test = new Cube(f, r, u, b, l, d);
    //
}
}


问:
module.exports function is not a function
I'm trying to require an endpoints.js file into my webpack.config.js

Expected

endpoints.js gets required correctly then sets a custom api file depending on the process.env.NODE_ENV

Results

const api = endpoints(process.env.NODE_ENV);

TypeError: endpoints is not a function

Webpack.config.js

```<code>const webpack = require('webpack')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require("path");
const dist = path.resolve(__dirname, "dist");
const src = path.resolve(__dirname, "src");
const endpoints = require("./src/endpoints");
const api = endpoints(process.env.NODE_ENV);

console.log('webpack endpoints', endpoints);
console.log('webpack api', api);
</code>```

endpoints.js

```<code>module.exports = {
    endpoints: function(env) {
        let prefix = env === 'development' ? 'http://localhost' : '';

        return {
            "login": `${prefix}/app/api/login`
        }
    }
}
</code>```

I also tried the following, but got an Unexpected token export

```<code>export default function endpoints(env) {
    let prefix = env === 'development' ? 'http://localhost' : '';

    return {
        "login": `${prefix}/app/api/login`
    }
};
</code>```

答:
Ah I was using module.exports wrong, however it looked correct according to this site.

This is how I needed to use module.exports to export out my endpoints function.

```<code>function endpoints(env) {
    let prefix = env === 'development' ? 'http://localhost' : '';

    return {
        "login": `${prefix}/app/api/login`
    }
}

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

Body:
I'm trying to require an endpoints.js file into my webpack.config.js

Expected

endpoints.js gets required correctly then sets a custom api file depending on the process.env.NODE_ENV

Results

const api = endpoints(process.env.NODE_ENV);

TypeError: endpoints is not a function

Webpack.config.js

const webpack = require('webpack')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require("path");
const dist = path.resolve(__dirname, "dist");
const src = path.resolve(__dirname, "src");
const endpoints = require("./src/endpoints");
const api = endpoints(process.env.NODE_ENV);

console.log('webpack endpoints', endpoints);
console.log('webpack api', api);

endpoints.js

module.exports = {
    endpoints: function(env) {
        let prefix = env === 'development' ? 'http://localhost' : '';

        return {
            "login": `${prefix}/app/api/login`
        }
    }
}

I also tried the following, but got an Unexpected token export

export default function endpoints(env) {
    let prefix = env === 'development' ? 'http://localhost' : '';

    return {
        "login": `${prefix}/app/api/login`
    }
};

Body:
Ah I was using module.exports wrong, however it looked correct according to this site.

This is how I needed to use module.exports to export out my endpoints function.

function endpoints(env) {
    let prefix = env === 'development' ? 'http://localhost' : '';

    return {
        "login": `${prefix}/app/api/login`
    }
}

module.exports = endpoints;


问:
Traversing a tree of objects in c#
I have a tree that consists of several objects, where each object has a name (string), id (int) and possibly an array of children that are of the same type. How do I go through the entire tree and print out all of the ids and names?

I'm new to programming and frankly, I'm having trouble wrapping my head around this because I don't know how many levels there are. Right now I'm using a foreach loop to fetch the parent objects directly below the root, but this means I cannot get the children.

答:
An algorithm which uses recursion goes like this:

```<code>printNode(Node node)
{
  printTitle(node.title)
  foreach (Node child in node.children)
  {
    printNode(child); //<-- recursive
  }
}
</code>```

Here's a version which also keeps track of how deeply nested the recursion is (i.e. whether we're printing children of the root, grand-children, great-grand-children, etc.):

```<code>printRoot(Node node)
{
  printNode(node, 0);
}

printNode(Node node, int level)
{
  printTitle(node.title)
  foreach (Node child in node.children)
  {
    printNode(child, level + 1); //<-- recursive
  }
}
</code>```

OwnerDisplayName: BeafTurkey

ContentLicense: CC BY-SA 4.0

Title: Traversing a tree of objects in c#

Body:
An algorithm which uses recursion goes like this:

printNode(Node node)
{
  printTitle(node.title)
  foreach (Node child in node.children)
  {
    printNode(child); //<-- recursive
  }
}

Here's a version which also keeps track of how deeply nested the recursion is (i.e. whether we're printing children of the root, grand-children, great-grand-children, etc.):

printRoot(Node node)
{
  printNode(node, 0);
}

printNode(Node node, int level)
{
  printTitle(node.title)
  foreach (Node child in node.children)
  {
    printNode(child, level + 1); //<-- recursive
  }
}

OwnerDisplayName: ChrisW

LastEditorDisplayName: ChrisW


问:
how to open screen on full screen
how i can open my asp.net program on full screen (like i press F11)

Through C# code ?

thanks

答: Have a look at this. Instead of linking, you can redirect your user from your default page with the proper javascript.</p>

Title: how to open screen on full screen


问:
How to check condition using For and If statement in SIL programming
Hi I am trying to figure out the fallowing scenario using SIL Condition on Jira
if any of the linked issue statuses is Rejected auto transition the current issue or neglect the transition

```<code>string value = linkedIssues(key);
 for (string link in linkissues) {
    if(%link%.status != "Rejected") {
       return false;
        } else {
       autotransition("Reject",key);
       boolean exists = true;
       }
}
</code>```

Please sujjest the best way to check this

答:
SIL Condition doesn't really work that way.  It is used to decide whether a transition is visible to users (for instance if they have to have set the fixVersion before using the Complete transition, you could hide the Complete transition until the fixVersion was filled in).  In this instance the issue would only be rejected if somebody looked at it, which seems... strange.

Without understanding your use case, I would guess you'd be better off triggering the transition when the original issue is rejected:

```<code>string[] linkissues = linkedIssues(key);
for (string link in linkissues) {
    if(%link%.status != "Rejected") {
        autotransition("Reject", link);
    }
}
</code>```

Body:
Hi I am trying to figure out the fallowing scenario using SIL Condition on Jira
if any of the linked issue statuses is Rejected auto transition the current issue or neglect the transition

string value = linkedIssues(key);
 for (string link in linkissues) {
    if(%link%.status != "Rejected") {
       return false;
        } else {
       autotransition("Reject",key);
       boolean exists = true;
       }
}

Please sujjest the best way to check this

Body:
SIL Condition doesn't really work that way.  It is used to decide whether a transition is visible to users (for instance if they have to have set the fixVersion before using the Complete transition, you could hide the Complete transition until the fixVersion was filled in).  In this instance the issue would only be rejected if somebody looked at it, which seems... strange.

Without understanding your use case, I would guess you'd be better off triggering the transition when the original issue is rejected:

string[] linkissues = linkedIssues(key);
for (string link in linkissues) {
    if(%link%.status != "Rejected") {
        autotransition("Reject", link);
    }
}


问:
What is the difference between API key and Build Secret in Fabric.io?
I am using Crashlytics tool from fabric.io in an android app. I have put the API key in the manifest file.
Fabric also provides a build secret string. But there is no instruction to use it. May be Fabric is assuming that users have prior knowledge about using BUILD SECRET.
 I have no idea what a build secret string is and where to use it in android projects.
Can anyone tell me what is BUILD SECRET in Fabric.io and where it is used in android project?

Thanks in advance

答: Mike from Fabric here. The build secret is used when distributing your apps through Beta to ensure that only folks that have access to both the API key and build secret can distribute your apps. You can include the build secret in a Fabric.properties file that is referenced when distributing through Beta.</p>


问:
PostgreSQL User data type in C Error: is only a shell
I'm creating an extension for PostgreSQL. I created the new Complex data type, as per PostgreSQL documentation show. Follow the code:

#include "postgres.h"
#include "fmgr.h"
#include "libpq/pqformat.h" /* needed for send/recv functions */

PG_MODULE_MAGIC;

typedef struct Complex {
    double x, y;
} Complex;

/**************************
 * Input/Output functions *
 *************************/

PG_FUNCTION_INFO_V1(complex_in);
PG_FUNCTION_INFO_V1(complex_out);

Datum complex_in(PG_FUNCTION_ARGS)  {
    char *str = PG_GETARG_CSTRING(0);
    double x, y;
    Complex *result;

    if (sscanf(str, " ( %lf , %lf )", &x, &y) != 2)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                 errmsg("invalid input syntax for complex: \"%s\"",
                        str)));

    result = (Complex *) palloc(sizeof(Complex));
    result->x = x;
    result->y = y;
    PG_RETURN_POINTER(result);
}

Datum complex_out(PG_FUNCTION_ARGS) {
    Complex *complex = (Complex *) PG_GETARG_POINTER(0);
    char    *result;

    result = psprintf("(%g,%g)", complex->x, complex->y);
    PG_RETURN_CSTRING(result);
}
```
<p>And SQL:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE OR REPLACE FUNCTION complex_in(cstring)
RETURNS complex
AS '$libdir/complex'
LANGUAGE C IMMUTABLE STRICT;

CREATE OR REPLACE FUNCTION complex_out(complex)
RETURNS cstring
AS '$libdir/complex'
LANGUAGE C IMMUTABLE STRICT;

CREATE OR REPLACE FUNCTION complex_recv(internal)
RETURNS complex
AS '$libdir/complex'
LANGUAGE C IMMUTABLE STRICT;

CREATE OR REPLACE FUNCTION complex_send(complex)
RETURNS bytea
AS '$libdir/complex'
LANGUAGE C IMMUTABLE STRICT;

CREATE TYPE complex (
    internallength = 16,
    input = complex_in,
    output = complex_out,
    receive = complex_recv,
    send = complex_send,
    alignment = double
);
</code>```

And Makefile

```<code>EXTENSION = complex        # the extensions name
DATA = complex--0.0.1.sql  # script files to install
MODULES = complex          # our c module file to build

# postgres build stuff
PG_CONFIG = pg_config
PGXS := $(shell $(PG_CONFIG) --pgxs)
include $(PGXS)
</code>```

I create the new type using CREATE TYPE complex, but when I use the new data type the following error appears

ERROR:  type "complex" is only a shell.

Is there anything wrong with the codes?

答:
Read the documentation of CREATE TYPE.

First, you create a shell type with a statement like

```<code>CREATE TYPE complex;
</code>```

That is just a name and cannot be used yet. Think of it as a function declaration in C.

Next you create the type input and output functions with CREATE FUNCTION, using the shell type in the definitions.

Finally you complete the type definition with a statement like

```<code>CREATE TYPE complex (
   internallength = 16,
   input = complex_in,
   output = complex_out,
   receive = complex_recv,
   send = complex_send,
   alignment = double
);
</code>```

This can be compared to a function definition in C. Now the type can be used.

From your error message it looks like you forgot to run that final CREATE TYPE statement.

Body:
I'm creating an extension for PostgreSQL. I created the new Complex data type, as per PostgreSQL documentation show. Follow the code:

#include "postgres.h"
#include "fmgr.h"
#include "libpq/pqformat.h" /* needed for send/recv functions */

PG_MODULE_MAGIC;

typedef struct Complex {
    double x, y;
} Complex;

/**************************
 * Input/Output functions *
 *************************/

PG_FUNCTION_INFO_V1(complex_in);
PG_FUNCTION_INFO_V1(complex_out);

Datum complex_in(PG_FUNCTION_ARGS)  {
    char *str = PG_GETARG_CSTRING(0);
    double x, y;
    Complex *result;

    if (sscanf(str, " ( %lf , %lf )", &x, &y) != 2)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                 errmsg("invalid input syntax for complex: \"%s\"",
                        str)));

    result = (Complex *) palloc(sizeof(Complex));
    result->x = x;
    result->y = y;
    PG_RETURN_POINTER(result);
}

Datum complex_out(PG_FUNCTION_ARGS) {
    Complex *complex = (Complex *) PG_GETARG_POINTER(0);
    char    *result;

    result = psprintf("(%g,%g)", complex->x, complex->y);
    PG_RETURN_CSTRING(result);
}

And SQL:

CREATE OR REPLACE FUNCTION complex_in(cstring)
RETURNS complex
AS '$libdir/complex'
LANGUAGE C IMMUTABLE STRICT;

CREATE OR REPLACE FUNCTION complex_out(complex)
RETURNS cstring
AS '$libdir/complex'
LANGUAGE C IMMUTABLE STRICT;

CREATE OR REPLACE FUNCTION complex_recv(internal)
RETURNS complex
AS '$libdir/complex'
LANGUAGE C IMMUTABLE STRICT;

CREATE OR REPLACE FUNCTION complex_send(complex)
RETURNS bytea
AS '$libdir/complex'
LANGUAGE C IMMUTABLE STRICT;

CREATE TYPE complex (
    internallength = 16,
    input = complex_in,
    output = complex_out,
    receive = complex_recv,
    send = complex_send,
    alignment = double
);

And Makefile

EXTENSION = complex        # the extensions name
DATA = complex--0.0.1.sql  # script files to install
MODULES = complex          # our c module file to build

# postgres build stuff
PG_CONFIG = pg_config
PGXS := $(shell $(PG_CONFIG) --pgxs)
include $(PGXS)

I create the new type using CREATE TYPE complex, but when I use the new data type the following error appears

ERROR:  type "complex" is only a shell.

Is there anything wrong with the codes?

Body:
Read the documentation of CREATE TYPE.

First, you create a shell type with a statement like

CREATE TYPE complex;

That is just a name and cannot be used yet. Think of it as a function declaration in C.

Next you create the type input and output functions with CREATE FUNCTION, using the shell type in the definitions.

Finally you complete the type definition with a statement like

CREATE TYPE complex (
   internallength = 16,
   input = complex_in,
   output = complex_out,
   receive = complex_recv,
   send = complex_send,
   alignment = double
);

This can be compared to a function definition in C. Now the type can be used.

From your error message it looks like you forgot to run that final CREATE TYPE statement.


问:
XML String parsing in Android?
I use the following code to parse the XML file.

```<code>DocumentBuilderFactory factory;
DocumentBuilder builder;
InputStream is;
Document dom;
try {
    factory = DocumentBuilderFactory.newInstance();
    is = new FileInputStream(strFileName);
    builder = factory.newDocumentBuilder();

    dom = builder.parse(is);
}
catch(Exception e){}
</code>```

Instead of XML file is there any way to parse the String.

```<code>String xml="<?xml version="1.0"?> <name> Application</name> <demo> Demo </demo> </xml>";
</code>```

答:
You can use StringReader :</p>

```<code>StringReader sr = new StringReader(xml);
InputSource is = new InputSource(sr);
Document d = builder.parse(is);
</code>```

Title: XML String parsing in Android?

Body:
I use the following code to parse the XML file.

DocumentBuilderFactory factory;
DocumentBuilder builder;
InputStream is;
Document dom;
try {
    factory = DocumentBuilderFactory.newInstance();
    is = new FileInputStream(strFileName);
    builder = factory.newDocumentBuilder();

    dom = builder.parse(is);
}
catch(Exception e){}

Instead of XML file is there any way to parse the String.

String xml="<?xml version="1.0"?> <name> Application</name> <demo> Demo </demo> </xml>";

Body:
You can use StringReader :

StringReader sr = new StringReader(xml);
InputSource is = new InputSource(sr);
Document d = builder.parse(is);


问:
MouseListener doesn't work the first time
I am new to Java and I am creating a simple GUI. I have a label in Java in a JFrame, and when I click it, the program is supposed to show another frame and to hide the current one. I make it print as well to check whether the label (which acts like a button) works. The first time it does not work at all. It works the in the next attempts starting from the second click but it does not hide the current frame.

My code is:

```<code>private void jLabel4MouseClicked(java.awt.event.MouseEvent evt) {

    MainFrame mf = new MainFrame();
    jLabel4.addMouseListener(new MouseAdapter (){

        @Override
        public void mousePressed(MouseEvent e){
            System.out.println("It works.");
            mf.setVisible(true);

            NewJFrame2 n2 = new NewJFrame2();
            n2.setVisible(false);

        }
    });
</code>```

Does anyone know how to fix it in order to work from the first click and hide the current frame?

答:
Instead of clicking on a JLabel why not create a JButton which already handles clicks with an ActionListener and make it look like a JLabel as shown in the multiple answers on this question.

but it does NOT hide the current JFrame

Well, you need to call JFrame#dispose() method on your listener, but also please take a look at The Use of Multiple JFrames: Good or Bad Practice?, it's better to use a Card Layout or maybe take a look at the tutorial on How to use Dialogs

Body:
I am new to Java and I am creating a simple GUI. I have a label in Java in a JFrame, and when I click it, the program is supposed to show another frame and to hide the current one. I make it print as well to check whether the label (which acts like a button) works. The first time it does not work at all. It works the in the next attempts starting from the second click but it does not hide the current frame.

My code is:

private void jLabel4MouseClicked(java.awt.event.MouseEvent evt) {

    MainFrame mf = new MainFrame();
    jLabel4.addMouseListener(new MouseAdapter (){

        @Override
        public void mousePressed(MouseEvent e){
            System.out.println("It works.");
            mf.setVisible(true);

            NewJFrame2 n2 = new NewJFrame2();
            n2.setVisible(false);

        }
    });

Does anyone know how to fix it in order to work from the first click and hide the current frame?


问:
C# - Capturing user clicks on other application
I need to create a program that can record user clicks for another Windows application. Essentially my program should read a data file and automatically run another application and enter the data. I understand that there are process automation tools but they are prohibitively expensive for one-time use. For refernce of this forum a simimar question was asked in past but was not answered so recreating it.

Capturing user events (button clicks etc) from another Windows application

Thanks

答:
https://msdn.microsoft.com/en-us/library/ms747327(v=vs.110).aspx

check this reference, for some time UI Automation is built in into VS. You don't have to rely on expensive tools to do so.


问:
Sound overlapping with multiple button clicks
```<code>package com.example.tobiadegoroye.pokemonsoundboard;

import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

public class PokemonSoundboard extends AppCompatActivity {

    MediaPlayer psyduckplayer; //member variable
    MediaPlayer pikachuplayer; //member variable
    MediaPlayer diglettplayer; //member variable

    ImageButton mpsyduckbutton;
    ImageButton mpikachubutton;
    ImageButton mdiglettbutton;

    View.OnClickListener psyducklistner = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            psyduckplayer.start();

        }
    };

    View.OnClickListener pikachulistner = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            pikachuplayer.start();

        }
    };

    View.OnClickListener digletlistner = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            diglettplayer.start();
        }
    };

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

        mpsyduckbutton = (ImageButton) findViewById(R.id.psyduckbutton);
        mpikachubutton = (ImageButton) findViewById(R.id.pikachubutton);
        mdiglettbutton = (ImageButton) findViewById(R.id.diglettbutton);

        psyduckplayer = MediaPlayer.create(this,R.raw.psyduck);
        pikachuplayer = MediaPlayer.create(this,R.raw.pikachu);
        diglettplayer = MediaPlayer.create(this,R.raw.diglett);

        mpsyduckbutton.setOnClickListener(psyducklistner);
        mpikachubutton.setOnClickListener(pikachulistner);
        mdiglettbutton.setOnClickListener(digletlistner);

    }
}
</code>```

答:
Use the MediaPlayer.isPlaying() and MediaPlayer.stop() methods.

```<code>public void stopPlaying()
{
    if(pikachuplayer != null && pikachuplayer.isPlaying())
    {
            pikachuplayer.stop();
    }
    if(digletplayer != null && digletplayer.isPlaying())
    {
            digletplayer.stop();
    }
    if(psyduckplayer != null && psyduckplayer.isPlaying())
    {
            psyduckplayer.stop();
    }
}

View.OnClickListener psyducklistner = new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        stopPlaying();
        psyduckplayer.start();

    }
};

View.OnClickListener pikachulistner = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        stopPlaying();
        pikachuplayer.start();

    }
};

View.OnClickListener digletlistner = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        stopPlaying();
        diglettplayer.start();
    }
};

View.OnClickListener digletlistner = new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        diglettplayer.start();
    }
};
</code>```

The stopPlaying() method stops all Medias from playing, only if they're playing and not null (They probably aren't null, as they're member variables, but it's still a good practice).

Body:
Use the MediaPlayer.isPlaying() and MediaPlayer.stop() methods.

public void stopPlaying()
{
    if(pikachuplayer != null && pikachuplayer.isPlaying())
    {
            pikachuplayer.stop();
    }
    if(digletplayer != null && digletplayer.isPlaying())
    {
            digletplayer.stop();
    }
    if(psyduckplayer != null && psyduckplayer.isPlaying())
    {
            psyduckplayer.stop();
    }
}

View.OnClickListener psyducklistner = new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        stopPlaying();
        psyduckplayer.start();

    }
};

View.OnClickListener pikachulistner = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        stopPlaying();
        pikachuplayer.start();

    }
};

View.OnClickListener digletlistner = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        stopPlaying();
        diglettplayer.start();
    }
};

View.OnClickListener digletlistner = new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        diglettplayer.start();
    }
};

The stopPlaying() method stops all Medias from playing, only if they're playing and not null (They probably aren't null, as they're member variables, but it's still a good practice).


问:
Setting Codeigniter Timestamp in accordance to user Timezone settings
How can I record the timestamp in accordance to the user's timezone settings?

For example:

The user has the timezone setting as $my_tz = "UP3";

The user sets the deadline of an item as $time_to_set = "2017-05-31 03:15 PM";

I need the users for example with different timezone settings to convert the time properly in accordance to their timezone (e.g. USER 1: UP3, USER 2: UP8). They need to see the time properly. I tried to set but the offset seems to have +1 hour difference and it is not accurate.

I would need time set to the timezone (UP3) to be converted to the (UTC) base without going off by +1 hour.

Thank you so much!

Here is my code you can test to see what I mean.

```<code>    $my_tz = "UP3";
    $utc_time = local_to_gmt(time());
    $current_time = gmt_to_local($utc_time, $my_tz, FALSE);

    echo "Current Time: ".unix_to_human($current_time)."</br>";
    echo $current_time;
    echo "</br></br></br></br>";

    $time_to_set = "2017-05-31 03:15 PM";
    $time_set_unix = human_to_unix($time_to_set);
    $time_to_normal = local_to_gmt($time_set_unix, "UP8", FALSE);

    echo $time_to_set."</br>";
    echo $time_set_unix."</br>";
    echo $time_to_normal."</br>";
    echo unix_to_human($time_to_normal)."</br>";
</code>```

答:
I solved my issue. I ditched the CI Date Helper and opted for the default PHP one. It is much better than going through trial and error and always getting an offset that is way off the actual time.

@astound's answer also helped in this.

Body:
How can I record the timestamp in accordance to the user's timezone settings?

For example:

The user has the timezone setting as $my_tz = "UP3";

The user sets the deadline of an item as $time_to_set = "2017-05-31 03:15 PM";

I need the users for example with different timezone settings to convert the time properly in accordance to their timezone (e.g. USER 1: UP3, USER 2: UP8). They need to see the time properly. I tried to set but the offset seems to have +1 hour difference and it is not accurate.

I would need time set to the timezone (UP3) to be converted to the (UTC) base without going off by +1 hour.

Thank you so much!

Here is my code you can test to see what I mean.

    $my_tz = "UP3";
    $utc_time = local_to_gmt(time());
    $current_time = gmt_to_local($utc_time, $my_tz, FALSE);

    echo "Current Time: ".unix_to_human($current_time)."
";
    echo $current_time;
    echo "

";

    $time_to_set = "2017-05-31 03:15 PM";
    $time_set_unix = human_to_unix($time_to_set);
    $time_to_normal = local_to_gmt($time_set_unix, "UP8", FALSE);

    echo $time_to_set."
";
    echo $time_set_unix."
";
    echo $time_to_normal."
";
    echo unix_to_human($time_to_normal)."
";


答:
Maybe you can send a F11 key pressed command from your application once it's loaded to force your browser to go full screen?

I doubt if there is a clean way of doing this as the F11 fullscreen command is handled by your internet browser.

Title: how to open screen on full screen

Body:
how i can open my asp.net program on full screen (like i press F11)

Through C# code ?

thanks