问:
Rename the default tables in asp.net identity 3 (dbo.ASPNetxxx) with Uniqueidentifier or int for IDs
I have created a new web application in ASP.Net Core 1.1, the default templates of ASP.Net identity 3 comes with nvarchar(400) or strings as the default data type for the "Id" fields.

I have changed the default TKey type from nvarchar(400) to Uniqueidentifier , Is there any way to change the default dbo.ASPNetxxx tables in asp.net identity to a custom name using the default code first approach?

答:
I have found the answer in a comment here and i would like to share it more organized here, Thanks to "Raffaele Garofalo" for answering this, I have copied the answer and added my 2 cents:

to rename the default tables in asp.net identity 3 and changing the data type to Uniqueidentifier, use the following steps:

In ApplicationDbContext.cs:

Change the ApplicationDbContext or whatever you used to reflect this one:

Change the class to be:

```<code>public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, Guid>
</code>```

and the OnModelCreating method to be:

```<code>protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    // Customizations
    builder.Entity<ApplicationUser>(i =>
    {
        i.ToTable("Users");
        i.HasKey(x => x.Id);
    });
    builder.Entity<ApplicationRole>(i =>
    {
        i.ToTable("Roles");
        i.HasKey(x => x.Id);
    });
    builder.Entity<IdentityUserRole<Guid>>(i =>
    {
        i.ToTable("UserRoles");
        i.HasKey(x => new { x.RoleId, x.UserId });
    });
    builder.Entity<IdentityUserLogin<Guid>>(i =>
    {
        i.ToTable("UserLogins");
        i.HasKey(x => new { x.ProviderKey, x.LoginProvider });
    });
    builder.Entity<IdentityRoleClaim<Guid>>(i =>
    {
        i.ToTable("RoleClaims");
        i.HasKey(x => x.Id);
    });
    builder.Entity<IdentityUserClaim<Guid>>(i =>
    {
        i.ToTable("UserClaims");
        i.HasKey(x => x.Id);
    });
    builder.Entity<IdentityUserToken<Guid>>(i =>
    {
        i.ToTable("UserTokens");
        i.HasKey(x => x.UserId);
    });

}
</code>```

To add a default Guid value for Users and Roles IDs:

```<code>        builder.Entity<ApplicationUser>(b =>
        {
            b.Property(u => u.Id).HasDefaultValueSql("NEWID()");
        });

        builder.Entity<ApplicationRole>(b =>
        {
            b.Property(u => u.Id).HasDefaultValueSql("NEWID()");
        });
</code>```

I have just removed the ASPNet extension from the names, you may add your custom table names. and you may replace Guid with int for integer IDs

In ApplicationUser.cs  i have created a Custom ApplicationUser class

```<code>public class ApplicationUser : IdentityUser<Guid>
{
}
</code>```

and a Custom ApplicationRole class

```<code>public class ApplicationRole : IdentityRole<Guid>
{
}
</code>```

In Startup.cs under ConfigureServices method

Change your ASP.NET Core Startup according:

```<code>services
    .AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services
        .AddIdentity<ApplicationUser, ApplicationRole>()
        .AddEntityFrameworkStores<ApplicationDbContext, Guid>()
        .AddDefaultTokenProviders();
</code>```

Delete the content inside the Data/Migrations folder, but keep the Migrations folder there.

Now in the commands line (CMD), change the directory to the application root:

```<code>CD X:\ApplicationPathHere
</code>```

If exist, Drop the existing DB because the schema can't be migrated from PK String to PK Guid

```<code>dotnet ef database drop -c ApplicationDbContext
</code>```

Create the initial migration

```<code>dotnet ef migrations add InitialCreate -c ApplicationDbContext
</code>```

Create the database

```<code>dotnet ef database update
</code>```

Update
For .Net Core 2.0 MVC project template,

You may get some errors in the ManageController, Just cast the Ids by adding .ToString()

and no need to pass int or GUID for:

```<code>protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    // Customizations
    builder.Entity<ApplicationUser>(i =>
    {
        i.ToTable("Users");
        i.HasKey(x => x.Id);
    });
    builder.Entity<ApplicationRole>(i =>
    {
        i.ToTable("Roles");
        i.HasKey(x => x.Id);
    });
    builder.Entity<IdentityUserRole<Guid>>(i =>
    {
        i.ToTable("UserRoles");
        i.HasKey(x => new { x.RoleId, x.UserId });
    });
    builder.Entity<IdentityUserLogin<Guid>>(i =>
    {
        i.ToTable("UserLogins");
        i.HasKey(x => new { x.ProviderKey, x.LoginProvider });
    });
    builder.Entity<IdentityRoleClaim<Guid>>(i =>
    {
        i.ToTable("RoleClaims");
        i.HasKey(x => x.Id);
    });
    builder.Entity<IdentityUserClaim<Guid>>(i =>
    {
        i.ToTable("UserClaims");
        i.HasKey(x => x.Id);
    });
    builder.Entity<IdentityUserToken<Guid>>(i =>
    {
        i.ToTable("UserTokens");
        i.HasKey(x => x.UserId);
    });

}
</code>```0

just add

```<code>protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    // Customizations
    builder.Entity<ApplicationUser>(i =>
    {
        i.ToTable("Users");
        i.HasKey(x => x.Id);
    });
    builder.Entity<ApplicationRole>(i =>
    {
        i.ToTable("Roles");
        i.HasKey(x => x.Id);
    });
    builder.Entity<IdentityUserRole<Guid>>(i =>
    {
        i.ToTable("UserRoles");
        i.HasKey(x => new { x.RoleId, x.UserId });
    });
    builder.Entity<IdentityUserLogin<Guid>>(i =>
    {
        i.ToTable("UserLogins");
        i.HasKey(x => new { x.ProviderKey, x.LoginProvider });
    });
    builder.Entity<IdentityRoleClaim<Guid>>(i =>
    {
        i.ToTable("RoleClaims");
        i.HasKey(x => x.Id);
    });
    builder.Entity<IdentityUserClaim<Guid>>(i =>
    {
        i.ToTable("UserClaims");
        i.HasKey(x => x.Id);
    });
    builder.Entity<IdentityUserToken<Guid>>(i =>
    {
        i.ToTable("UserTokens");
        i.HasKey(x => x.UserId);
    });

}
</code>```1

Body:
I have found the answer in a comment here and i would like to share it more organized here, Thanks to "Raffaele Garofalo" for answering this, I have copied the answer and added my 2 cents:

to rename the default tables in asp.net identity 3 and changing the data type to Uniqueidentifier, use the following steps:

In ApplicationDbContext.cs:

Change the ApplicationDbContext or whatever you used to reflect this one:

Change the class to be:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, Guid>

and the OnModelCreating method to be:

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    // Customizations
    builder.Entity<ApplicationUser>(i =>
    {
        i.ToTable("Users");
        i.HasKey(x => x.Id);
    });
    builder.Entity<ApplicationRole>(i =>
    {
        i.ToTable("Roles");
        i.HasKey(x => x.Id);
    });
    builder.Entity<IdentityUserRole<Guid>>(i =>
    {
        i.ToTable("UserRoles");
        i.HasKey(x => new { x.RoleId, x.UserId });
    });
    builder.Entity<IdentityUserLogin<Guid>>(i =>
    {
        i.ToTable("UserLogins");
        i.HasKey(x => new { x.ProviderKey, x.LoginProvider });
    });
    builder.Entity<IdentityRoleClaim<Guid>>(i =>
    {
        i.ToTable("RoleClaims");
        i.HasKey(x => x.Id);
    });
    builder.Entity<IdentityUserClaim<Guid>>(i =>
    {
        i.ToTable("UserClaims");
        i.HasKey(x => x.Id);
    });
    builder.Entity<IdentityUserToken<Guid>>(i =>
    {
        i.ToTable("UserTokens");
        i.HasKey(x => x.UserId);
    });

}

To add a default Guid value for Users and Roles IDs:

        builder.Entity<ApplicationUser>(b =>
        {
            b.Property(u => u.Id).HasDefaultValueSql("NEWID()");
        });

        builder.Entity<ApplicationRole>(b =>
        {
            b.Property(u => u.Id).HasDefaultValueSql("NEWID()");
        });

I have just removed the ASPNet extension from the names, you may add your custom table names. and you may replace Guid with int for integer IDs

In ApplicationUser.cs  i have created a Custom ApplicationUser class

public class ApplicationUser : IdentityUser<Guid>
{
}

and a Custom ApplicationRole class

public class ApplicationRole : IdentityRole<Guid>
{
}

In Startup.cs under ConfigureServices method

Change your ASP.NET Core Startup according:

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

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

Delete the content inside the Data/Migrations folder, but keep the Migrations folder there.

Now in the commands line (CMD), change the directory to the application root:

CD X:\ApplicationPathHere

If exist, Drop the existing DB because the schema can't be migrated from PK String to PK Guid

dotnet ef database drop -c ApplicationDbContext

Create the initial migration

dotnet ef migrations add InitialCreate -c ApplicationDbContext

Create the database

dotnet ef database update

Update
For .Net Core 2.0 MVC project template,

You may get some errors in the ManageController, Just cast the Ids by adding .ToString()

and no need to pass int or GUID for:

.AddEntityFrameworkStores<ApplicationDbContext, Guid>()

just add

.AddEntityFrameworkStores<ApplicationDbContext>()


来源: stackexchange

问:
Dynamically insert child components inside vuejs2 data (without $compile or abusing v-html)
I'd like to insert new vuejs components on the fly, at arbitrary points within a block of not-necessarily-predefined HTML.

Here's a slightly contrived example that demonstrates the sort of thing I'm trying to do:

Vue.component('child', {
  // pretend I do something useful
  template: '--><slot></slot><--'
})

Vue.component('parent', {
  data() {
    return {
      input: 'lorem',
      text: '
Lorem ipsum dolor sit amet.

Lorem ipsum!
'
    }
  },
  template: `

      Search: <input type='text' v-model="input">

      This inserts the child component but doesn't render it
      or the HTML:

{{output}}

      This renders the HTML but of course strips out the child component:

      (This is the child component, just to show that it's usable here:
      <child>hello</child>)

      This is the goal: it renders both the input html
      and the inserted child components:
      TODO ¯\_(ツ)_/¯

`,
  computed: {
    output() {
      /* This is the wrong approach; what do I replace it with? */
      var out = this.text;
      if (this.input) {
        this.input = this.input.replace(/[^a-zA-Z\s]/g,'');
        var regex = new RegExp(this.input, "gi");
        out = out.replace(regex, '<child>' + this.input + '</child>');
      }
      return out;
    }
  }
});

new Vue({
  el: '#app'
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.js"></script>
<div id="app">
  <parent></parent>
</div></code>```

In the above snippet, assume data.text is sanitized HTML. <child> is some sub-component that does something useful, which I want to wrap around chunks of data.text that aren't known ahead of time.  (input is just for demo here. This MCVE doesn't really resemble the code I'm building, it's just an example that shows the sort of situation I'm stuck on.)

So: how would I change either the output function or the parent component's template, such that both the HTML from input and the inserted <child> templates are rendered properly?

What I've tried

In Vue 1, the answer to this would be a straightforward $compile. I'm using vuejs2 which removed $compile (out of justifiable concern that it made it too easy to naively introduce XSS vulnerabilities.)

v-html sanitizes what you feed it, which strips the child component out. Obviously this is not the way to do this. (That page suggests using partials instead, but I'm not sure how that could be applied to this situation; in any case partials have also been removed from vue2.)

I've tried passing the results of output() into another component which would then use it as its template. This seems like a promising approach, but I can't figure out how to change that secondary component's template. template only accepts a string, not a function like many of the other component properties, so I can't pass the template html in, say, a prop. Something like rewriting this.template inside beforeMount() or bind() would have been nice, but no joy there either. Is there some other way to replace a component's template string before it's mounted?

Unlike template, I can pass data to a component's render() function... but then I'm still stuck having to parse that html string into nested createElement functions. Which is exactly what Vue is doing internally in the first place; is there some way to hook into that here short of reinventing it myself?

Vue.component('foo', {
  props: ['myInput'],
  render(createElement) {
    console.log(this.myInput); // this works...
    // ...but how to parse the html in this.myInput into a usable render function?
    // return createElement('div', this.myInput);
  },
})
```
<ul>
<li><p>I wasn't able to cheat my around this with inline-template, either: <code><foo inline-template>{{$parent.output}}</foo></code> does exactly the same thing as a plain old <code>{{output}}</code>.  In retrospect that should have been obvious, but it was worth a shot.</p>
</li>
<li><p>Maybe constructing an async component on the fly is the answer? This could clearly generate a component with an arbitrary template, but how would I reasonably call that from the parent component, and feed <code>output</code> to the constructor?  (It would need to be reusable with different input, with multiple instances potentially visible simultaneously; no globals or singletons.)</p>
</li>
<li><p>I've even considered ridiculous stuff like having <code>output()</code> split the input into an array at the points where it would have inserted <code><child></code>, and then doing something like this in the main template:</p>
</li>
</ul>
<pre class="lang-html prettyprint-override"><code>  ...
  <template v-for="chunk in output">
      <span v-html="chunk"></span>
      <child>...</child>
  </template>
  ....
</code>```

That would be doable, if laborious -- I'd have to split out what goes in the child's slot into a separate array too and get it by index during the v-for, but that could be done... if input were plain text instead of HTML.  In splitting HTML I'll often wind up with unbalanced tags in each chunk, which can mess up the formatting when v-html rebalances it for me.   And anyway this whole strategy feels like a bad hack; there must be a better way.

Maybe I just drop the whole input into a v-html and then (somehow) insert the child components at the proper positions through after-the-fact DOM manipulation?  I haven't explored this option too deeply because it, too, feels like a hack, and the reverse of the data-driven strategy, but maybe it's a way to go if all else fails?

A couple of pre-emptive disclaimers

I'm very well aware of the XSS risks involved in $compile-like operations.  Please be assured that none of what I'm doing involves unsanitized user input in any way; the user isn't inserting arbitrary component code, instead a component needs to insert child components at user-defined positions.

I'm reasonably confident that this is not an XY problem, that I really do need to insert components on the fly.  (I hope it's obvious from the number of failed attempts and blind alleys I've run down that I've put more than a little thought into this one!) That said, if there's a different approach that leads to similar results, I'm all ears. The salient point is that I know which component I need to add, but I can't know ahead of time where to add it; that decision happens at run time.

If it's relevant, in real life I'm using the single-file component structure from vue-cli webpack template, not Vue.component() as in the samples above.  Answers that don't stray too far from that structure are preferred, though anything that works will work.

Progress!

@BertEvans points out in comments that Vue.compile() is a thing that exists, which is an I-can't-believe-I-missed-that if ever there was one.

But I'm still having trouble using it without resorting to global variables as in that documentation.  This renders, but hardcodes the template in a global:

```<code>var precompiled = Vue.compile('<span><child>test</child></span>');
Vue.component('test', {
  render: precompiled.render,
  staticRenderFns: precompiled.staticRenderFns
});
</code>```

But various attempts to rejigger that into something that can accept an input property have been unsuccessful (the following for example throws "Error in render function: ReferenceError: _c is not defined", I assume because the staticRenderFns aren't ready to go when render needs them?

```<code>Vue.component('test', {
  props: ['input'],
  render() { return Vue.compile(this.input).render()},
  staticRenderFns() {return Vue.compile(this.input).staticRenderFns()}
});
</code>```

(It's not because there are two separate compile()s -- doing the precompile inside beforeMount() and then returning its render and staticRenderFns throws the same error.)

This really feels like it's on the right track but I'm just stuck on a dumb syntax error or the like...

答:
As mentioned in the my comment above, $compile was removed, but Vue.compile is available in certain builds. Using that below works as I believe you intend except in a couple cases.

Vue.component('child', {
  // pretend I do something useful
  template: '--><slot></slot><--'
})

Vue.component('parent', {
  data() {
    return {
      input: 'lorem',
      text: '

Lorem ipsum dolor sit amet.

Lorem ipsum!

'
    }
  },
  template: `

      Search: <input type='text' v-model="input">

<component :is="output"></component>

`,
  computed: {
    output() {
      if (!this.input)
         return Vue.compile(this.text)
      /* This is the wrong approach; what do I replace it with? */
      var out = this.text;
      if (this.input) {
        this.input = this.input.replace(/[^a-zA-Z\s]/g,'');
        var regex = new RegExp(this.input, "gi");
        out = out.replace(regex, '<child>' + this.input + '</child>');
        out = Vue.compile(out)
      }
      return out;
    }
  }
});

new Vue({
  el: '#app'
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.js"></script>
<div id="app">
  <parent></parent>
</div></code>```

You mentioned you are building with webpack and I believe the default for that build is Vue without the compiler, so you would need to modify it to use a different build.

I added a dynamic component to accept the results of the compiled output.

The sample text is not a valid template because it has more than one root. I added a wrapping div to make it a valid template.

One note: this will fail if the search term matches all or part of any of the HTML tags in the text. For example, if you enter "i", or "di" or "p" the results will not be what you expect and certain combinations will throw an error on compilation.

ContentLicense: CC BY-SA 4.0

Body:
I'd like to insert new vuejs components on the fly, at arbitrary points within a block of not-necessarily-predefined HTML.

Here's a slightly contrived example that demonstrates the sort of thing I'm trying to do:

Vue.component('child', {
  // pretend I do something useful
  template: '--><slot></slot><--'
})

Vue.component('parent', {
  data() {
    return {
      input: 'lorem',
      text: '
Lorem ipsum dolor sit amet.

Lorem ipsum!
'
    }
  },
  template: `

      Search: <input type='text' v-model="input">

      This inserts the child component but doesn't render it
      or the HTML:

{{output}}

      This renders the HTML but of course strips out the child component:

      (This is the child component, just to show that it's usable here:
      <child>hello</child>)

      This is the goal: it renders both the input html
      and the inserted child components:
      TODO ¯\_(ツ)_/¯

`,
  computed: {
    output() {
      /* This is the wrong approach; what do I replace it with? */
      var out = this.text;
      if (this.input) {
        this.input = this.input.replace(/[^a-zA-Z\s]/g,'');
        var regex = new RegExp(this.input, "gi");
        out = out.replace(regex, '<child>' + this.input + '</child>');
      }
      return out;
    }
  }
});

new Vue({
  el: '#app'
})

  <parent></parent>

In the above snippet, assume data.text is sanitized HTML. <child> is some sub-component that does something useful, which I want to wrap around chunks of data.text that aren't known ahead of time.  (input is just for demo here. This MCVE doesn't really resemble the code I'm building, it's just an example that shows the sort of situation I'm stuck on.)

So: how would I change either the output function or the parent component's template, such that both the HTML from input and the inserted <child> templates are rendered properly?

What I've tried

In Vue 1, the answer to this would be a straightforward $compile. I'm using vuejs2 which removed $compile (out of justifiable concern that it made it too easy to naively introduce XSS vulnerabilities.)

v-html sanitizes what you feed it, which strips the child component out. Obviously this is not the way to do this. (That page suggests using partials instead, but I'm not sure how that could be applied to this situation; in any case partials have also been removed from vue2.)

I've tried passing the results of output() into another component which would then use it as its template. This seems like a promising approach, but I can't figure out how to change that secondary component's template. template only accepts a string, not a function like many of the other component properties, so I can't pass the template html in, say, a prop. Something like rewriting this.template inside beforeMount() or bind() would have been nice, but no joy there either. Is there some other way to replace a component's template string before it's mounted?

Unlike template, I can pass data to a component's render() function... but then I'm still stuck having to parse that html string into nested createElement functions. Which is exactly what Vue is doing internally in the first place; is there some way to hook into that here short of reinventing it myself?

Vue.component('foo', {
  props: ['myInput'],
  render(createElement) {
    console.log(this.myInput); // this works...
    // ...but how to parse the html in this.myInput into a usable render function?
    // return createElement('div', this.myInput);
  },
})

I wasn't able to cheat my around this with inline-template, either: <foo inline-template>{{$parent.output}}</foo> does exactly the same thing as a plain old {{output}}.  In retrospect that should have been obvious, but it was worth a shot.

Maybe constructing an async component on the fly is the answer? This could clearly generate a component with an arbitrary template, but how would I reasonably call that from the parent component, and feed output to the constructor?  (It would need to be reusable with different input, with multiple instances potentially visible simultaneously; no globals or singletons.)

I've even considered ridiculous stuff like having output() split the input into an array at the points where it would have inserted <child>, and then doing something like this in the main template:

  ...
  <template v-for="chunk in output">

      <child>...</child>
  </template>
  ....

That would be doable, if laborious -- I'd have to split out what goes in the child's slot into a separate array too and get it by index during the v-for, but that could be done... if input were plain text instead of HTML.  In splitting HTML I'll often wind up with unbalanced tags in each chunk, which can mess up the formatting when v-html rebalances it for me.   And anyway this whole strategy feels like a bad hack; there must be a better way.

Maybe I just drop the whole input into a v-html and then (somehow) insert the child components at the proper positions through after-the-fact DOM manipulation?  I haven't explored this option too deeply because it, too, feels like a hack, and the reverse of the data-driven strategy, but maybe it's a way to go if all else fails?

A couple of pre-emptive disclaimers

I'm very well aware of the XSS risks involved in $compile-like operations.  Please be assured that none of what I'm doing involves unsanitized user input in any way; the user isn't inserting arbitrary component code, instead a component needs to insert child components at user-defined positions.

I'm reasonably confident that this is not an XY problem, that I really do need to insert components on the fly.  (I hope it's obvious from the number of failed attempts and blind alleys I've run down that I've put more than a little thought into this one!) That said, if there's a different approach that leads to similar results, I'm all ears. The salient point is that I know which component I need to add, but I can't know ahead of time where to add it; that decision happens at run time.

If it's relevant, in real life I'm using the single-file component structure from vue-cli webpack template, not Vue.component() as in the samples above.  Answers that don't stray too far from that structure are preferred, though anything that works will work.

Progress!

@BertEvans points out in comments that Vue.compile() is a thing that exists, which is an I-can't-believe-I-missed-that if ever there was one.

But I'm still having trouble using it without resorting to global variables as in that documentation.  This renders, but hardcodes the template in a global:

var precompiled = Vue.compile('<child>test</child>');
Vue.component('test', {
  render: precompiled.render,
  staticRenderFns: precompiled.staticRenderFns
});

But various attempts to rejigger that into something that can accept an input property have been unsuccessful (the following for example throws "Error in render function: ReferenceError: _c is not defined", I assume because the staticRenderFns aren't ready to go when render needs them?

Vue.component('test', {
  props: ['input'],
  render() { return Vue.compile(this.input).render()},
  staticRenderFns() {return Vue.compile(this.input).staticRenderFns()}
});

(It's not because there are two separate compile()s -- doing the precompile inside beforeMount() and then returning its render and staticRenderFns throws the same error.)

This really feels like it's on the right track but I'm just stuck on a dumb syntax error or the like...

Body:
As mentioned in the my comment above, $compile was removed, but Vue.compile is available in certain builds. Using that below works as I believe you intend except in a couple cases.

Vue.component('child', {
  // pretend I do something useful
  template: '<span>--&gt;<slot></slot>&lt;--</span>'
})

Vue.component('parent', {
  data() {
    return {
      input: 'lorem',
      text: '<div><p>Lorem ipsum dolor sit amet.</p><p><i>Lorem ipsum!</i></p></div>'
    }
  },
  template: `<div>
      Search: <input type='text' v-model="input"><br>
      <hr>
      <div><component :is="output"></component></div>
    </div>`,
  computed: {
    output() {
      if (!this.input)
         return Vue.compile(this.text)
      /* This is the wrong approach; what do I replace it with? */
      var out = this.text;
      if (this.input) {
        this.input = this.input.replace(/[^a-zA-Z\s]/g,'');
        var regex = new RegExp(this.input, "gi");
        out = out.replace(regex, '<child><b>' + this.input + '</b></child>');
        out = Vue.compile(out)
      }
      return out;
    }
  }
});

new Vue({
  el: '#app'
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.js"></script>
<div id="app">
  <parent></parent>
</div>

You mentioned you are building with webpack and I believe the default for that build is Vue without the compiler, so you would need to modify it to use a different build.

I added a dynamic component to accept the results of the compiled output.

The sample text is not a valid template because it has more than one root. I added a wrapping div to make it a valid template.

One note: this will fail if the search term matches all or part of any of the HTML tags in the text. For example, if you enter "i", or "di" or "p" the results will not be what you expect and certain combinations will throw an error on compilation.

ContentLicense: CC BY-SA 3.0


问:
how to catch android force to close
Now i am working json application.The Force close message occured the app is crosed.  so

how to catch force to close error in try catch exception.Help me.....

答:
put log.d commands everywhr and check the log messages in the log view....

open window > Android > Log

ContentLicense: CC BY-SA 2.5

Title: how to catch android force to close


问:
How can I use Twilio queues without agents having to dial in?
I'd like to have a support queue and a sales queue that call an available agent when there's someone in the queue. The way queue functionality is described in the Twilio docs, it seems that the only way to connect an agent and a caller is to have the agent call into the queue. Well, that's no good for a queue that would be empty for most of the time -- how would they know when to dial in?

Is there a way for an agent to be called and then connected to the queue when someone is waiting?

答:
Twilio developer evangelist here.

This is the exact use case for the Twilio TaskRouter API. From the docs:

Twilio TaskRouter is a system for distributing tasks such as phone calls, leads, support tickets, and other work items to the people and processes that can best handle them. Example applications for TaskRouter include:

Distributing calls to call center agents. TaskRouter supports common features required in call center environments, such as skills-based routing and task prioritization.

Prioritizing and assigning CRM cases to agents in order to make sure they're handled within service level. TaskRouter lets you specify overflow rules for tasks, allowing you to vary assignment rules based on time spent in queue and case content.

Distributing leads to inside sales teams. TaskRouter's business rules allow you to control prioritization so that your team is always working on the most important opportunity.

Check out the quickstart guide for TaskRouter which takes you through creating a workspace and workers and creating tasks for the workers from phone calls.


问:
ActiveMQ get dequeued or consumed messages
Is there any way to get the consumed message,i want to get All messages since the start of the ActiveMQ </p>

答: Once a message is consumed it is gone, the broker marks it as consumed and the storage location it was in is dropped or reused.  </p>


问:
Filter DataFrame by selecting the first row with not-NaN in the given column (or any one row if doesn't exist)
I have a pandas dataframe df with (at least) two columns: id, value and possibly more. id's are not unique. I need to filter the dataframe so that only one row per id remains. The row I want to select is the row where value is not NaN. It is guaranteed that there is at most one such row. For those id's with all NaN's in the value column I don't care which row is selected. What is the best way to achieve this?

Example: if the dataframe is

```<code>id  other   value
0   0   3.14
0   1   NaN
1   2   NaN
1   3   NaN
</code>```

the result may be either

```<code>id  other   value
0   0   3.14
1   2   NaN
</code>```

or

```<code>id  other   value
0   0   3.14
1   3   NaN
</code>```

答:
You could sort_values, there is a parameter na_position which defaults to 'last' meaning that it will push all NaN for that column to the bottom.  Therefore, you can use the following to get a single records for each 'id'.

```<code>df.sort_values(by='value').groupby('id').head(1)
</code>```

Output:

```<code>   id  other  value
0   0      0   3.14
2   1      2    NaN
</code>```

Timing:

Abdou Solution:

f = lambda x: x.head(1) if x.value.isnull().all() else x[~x.value.isnull()].head(1)

df.groupby('id').apply(f)

100 loops, best of 3: 5.62 ms per loop

This solution

df.sort_values(by='value').groupby('id').head(1)

1000 loops, best of 3: 1.44 ms per loop

Body:
I have a pandas dataframe df with (at least) two columns: id, value and possibly more. id's are not unique. I need to filter the dataframe so that only one row per id remains. The row I want to select is the row where value is not NaN. It is guaranteed that there is at most one such row. For those id's with all NaN's in the value column I don't care which row is selected. What is the best way to achieve this?

Example: if the dataframe is

id  other   value
0   0   3.14
0   1   NaN
1   2   NaN
1   3   NaN

the result may be either

id  other   value
0   0   3.14
1   2   NaN

or

id  other   value
0   0   3.14
1   3   NaN

Body:
You could sort_values, there is a parameter na_position which defaults to 'last' meaning that it will push all NaN for that column to the bottom.  Therefore, you can use the following to get a single records for each 'id'.

df.sort_values(by='value').groupby('id').head(1)

Output:

   id  other  value
0   0      0   3.14
2   1      2    NaN

Timing:

Abdou Solution:

f = lambda x: x.head(1) if x.value.isnull().all() else x[~x.value.isnull()].head(1)

df.groupby('id').apply(f)

100 loops, best of 3: 5.62 ms per loop

This solution

df.sort_values(by='value').groupby('id').head(1)

1000 loops, best of 3: 1.44 ms per loop


问:
UIScrollView With next and previous button Action
i am new in iphone,i am using horizontal scrollview these are horizontally scrolling properly
  but i want these horizontally scrolling on previous and next button action.please help me asap.

Thanks:)

答:
Use this one when you want to go on next visible content of Scroll view:

(Put this one inside next button method)

```<code>float coordinate = 2.0f;
[nodeScrollView setContentOffset:CGPointMake(460 * coordinate, 0) animated:YES];
</code>```

move on previous visible content view:

```<code>float coordinate = 1.0f;

[nodeScrollView setContentOffset:CGPointMake(460 * coordinate, 0) animated:YES];
</code>```

(Put this one inside previous button method)

**You need some mathematical calculation with coordinate

Body:
Use this one when you want to go on next visible content of Scroll view:

(Put this one inside next button method)

float coordinate = 2.0f;
[nodeScrollView setContentOffset:CGPointMake(460 * coordinate, 0) animated:YES];

move on previous visible content view:

float coordinate = 1.0f;

[nodeScrollView setContentOffset:CGPointMake(460 * coordinate, 0) animated:YES];

(Put this one inside previous button method)

**You need some mathematical calculation with coordinate


问:
Microsoft JScript runtime error: Member not found
i am using asp.net mvc3 and jquery dialogue to open partial view in main view

here is my structure..

partialview 1

```<code><input type="button" onclick="function1();">
</code>```

partial view 2

```<code><form method="post">
    //some elements

    @Html.RenderPartial("partialview1");
</form>
</code>```

view 1

```<code><script src="myscript.js" />
<script src="jquery.js"/>
//some element

<div>
    load partialview 2 as jquery dialogue
</div>
</code>```

myscript.js

```<code>  function function1()
  {
     //some code
  }
</code>```

this is just only overview of my application

now in above structure if i click on button in the partialview1 i am getting this error : Microsoft JScript runtime error: Member not found.

答: Actually, 'Member Not Found' occurs on all browsers and other non-browser programs. In browsers, placing a button or radial with the same name as the function it calls within a form induces this error. Either rename the button or move it outside of the form.</p>

Body:
i am using asp.net mvc3 and jquery dialogue to open partial view in main view

here is my structure..

partialview 1

<input type="button" onclick="function1();">

partial view 2

<form method="post">
    //some elements

    @Html.RenderPartial("partialview1");
</form>

view 1


问:
EarlGrey launches APP with black screen
After successfully adding EarlGrey to existing project (using CocoaPods) project is successfully built (both "for running" and "for testing"). The problem is that if I run the app from XCode it runs as expected. If I run it as a test only splash screen appears and then whole screen turns black. Have anyone encountered such issue? What might be a problem here?

There is somewhat similar question Black screen with EarlGrey but author did not share his solution.

Additional info:

XCode 8

CocoaPods 1.2.1

EarlGrey 1.9.3

答:
I followed @khandpur advice and tried debugging my app first. So I found out, that in main.m file we're checking if current run is a test run, by

BOOL areWeRunningTests = NSClassFromString(@"XCTestCase") != nil;

Based on that we are running app differently.

To everyone in similar situation: I've added a check

BOOL areWeRunningUITests = NSClassFromString(@"EarlGreyImpl") != nil;

and if that's true app is starting normally.

Final comments - you have to know your app a little to be able to use EarlGrey easily... :)

Title: EarlGrey launches APP with black screen


问:
Modify one element in each row of a numpy array by column indices
I would like to decrement exactly one element in each row of a two-dimensional array, given some indices, one for each row. So basically I want the following to be vectorized:

```<code>for row, col in enumerate(indices):
    array[row,col] -= 1
</code>```

I can select the elements which I want to modify using numpy.choose, but then unfortunately those elements just get copied. Or in other words, something like this does not work:

```<code>selection = np.choose(indices, array.T)
selection -= 1
</code>```

答:
Use integer array indexing for a vectorized access and thus assignment -

```<code>array[np.arange(len(indices)), indices] -= 1
</code>```

Body:
I would like to decrement exactly one element in each row of a two-dimensional array, given some indices, one for each row. So basically I want the following to be vectorized:

for row, col in enumerate(indices):
    array[row,col] -= 1

I can select the elements which I want to modify using numpy.choose, but then unfortunately those elements just get copied. Or in other words, something like this does not work:

selection = np.choose(indices, array.T)
selection -= 1

Body:
Use integer array indexing for a vectorized access and thus assignment -

array[np.arange(len(indices)), indices] -= 1


问:
Checkbox create multiple AJAX request
On my way to solve an issue about an xhr 200 status (So the request is "ok") who's in fact isn't so ok (nothing land in the db), I've found out something weird.

On chrome, I hit F12, then go to network to see all the activities and complete the form randomly. In this form there's some checkboxes, so I've checked them all to see if the values are correctly transfered.. And surprise !

The network activities showed up 6 times the same php files who's used for the request. In the 1st activity of this php file, I've been able to see this (1 for checked, 0 for unchecked) :

```<code>windows:1
shutter:0
garage:0
portal:0
door:0
blind:0
</code>```

In the 2nd call :

```<code>windows:1
shutter:1
garage:0
portal:0
door:0
blind:0
</code>```

Ect... To get this final data when the file is called for the 6th time, with only one click :

```<code>windows:1
shutter:1
garage:1
portal:1
door:1
blind:1
</code>```

This last transfert is the one who should be done in the first place, without going through a loop.

I wonder what's going on here. If you want some code, feel free to ask. To be honest I've never seen this before.

EDIT :
Here's the full script, maybe the $(':checkbox:checked').each(function(i) should be closed before the AJAX request ?

```<code>  $(function() {

    // Only if the form is submitted
    $('#estimate').on('click', function(e) {
      // To prevent the page to be reloaded on submit
      e.preventDefault();

      // Declare all variable
      var civil = $('input[name="gender"]:checked').val();
      var lastname = $('input[name="lastname"]').val();
      var firstname = $('input[name="firstname"]').val();
      var address = $('input[name="address"]').val();
      var zipcode = $('input[name="zipcode"]').val();
      var city = $('input[name="city"]').val();
      var tel = $('input[name="tel"]').val();
      var email = $('input[name="email"]').val();
      var situation = $('input[name="situation"]:checked').val();
      var place = $('input[name="place"]:checked').val();
      var message = $('#message').val();
      var selectedProject = [];

      // Set 0 to get a false boolean
      var windows = 0;
      var shutter = 0;
      var garage = 0;
      var portal = 0;
      var door = 0;
      var blind = 0;

      // At least one checkbox need to be checked
      if ( $('div.checkbox-group :checkbox:checked').length > 0 ) {
        // If the last message was displayed for an error
        $('.select').fadeOut('slow')

        // Get the value of the checked box
        $(':checkbox:checked').each(function(i) {
          selectedProject[i] = $(this).val();

          // Set 1 to get a true boolean for the checked box
          if ( selectedProject[i] == 'windows') {
            windows = 1
          }
          if ( selectedProject[i] == 'shutter') {
            shutter = 1
          }
          if ( selectedProject[i] == 'garage') {
            garage = 1
          }
          if ( selectedProject[i] == 'portal') {
            portal = 1
          }
          if ( selectedProject[i] == 'door') {
            door = 1
          }
          if ( selectedProject[i] == 'blind') {
            blind = 1
          }

          // Declare the data for the AJAX request
          data = {
            civil : civil,
            lastname : lastname,
            firstname : firstname,
            address : address,
            zipcode : zipcode,
            city : city,
            tel : tel,
            email : email,
            situation : situation,
            place : place,
            windows : windows,
            shutter : shutter,
            garage : garage,
            portal : portal,
            door : door,
            blind : blind,
            message : message,
          }

          // Beginning of the AJAX request
          $.ajax({
            url : "transfert/db_transfert.php",
            method :"POST",
            data : data,
            success : function(res){
              if ( res == "done" ) {
                $("#res").hide().html("<p style=\"color:green;\">Votre demande à était envoyée</p>").fadeIn('slow');
              } else if ( res == "missing" ) {
                $("#res").hide().html("<p style=\"color:red;\">Il manque des renseignements</p>").fadeIn('slow');
              } else {
                $("#res").hide().html("<p style=\"color:red;\">Une erreur s'est produite, recommencez ultérieurement</p>").fadeIn('slow');
              }
            }
          })
        });

      } else {
        $('.select').hide().html('<p style="color:red;">Veuillez choisir votre projet avant de continuer.</p>').fadeIn('slow');
      }

    })

  })
</code>```

答:
You could do the AJAX request out side the loop. But I don't think you need the loop at all. Just set the variables related to the checkboxes similarly to the way you set the other variables earlier:

```<code>var windows = $(":checkbox[value=windows]:checked").length;
var shutter = $(":checkbox[value=shutter]:checked").length;
...
</code>```

Another way you could do it is to create the data object before the loop, and then update it from the checkboxes.

```<code>  data = {
    civil : civil,
    lastname : lastname,
    firstname : firstname,
    address : address,
    zipcode : zipcode,
    city : city,
    tel : tel,
    email : email,
    situation : situation,
    place : place,
    windows : 0,
    shutter : 0,
    garage : 0,
    portal : 0,
    door : 0,
    blind : 0,
    message : message,
  }

$(":checkbox:checked").each(function() {
    data[this.value] = 1;
});
</code>```

Title: Checkbox create multiple AJAX request

Body:
On my way to solve an issue about an xhr 200 status (So the request is "ok") who's in fact isn't so ok (nothing land in the db), I've found out something weird.

On chrome, I hit F12, then go to network to see all the activities and complete the form randomly. In this form there's some checkboxes, so I've checked them all to see if the values are correctly transfered.. And surprise !

The network activities showed up 6 times the same php files who's used for the request. In the 1st activity of this php file, I've been able to see this (1 for checked, 0 for unchecked) :

windows:1
shutter:0
garage:0
portal:0
door:0
blind:0

In the 2nd call :

windows:1
shutter:1
garage:0
portal:0
door:0
blind:0

Ect... To get this final data when the file is called for the 6th time, with only one click :

windows:1
shutter:1
garage:1
portal:1
door:1
blind:1

This last transfert is the one who should be done in the first place, without going through a loop.

I wonder what's going on here. If you want some code, feel free to ask. To be honest I've never seen this before.

EDIT :
Here's the full script, maybe the $(':checkbox:checked').each(function(i) should be closed before the AJAX request ?

  $(function() {

    // Only if the form is submitted
    $('#estimate').on('click', function(e) {
      // To prevent the page to be reloaded on submit
      e.preventDefault();

      // Declare all variable
      var civil = $('input[name="gender"]:checked').val();
      var lastname = $('input[name="lastname"]').val();
      var firstname = $('input[name="firstname"]').val();
      var address = $('input[name="address"]').val();
      var zipcode = $('input[name="zipcode"]').val();
      var city = $('input[name="city"]').val();
      var tel = $('input[name="tel"]').val();
      var email = $('input[name="email"]').val();
      var situation = $('input[name="situation"]:checked').val();
      var place = $('input[name="place"]:checked').val();
      var message = $('#message').val();
      var selectedProject = [];

      // Set 0 to get a false boolean
      var windows = 0;
      var shutter = 0;
      var garage = 0;
      var portal = 0;
      var door = 0;
      var blind = 0;

      // At least one checkbox need to be checked
      if ( $('div.checkbox-group :checkbox:checked').length > 0 ) {
        // If the last message was displayed for an error
        $('.select').fadeOut('slow')

        // Get the value of the checked box
        $(':checkbox:checked').each(function(i) {
          selectedProject[i] = $(this).val();

          // Set 1 to get a true boolean for the checked box
          if ( selectedProject[i] == 'windows') {
            windows = 1
          }
          if ( selectedProject[i] == 'shutter') {
            shutter = 1
          }
          if ( selectedProject[i] == 'garage') {
            garage = 1
          }
          if ( selectedProject[i] == 'portal') {
            portal = 1
          }
          if ( selectedProject[i] == 'door') {
            door = 1
          }
          if ( selectedProject[i] == 'blind') {
            blind = 1
          }

          // Declare the data for the AJAX request
          data = {
            civil : civil,
            lastname : lastname,
            firstname : firstname,
            address : address,
            zipcode : zipcode,
            city : city,
            tel : tel,
            email : email,
            situation : situation,
            place : place,
            windows : windows,
            shutter : shutter,
            garage : garage,
            portal : portal,
            door : door,
            blind : blind,
            message : message,
          }

          // Beginning of the AJAX request
          $.ajax({
            url : "transfert/db_transfert.php",
            method :"POST",
            data : data,
            success : function(res){
              if ( res == "done" ) {
                $("#res").hide().html("
Votre demande à était envoyée
").fadeIn('slow');
              } else if ( res == "missing" ) {
                $("#res").hide().html("
Il manque des renseignements
").fadeIn('slow');
              } else {
                $("#res").hide().html("
Une erreur s'est produite, recommencez ultérieurement
").fadeIn('slow');
              }
            }
          })
        });

      } else {
        $('.select').hide().html('
Veuillez choisir votre projet avant de continuer.
').fadeIn('slow');
      }

    })

  })

Body:
You could do the AJAX request out side the loop. But I don't think you need the loop at all. Just set the variables related to the checkboxes similarly to the way you set the other variables earlier:

var windows = $(":checkbox[value=windows]:checked").length;
var shutter = $(":checkbox[value=shutter]:checked").length;
...

Another way you could do it is to create the data object before the loop, and then update it from the checkboxes.

  data = {
    civil : civil,
    lastname : lastname,
    firstname : firstname,
    address : address,
    zipcode : zipcode,
    city : city,
    tel : tel,
    email : email,
    situation : situation,
    place : place,
    windows : 0,
    shutter : 0,
    garage : 0,
    portal : 0,
    door : 0,
    blind : 0,
    message : message,
  }

$(":checkbox:checked").each(function() {
    data[this.value] = 1;
});


问:
Why does my application stop working?
So, I am trying to do an application which gets a random number between 1 and 4 ( 1 inclusive and 4 exclusive ) and after, getting that number, it would change the background color of my Main Activity to the related number:

If it gets the number 1: Change to Blue
If number 2: Change to Black
If 3: Change to Yellow

Here's the code:

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

    Button button = (Button) findViewById(R.id.button);
    Button button2 = (Button) findViewById(R.id.button2);

    button.setOnClickListener( new  View.OnClickListener() {

            public void onClick(View v) {

            LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
            Random rnd = new Random();
            int random = rnd.nextInt(1 - 4);

                if (random == 1) {

                layout.setBackgroundColor(Color.BLUE);

                } else if (random == 2) {

                layout.setBackgroundColor(Color.BLACK);

                } else {

                layout.setBackgroundColor(Color.YELLOW);

                }

            }
        }
    );
}
</code>```

The code seems fine to me and Android Studio doesn't report any errors ( only a warning because of the button2 ), but everytime I tap the button, the app just closes and says "Unfortunatly, Exercise has stopped."

My question is: Why does the application stop working after I tap the button?

( If any more information is needed, tell. I never asked and I am quite a novice in asking and Android Development )

答:
rnd.nextInt(1 - 4); evaluates to rnd.nextInt(-3); and that will throw an IllegalArgumentException due to a negative argument.

As you are not handling that exception yourself, bad things happen to your application. To generate random integers in a range, see How do I generate random integers within a specific range in Java?

Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt(int)

Title: Why does my application stop working?

Body:
So, I am trying to do an application which gets a random number between 1 and 4 ( 1 inclusive and 4 exclusive ) and after, getting that number, it would change the background color of my Main Activity to the related number:

If it gets the number 1: Change to Blue
If number 2: Change to Black
If 3: Change to Yellow

Here's the code:

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

    Button button = (Button) findViewById(R.id.button);
    Button button2 = (Button) findViewById(R.id.button2);

    button.setOnClickListener( new  View.OnClickListener() {

            public void onClick(View v) {

            LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
            Random rnd = new Random();
            int random = rnd.nextInt(1 - 4);

                if (random == 1) {

                layout.setBackgroundColor(Color.BLUE);

                } else if (random == 2) {

                layout.setBackgroundColor(Color.BLACK);

                } else {

                layout.setBackgroundColor(Color.YELLOW);

                }

            }
        }
    );
}

The code seems fine to me and Android Studio doesn't report any errors ( only a warning because of the button2 ), but everytime I tap the button, the app just closes and says "Unfortunatly, Exercise has stopped."

My question is: Why does the application stop working after I tap the button?

( If any more information is needed, tell. I never asked and I am quite a novice in asking and Android Development )


问:
Image files download from FTP with 0 bytes
I find this code to download images files from directories and subdirectories in FTP:

C# Download all files and subdirectories through FTP.

So this is my code in VB.NET:

```<code>Private Sub DownloadFtpDirectory(ByVal url As String, ByVal credentials As NetworkCredential, ByVal localPath As String)
    Dim listRequest As FtpWebRequest = CType(WebRequest.Create(url), FtpWebRequest)
    listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails
    listRequest.Credentials = credentials
    Dim lines As List(Of String) = New List(Of String)
    Dim listResponse As FtpWebResponse = CType(listRequest.GetResponse, FtpWebResponse)
    Dim listStream As Stream = listResponse.GetResponseStream
    Dim listReader As StreamReader = New StreamReader(listStream)

    While Not listReader.EndOfStream
        lines.Add(listReader.ReadLine)

    End While

    For Each line As String In lines
        Dim tokens As String() = line.Split({" "}, 9, StringSplitOptions.RemoveEmptyEntries)
        Dim name As String = tokens(8)
        Dim permissions As String = tokens(0)
        Dim localFilePath As String = Path.Combine(localPath, name)
        Dim fileUrl As String = (url + name)
        If (permissions(0) = ChrW(100)) Then
            If Not Directory.Exists(localFilePath) Then
                Directory.CreateDirectory(localFilePath)
            End If

            DownloadFtpDirectory((fileUrl + "/"), credentials, localFilePath)
        Else
            Dim downloadRequest As FtpWebRequest = CType(WebRequest.Create(fileUrl), FtpWebRequest)
            downloadRequest.Credentials = credentials
            downloadRequest.KeepAlive = False
            downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile
            downloadRequest.UseBinary = True
            downloadRequest.Proxy = Nothing
            downloadRequest.UsePassive = False

            Dim downloadResponse As FtpWebResponse = CType(downloadRequest.GetResponse, FtpWebResponse)
            Dim sourceStream As Stream = downloadResponse.GetResponseStream
            Dim targetStream As FileStream = New FileStream(localFilePath, FileMode.Create)

            Dim buffer() As Byte = New Byte((10240) - 1) {}
            Dim read As Integer

            While (sourceStream.Read(buffer, 0, buffer.Length) > 0)
                targetStream.Write(buffer, 0, read)

            End While

        End If

    Next
End Sub
</code>```

and I call the function from this method:

```<code>Private Sub btnDownloadImagesFromFTP_Click(sender As Object, e As EventArgs) Handles btnDownloadImagesFromFTP.Click
    Try
        Dim credentials As NetworkCredential = New NetworkCredential("user", "password")
        Dim url As String = "ftp://myftp/imagesDirectory/"
        DownloadFtpDirectory(url, credentials, "C:\Users\Admin\Desktop\imagesFromFTP")
    Catch ex As Exception
        MessageBox.Show(ex.Message.ToString)
    End Try
End Sub
</code>```

The code works correctly and downloads the subdirectories with the images files inside and the names well, but when I open any image, is empty with (0 bytes)

Anyone knows why this happens? Thanks.

答:
You never assign the read variable.

```<code>While ((read = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
</code>```

Body:
I find this code to download images files from directories and subdirectories in FTP:

C# Download all files and subdirectories through FTP.

So this is my code in VB.NET:

Private Sub DownloadFtpDirectory(ByVal url As String, ByVal credentials As NetworkCredential, ByVal localPath As String)
    Dim listRequest As FtpWebRequest = CType(WebRequest.Create(url), FtpWebRequest)
    listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails
    listRequest.Credentials = credentials
    Dim lines As List(Of String) = New List(Of String)
    Dim listResponse As FtpWebResponse = CType(listRequest.GetResponse, FtpWebResponse)
    Dim listStream As Stream = listResponse.GetResponseStream
    Dim listReader As StreamReader = New StreamReader(listStream)

    While Not listReader.EndOfStream
        lines.Add(listReader.ReadLine)

    End While

    For Each line As String In lines
        Dim tokens As String() = line.Split({" "}, 9, StringSplitOptions.RemoveEmptyEntries)
        Dim name As String = tokens(8)
        Dim permissions As String = tokens(0)
        Dim localFilePath As String = Path.Combine(localPath, name)
        Dim fileUrl As String = (url + name)
        If (permissions(0) = ChrW(100)) Then
            If Not Directory.Exists(localFilePath) Then
                Directory.CreateDirectory(localFilePath)
            End If

            DownloadFtpDirectory((fileUrl + "/"), credentials, localFilePath)
        Else
            Dim downloadRequest As FtpWebRequest = CType(WebRequest.Create(fileUrl), FtpWebRequest)
            downloadRequest.Credentials = credentials
            downloadRequest.KeepAlive = False
            downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile
            downloadRequest.UseBinary = True
            downloadRequest.Proxy = Nothing
            downloadRequest.UsePassive = False

            Dim downloadResponse As FtpWebResponse = CType(downloadRequest.GetResponse, FtpWebResponse)
            Dim sourceStream As Stream = downloadResponse.GetResponseStream
            Dim targetStream As FileStream = New FileStream(localFilePath, FileMode.Create)

            Dim buffer() As Byte = New Byte((10240) - 1) {}
            Dim read As Integer

            While (sourceStream.Read(buffer, 0, buffer.Length) > 0)
                targetStream.Write(buffer, 0, read)

            End While

        End If

    Next
End Sub

and I call the function from this method:

Private Sub btnDownloadImagesFromFTP_Click(sender As Object, e As EventArgs) Handles btnDownloadImagesFromFTP.Click
    Try
        Dim credentials As NetworkCredential = New NetworkCredential("user", "password")
        Dim url As String = "ftp://myftp/imagesDirectory/"
        DownloadFtpDirectory(url, credentials, "C:\Users\Admin\Desktop\imagesFromFTP")
    Catch ex As Exception
        MessageBox.Show(ex.Message.ToString)
    End Try
End Sub

The code works correctly and downloads the subdirectories with the images files inside and the names well, but when I open any image, is empty with (0 bytes)

Anyone knows why this happens? Thanks.

Body:
You never assign the read variable.

While ((read = sourceStream.Read(buffer, 0, buffer.Length)) > 0)


问:
Route an event into sibling control in WPF
I have a TextBox control for search, and a TreeView control below it. What I need is when I press the "Down Key ↓" while the focus on the search TextBox, I need to tell the TreeView "a Down Key has been pressed while the focus on you" ... I don't need to raise a KeyUp event on the TreeView or something, I need it to do the same action as if I pressed the Down Key while the focus on it!

Is this possible?

答:
```<code>protected override void OnStartup(StartupEventArgs e)
{
    EventManager.RegisterClassHandler(typeof(TextBox),
        TextBox.KeyUpEvent,
        new System.Windows.Input.KeyEventHandler(TextBox_KeyUp));

    base.OnStartup(e);
}

private void TextBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
    if (e.Key != System.Windows.Input.Key.Down) return;

    TreeViewItem newChild = new TreeViewItem();

    newChild.Header = "a Down Key has been pressed while the focus on you";

    Parent.Items.Add(newChild);
    e.Handled = true;
    //MessageBox.Show("Enter pressed");
}
</code>```


问:
Get the id from a Img without the ID
i'm creating  a simple bootstrap gallery thumbnail with images that are being called from database. I succeed in calling all the info, but now i'm struggling with getting the id of each image. This is my code:

```<code> <div class="col-sm-6 col-md-4">
<div class="thumbnail">
  <img id="<?php echo $row['ID_Category']?>" src="<?php echo $row['category_image'] ?>" alt="<?php $row['Categories'] ?>">
  <div class="caption">
    <h3><?php echo $row['ID_Category']?></h3>
    <p><?php echo $row['Categories'] ?></p>
    <p><a href="#" onclick="return getID(this);" class="btn btn-primary" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>
  </div>
</div>
</code>```

And this is my function in javascript:

```<code>function getID(e)
{
    var x = e.src;
    alert(x);
}
</code>```

But it is not working, how do I get the id of each image if is being called from a database?

答:
function getID(obj){
   if(obj instanceof HTMLElement) {
    alert(obj.getAttribute("data-target-id"));
   }
   else {
    alert(obj);
   }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-sm-6 col-md-4">
<div class="thumbnail">
  <img id="1" src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c4/PM5544_with_non-PAL_signals.png/320px-PM5544_with_non-PAL_signals.png" alt="test test">
  <div class="caption">
    <h3>Example 1</h3>
    <p>Using data-* attribute</p>
    <p>Button</p>
  </div>
</div>

<div class="col-sm-6 col-md-4">
<div class="thumbnail">
  <img id="2" src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c4/PM5544_with_non-PAL_signals.png/320px-PM5544_with_non-PAL_signals.png" alt="test test">
  <div class="caption">
    <h3>Example 2</h3>
    <p>Passing id directly</p>
    <p>Button</p>
  </div>
</div></code>```

Title: Get the id from a Img without the ID

Body:
i'm creating  a simple bootstrap gallery thumbnail with images that are being called from database. I succeed in calling all the info, but now i'm struggling with getting the id of each image. This is my code:

  <img id="<?php echo $row['ID_Category']?>" src="<?php echo $row['category_image'] ?>" alt="<?php $row['Categories'] ?>">

<?php echo $row['ID_Category']?>

<?php echo $row['Categories'] ?>

Button Button

And this is my function in javascript:

function getID(e)
{
    var x = e.src;
    alert(x);
}

But it is not working, how do I get the id of each image if is being called from a database?

Body:
function getID(obj){
   if(obj instanceof HTMLElement) {
    alert(obj.getAttribute("data-target-id"));
   }
   else {
    alert(obj);
   }
}

<div class="col-sm-6 col-md-4">
<div class="thumbnail">
  <img id="1" src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c4/PM5544_with_non-PAL_signals.png/320px-PM5544_with_non-PAL_signals.png" alt="test test">
  <div class="caption">
    <h3>Example 1</h3>
    <p>Using data-* attribute</p>
    <p><a href="#" onclick="getID(this);" class="btn btn-primary" role="button" data-target-id="1">Button</a></p>
  </div>
</div>

<div class="col-sm-6 col-md-4">
<div class="thumbnail">
  <img id="2" src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c4/PM5544_with_non-PAL_signals.png/320px-PM5544_with_non-PAL_signals.png" alt="test test">
  <div class="caption">
    <h3>Example 2</h3>
    <p>Passing id directly</p>
    <p><a href="#" onclick="getID(1);" class="btn btn-primary" role="button">Button</a></p>
  </div>
</div>


问:
Acumatic End Point does not support REST
I'm getting the following error when trying do a put to customer endpoint

"System contract version 1 for endpoint BI/100 does not support REST"

any idea what this error means and how to fix it?

答:
This error means precisely what it says: you are trying to perform REST operation against a Contract-based endpoint that does not support REST operations. Acumatica has a notion of "system contract version" (which can be seen on the Endpoint Properties page on Web Services Endpoint screen), and at this point only system contract version 2 supports REST operations.

There are two ways of getting system contract version 2 endpoint - either by extending an existing system contract version 2 endpoint, or by creating a brand new endpoint in the (recent version of) Acumatica. To expand on the latter, Acumatica always creates new endpoints with the latest available public system contract version (which is 2 at the moment).


问:
Android: code works with api 19 but not with api 24
```<code>import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.media.MediaPlayer
import android.media.MediaRecorder
import android.os.Environment
import android.view.View
import android.widget.Toast
import java.io.IOException
import android.widget.ImageButton

class record : AppCompatActivity() {

    var buttonStart: ImageButton? = null
    var buttonStop: ImageButton? = null
    var buttonPlayLastRecordAudio: ImageButton? = null
    var buttonStopPlayingRecording: ImageButton? = null
    var AudioSavePathInDevice = "Blesson"
    var mediaRecorder: MediaRecorder? = null

    var mediaPlayer: MediaPlayer? = null

    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_record)

        buttonStart = findViewById(R.id.record) as ImageButton
        buttonStop = findViewById(R.id.stop) as ImageButton
        buttonPlayLastRecordAudio = findViewById(R.id.play) as ImageButton
        buttonStopPlayingRecording= findViewById(R.id.playstop) as ImageButton
        buttonStop!!.isEnabled = false
        buttonPlayLastRecordAudio!!.isEnabled = false

        buttonStart!!.setOnClickListener {

            AudioSavePathInDevice = Environment.getExternalStorageDirectory().absolutePath + "/" +"Medpro.mp3"

            MediaRecorderReady()

            try {
                mediaRecorder!!.prepare()
                mediaRecorder!!.start()
            } catch (e: IllegalStateException) {
                Toast.makeText(this, "Recording roblem started",
                        Toast.LENGTH_LONG).show()
            }

            buttonStart!!.isEnabled = false
            buttonStart!!.visibility = View.INVISIBLE
            buttonStop!!.visibility = View.VISIBLE
            buttonStop!!.isEnabled = true

            Toast.makeText(this, "Recording started",
                    Toast.LENGTH_LONG).show()

        }
            buttonStop!!.setOnClickListener {

                 mediaRecorder!!.stop()
                 buttonStop!!.isEnabled = false
                 buttonPlayLastRecordAudio!!.isEnabled = true
                // buttonStart!!.isEnabled = true
                 buttonStopPlayingRecording!!.isEnabled = false

                     Toast.makeText(this, "Recording Completed",
                            Toast.LENGTH_LONG).show()
                 buttonStop!!.visibility = View.INVISIBLE
                  buttonPlayLastRecordAudio!!.visibility = View.VISIBLE

        }

              buttonPlayLastRecordAudio!!.setOnClickListener {
                  buttonStop!!.isEnabled = false
                  buttonStart!!.isEnabled = false
                  buttonPlayLastRecordAudio!!.visibility=View.INVISIBLE
                  buttonStopPlayingRecording!!.isEnabled = true
                  buttonStopPlayingRecording!!.visibility=View.VISIBLE

                    mediaPlayer = MediaPlayer()
                     try {
                         mediaPlayer!!.setDataSource(AudioSavePathInDevice)
                         mediaPlayer!!.prepare()
                        } catch (e: IOException) {
                                Toast.makeText(this, "Recoring not found",
                                 Toast.LENGTH_LONG).show()
                        }

                          mediaPlayer!!.start()
                          Toast.makeText(this, "Recording Playing",
                          Toast.LENGTH_LONG).show()
              }

                 buttonStopPlayingRecording!!.setOnClickListener {

                 buttonStopPlayingRecording!!.isEnabled = false
                 buttonPlayLastRecordAudio!!.isEnabled = true

                      if (mediaPlayer != null) {
                      mediaPlayer!!.stop()
                      mediaPlayer!!.release()
                     MediaRecorderReady()
                      }
              }

        }

        fun MediaRecorderReady() {
            mediaRecorder = MediaRecorder()
            mediaRecorder!!.setAudioSource(MediaRecorder.AudioSource.MIC)
            mediaRecorder!!.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
            mediaRecorder!!.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB)
            mediaRecorder!!.setOutputFile(AudioSavePathInDevice)
        }
    }
</code>```

/*
The error that is associated with this code

FATAL EXCEPTION: main
                                                                            Process: com.example.admin.lifeplus, PID: 21679
                                                                            java.lang.RuntimeException: setAudioSource failed.
                                                                                at android.media.MediaRecorder.setAudioSource(Native Method)
                                                                                at com.example.admin.lifeplus.record.MediaRecorderReady(record.kt:138)
                                                                                at com.example.admin.lifeplus.record$onCreate$1.onClick(record.kt:45)
                                                                                at android.view.View.performClick(View.java:5623)
                                                                                at android.view.View$PerformClick.run(View.java:22433)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6247)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
*/

The given above is my code for recording an audio file, it works fine with api 19 devices but does not work with api 24. Can you help me?

答:
You must need to ask for RECORD_AUDIO permission at runtime for API level 23 and above.

Check out this link for more information.

Body:
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.media.MediaPlayer
import android.media.MediaRecorder
import android.os.Environment
import android.view.View
import android.widget.Toast
import java.io.IOException
import android.widget.ImageButton

class record : AppCompatActivity() {

    var buttonStart: ImageButton? = null
    var buttonStop: ImageButton? = null
    var buttonPlayLastRecordAudio: ImageButton? = null
    var buttonStopPlayingRecording: ImageButton? = null
    var AudioSavePathInDevice = "Blesson"
    var mediaRecorder: MediaRecorder? = null

    var mediaPlayer: MediaPlayer? = null

    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_record)

        buttonStart = findViewById(R.id.record) as ImageButton
        buttonStop = findViewById(R.id.stop) as ImageButton
        buttonPlayLastRecordAudio = findViewById(R.id.play) as ImageButton
        buttonStopPlayingRecording= findViewById(R.id.playstop) as ImageButton
        buttonStop!!.isEnabled = false
        buttonPlayLastRecordAudio!!.isEnabled = false

        buttonStart!!.setOnClickListener {

            AudioSavePathInDevice = Environment.getExternalStorageDirectory().absolutePath + "/" +"Medpro.mp3"

            MediaRecorderReady()

            try {
                mediaRecorder!!.prepare()
                mediaRecorder!!.start()
            } catch (e: IllegalStateException) {
                Toast.makeText(this, "Recording roblem started",
                        Toast.LENGTH_LONG).show()
            }

            buttonStart!!.isEnabled = false
            buttonStart!!.visibility = View.INVISIBLE
            buttonStop!!.visibility = View.VISIBLE
            buttonStop!!.isEnabled = true

            Toast.makeText(this, "Recording started",
                    Toast.LENGTH_LONG).show()

        }
            buttonStop!!.setOnClickListener {

                 mediaRecorder!!.stop()
                 buttonStop!!.isEnabled = false
                 buttonPlayLastRecordAudio!!.isEnabled = true
                // buttonStart!!.isEnabled = true
                 buttonStopPlayingRecording!!.isEnabled = false

                     Toast.makeText(this, "Recording Completed",
                            Toast.LENGTH_LONG).show()
                 buttonStop!!.visibility = View.INVISIBLE
                  buttonPlayLastRecordAudio!!.visibility = View.VISIBLE

        }

              buttonPlayLastRecordAudio!!.setOnClickListener {
                  buttonStop!!.isEnabled = false
                  buttonStart!!.isEnabled = false
                  buttonPlayLastRecordAudio!!.visibility=View.INVISIBLE
                  buttonStopPlayingRecording!!.isEnabled = true
                  buttonStopPlayingRecording!!.visibility=View.VISIBLE

                    mediaPlayer = MediaPlayer()
                     try {
                         mediaPlayer!!.setDataSource(AudioSavePathInDevice)
                         mediaPlayer!!.prepare()
                        } catch (e: IOException) {
                                Toast.makeText(this, "Recoring not found",
                                 Toast.LENGTH_LONG).show()
                        }

                          mediaPlayer!!.start()
                          Toast.makeText(this, "Recording Playing",
                          Toast.LENGTH_LONG).show()
              }

                 buttonStopPlayingRecording!!.setOnClickListener {

                 buttonStopPlayingRecording!!.isEnabled = false
                 buttonPlayLastRecordAudio!!.isEnabled = true

                      if (mediaPlayer != null) {
                      mediaPlayer!!.stop()
                      mediaPlayer!!.release()
                     MediaRecorderReady()
                      }
              }

        }

        fun MediaRecorderReady() {
            mediaRecorder = MediaRecorder()
            mediaRecorder!!.setAudioSource(MediaRecorder.AudioSource.MIC)
            mediaRecorder!!.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
            mediaRecorder!!.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB)
            mediaRecorder!!.setOutputFile(AudioSavePathInDevice)
        }
    }

/*
The error that is associated with this code

FATAL EXCEPTION: main
                                                                            Process: com.example.admin.lifeplus, PID: 21679
                                                                            java.lang.RuntimeException: setAudioSource failed.
                                                                                at android.media.MediaRecorder.setAudioSource(Native Method)
                                                                                at com.example.admin.lifeplus.record.MediaRecorderReady(record.kt:138)
                                                                                at com.example.admin.lifeplus.record$onCreate$1.onClick(record.kt:45)
                                                                                at android.view.View.performClick(View.java:5623)
                                                                                at android.view.View$PerformClick.run(View.java:22433)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6247)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
*/

The given above is my code for recording an audio file, it works fine with api 19 devices but does not work with api 24. Can you help me?


问:
How to split columns into two sets per type?
I have a CSV input file. We read that using the following

```<code>val rawdata = spark.
  read.
  format("csv").
  option("header", true).
  option("inferSchema", true).
  load(filename)
</code>```

This neatly reads the data and builds the schema.

The next step is to split the columns into String and Integer columns. How?

If the following is the schema of my dataset...

```<code>scala> rawdata.printSchema
root
 |-- ID: integer (nullable = true)
 |-- First Name: string (nullable = true)
 |-- Last Name: string (nullable = true)
 |-- Age: integer (nullable = true)
 |-- DailyRate: integer (nullable = true)
 |-- Dept: string (nullable = true)
 |-- DistanceFromHome: integer (nullable = true)
</code>```

I'd like to split this into two variables (StringCols, IntCols) where:

StringCols should have "First Name","Last Name","Dept"

IntCols should have "ID","Age","DailyRate","DistanceFromHome"

This is what I have tried :

```<code>val names = rawdata.schema.fieldNames
val types = rawdata.schema.fields.map(r => r.dataType)
</code>```

Now in types, I would like to loop and find all StringType and lookup up in names for the column name, similarly for IntegerType.

答:
Use dtypes operator:

dtypes: Array[(String, String)] Returns all column names and their data types as an array.

That would give you a more idiomatic way of dealing with schema of a dataset.

```<code>val rawdata = Seq(
  (1, "First Name", "Last Name", 43, 2000, "Dept", 0)
).toDF("ID", "First Name", "Last Name", "Age", "DailyRate", "Dept", "DistanceFromHome")
scala> rawdata.dtypes.foreach(println)
(ID,IntegerType)
(First Name,StringType)
(Last Name,StringType)
(Age,IntegerType)
(DailyRate,IntegerType)
(Dept,StringType)
(DistanceFromHome,IntegerType)
</code>```

I want to split this into two variables (StringCols, IntCols)

(I'd rather stick to using immutable values instead if you don't mind)

```<code>val emptyPair = (Seq.empty[String], Seq.empty[String])
val (stringCols, intCols) = rawdata.dtypes.foldLeft(emptyPair) { case ((strings, ints), (name: String, typ)) =>
  typ match {
    case _ if typ == "StringType" => (name +: strings, ints)
    case _ if typ == "IntegerType" => (strings, name +: ints)
  }
}
</code>```

StringCols should have "First Name","Last Name","Dept" and IntCols should have "ID","Age","DailyRate","DistanceFromHome"

You can reverse the collections, but I'd rather avoid doing it as performance expensive and giving you nothing in return.

Body:
I have a CSV input file. We read that using the following

val rawdata = spark.
  read.
  format("csv").
  option("header", true).
  option("inferSchema", true).
  load(filename)

This neatly reads the data and builds the schema.

The next step is to split the columns into String and Integer columns. How?

If the following is the schema of my dataset...

scala> rawdata.printSchema
root
 |-- ID: integer (nullable = true)
 |-- First Name: string (nullable = true)
 |-- Last Name: string (nullable = true)
 |-- Age: integer (nullable = true)
 |-- DailyRate: integer (nullable = true)
 |-- Dept: string (nullable = true)
 |-- DistanceFromHome: integer (nullable = true)

I'd like to split this into two variables (StringCols, IntCols) where:

StringCols should have "First Name","Last Name","Dept"

IntCols should have "ID","Age","DailyRate","DistanceFromHome"

This is what I have tried :

val names = rawdata.schema.fieldNames
val types = rawdata.schema.fields.map(r => r.dataType)

Now in types, I would like to loop and find all StringType and lookup up in names for the column name, similarly for IntegerType.

Body:
Use dtypes operator:

dtypes: Array[(String, String)] Returns all column names and their data types as an array.

That would give you a more idiomatic way of dealing with schema of a dataset.

val rawdata = Seq(
  (1, "First Name", "Last Name", 43, 2000, "Dept", 0)
).toDF("ID", "First Name", "Last Name", "Age", "DailyRate", "Dept", "DistanceFromHome")
scala> rawdata.dtypes.foreach(println)
(ID,IntegerType)
(First Name,StringType)
(Last Name,StringType)
(Age,IntegerType)
(DailyRate,IntegerType)
(Dept,StringType)
(DistanceFromHome,IntegerType)

I want to split this into two variables (StringCols, IntCols)

(I'd rather stick to using immutable values instead if you don't mind)

val emptyPair = (Seq.empty[String], Seq.empty[String])
val (stringCols, intCols) = rawdata.dtypes.foldLeft(emptyPair) { case ((strings, ints), (name: String, typ)) =>
  typ match {
    case _ if typ == "StringType" => (name +: strings, ints)
    case _ if typ == "IntegerType" => (strings, name +: ints)
  }
}

StringCols should have "First Name","Last Name","Dept" and IntCols should have "ID","Age","DailyRate","DistanceFromHome"

You can reverse the collections, but I'd rather avoid doing it as performance expensive and giving you nothing in return.


问:
How MySQL's 'UNION' remove duplicates with multiple columns?
I know the main difference between UNION and UNION ALL is the former removes duplicated records, while the latter keeps all. My question is on how UNION removes duplicated record if there are multiple columns? For example, to union T1(A, B, C) and T2(A, B, C),

will MySQL consider (a1, b1, c1) and (a1, b2, c2) duplicates?

if there were duplicates in T1 itself, will MySQL remove this kind of duplicates?

答:
During a UNION (not a UNION ALL) query, MySQL first combines the records from all the tables involved, and then removes all duplicates.

Consider taking the UNION of the following two tables:

```<code>table1
col1 | col2
1    | 1
1    | 1
2    | 2
2    | 2
3    | 4

table2
col1 | col2
1    | 1
1    | 1
3    | 4
</code>```

Consider the following query

```<code>SELECT * FROM table1
UNION
SELECT * FROM table2
</code>```

The output would be this:

```<code>col1 | col2
1    | 1
2    | 2
3    | 4
</code>```

In other words, simply because (1, 1) was duplicated within each separate table does not mean that it appears in duplicate in the result set.  This output is only consistent with MySQL first combining all records and then removing duplicates.  This has the side effect that if a record appear in duplicate within one of the tables, it also gets removed.

Demo here:

Rextester

Body:
During a UNION (not a UNION ALL) query, MySQL first combines the records from all the tables involved, and then removes all duplicates.

Consider taking the UNION of the following two tables:

table1
col1 | col2
1    | 1
1    | 1
2    | 2
2    | 2
3    | 4

table2
col1 | col2
1    | 1
1    | 1
3    | 4

Consider the following query

SELECT * FROM table1
UNION
SELECT * FROM table2

The output would be this:

col1 | col2
1    | 1
2    | 2
3    | 4

In other words, simply because (1, 1) was duplicated within each separate table does not mean that it appears in duplicate in the result set.  This output is only consistent with MySQL first combining all records and then removing duplicates.  This has the side effect that if a record appear in duplicate within one of the tables, it also gets removed.

Demo here:

Rextester


答:
Check your logcat for more information.

This line seems strange to me: rnd.nextInt(1 - 4);

Is it right?

Title: Why does my application stop working?


问:
Tkinter timer to start at 0 on button click
I would like to create a timer that starts at 0 when a user presses a button and stop at whatever time it has displayed when the user presses the button again. So far, all of the questions user after that looks at the current time and updates in seconds from whatever time it is like so:

```<code>def timer(self):
    now = time.strftime("%H:%M:%S")
    self.label.configure(text=now)
    self.after(1000, self.timer)
</code>```

But I would like to start at zero, display the minutes and seconds. Is there anyway to achieve this?

答:
```<code>import tkinter as tk
import time

class GUI:
    def __init__(self, master):
        self.root = master

        self.parent = tk.Frame(self.root)
        self.parent.pack(fill = tk.BOTH)
        self.parent.config(bg = "black")

        self.now         = time.time()
        self.buttonVar   = tk.IntVar()
        self.buttonCycle = False
        self.buttonVar.set(0)

        self.button = tk.Button(root,
                                textvariable = self.buttonVar,
                                command      = self.updateButton)
        self.button.pack(fill = tk.BOTH)

        self.button_cycle()

    def updateButton(self):
        if self.buttonCycle:
            self.buttonCycle = False
            self.now = time.time()
        elif not self.buttonCycle:
            self.buttonCycle = True

    def button_cycle(self):
        if self.buttonCycle:
            now            = time.time()
            timeDifference = int(now - self.now)
            self.buttonVar.set(timeDifference)
        self.root.after(1000, self.button_cycle)

root = tk.Tk()
myApp = GUI(root)
root.mainloop()
</code>```

Body:
I would like to create a timer that starts at 0 when a user presses a button and stop at whatever time it has displayed when the user presses the button again. So far, all of the questions user after that looks at the current time and updates in seconds from whatever time it is like so:

def timer(self):
    now = time.strftime("%H:%M:%S")
    self.label.configure(text=now)
    self.after(1000, self.timer)

But I would like to start at zero, display the minutes and seconds. Is there anyway to achieve this?


问:
Using Docker with nodejs with node-gyp dependencies
I'm planning to use Docker to deploy a node.js app.  The app has several dependencies that require node-gyp.  Node-gyp builds these modules (e.g. canvas, lwip, qrcode) against compiled libraries on the delivery platform, and in my experience these builds can be highly dependent on the o/s version and libraries installed, and they often break a simple npm install.

So is building my Dockerfile FROM node:version the correct approach?  This seems to be the approach shown in every Docker/Node tutorial I've found so far.  But if I build from a node image, what will happen when I deploy the container?  How can I ensure the target host will have the libraries needed to compile the node-gyp modules?

The other way I'm looking at is to build the Dockerfile FROM ubuntu:version.   But I think this would mean installing nodeJS into the Ubuntu image and the whole thing would be much larger.

Are there other ways of handling this?

答:
How can I ensure the target host will have the libraries needed to compile the node-gyp modules?

The target host is running docker as well. As long as the dependencies are in your image then your server has them as well. That's the entire point with docker if you ask me. If it runs locally, then it runs on the server as well.

I'd go with node-alpine (FROM node:8-alpine) for even smaller files. I struggled with node-gyp before I wrapped my head around it, but now I don't even see how I ever thought it was a problem. As long as you add build tools RUN apk add python make gcc g++ you are good to go (this adds some 100-200mb to the size however).

Also if it ever gets time consuming (say you find yourself rebuilding your image with --no-cache every now and then) then it can be a good idea to split it up into a base-image of your own and another image FROM my-base-image:latest which contains things that you change a more often.

There is some learning curve for sure, but I didn't find it that steep. At least not if you have touched docker before.

The other way I'm looking at is to build the Dockerfile FROM ubuntu:version.

I had only used CentOS before jumping on docker, and I run CentOS on my servers. So I thought it would be a good idea to run CentOS-images as well, but I found that to be just silly. There is absolutely zero gain unless you need something very OS-specific. Now I've only used alpine for maybe half a year, and so far the only alpine-specific command I've needed to learn is apk add/del.

And you probably know already, but don't spend too much time optimizing docker file size in the beginning. (You can reduce layer size a lot by combining commands on one line, (adding packages, running command, removing packages). But that cancels out the use of the docker image cache if you make any small changes in big layers. Better to leave that out until it matters.


答:
The random.nextInt(int bound) method accepts the bound parameter, this is that method in JDK:

public int nextInt(int bound) {
  if (bound <= 0)
    throw new IllegalArgumentException(BadBound);

  int r = next(31);
  int m = bound - 1;
  if ((bound & m) == 0)  // i.e., bound is a power of 2
    r = (int)((bound * (long)r) >> 31);
  else {
    for (int u = r;
      u - (r = u % bound) + m < 0;
      u = next(31))
      ;
  }
  return r;
}
```

So, if the bound is less or equal to 0 it throws exception, your bound is -3, thus resulting in that exception. Change your bound to random.nextInt(3) + 1.

Title: Why does my application stop working?

Body:
The random.nextInt(int bound) method accepts the bound parameter, this is that method in JDK:

public int nextInt(int bound) {
  if (bound <= 0)
    throw new IllegalArgumentException(BadBound);

  int r = next(31);
  int m = bound - 1;
  if ((bound & m) == 0)  // i.e., bound is a power of 2
    r = (int)((bound * (long)r) >> 31);
  else {
    for (int u = r;
      u - (r = u % bound) + m < 0;
      u = next(31))
      ;
  }
  return r;
}

So, if the bound is less or equal to 0 it throws exception, your bound is -3, thus resulting in that exception. Change your bound to random.nextInt(3) + 1.


问:
How can div maintain the same size when on mobile
I am working on a UI that, when displaying on a mobile device, gets too small for it to be used properly.

I have the size of the div fixed in pixels, and it keeps the size if the window is resized, but when I test it on mobile mode on chrome or on a actual mobile device, it shrinks. How can I stop it from behaving like that?

答:
Sounds like your page is zoomed down because it does not contain this line of code in the head:

```<code><meta name="viewport" content="width=device-width"; initial-scale="1.0" />
</code>```

Body:
Sounds like your page is zoomed down because it does not contain this line of code in the head:

<meta name="viewport" content="width=device-width"; initial-scale="1.0" />


问:
Symfony 2 second level cache enabled but not being used?
I have list of records which have at least one related entity. On record list I display main list and data from related records so if table has ~100 records doctrine generates and executes ~150 queries: one for list and one for each related entity which is not great thing. It can be easily reduced to just 2 queries: one for list and one for all related entities at once.

As I found, second level cache in doctrine would be perfect for such case.

So, I have enabled cache in config:

```<code>doctrine:
  orm:
    second_level_cache:
      enabled: true
</code>```

And added to all entities annotation @ORM\Cache(usage="READ_ONLY"). Then before generating list I am fetching all records form both tables:

```<code>$this->getDoctrine()->getRepository('AppBundle:Refuel')->findAll();
$this->getDoctrine()->getRepository('AppBundle:FuelType')->findAll();
</code>```

As I hoped they will got cached and durign actual list render reused without generating ~150 queries. But it is not a case. Debug panel shows that there are still ~150 queries executed and cache stats are:

```<code>Hits: 0
Misses: 2
Puts: 319
</code>```

So as I guess entities are being cached but not reused. Why?

All i found already about second level cache is related to redis - do not want to use it - is redis required to use that cache?

It is sad that there is so little documentation on how to configure that.

答:
Just to expand on @BDS and @Jakub's comments, who have the right answers, if you only do one thing it should be to change your query to eager loading (note that we are selecting both entity types in our query so all records will be fetched in one go):

```<code>$refuel= $this->m_em
        ->getRepository('AppBundle:Refuel')
        ->createQueryBuilder('r')
        ->select('r,t')
        ->join('r.fuel_type', 't')
        ->getQuery()
        ->getResult();
</code>```

Once you've done that, you can start to look at utilising the second level cache. For that, you need to specify the cache driver in your config[_prod].yml:

```<code>second_level_cache:
  region_cache_driver:
    type: memcache
  enabled: true
  log_enabled: false
  regions:
    my_region:
      cache_driver: memcache
      lifetime: 3600
</code>```

And then add annotations to your cachable entities:

```<code>/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 * @ORM\Cache(usage="NONSTRICT_READ_WRITE", region="my_region")
 */
</code>```

Body:
I have list of records which have at least one related entity. On record list I display main list and data from related records so if table has ~100 records doctrine generates and executes ~150 queries: one for list and one for each related entity which is not great thing. It can be easily reduced to just 2 queries: one for list and one for all related entities at once.

As I found, second level cache in doctrine would be perfect for such case.

So, I have enabled cache in config:

doctrine:
  orm:
    second_level_cache:
      enabled: true

And added to all entities annotation @ORM\Cache(usage="READ_ONLY"). Then before generating list I am fetching all records form both tables:

$this->getDoctrine()->getRepository('AppBundle:Refuel')->findAll();
$this->getDoctrine()->getRepository('AppBundle:FuelType')->findAll();

As I hoped they will got cached and durign actual list render reused without generating ~150 queries. But it is not a case. Debug panel shows that there are still ~150 queries executed and cache stats are:

Hits: 0
Misses: 2
Puts: 319

So as I guess entities are being cached but not reused. Why?

All i found already about second level cache is related to redis - do not want to use it - is redis required to use that cache?

It is sad that there is so little documentation on how to configure that.

Body:
Just to expand on @BDS and @Jakub's comments, who have the right answers, if you only do one thing it should be to change your query to eager loading (note that we are selecting both entity types in our query so all records will be fetched in one go):

$refuel= $this->m_em
        ->getRepository('AppBundle:Refuel')
        ->createQueryBuilder('r')
        ->select('r,t')
        ->join('r.fuel_type', 't')
        ->getQuery()
        ->getResult();

Once you've done that, you can start to look at utilising the second level cache. For that, you need to specify the cache driver in your config[_prod].yml:

second_level_cache:
  region_cache_driver:
    type: memcache
  enabled: true
  log_enabled: false
  regions:
    my_region:
      cache_driver: memcache
      lifetime: 3600

And then add annotations to your cachable entities:

/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 * @ORM\Cache(usage="NONSTRICT_READ_WRITE", region="my_region")
 */