问:
Oracle - change variable value for multiple objects
I was wondering if it was possible to write a script where I change the value for a variable in multiple objects.

I ran the following query to get a list of the objects that need to be changed:

```<code>select distinct owner, name, type from dba_source
where lower(text) like '%environment_v%';
</code>```

Is there a script I can write to change the value of environment_v from 10 to 20 in all of those objects?

thanks

答:
This is a problem you almost certainly do NOT want to fully automate.  The below code will find the relevant objects and return their DDL.  But changing the code and running the code should be done manually.

Correctly parsing and changing code is a difficult problem.  The search string you are using returns many false-positives in the SYS schemas on 12.2. - you probably do not want to change those objects.

```<code>--Create DDL statements that contain "%environment_v%".
--These statements must be modified to include the new code.
select owner, object_type, object_name, dbms_metadata.get_ddl(object_type, object_name, owner)
from
(
    --Convert DBA_OBJECTS.OBJECT_TYPE to DBMS_METADATA object type:
    select
        owner,
        --Java object names may need to be converted with DBMS_JAVA.LONGNAME.
        --That code is not included since many database don't have Java installed.
        object_name,
        decode(object_type,
            'DATABASE LINK',      'DB_LINK',
            'JOB',                'PROCOBJ',
            'RULE SET',           'PROCOBJ',
            'RULE',               'PROCOBJ',
            'EVALUATION CONTEXT', 'PROCOBJ',
            'PACKAGE',            'PACKAGE_SPEC',
            'PACKAGE BODY',       'PACKAGE_BODY',
            'TYPE',               'TYPE_SPEC',
            'TYPE BODY',          'TYPE_BODY',
            'MATERIALIZED VIEW',  'MATERIALIZED_VIEW',
            'QUEUE',              'AQ_QUEUE',
            'JAVA CLASS',         'JAVA_CLASS',
            'JAVA TYPE',          'JAVA_TYPE',
            'JAVA SOURCE',        'JAVA_SOURCE',
            'JAVA RESOURCE',      'JAVA_RESOURCE',
            object_type
        ) object_type
    from dba_objects
    where
        --These objects are included with other object types.
        object_type not in ('INDEX PARTITION','INDEX SUBPARTITION',
           'LOB','LOB PARTITION','TABLE PARTITION','TABLE SUBPARTITION')
        --Ignore system-generated types that support collection processing.
        and not (object_type = 'TYPE' and object_name like 'SYS_PLSQL_%')
        --Exclude nested tables, their DDL is part of their parent table.
        and (owner, object_name) not in (select owner, table_name from dba_nested_tables)
        --Exclude overflow segments, their DDL is part of their parent table.
        and (owner, object_name) not in (select owner, table_name from dba_tables where iot_type = 'IOT_OVERFLOW')
        --Only look for objects with a specific variable.
        and (owner, object_name, object_type) in
        (
            select owner, name, type
            from dba_source
            where lower(text) like '%environment_v%'
        )
)
order by owner, object_type, object_name;
</code>```

The above query is based on this answer.  That answer has been edited 10 times, and I've used it on thousands of objects, so it should be a pretty good starting point for generating DDL.

Ideally you would make these changes in version-controlled text files, not directly on a database.

Body:
I was wondering if it was possible to write a script where I change the value for a variable in multiple objects.

I ran the following query to get a list of the objects that need to be changed:

select distinct owner, name, type from dba_source
where lower(text) like '%environment_v%';

Is there a script I can write to change the value of environment_v from 10 to 20 in all of those objects?

thanks

Body:
This is a problem you almost certainly do NOT want to fully automate.  The below code will find the relevant objects and return their DDL.  But changing the code and running the code should be done manually.

Correctly parsing and changing code is a difficult problem.  The search string you are using returns many false-positives in the SYS schemas on 12.2. - you probably do not want to change those objects.

--Create DDL statements that contain "%environment_v%".
--These statements must be modified to include the new code.
select owner, object_type, object_name, dbms_metadata.get_ddl(object_type, object_name, owner)
from
(
    --Convert DBA_OBJECTS.OBJECT_TYPE to DBMS_METADATA object type:
    select
        owner,
        --Java object names may need to be converted with DBMS_JAVA.LONGNAME.
        --That code is not included since many database don't have Java installed.
        object_name,
        decode(object_type,
            'DATABASE LINK',      'DB_LINK',
            'JOB',                'PROCOBJ',
            'RULE SET',           'PROCOBJ',
            'RULE',               'PROCOBJ',
            'EVALUATION CONTEXT', 'PROCOBJ',
            'PACKAGE',            'PACKAGE_SPEC',
            'PACKAGE BODY',       'PACKAGE_BODY',
            'TYPE',               'TYPE_SPEC',
            'TYPE BODY',          'TYPE_BODY',
            'MATERIALIZED VIEW',  'MATERIALIZED_VIEW',
            'QUEUE',              'AQ_QUEUE',
            'JAVA CLASS',         'JAVA_CLASS',
            'JAVA TYPE',          'JAVA_TYPE',
            'JAVA SOURCE',        'JAVA_SOURCE',
            'JAVA RESOURCE',      'JAVA_RESOURCE',
            object_type
        ) object_type
    from dba_objects
    where
        --These objects are included with other object types.
        object_type not in ('INDEX PARTITION','INDEX SUBPARTITION',
           'LOB','LOB PARTITION','TABLE PARTITION','TABLE SUBPARTITION')
        --Ignore system-generated types that support collection processing.
        and not (object_type = 'TYPE' and object_name like 'SYS_PLSQL_%')
        --Exclude nested tables, their DDL is part of their parent table.
        and (owner, object_name) not in (select owner, table_name from dba_nested_tables)
        --Exclude overflow segments, their DDL is part of their parent table.
        and (owner, object_name) not in (select owner, table_name from dba_tables where iot_type = 'IOT_OVERFLOW')
        --Only look for objects with a specific variable.
        and (owner, object_name, object_type) in
        (
            select owner, name, type
            from dba_source
            where lower(text) like '%environment_v%'
        )
)
order by owner, object_type, object_name;

The above query is based on this answer.  That answer has been edited 10 times, and I've used it on thousands of objects, so it should be a pretty good starting point for generating DDL.

Ideally you would make these changes in version-controlled text files, not directly on a database.


来源: stackexchange

问:
How to extend ComplexTypeModelBinder
I need to customize model binding for a particular class Foo that involves extending the normal binding logic with some additional post-processing (e.g., conditionally set null collection fields to an empty collection). I want to add this logic to model binding so that the results are available to action filters, etc.

The most direct approach would be to derive from ComplexTypeModelBinder and override BindModelAsync. However, that method is unfortunately not virtual.

Composition is the next alternative. I'm trying to create a FooModelBinder class that has or obtains an instance of ComplexTypeModelBinder. However, I can't figure out how to inject or resolve a ComplexTypeModelBinder. Is this possible? Is there a better way to extend the functionality of ComplexTypeModelBinder?

答:
I finally realized that model binders are obtained from model binder providers, not via dependency injection. To properly instantiate my FooModelBinder, I need to create a FooModelBinderProvider. And to properly obtain an instance of ComplexTypeModelBinder for composition, my provider needs access to a ComplexTypeModelBinderProvider. In other words, to compose over a model binder, you also need to compose over a model binder provider.

Here's the provider. Note that we don't need to specify the exact type of the injected provider because we're simply wrapping the existing functionality of another model binder.

```<code>public class FooModelBinderProvider : IModelBinderProvider
{
  private readonly IModelBinderProvider workerProvider;

  public FooModelBinderProvider(IModelBinderProvider workerProvider)
  {
    this.workerProvider = workerProvider;
  }

  public IModelBinder GetBinder(ModelBinderProviderContext context)
  {
    if (context == null)
    {
      throw new ArgumentNullException(nameof(context));
    }

    if (context.Metadata.ModelType == typeof(Foo))
    {
      return new FooModelBinder(this.workerProvider.GetBinder(context));
    }

    return null;
  }
}
</code>```

And here is the binder. Note that the first thing we do in BindModelAsync is trampoline into the "worker" binder.

```<code>public class FooModelBinder : IModelBinder
{
  private readonly IModelBinder worker;

  public FooModelBinder(IModelBinder worker)
  {
    this.worker = worker;
  }

  public  async Task BindModelAsync(ModelBindingContext bindingContext)
  {
    await this.worker.BindModelAsync(bindingContext);
    if (!bindingContext.Result.IsModelSet)
    {
      return;
    }

    var foo = bindingContext.Result.Model as Foo;
    if (foo == null)
    {
      throw new InvalidOperationException($"Expected {bindingContext.ModelName} to have been bound by ComplexTypeModelBinder");
    }

    // NOW DO SOME INTERESTING POST-PROCESSING
  }
}
</code>```

Finally, here's how to register the custom binder:

```<code>  services.AddMvc(options =>
  {
    var workerProvider = options.ModelBinderProviders.First(p => p.GetType() == typeof(ComplexTypeModelBinderProvider));
    options.ModelBinderProviders.Insert(options.ModelBinderProviders.IndexOf(workerProvider), new FooModelBinderProvider(workerProvider));
  })
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to extend ComplexTypeModelBinder

Body:
I finally realized that model binders are obtained from model binder providers, not via dependency injection. To properly instantiate my FooModelBinder, I need to create a FooModelBinderProvider. And to properly obtain an instance of ComplexTypeModelBinder for composition, my provider needs access to a ComplexTypeModelBinderProvider. In other words, to compose over a model binder, you also need to compose over a model binder provider.

Here's the provider. Note that we don't need to specify the exact type of the injected provider because we're simply wrapping the existing functionality of another model binder.

public class FooModelBinderProvider : IModelBinderProvider
{
  private readonly IModelBinderProvider workerProvider;

  public FooModelBinderProvider(IModelBinderProvider workerProvider)
  {
    this.workerProvider = workerProvider;
  }

  public IModelBinder GetBinder(ModelBinderProviderContext context)
  {
    if (context == null)
    {
      throw new ArgumentNullException(nameof(context));
    }

    if (context.Metadata.ModelType == typeof(Foo))
    {
      return new FooModelBinder(this.workerProvider.GetBinder(context));
    }

    return null;
  }
}

And here is the binder. Note that the first thing we do in BindModelAsync is trampoline into the "worker" binder.

public class FooModelBinder : IModelBinder
{
  private readonly IModelBinder worker;

  public FooModelBinder(IModelBinder worker)
  {
    this.worker = worker;
  }

  public  async Task BindModelAsync(ModelBindingContext bindingContext)
  {
    await this.worker.BindModelAsync(bindingContext);
    if (!bindingContext.Result.IsModelSet)
    {
      return;
    }

    var foo = bindingContext.Result.Model as Foo;
    if (foo == null)
    {
      throw new InvalidOperationException($"Expected {bindingContext.ModelName} to have been bound by ComplexTypeModelBinder");
    }

    // NOW DO SOME INTERESTING POST-PROCESSING
  }
}

Finally, here's how to register the custom binder:

  services.AddMvc(options =>
  {
    var workerProvider = options.ModelBinderProviders.First(p => p.GetType() == typeof(ComplexTypeModelBinderProvider));
    options.ModelBinderProviders.Insert(options.ModelBinderProviders.IndexOf(workerProvider), new FooModelBinderProvider(workerProvider));
  })


问:
Jenkins fail with Fastlane
My job on a MacMini, using Jenkins, is failing. The job is consisted by a script that will execute some unit tests with Fastlane for iOS. The job executes correctly, but just after the build it logs the error:

```<code>FATAL: Remote call on SLAVE failed
java.lang.ClassNotFoundException: Classloading from system classloader disabled
    at hudson.remoting.RemoteClassLoader$ClassLoaderProxy.fetch4(RemoteClassLoader.java:834)
    at hudson.remoting.RemoteClassLoader$ClassLoaderProxy.fetch3(RemoteClassLoader.java:867)
    at sun.reflect.GeneratedMethodAccessor72.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at hudson.remoting.RemoteInvocationHandler$RPCRequest.perform(RemoteInvocationHandler.java:896)
    at hudson.remoting.Request$2.run(Request.java:336)
    at hudson.remoting.InterceptingExecutorService$1.call(InterceptingExecutorService.java:68)
    at org.jenkinsci.remoting.CallableDecorator.call(CallableDecorator.java:19)
    at hudson.remoting.CallableDecoratorList$1.call(CallableDecoratorList.java:21)
    at jenkins.util.ContextResettingExecutorService$2.call(ContextResettingExecutorService.java:46)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
    at ......remote call to channel(Native Method)
    at hudson.remoting.Channel.attachCallSiteStackTrace(Channel.java:1554)
    at hudson.remoting.Request.call(Request.java:172)
    at hudson.remoting.RemoteInvocationHandler.invoke(RemoteInvocationHandler.java:260)
    at com.sun.proxy.$Proxy6.fetch3(Unknown Source)
    at hudson.remoting.RemoteClassLoader.findClass(RemoteClassLoader.java:195)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:563)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:496)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:292)
    at hudson.util.ProcessTree$UnixReflection.<clinit>(ProcessTree.java:699)
    at hudson.util.ProcessTree$UnixProcess.kill(ProcessTree.java:647)
    at hudson.util.ProcessTree$UnixProcess.killRecursively(ProcessTree.java:668)
    at hudson.util.ProcessTree$UnixProcess.killRecursively(ProcessTree.java:667)
    at hudson.util.ProcessTree$Unix.killAll(ProcessTree.java:589)
    at hudson.Launcher$RemoteLauncher$KillTask.call(Launcher.java:1091)
    at hudson.Launcher$RemoteLauncher$KillTask.call(Launcher.java:1082)
    at hudson.remoting.UserRequest.perform(UserRequest.java:181)
    at hudson.remoting.UserRequest.perform(UserRequest.java:52)
    at hudson.remoting.Request$2.run(Request.java:336)
    at hudson.remoting.InterceptingExecutorService$1.call(InterceptingExecutorService.java:68)
    at java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.lang.Thread.run(Thread.java:844)
Caused: java.lang.LinkageError
    at hudson.util.ProcessTree$UnixReflection.<clinit>(ProcessTree.java:710)
    at hudson.util.ProcessTree$UnixProcess.kill(ProcessTree.java:647)
    at hudson.util.ProcessTree$UnixProcess.killRecursively(ProcessTree.java:668)
    at hudson.util.ProcessTree$UnixProcess.killRecursively(ProcessTree.java:667)
    at hudson.util.ProcessTree$Unix.killAll(ProcessTree.java:589)
    at hudson.Launcher$RemoteLauncher$KillTask.call(Launcher.java:1091)
    at hudson.Launcher$RemoteLauncher$KillTask.call(Launcher.java:1082)
    at hudson.remoting.UserRequest.perform(UserRequest.java:181)
    at hudson.remoting.UserRequest.perform(UserRequest.java:52)
    at hudson.remoting.Request$2.run(Request.java:336)
    at hudson.remoting.InterceptingExecutorService$1.call(InterceptingExecutorService.java:68)
    at java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.lang.Thread.run(Thread.java:844)
    at ......remote call to IOS-SLAVE(Native Method)
    at hudson.remoting.Channel.attachCallSiteStackTrace(Channel.java:1554)
    at hudson.remoting.UserResponse.retrieve(UserRequest.java:281)
    at hudson.remoting.Channel.call(Channel.java:839)
Caused: java.io.IOException: Remote call on SLAVE failed
    at hudson.remoting.Channel.call(Channel.java:847)
    at hudson.Launcher$RemoteLauncher.kill(Launcher.java:1079)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:502)
    at hudson.model.Run.execute(Run.java:1737)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:419)
Finished: FAILURE
</code>```

The current version of JDK I am running is 1.8.0_151 and Jenkins version is 2.73.

答:
try to update your jenkins to latest version and don't forget update his plugin too, then restart jenkins

Hope this helps,

Best regards

Title: Jenkins fail with Fastlane

Body:
My job on a MacMini, using Jenkins, is failing. The job is consisted by a script that will execute some unit tests with Fastlane for iOS. The job executes correctly, but just after the build it logs the error:

FATAL: Remote call on SLAVE failed
java.lang.ClassNotFoundException: Classloading from system classloader disabled
    at hudson.remoting.RemoteClassLoader$ClassLoaderProxy.fetch4(RemoteClassLoader.java:834)
    at hudson.remoting.RemoteClassLoader$ClassLoaderProxy.fetch3(RemoteClassLoader.java:867)
    at sun.reflect.GeneratedMethodAccessor72.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at hudson.remoting.RemoteInvocationHandler$RPCRequest.perform(RemoteInvocationHandler.java:896)
    at hudson.remoting.Request$2.run(Request.java:336)
    at hudson.remoting.InterceptingExecutorService$1.call(InterceptingExecutorService.java:68)
    at org.jenkinsci.remoting.CallableDecorator.call(CallableDecorator.java:19)
    at hudson.remoting.CallableDecoratorList$1.call(CallableDecoratorList.java:21)
    at jenkins.util.ContextResettingExecutorService$2.call(ContextResettingExecutorService.java:46)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
    at ......remote call to channel(Native Method)
    at hudson.remoting.Channel.attachCallSiteStackTrace(Channel.java:1554)
    at hudson.remoting.Request.call(Request.java:172)
    at hudson.remoting.RemoteInvocationHandler.invoke(RemoteInvocationHandler.java:260)
    at com.sun.proxy.$Proxy6.fetch3(Unknown Source)
    at hudson.remoting.RemoteClassLoader.findClass(RemoteClassLoader.java:195)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:563)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:496)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:292)
    at hudson.util.ProcessTree$UnixReflection.<clinit>(ProcessTree.java:699)
    at hudson.util.ProcessTree$UnixProcess.kill(ProcessTree.java:647)
    at hudson.util.ProcessTree$UnixProcess.killRecursively(ProcessTree.java:668)
    at hudson.util.ProcessTree$UnixProcess.killRecursively(ProcessTree.java:667)
    at hudson.util.ProcessTree$Unix.killAll(ProcessTree.java:589)
    at hudson.Launcher$RemoteLauncher$KillTask.call(Launcher.java:1091)
    at hudson.Launcher$RemoteLauncher$KillTask.call(Launcher.java:1082)
    at hudson.remoting.UserRequest.perform(UserRequest.java:181)
    at hudson.remoting.UserRequest.perform(UserRequest.java:52)
    at hudson.remoting.Request$2.run(Request.java:336)
    at hudson.remoting.InterceptingExecutorService$1.call(InterceptingExecutorService.java:68)
    at java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.lang.Thread.run(Thread.java:844)
Caused: java.lang.LinkageError
    at hudson.util.ProcessTree$UnixReflection.<clinit>(ProcessTree.java:710)
    at hudson.util.ProcessTree$UnixProcess.kill(ProcessTree.java:647)
    at hudson.util.ProcessTree$UnixProcess.killRecursively(ProcessTree.java:668)
    at hudson.util.ProcessTree$UnixProcess.killRecursively(ProcessTree.java:667)
    at hudson.util.ProcessTree$Unix.killAll(ProcessTree.java:589)
    at hudson.Launcher$RemoteLauncher$KillTask.call(Launcher.java:1091)
    at hudson.Launcher$RemoteLauncher$KillTask.call(Launcher.java:1082)
    at hudson.remoting.UserRequest.perform(UserRequest.java:181)
    at hudson.remoting.UserRequest.perform(UserRequest.java:52)
    at hudson.remoting.Request$2.run(Request.java:336)
    at hudson.remoting.InterceptingExecutorService$1.call(InterceptingExecutorService.java:68)
    at java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.lang.Thread.run(Thread.java:844)
    at ......remote call to IOS-SLAVE(Native Method)
    at hudson.remoting.Channel.attachCallSiteStackTrace(Channel.java:1554)
    at hudson.remoting.UserResponse.retrieve(UserRequest.java:281)
    at hudson.remoting.Channel.call(Channel.java:839)
Caused: java.io.IOException: Remote call on SLAVE failed
    at hudson.remoting.Channel.call(Channel.java:847)
    at hudson.Launcher$RemoteLauncher.kill(Launcher.java:1079)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:502)
    at hudson.model.Run.execute(Run.java:1737)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:419)
Finished: FAILURE

The current version of JDK I am running is 1.8.0_151 and Jenkins version is 2.73.


问:
How to make a variable that changes depending on user input in batch
I am trying to make something just random for fun, so this is what  i have:

```<code>:login
echo Please login.
set /p x=Username:
if %x% == example.user goto home
if not %x% == example.user goto login

:home
echo Welcome 'example.user'!
</code>```

I want it to change to example.user or whatever the user logs in as, so how would I do that? I don't know how to do that in batch. All code and help are amazing. Thank you all sooooo much.

答:
This should work.</p>

```<code>:login
echo Please login.
set /p x=Username:
if "%x%" == "%USERNAME%" (goto home)
if not "%x%" == "%USERNAME%" (goto login)

:home
echo Welcome %x%!
</code>```

Body:
I am trying to make something just random for fun, so this is what  i have:

:login
echo Please login.
set /p x=Username:
if %x% == example.user goto home
if not %x% == example.user goto login

:home
echo Welcome 'example.user'!

I want it to change to example.user or whatever the user logs in as, so how would I do that? I don't know how to do that in batch. All code and help are amazing. Thank you all sooooo much.

Body:
This should work.

:login
echo Please login.
set /p x=Username:
if "%x%" == "%USERNAME%" (goto home)
if not "%x%" == "%USERNAME%" (goto login)

:home
echo Welcome %x%!


问:
Getting sum with multiple constraints. In a sql file
```<code>CREATE TABLE Insurance (
    P_ID   varchar
    I_2011 decimal
    I_2012 decimal
    LAT    decimal
    LON    decimal
)
</code>```

The line above is the schema of a table 'INSURANCE'. I am trying to add the contents of the column I_2012 with 2 conditions:

Any 2 or more P_ID's have the same I_2011 data

The LAT and LON must be distinct.

This is my query:

```<code>SELECT
    SUM(I_2012)
FROM
(
    SELECT DISTINCT
        LAT,
        LON,
        I_2012
    FROM
        INSURANCE
    GROUP BY
        I_2011
    HAVING
        COUNT(*) > 1
);
</code>```

答:
Tricky question.  One approach here is to actually find the I_2011 values which fail the unique latitude/longitude test, and then retain all records which do not fail:

```<code>SELECT SUM(t1.I_2012)
FROM yourTable t1
LEFT JOIN
(
    SELECT I_2011
    FROM yourTable
    GROUP BY I_2011, LAT, LON
    HAVING COUNT(*) > 1
) t2
    ON t1.I_2011 = t2.I_2011
WHERE
    t2.I_2011 IS NULL
GROUP BY
    t1.I_2011;
</code>```

The subquery aliased as t2 will return all I_2011 values which have two or more records with the same latitude longitude pair.  These are values we do not want in the result set.

Body:
CREATE TABLE Insurance (
    P_ID   varchar
    I_2011 decimal
    I_2012 decimal
    LAT    decimal
    LON    decimal
)

The line above is the schema of a table 'INSURANCE'. I am trying to add the contents of the column I_2012 with 2 conditions:

Any 2 or more P_ID's have the same I_2011 data

The LAT and LON must be distinct.

This is my query:

SELECT
    SUM(I_2012)
FROM
(
    SELECT DISTINCT
        LAT,
        LON,
        I_2012
    FROM
        INSURANCE
    GROUP BY
        I_2011
    HAVING
        COUNT(*) > 1
);

Body:
Tricky question.  One approach here is to actually find the I_2011 values which fail the unique latitude/longitude test, and then retain all records which do not fail:

SELECT SUM(t1.I_2012)
FROM yourTable t1
LEFT JOIN
(
    SELECT I_2011
    FROM yourTable
    GROUP BY I_2011, LAT, LON
    HAVING COUNT(*) > 1
) t2
    ON t1.I_2011 = t2.I_2011
WHERE
    t2.I_2011 IS NULL
GROUP BY
    t1.I_2011;

The subquery aliased as t2 will return all I_2011 values which have two or more records with the same latitude longitude pair.  These are values we do not want in the result set.


问:
JQuery clone <select> element
I want to clone a <select> input in HTML using JQuery.

I'm not sure how to go about it, so thought I'd ask here.

Particularly interested in the best way to write it back into the document as well.

My select element looks like this:

```<code><select id="options">
    <option value="1">Opt 1</option>
    <option value="2">Opt 2</option>
    <option value="3">Opt 3</option>
</select>
</code>```

Thanks.

答:
you can attr option selected true with select change, then use clone is ok.

$("#options").off("change").on("change", function() {
    var val = $(this).val();

    $(this).find("option[value=" + val + "]").attr("selected", true);
});```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$("#options").off("change").on("change", function() {
    var val = $(this).val();

    $(this).find("option[value=" + val + "]").attr("selected", true);
});</code>```

ContentLicense: CC BY-SA 2.5

Title: JQuery clone <select> element

Body:
I want to clone a <select> input in HTML using JQuery.

I'm not sure how to go about it, so thought I'd ask here.

Particularly interested in the best way to write it back into the document as well.

My select element looks like this:

<select id="options">
    <option value="1">Opt 1</option>
    <option value="2">Opt 2</option>
    <option value="3">Opt 3</option>
</select>

Thanks.

Body:
you can attr option selected true with select change, then use clone is ok.

$("#options").off("change").on("change", function() {
    var val = $(this).val();

    $(this).find("option[value=" + val + "]").attr("selected", true);
});

$("#options").off("change").on("change", function() {
    var val = $(this).val();

    $(this).find("option[value=" + val + "]").attr("selected", true);
});


问:
tf.concat operation in PyTorch
torch.stack is not what I am searching.

I am looking for the Tensorflow's concat operation for Pytorch.

I have searched the doc http://pytorch.org/docs/0.3.0/

答:
I belive torch.cat is what you are looking for.

http://pytorch.org/docs/master/torch.html#torch.cat

Title: tf.concat operation in PyTorch


问:
Microsoft Access Forms - Listbox, Textbox (Two Tables)
I have two tables:

Help Table
HelpID
FormText
HelpFileID

HelpFileID
HelpFileID
HelpText

I would like to display FormText in a listbox and then have a textbox with HelpText in it. So when they select the FormText the associated HelpText in the other table is displayed in the textbox.

How do I go about this?

答:
The listbox RowSource can be a query that joins the two tables. Set the listbox
ColumnCount and ColumnWidths properties. Textbox ControlSource property can reference columns of the listbox by index. Index begins with 0. If HelpText is in column 3 then index is 2.

=listboxname.Column(2)


问:
How to GetCurrentMethod() for an inherited class function
I have built out a UI testing suite and framework that utilizes Selenium for testing. In my framework I utilize a BaseTest class that is inherited by the Test classes in order to simplify my SetUp and Teardown. In the base test I do a few things including starting the driver, initializing the logger, and maximizing the browser for functional testing.

My problem is that when I initialize the logger, I need to pass the logger a name. I am wanting to utilize the actual test's namespace plus the actual test name so I can filter through logs on individual tests to help diagnose issues with tests and with bugs as well.

This is how I currently have my base test set up:

```<code>[SetUp]
public void RemoteSetUp()
{
    string LoggerName = GetType().Namespace + "_" + System.Reflection.MethodBase.GetCurrentMethod();
    logger = LogManager.GetLogger(LoggerName);
    DesiredCapabilities capabilities = DesiredCapabilities.InternetExplorer();
    capabilities.AcceptInsecureCerts = true;
    driver = new RemoteWebDriver(new Uri("http://10.16.199.64:4444/wd/hub"), capabilities);
    driver.Manage().Window.Maximize();
}
</code>```

This is only doing half of what I want correctly. Where I declare the LoggerName it is returning the TEST'S namespace (not the base test's namespace) however the System.Reflection.MethodBase.GetCurrentMethod(); is returning the BASE TEST'S method name. This causes my LoggerName to equal [TestNamespace]_[BaseTestMethodName].

How can I make my LoggerName equal to [TestNamespace]_[TestMethodName]?

答:
Not sure what your BaseTest looks like. Here's how you get the underlying type. Note: I tested this with Nullable: </p>

```<code>var t = typeof(BaseTest<int>);

if (t.GetType().IsGenericType &&
    t.GetType().GetGenericTypeDefinition() == typeof(BaseTest<>))
{
    var type = t.GetGenericArguments()[0];
}
</code>```

Body:
I have built out a UI testing suite and framework that utilizes Selenium for testing. In my framework I utilize a BaseTest class that is inherited by the Test classes in order to simplify my SetUp and Teardown. In the base test I do a few things including starting the driver, initializing the logger, and maximizing the browser for functional testing.

My problem is that when I initialize the logger, I need to pass the logger a name. I am wanting to utilize the actual test's namespace plus the actual test name so I can filter through logs on individual tests to help diagnose issues with tests and with bugs as well.

This is how I currently have my base test set up:

[SetUp]
public void RemoteSetUp()
{
    string LoggerName = GetType().Namespace + "_" + System.Reflection.MethodBase.GetCurrentMethod();
    logger = LogManager.GetLogger(LoggerName);
    DesiredCapabilities capabilities = DesiredCapabilities.InternetExplorer();
    capabilities.AcceptInsecureCerts = true;
    driver = new RemoteWebDriver(new Uri("http://10.16.199.64:4444/wd/hub"), capabilities);
    driver.Manage().Window.Maximize();
}

This is only doing half of what I want correctly. Where I declare the LoggerName it is returning the TEST'S namespace (not the base test's namespace) however the System.Reflection.MethodBase.GetCurrentMethod(); is returning the BASE TEST'S method name. This causes my LoggerName to equal [TestNamespace]_[BaseTestMethodName].

How can I make my LoggerName equal to [TestNamespace]_[TestMethodName]?

Body:
Not sure what your BaseTest looks like. Here's how you get the underlying type. Note: I tested this with Nullable:

var t = typeof(BaseTest<int>);

if (t.GetType().IsGenericType &&
    t.GetType().GetGenericTypeDefinition() == typeof(BaseTest<>))
{
    var type = t.GetGenericArguments()[0];
}


问:
Custom domain for API Gateway returning 403
I am creating an api using API Gateway and Lambda. Using the url designated in the API Gateway Stage editor everything works fine; however, when I try and move to a custom domain I am running into some issues.

The first thing I tried was using a CNAME record in Route 53 straight from my domain onto the domain that I got from the API Gateway. That was returning some errors and I think it is the incorrect solution is that correct?

Next I tried the Custom Domain Names feature in API Gateway. My understanding is this will roll up a CloudFront distribution that I can then map onto from Route 53. When I created the custom domain and added a Domain Mapping it provides me with a url to what I assume is a CloudFront distribution. The link is returning a 403 response and no distribution has been made in CloudFront. What is a good way of debugging this problem?

答: In my case I had to add base path mapping.</p>


问:
How can I send WM_DROPFILES from C#?
I want to use C# code to simulate a user dragging and dropping a file onto a control in a separate process.  As a stepping stone to this goal, I am trying to send a WM_DROPFILES message to my own TextBox and verifying that the DragDrop event is triggered.

With the code below in a Form containing a single TextBox and two Buttons, clicking on button1 successfully sets the text of textBox1 to "Hello world".  So, it seems that I'm using SendMessage correctly and am able to supply arguments via pointers.  Dragging and dropping a file from Windows Explorer onto textBox1 displays the MessageBox, so textBox1 is set up to receive drag-dropped files correctly.  However, when I click button2, nothing happens.  Why don't I see a MessageBox when I click button2?

```<code>using System;
using System.Data;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace StackOverflow
{
    public partial class BadDragDrop : Form
    {
        #region WINAPI

        [Serializable]
        [StructLayout(LayoutKind.Sequential)]
        struct POINT
        {
            public Int32 X;
            public Int32 Y;
        }

        [Serializable]
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
        class DROPFILES
        {
            public Int32 size;
            public POINT pt;
            public Int32 fND;
            public Int32 WIDE;
        }

        const uint WM_DROPFILES = 0x0233;
        const uint WM_SETTEXT = 0x000C;

        [DllImport("Kernel32.dll", SetLastError = true)]
        static extern int GlobalLock(IntPtr Handle);

        [DllImport("Kernel32.dll", SetLastError = true)]
        static extern int GlobalUnlock(IntPtr Handle);

        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        #endregion

        public BadDragDrop()
        {
            InitializeComponent();
            textBox1.AllowDrop = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string textToSet = "Hello world\0";
            IntPtr p = Marshal.AllocHGlobal(textToSet.Length);
            Marshal.Copy(textToSet.Select(c => (byte)c).ToArray(), 0, p, textToSet.Length);
            int success = GlobalUnlock(p);
            SendMessage(textBox1.Handle, WM_SETTEXT, IntPtr.Zero, p);
            Marshal.FreeHGlobal(p);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string filePath = @"C:\Windows\win.ini" + "\0\0";

            DROPFILES s = new DROPFILES()
            {
                size = Marshal.SizeOf<DROPFILES>(),
                pt = new POINT() { X = 10, Y = 10 },
                fND = 0,
                WIDE = 0,
            };

            int wparamLen = s.size + filePath.Length;

            IntPtr p = Marshal.AllocHGlobal(wparamLen);
            int iSuccess = GlobalLock(p);

            Marshal.StructureToPtr(s, p, false);
            Marshal.Copy(filePath.Select(c => (byte)c).ToArray(), 0, p + s.size, filePath.Length);

            iSuccess = GlobalUnlock(p);

            var verify = new byte[wparamLen];
            Marshal.Copy(p, verify, 0, wparamLen);

            var ipSuccess = SendMessage(textBox1.Handle, WM_DROPFILES, p, IntPtr.Zero);
            Marshal.FreeHGlobal(p);
        }

        private void textBox1_DragDrop(object sender, DragEventArgs e)
        {
            MessageBox.Show(this, "Drag drop!");
        }

        private void textBox1_DragOver(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Copy;
        }
    }
}
</code>```

答:
The reason you don't see your MessageBox appear is likely because the TextBox doesn't handle WM_DROPFILES messages to begin with.  It implements its drop support using OLE Drag&Drop instead by implementing the IDropTarget interface (see Drag and Drop Overview in the WPF documentation).

WM_DROPFILES has been deprecated ever since DoDragDrop() was introduced way back in Windows 95.  OLE Drag&Drop has been the preferred way to implement drag&drop on Windows for a very long time.  WM_DROPFILES is still supported by Windows (but not .NET) but only for backwards compatibility with legacy apps.

Dragging items from Windows Explorer to other apps uses OLE Drag&Drop under the hood, even if the receiver doesn't implement OLE Drag&Drop.

If you drag&drop an IDataObject onto a window that has had RegisterDragDrop() called on it (like your TextBox has), the IDataObject will be passed to the window's IDropTarget interface for handling.

If you drag&drop an IDataObject onto a window that doesn't implement IDropTarget, but has had DragAcceptFiles() called on it, or at least has the WS_EX_ACCEPTFILES window style, Windows will generate a WM_DROPFILES message if the IDataObject contains CF_HDROP data in it.

So, to do what you are attempting with your TextBox, you need to implement the IDropSource and IDataObject interfaces, and then call DoDragDrop() with them.  Let Windows handle the actual dragging and dropping for you.  See Shell Clipboard Formats and Handling Shell Data Transfer Scenarios.

Now, with that said, if you are still determined to send a WM_DROPFILES message to another process (which your question says is your ultimate goal), you can do that, and Windows will marshal your DROPFILES struct across process boundaries for you, but you need to use PostMessage() instead of SendMessage() (not sure why, only that it is required), and be sure to free the DROPFILES only if PostMessage() fails.  Windows will free the DROPFILES for you if PostMessage() is successful.

But even then, there is no guarantee that the receiving process actually handles WM_DROPFILES messages (and even if it does, your manual WM_DROPFILES message might get blocked by UIPI, unless the receiver calls ChangeWindowMessageFilter/Ex() on itself to allow WM_DROPFILES and WM_COPYGLOBALDATA messages).  The receiver might be expecting IDataObject instead.  If the receiver even supports drag&drop at all.

Title: How can I send WM_DROPFILES from C#?

Body:
I want to use C# code to simulate a user dragging and dropping a file onto a control in a separate process.  As a stepping stone to this goal, I am trying to send a WM_DROPFILES message to my own TextBox and verifying that the DragDrop event is triggered.

With the code below in a Form containing a single TextBox and two Buttons, clicking on button1 successfully sets the text of textBox1 to "Hello world".  So, it seems that I'm using SendMessage correctly and am able to supply arguments via pointers.  Dragging and dropping a file from Windows Explorer onto textBox1 displays the MessageBox, so textBox1 is set up to receive drag-dropped files correctly.  However, when I click button2, nothing happens.  Why don't I see a MessageBox when I click button2?

using System;
using System.Data;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace StackOverflow
{
    public partial class BadDragDrop : Form
    {
        #region WINAPI

        [Serializable]
        [StructLayout(LayoutKind.Sequential)]
        struct POINT
        {
            public Int32 X;
            public Int32 Y;
        }

        [Serializable]
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
        class DROPFILES
        {
            public Int32 size;
            public POINT pt;
            public Int32 fND;
            public Int32 WIDE;
        }

        const uint WM_DROPFILES = 0x0233;
        const uint WM_SETTEXT = 0x000C;

        [DllImport("Kernel32.dll", SetLastError = true)]
        static extern int GlobalLock(IntPtr Handle);

        [DllImport("Kernel32.dll", SetLastError = true)]
        static extern int GlobalUnlock(IntPtr Handle);

        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        #endregion

        public BadDragDrop()
        {
            InitializeComponent();
            textBox1.AllowDrop = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string textToSet = "Hello world\0";
            IntPtr p = Marshal.AllocHGlobal(textToSet.Length);
            Marshal.Copy(textToSet.Select(c => (byte)c).ToArray(), 0, p, textToSet.Length);
            int success = GlobalUnlock(p);
            SendMessage(textBox1.Handle, WM_SETTEXT, IntPtr.Zero, p);
            Marshal.FreeHGlobal(p);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string filePath = @"C:\Windows\win.ini" + "\0\0";

            DROPFILES s = new DROPFILES()
            {
                size = Marshal.SizeOf<DROPFILES>(),
                pt = new POINT() { X = 10, Y = 10 },
                fND = 0,
                WIDE = 0,
            };

            int wparamLen = s.size + filePath.Length;

            IntPtr p = Marshal.AllocHGlobal(wparamLen);
            int iSuccess = GlobalLock(p);

            Marshal.StructureToPtr(s, p, false);
            Marshal.Copy(filePath.Select(c => (byte)c).ToArray(), 0, p + s.size, filePath.Length);

            iSuccess = GlobalUnlock(p);

            var verify = new byte[wparamLen];
            Marshal.Copy(p, verify, 0, wparamLen);

            var ipSuccess = SendMessage(textBox1.Handle, WM_DROPFILES, p, IntPtr.Zero);
            Marshal.FreeHGlobal(p);
        }

        private void textBox1_DragDrop(object sender, DragEventArgs e)
        {
            MessageBox.Show(this, "Drag drop!");
        }

        private void textBox1_DragOver(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Copy;
        }
    }
}


问:
Code First Mapping and Repositories
I am learning the repository pattern and entity framework. I have a question regarding how to map my classes with EF 6 Code First (Existing Db). I know there a lot of questions about this (and I've readed maany of them) but still it's hard for me to understand something, which appears to be "logic" but it's getting me crazy (maybe I have readed too many different opinions...)

Problem (Example)

A table Processes which stores different processes like offer, receipt, order etc.. One of the columns of the table is AddDate which represents when this process was added to the DB.

Now I want to write a library to access this DB to use it in different apps, since it's the core Db in the company.

In the library I want to expose for example a ProcessRepository with a method GetByAddDateRange which returns the processes added after, before or in a given time range.

Question

So, now EF with CodeFirst to an existing DB first generates for me a class for every table with a property for every field. So I have a class Process (from now ProcessEntity) with a property AddDate.

Now in my "domain model", the classes that I want to use in my businnes logic etc, I want to have a class Process (from now ProcessDomain) but this should not have an AddDate property, since it's not important for the "object" or is part of its "properties".

So now how should I do then if I want to get ProcessDomains from my ProcessRepository using this AddDate as condition?

If I use directly ProcessEntity as "domain model" (class generated by EF) and if I understand it right, I have to have a property called AddDate since I will need it in my repo when doing sth like Return _dbContext.Set(Of Process).Where(Func(s)s.AddDate>addDate) or not?

I could (like I've read) have a class ProcessEntity and ProcessDomain and map manually between them in my repository. If I understand it right the repo should return the expected type for the layer above, in this case should return my domainModel class.

Do I understand it?

So for me the first option appears just in close to all scenarios useless, since you have to have specific properties in your classes.  so it doesn't matter how I try to look at the problem I always see the need to map manually when using an existing db.

Maybe I am missing sth or understanding sth wrong, so please let me know.

答:
Your EF entities need to have properties for all the database columns you want to use, which includes those you want to filter by. This means that your EF class that corresponds to that table must have that AddDate property. If you want a class that doesn't have that property then you need to define another class.

Many developers/teams will do that anyway. We do mostly ASP.NET MVC work in my office and we have an EF model that corresponds to the database and repositories that return types from that, then we have a service layer that maps those EF entities to data transfer objects (DTOs).  The DTOs may map 100% to a corresponding entity but they may also be missing some properties and/or have extra properties. There may also be DTOs that don't correspond to a single entity.  We usually use web services between app and database so the DTOs are as efficient as they can be for reduced data transfer.

We have our own tool to generate the DTOs based on the EF model.  We will then adjust the generated code as required.  If we need to add members, we generally do so in a partial class, so future regeneration doesn't affect that code.  If we need to remove members then we have no choice but to edit the generated code.  We also use AutoMapper to map data between EF entities and DTOs and vice versa.

Title: Code First Mapping and Repositories


问:
flexbox flex-basis column distribution
I have a flexbox container that has up to 6 child elements their widths are 16.666667% minus it's gutter of 10px. I can create the grid with six items and they get evenly distributed in the flex-row but the problem I'm having is when I only have 5 items the child elements do not distribute evenly when I compare two grids together. So when I have only five elements there is a 5px or so added extra to each element because their isn't a 6th item how do I fix this so that both grid are lining up. What I don't want happening is the redistribution of spaces for 5 columns instead of 6

.flex-grid {
  background: green;
}

.flex-grid .flex-row {
  display: flex;
}

.flex-grid .flex-1-6-5 {
  flex: calc( 16.6666666667% - 10px);
  /* I've tried flex: 0 0 calc() */
}

.flex-grid.flex-gutter-5>.flex-row>div:not(:last-of-type) {
  margin-right: 10px;
}

.box {
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex-grid flex-gutter-5 six-columns">
  <div class="flex-row">
    <div class="flex-1-6-5 box">1</div>
    <div class="flex-1-6-5 box">2</div>
    <div class="flex-1-6-5 box">3</div>
    <div class="flex-1-6-5 box">4</div>
    <div class="flex-1-6-5 box">5</div>
    <div class="flex-1-6-5 box">6</div>
  </div>
</div>
<div class="flex-grid flex-gutter-5 five-columns" style="margin-top: 40px">
  <div class="flex-row">
    <div class="flex-1-6-5 box">1</div>
    <div class="flex-1-6-5 box">2</div>
    <div class="flex-1-6-5 box">3</div>
    <div class="flex-1-6-5 box">4</div>
    <div class="flex-1-6-5 box">5</div>
  </div>
</div></code>```

答:
Sounds like a max-width of calc(16.6666666667% - 10px) might do the trick.

.flex-grid {
  background: green;
}

.flex-grid .flex-row {
  display: flex;
}

.flex-grid .flex-1-6-5 {
  flex: 1;
  max-width: calc( 16.6666666667% - 10px);
}

.flex-grid.flex-gutter-5>.flex-row>div:not(:last-of-type) {
  margin-right: 10px;
}

.box {
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex-grid flex-gutter-5 six-columns">
  <div class="flex-row">
    <div class="flex-1-6-5 box">1</div>
    <div class="flex-1-6-5 box">2</div>
    <div class="flex-1-6-5 box">3</div>
    <div class="flex-1-6-5 box">4</div>
    <div class="flex-1-6-5 box">5</div>
    <div class="flex-1-6-5 box">6</div>
  </div>
</div>
<div class="flex-grid flex-gutter-5 five-columns" style="margin-top: 40px">
  <div class="flex-row">
    <div class="flex-1-6-5 box">1</div>
    <div class="flex-1-6-5 box">2</div>
    <div class="flex-1-6-5 box">3</div>
    <div class="flex-1-6-5 box">4</div>
    <div class="flex-1-6-5 box">5</div>
  </div>
</div></code>```

Title: flexbox flex-basis column distribution

Body:
I have a flexbox container that has up to 6 child elements their widths are 16.666667% minus it's gutter of 10px. I can create the grid with six items and they get evenly distributed in the flex-row but the problem I'm having is when I only have 5 items the child elements do not distribute evenly when I compare two grids together. So when I have only five elements there is a 5px or so added extra to each element because their isn't a 6th item how do I fix this so that both grid are lining up. What I don't want happening is the redistribution of spaces for 5 columns instead of 6

.flex-grid {
  background: green;
}

.flex-grid .flex-row {
  display: flex;
}

.flex-grid .flex-1-6-5 {
  flex: calc( 16.6666666667% - 10px);
  /* I've tried flex: 0 0 calc() */
}

.flex-grid.flex-gutter-5>.flex-row>div:not(:last-of-type) {
  margin-right: 10px;
}

.box {
  background: red;
}

1

2

3

4

5

6

1

2

3

4

5

Body:
Sounds like a max-width of calc(16.6666666667% - 10px) might do the trick.

.flex-grid {
  background: green;
}

.flex-grid .flex-row {
  display: flex;
}

.flex-grid .flex-1-6-5 {
  flex: 1;
  max-width: calc( 16.6666666667% - 10px);
}

.flex-grid.flex-gutter-5>.flex-row>div:not(:last-of-type) {
  margin-right: 10px;
}

.box {
  background: red;
}

<div class="flex-grid flex-gutter-5 six-columns">
  <div class="flex-row">
    <div class="flex-1-6-5 box">1</div>
    <div class="flex-1-6-5 box">2</div>
    <div class="flex-1-6-5 box">3</div>
    <div class="flex-1-6-5 box">4</div>
    <div class="flex-1-6-5 box">5</div>
    <div class="flex-1-6-5 box">6</div>
  </div>
</div>
<div class="flex-grid flex-gutter-5 five-columns" style="margin-top: 40px">
  <div class="flex-row">
    <div class="flex-1-6-5 box">1</div>
    <div class="flex-1-6-5 box">2</div>
    <div class="flex-1-6-5 box">3</div>
    <div class="flex-1-6-5 box">4</div>
    <div class="flex-1-6-5 box">5</div>
  </div>
</div>


问:
"Only one instance of babel-polyfill is allowed" error
I need help diagnosing and fixing this error:

```<code>"Error: only one instance of babel-polyfill is allowed"
</code>```

I have the following in my package.json:

```<code>"devDependencies": {
    "babel-core": "^6.23.1",
    "babel-jest": "^19.0.0",
    "babel-loader": "^6.3.2",
    "babel-plugin-transform-object-rest-spread": "^6.23.0",
    "babel-preset-es2015": "^6.22.0",
    "babel-preset-react": "^6.23.0" ...

"dependencies": {
    "babel-polyfill": "^6.23.0" ...
</code>```

And this and this entry line in my webpack config:

```<code>entry: ["babel-polyfill", path.resolve(APP_PATH, 'index')],
...
module: {
 rules: [
  {
    test: /\.js$/,
    exclude: /node_modules/,
    loader: 'babel-loader',
    query: {
      // specify that we will be dealing with React code
      presets: ['react', 'es2015']
    }
  }
]}
</code>```

答: If the culprit is HtmlWebpackPlugin, you need to add the option inject: false when instancing the plugin. Certain configurations without this option causes your built javascript code to be loaded twice.

Body:
I need help diagnosing and fixing this error:

"Error: only one instance of babel-polyfill is allowed"

I have the following in my package.json:

"devDependencies": {
    "babel-core": "^6.23.1",
    "babel-jest": "^19.0.0",
    "babel-loader": "^6.3.2",
    "babel-plugin-transform-object-rest-spread": "^6.23.0",
    "babel-preset-es2015": "^6.22.0",
    "babel-preset-react": "^6.23.0" ...

"dependencies": {
    "babel-polyfill": "^6.23.0" ...

And this and this entry line in my webpack config:

entry: ["babel-polyfill", path.resolve(APP_PATH, 'index')],
...
module: {
 rules: [
  {
    test: /\.js$/,
    exclude: /node_modules/,
    loader: 'babel-loader',
    query: {
      // specify that we will be dealing with React code
      presets: ['react', 'es2015']
    }
  }
]}


问:
Add rectangle to Canvas using MVVM
How do i add Rectangle to my View using MVVM?

This is the code for my view.

```<code><Grid>
            <Image  x:Name="img"  Source="{Binding ImagePath, Source={x:Static vm:DrawingVM.instance}, Converter={StaticResource nullImageConverter}}" Stretch="None" >
            </Image>

            <ItemsControl ItemsSource="{Binding ListRectangle, Source={x:Static vm:DrawingVM.instance}}" >

                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <Canvas Background="Transparent"  x:Name="cnvas" Width="{Binding ElementName=img, Path=ActualWidth}"
                        Height="{Binding ElementName=img,Path=ActualHeight}"
                        LayoutTransform="{Binding ElementName=img, Path=LayoutTransform}" >
                            <i:Interaction.Triggers>
                                <i:EventTrigger EventName="MouseDown">
                                    <!--<command:EventToCommand CommandParameter="{Binding ElementName=cnvas}" Command="{Binding MouseDownCommand, Source={x:Static vm:DrawingVM.instance}}" PassEventArgsToCommand="True" />-->
                                    <ei:CallMethodAction MethodName="MouseDownEvente" TargetObject="{Binding Source={x:Static vm:DrawingVM.instance}}" />
                                </i:EventTrigger>

                            </i:Interaction.Triggers>
                        </Canvas>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemContainerStyle>
                    <Style TargetType="ContentPresenter">
                        <Setter Property="Canvas.Left" Value="{Binding X}"/>
                        <Setter Property="Canvas.Top" Value="{Binding Y}"/>
                    </Style>
                </ItemsControl.ItemContainerStyle>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Rectangle Width="{Binding Width}" Height="{Binding Height}" Stroke="Blue"  Fill="Transparent" />
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </Grid>
</code>```

and this is my View Model

```<code>Canvas canvas = new Canvas();
        public void MouseDownEvente(object s, MouseButtonEventArgs e)
        {
            try
            {
                if (s == null) return;
                canvas = s as Canvas;
                if (canvas == null) return;

                startPoint = e.GetPosition(canvas);

                // Remove the drawn rectanglke if any.
                // At a time only one rectangle should be there
                //if (rectSelectArea != null)
                //    canvas.Children.Remove(rectSelectArea);

                // Initialize the rectangle.
                // Set border color and width
                rectSelectArea = new Rectangle
                {
                    Stroke = Brushes.Blue,
                    StrokeThickness = 2,
                    Fill = Brushes.Transparent,
                };

                Canvas.SetLeft(rectSelectArea, startPoint.X);
                Canvas.SetTop(rectSelectArea, startPoint.X);
                canvas.Children.Add(rectSelectArea);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                throw ex;
            }
        }
</code>```

But its throwing an error:

```<code>Cannot explicitly modify Children collection of Panel used as ItemsPanel for ItemsControl. ItemsControl generates child elements for Panel.
</code>```

So how do i solve this?

I tried searching the same problem with mine. And used the solution that worked to them. But the error still persist. Can someone help me. Thank you.

答:
Cannot explicitly modify Children collection of Panel used as ItemsPanel for ItemsControl. ItemsControl generates child elements for Panel.

This means that you cannot use Canvas.Children.Add when you use Canvas as an ItemsPanel for an ItemsControl. You should add items on where the ItemsControl.ItemsSource property is bound to (in your case ListRectangle).

Title: Add rectangle to Canvas using MVVM

Body:
How do i add Rectangle to my View using MVVM?

This is the code for my view.

<Grid>
            <Image  x:Name="img"  Source="{Binding ImagePath, Source={x:Static vm:DrawingVM.instance}, Converter={StaticResource nullImageConverter}}" Stretch="None" >
            </Image>

            <ItemsControl ItemsSource="{Binding ListRectangle, Source={x:Static vm:DrawingVM.instance}}" >

                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <Canvas Background="Transparent"  x:Name="cnvas" Width="{Binding ElementName=img, Path=ActualWidth}"
                        Height="{Binding ElementName=img,Path=ActualHeight}"
                        LayoutTransform="{Binding ElementName=img, Path=LayoutTransform}" >

                                    <ei:CallMethodAction MethodName="MouseDownEvente" TargetObject="{Binding Source={x:Static vm:DrawingVM.instance}}" />

                        </Canvas>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemContainerStyle>

                </ItemsControl.ItemContainerStyle>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Rectangle Width="{Binding Width}" Height="{Binding Height}" Stroke="Blue"  Fill="Transparent" />
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </Grid>

and this is my View Model

Canvas canvas = new Canvas();
        public void MouseDownEvente(object s, MouseButtonEventArgs e)
        {
            try
            {
                if (s == null) return;
                canvas = s as Canvas;
                if (canvas == null) return;

                startPoint = e.GetPosition(canvas);

                // Remove the drawn rectanglke if any.
                // At a time only one rectangle should be there
                //if (rectSelectArea != null)
                //    canvas.Children.Remove(rectSelectArea);

                // Initialize the rectangle.
                // Set border color and width
                rectSelectArea = new Rectangle
                {
                    Stroke = Brushes.Blue,
                    StrokeThickness = 2,
                    Fill = Brushes.Transparent,
                };

                Canvas.SetLeft(rectSelectArea, startPoint.X);
                Canvas.SetTop(rectSelectArea, startPoint.X);
                canvas.Children.Add(rectSelectArea);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                throw ex;
            }
        }

But its throwing an error:

Cannot explicitly modify Children collection of Panel used as ItemsPanel for ItemsControl. ItemsControl generates child elements for Panel.

So how do i solve this?

I tried searching the same problem with mine. And used the solution that worked to them. But the error still persist. Can someone help me. Thank you.


问:
Pygame + Sprite rotation not staying centered
I've been banging my head on this for a couple days now. I'm trying to rotate a sprite on its' center axis and have been referencing this previous post about the same issue:

How do I rotate an image around its center using Pygame?

I'm using the exact same code as described in the previous post and also utilizing a image_clean attribute as to not distort the image on successive rotations. When I try and rotate my sprite the center of the image oscillates back and forth between two points.

```<code>def rotate_center(image, angle):
    """rotate a Surface, maintaining position."""
    loc = image.get_rect().center  #rot_image is not defined
    rot_img = pg.transform.rotate(image, angle)
    print('')
    print('>>> before: ' + str(rot_img.get_rect().center))
    rot_img.get_rect().center = loc
    print('>>> after: ' + str(rot_img.get_rect().center))
    return rot_img
</code>```

print statements verify that the line:

```<code>rot_sprite.get_rect().center = loc
</code>```

Doesn't seem to assign the loc value to the image center. The output is always like this:

```<code>>>> before: (32, 32)
>>> after: (32, 32)

>>> before: (37, 37)
>>> after: (37, 37)

>>> before: (41, 41)
>>> after: (41, 41)

>>> before: (43, 43)
>>> after: (43, 43)

>>> before: (45, 45)
>>> after: (45, 45)

>>> before: (45, 45)
>>> after: (45, 45)

>>> before: (43, 43)
>>> after: (43, 43)

>>> before: (41, 41)
>>> after: (41, 41)

>>> before: (37, 37)
>>> after: (37, 37)
</code>```

I always want the center to be at (32, 32) (I believe). Any help would be greatly appreciated.

Code:

```<code>def main():
    pg.init()

# Screen Setup
size = (SCREEN_WIDTH, SCREEN_HEIGHT)
screen = pg.display.set_mode(size)
screen_flags = screen.get_flags()
pg.display.set_caption(GAME_NAME)
done = False
clock = pg.time.Clock()

# SPRITE GROUPS
all_sprites = pg.sprite.Group()
turrets = pg.sprite.Group()

turret = Tower2((SCREEN_WIDTH/2, SCREEN_HEIGHT/2))
turrets.add(turret)
all_sprites.add(turret)

# -------- Main Program Loop -----------
while not done:
    # Process Incoming Events
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_q:
                done = True
            if event.key == pg.K_f:
                if screen_flags & pg.FULLSCREEN == False:
                    screen_flags |= pg.FULLSCREEN
                    pg.display.set_mode(size, screen_flags)
                else:
                    screen_flags ^= pg.FULLSCREEN
                    pg.display.set_mode(size, screen_flags)

    turret.angle += 10
    turret.image = rotate_center(turret.image_clean, turret.angle)

    screen.fill(WHITE)
    all_sprites.draw(screen)
    pg.display.flip()
    clock.tick(15)

pg.quit()

class Tower2(pg.sprite.Sprite):
    def __init__(self, pos, image, tRange, attackSpeed=1):
        super().__init__()
        self.image = image
        self.image_clean = image
        self.rect = self.image.get_rect()
        self.rect.center = pos
        self.range = tRange
        self.attackSpeed = attackSpeed
        self.lastAttack = time.time()
        self.angle = 0

    def __iter__(self):
        return self

    def canAttack(self):
        if time.time() - self.lastAttack > self.attackSpeed:
            return True
        else:
            return False

    def rotate(self):
        pass

    def update(self):
        self.angle += 10
        self.image = pg.transform.rotate(self.image_clean, self.angle)
        self.image.get_rect().center = self.image_clean.get_rect().center

class Turret1(Tower2):
    def __init__(self, pos):
        TOWER_WIDTH = 64
        TOWER_HEIGHT = 64
        INIT_RANGE = 200
        INIT_RATE = 1
        SPEED = 1
        tower_img = pg.image.load('imgs/test_rotate.png')
        tower_img = pg.transform.scale(tower_img, (TOWER_WIDTH, TOWER_HEIGHT))
        super().__init__(pos, tower_img, INIT_RANGE, SPEED)
</code>```

答:
You have to pass the rect of the sprite as well, because it holds the actual position of the sprite and then pass the center coords to .get_rect or assign them to the new rect's center. If you just call .get_rect(), you get a rect with the topleft coords (0, 0).

```<code>def rotate_center(image, rect, angle):
    """Rotate a Surface, maintaining position."""
    rot_img = pg.transform.rotate(image, angle)
    # Get a new rect and pass the center position of the old
    # rect, so that it rotates around the center.
    rect = rot_img.get_rect(center=rect.center)
    return rot_img, rect  # Return the new rect as well.

# In the main while loop.
turret.angle += 10
# Also pass the turret's rect which holds the position of the sprite.
image, rect = rotate_center(turret.image_clean, turret.rect, turret.angle)
turret.image = image  # Assign the new image.
turret.rect = rect  # Assign the new rect.
</code>```

You could also do this in the update method of the sprite:

```<code>import pygame as pg

WHITE = pg.Color('white')

class Tower2(pg.sprite.Sprite):
    def __init__(self, pos, tRange=1, attackSpeed=1):
        super().__init__()
        self.image = your_image
        self.image_clean = self.image
        self.rect = self.image.get_rect()
        self.rect.center = pos
        self.angle = 0

    def update(self):
        self.angle += 10
        self.image = pg.transform.rotate(self.image_clean, self.angle)
        self.rect = self.image.get_rect(center=self.rect.center)

def main():
    pg.init()

    SCREEN_WIDTH = 640
    SCREEN_HEIGHT = 480
    size = (SCREEN_WIDTH, SCREEN_HEIGHT)
    screen = pg.display.set_mode(size)
    done = False
    clock = pg.time.Clock()

    all_sprites = pg.sprite.Group()

    turret = Tower2((SCREEN_WIDTH/2, SCREEN_HEIGHT/2))
    all_sprites.add(turret)

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True

        all_sprites.update()

        screen.fill(WHITE)
        all_sprites.draw(screen)
        pg.display.flip()
        clock.tick(15)

main()
pg.quit()
</code>```

Body:
I've been banging my head on this for a couple days now. I'm trying to rotate a sprite on its' center axis and have been referencing this previous post about the same issue:

How do I rotate an image around its center using Pygame?

I'm using the exact same code as described in the previous post and also utilizing a image_clean attribute as to not distort the image on successive rotations. When I try and rotate my sprite the center of the image oscillates back and forth between two points.

def rotate_center(image, angle):
    """rotate a Surface, maintaining position."""
    loc = image.get_rect().center  #rot_image is not defined
    rot_img = pg.transform.rotate(image, angle)
    print('')
    print('>>> before: ' + str(rot_img.get_rect().center))
    rot_img.get_rect().center = loc
    print('>>> after: ' + str(rot_img.get_rect().center))
    return rot_img

print statements verify that the line:

rot_sprite.get_rect().center = loc

Doesn't seem to assign the loc value to the image center. The output is always like this:

>>> before: (32, 32)
>>> after: (32, 32)

>>> before: (37, 37)
>>> after: (37, 37)

>>> before: (41, 41)
>>> after: (41, 41)

>>> before: (43, 43)
>>> after: (43, 43)

>>> before: (45, 45)
>>> after: (45, 45)

>>> before: (45, 45)
>>> after: (45, 45)

>>> before: (43, 43)
>>> after: (43, 43)

>>> before: (41, 41)
>>> after: (41, 41)

>>> before: (37, 37)
>>> after: (37, 37)

I always want the center to be at (32, 32) (I believe). Any help would be greatly appreciated.

Code:

def main():
    pg.init()

# Screen Setup
size = (SCREEN_WIDTH, SCREEN_HEIGHT)
screen = pg.display.set_mode(size)
screen_flags = screen.get_flags()
pg.display.set_caption(GAME_NAME)
done = False
clock = pg.time.Clock()

# SPRITE GROUPS
all_sprites = pg.sprite.Group()
turrets = pg.sprite.Group()

turret = Tower2((SCREEN_WIDTH/2, SCREEN_HEIGHT/2))
turrets.add(turret)
all_sprites.add(turret)

# -------- Main Program Loop -----------
while not done:
    # Process Incoming Events
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_q:
                done = True
            if event.key == pg.K_f:
                if screen_flags & pg.FULLSCREEN == False:
                    screen_flags |= pg.FULLSCREEN
                    pg.display.set_mode(size, screen_flags)
                else:
                    screen_flags ^= pg.FULLSCREEN
                    pg.display.set_mode(size, screen_flags)

    turret.angle += 10
    turret.image = rotate_center(turret.image_clean, turret.angle)

    screen.fill(WHITE)
    all_sprites.draw(screen)
    pg.display.flip()
    clock.tick(15)

pg.quit()

class Tower2(pg.sprite.Sprite):
    def __init__(self, pos, image, tRange, attackSpeed=1):
        super().__init__()
        self.image = image
        self.image_clean = image
        self.rect = self.image.get_rect()
        self.rect.center = pos
        self.range = tRange
        self.attackSpeed = attackSpeed
        self.lastAttack = time.time()
        self.angle = 0

    def __iter__(self):
        return self

    def canAttack(self):
        if time.time() - self.lastAttack > self.attackSpeed:
            return True
        else:
            return False

    def rotate(self):
        pass

    def update(self):
        self.angle += 10
        self.image = pg.transform.rotate(self.image_clean, self.angle)
        self.image.get_rect().center = self.image_clean.get_rect().center

class Turret1(Tower2):
    def __init__(self, pos):
        TOWER_WIDTH = 64
        TOWER_HEIGHT = 64
        INIT_RANGE = 200
        INIT_RATE = 1
        SPEED = 1
        tower_img = pg.image.load('imgs/test_rotate.png')
        tower_img = pg.transform.scale(tower_img, (TOWER_WIDTH, TOWER_HEIGHT))
        super().__init__(pos, tower_img, INIT_RANGE, SPEED)

Body:
You have to pass the rect of the sprite as well, because it holds the actual position of the sprite and then pass the center coords to .get_rect or assign them to the new rect's center. If you just call .get_rect(), you get a rect with the topleft coords (0, 0).

def rotate_center(image, rect, angle):
    """Rotate a Surface, maintaining position."""
    rot_img = pg.transform.rotate(image, angle)
    # Get a new rect and pass the center position of the old
    # rect, so that it rotates around the center.
    rect = rot_img.get_rect(center=rect.center)
    return rot_img, rect  # Return the new rect as well.

# In the main while loop.
turret.angle += 10
# Also pass the turret's rect which holds the position of the sprite.
image, rect = rotate_center(turret.image_clean, turret.rect, turret.angle)
turret.image = image  # Assign the new image.
turret.rect = rect  # Assign the new rect.

You could also do this in the update method of the sprite:

import pygame as pg

WHITE = pg.Color('white')

class Tower2(pg.sprite.Sprite):
    def __init__(self, pos, tRange=1, attackSpeed=1):
        super().__init__()
        self.image = your_image
        self.image_clean = self.image
        self.rect = self.image.get_rect()
        self.rect.center = pos
        self.angle = 0

    def update(self):
        self.angle += 10
        self.image = pg.transform.rotate(self.image_clean, self.angle)
        self.rect = self.image.get_rect(center=self.rect.center)

def main():
    pg.init()

    SCREEN_WIDTH = 640
    SCREEN_HEIGHT = 480
    size = (SCREEN_WIDTH, SCREEN_HEIGHT)
    screen = pg.display.set_mode(size)
    done = False
    clock = pg.time.Clock()

    all_sprites = pg.sprite.Group()

    turret = Tower2((SCREEN_WIDTH/2, SCREEN_HEIGHT/2))
    all_sprites.add(turret)

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True

        all_sprites.update()

        screen.fill(WHITE)
        all_sprites.draw(screen)
        pg.display.flip()
        clock.tick(15)

main()
pg.quit()


问:
Mailkit - Get HTML and Text parts without having full mime message
I want to download text and html parts from mime message and store it in the database and later if needed to download attachments. I need this because I don't want to store the attachments in my database to save disk space and bandwidth. They will be downloaded on demand later. I am not sure if I can do that and still be able to use MimeParser from MimeKit

I am planning to do that:

Get message body structure and find the text and html parts

Download text and html body parts using ImapFolder.GetStream and store in database preserving mime tree structure by saving section names along with headers. Attachment will not be downloaded

Later I want to show the message in the UI but I want to delay parsing until the mail message needs to be shown in the UI.

This is my progress so far

```<code>var msgSummaries = remoteFolder.Fetch(new int[] { remoteMessage.Index }, MessageSummaryItems.BodyStructure);

 var stream = remoteFolder.GetStream(remoteMessage.Index, msgSummaries[0].HtmlBody.PartSpecifier);

 //at this point i am saving the stream to the database and later i am trying to convert it to mime entity like that
 var parser = new MimeParser(ParserOptions.Default, stream, true);
 var mimeEntity = parser.ParseEntity(cancellationToken);
</code>```

Unfortunatelly the stream doesn't contain mime part headers and cannot be parsed and I don't see an option to request headers inside GetStream method like this

FETCH 1 (BODY.PEEK[2.MIME] BODY.PEEK[2])

Any suggestions?

答:
Well, first of all, have you tried:

```<code>var mimeEntity = remoteFolder.GetBodyPart (remoteMessage.Index, msgSummaries[0].HtmlBody);
</code>```

or, if you really want to use streams:

```<code>var headerStream = remoteFolder.GetStream (remoteMessage.Index, msgSummaries[0].HtmlBody.PartSpecifier + ".MIME");
var contentStream = remoteFolder.GetStream (remoteMessage.Index, msgSummaries[0].HtmlBody.PartSpecifier);

var stream = new MemoryStream ();
headerStream.CopyTo (stream);
headerStream.Dispose ();
contentStream.CopyTo (stream);
contentStream.Dispose ();
stream.Position = 0;

//at this point i am saving the stream to the database and later i am trying to convert it to mime entity like that
var parser = new MimeParser(ParserOptions.Default, stream, true);
var mimeEntity = parser.ParseEntity(cancellationToken);
</code>```

Body:
I want to download text and html parts from mime message and store it in the database and later if needed to download attachments. I need this because I don't want to store the attachments in my database to save disk space and bandwidth. They will be downloaded on demand later. I am not sure if I can do that and still be able to use MimeParser from MimeKit

I am planning to do that:

Get message body structure and find the text and html parts

Download text and html body parts using ImapFolder.GetStream and store in database preserving mime tree structure by saving section names along with headers. Attachment will not be downloaded

Later I want to show the message in the UI but I want to delay parsing until the mail message needs to be shown in the UI.

This is my progress so far

var msgSummaries = remoteFolder.Fetch(new int[] { remoteMessage.Index }, MessageSummaryItems.BodyStructure);

 var stream = remoteFolder.GetStream(remoteMessage.Index, msgSummaries[0].HtmlBody.PartSpecifier);

 //at this point i am saving the stream to the database and later i am trying to convert it to mime entity like that
 var parser = new MimeParser(ParserOptions.Default, stream, true);
 var mimeEntity = parser.ParseEntity(cancellationToken);

Unfortunatelly the stream doesn't contain mime part headers and cannot be parsed and I don't see an option to request headers inside GetStream method like this

FETCH 1 (BODY.PEEK[2.MIME] BODY.PEEK[2])

Any suggestions?

Body:
Well, first of all, have you tried:

var mimeEntity = remoteFolder.GetBodyPart (remoteMessage.Index, msgSummaries[0].HtmlBody);

or, if you really want to use streams:

var headerStream = remoteFolder.GetStream (remoteMessage.Index, msgSummaries[0].HtmlBody.PartSpecifier + ".MIME");
var contentStream = remoteFolder.GetStream (remoteMessage.Index, msgSummaries[0].HtmlBody.PartSpecifier);

var stream = new MemoryStream ();
headerStream.CopyTo (stream);
headerStream.Dispose ();
contentStream.CopyTo (stream);
contentStream.Dispose ();
stream.Position = 0;

//at this point i am saving the stream to the database and later i am trying to convert it to mime entity like that
var parser = new MimeParser(ParserOptions.Default, stream, true);
var mimeEntity = parser.ParseEntity(cancellationToken);


问:
aurelia-cli production build error
I've created an aurelia plugin (based on the skeleton-plugin) that consists of a custom element with a .js and .html file.
I'm using this in another aurelia client application created using the aurelia cli. It gets installed with npm (from a local nexus repo).
To get the client app to find the plugin, I had to add the following to the aurelia.json file

```<code>{
    "name": "@some-scope/some-plugin",
    "path": "../node_modules/@some-scope/some-plugin/dist/amd",
    "main": "some-plugin"
}
</code>```

This works fine in dev, but the problem occurs when trying to build and run the production version from a server.

To build I run: au build --env prod this completes without error. Next I copy the scripts folder and index.html over to the server root.
When I load the page that uses the plugin I get the following error in the dev tools of the browser

```<code>GET http://127.0.0.1:8080/node_modules/@some-scope/some-plugin/dist/amd/some-plugin.html 404 (Not Found)
</code>```

Its trying to load the plugins html file from the node modules folder. What I would have expected is that the html required would have
been bundled up into the bundled file vendor-bundle.js.

Am I missing something here?

答:
Aurelia cli only traces through the dependencies in your main file some-plugin.js.

This means all html/css files are not traced and bundled. Your additional js files could also be ignored if you did not explicitly import them in your main js file.

To be safe, when loading a plugin, tell cli to bundle all additional files.

```<code>{
    "name": "@some-scope/some-plugin",
    "path": "../node_modules/@some-scope/some-plugin/dist/amd",
    "main": "some-plugin",
    "resources": ["**/*.{js,html,css}"]
}
</code>```

Title: aurelia-cli production build error

Body:
I've created an aurelia plugin (based on the skeleton-plugin) that consists of a custom element with a .js and .html file.
I'm using this in another aurelia client application created using the aurelia cli. It gets installed with npm (from a local nexus repo).
To get the client app to find the plugin, I had to add the following to the aurelia.json file

{
    "name": "@some-scope/some-plugin",
    "path": "../node_modules/@some-scope/some-plugin/dist/amd",
    "main": "some-plugin"
}

This works fine in dev, but the problem occurs when trying to build and run the production version from a server.

To build I run: au build --env prod this completes without error. Next I copy the scripts folder and index.html over to the server root.
When I load the page that uses the plugin I get the following error in the dev tools of the browser

GET http://127.0.0.1:8080/node_modules/@some-scope/some-plugin/dist/amd/some-plugin.html 404 (Not Found)

Its trying to load the plugins html file from the node modules folder. What I would have expected is that the html required would have
been bundled up into the bundled file vendor-bundle.js.

Am I missing something here?

Body:
Aurelia cli only traces through the dependencies in your main file some-plugin.js.

This means all html/css files are not traced and bundled. Your additional js files could also be ignored if you did not explicitly import them in your main js file.

To be safe, when loading a plugin, tell cli to bundle all additional files.

{
    "name": "@some-scope/some-plugin",
    "path": "../node_modules/@some-scope/some-plugin/dist/amd",
    "main": "some-plugin",
    "resources": ["**/*.{js,html,css}"]
}


问:
How to get input value from templates and store to database [Django]
I'm trying to get {{ id }} when user clicks on movie and save it to models. I can't use modelForm because id parameter comes from html template. Any suggestions?

Maybe, there is a different way to get an id of that movie user clicks?

Btw, I'm using tmdb api.

```<code>{% for id, poster in poster_id_zip %}
    <div style="display: inline-block; margin: 10px;" class="">
      <a href="{{ movie_details }}"><img src="{{ poster }}" alt=""></a>
      <form class="add-movie-form" method="POST">
        {% csrf_token %}
        <input type="hidden" name="movie-id" value="{{ id }}">
        <button style="display: block; margin: 5px auto 0 auto;" type="submit" name="add">Add</button>
      </form>
    </div>
{% endfor %}
</code>```

views.py

```<code>def index(request):
    api_key = "api_key"
    image_base_url = "https://image.tmdb.org/t/p/"
    if request.method == "POST":
        user_query = request.POST.get('search-box', ' ')
        if user_query == '':
            user_query = ' '

        search_movies_url = "https://api.themoviedb.org/3/search/movie?api_key={}&query={}".format(api_key, user_query)

        search_results_data = requests.get(search_movies_url)

        total_results = search_results_data.json().get("total_results") # for handling no search results

        movie_ids, poster_path, poster_full_url = [], [], []

        for movie in search_results_data.json().get("results"):
            movie_ids.append(movie.get("id"))
            poster_path.append(movie.get("poster_path"))

        for poster in poster_path:
            poster_full_url.append(image_base_url+"{}{}".format("w185", poster))

        movie_details = "https://api.themoviedb.org/3/movie/{}?api_key={}".format(movie_ids, api_key)

        poster_id_zip = zip(movie_ids, poster_full_url) # grouping ids with poster images

        context = {"movie_ids": movie_ids, "poster_url": poster_full_url, "movie_details": movie_details, "poster_id_zip": poster_id_zip, "total_results": total_results,}

        return render(request, 'homepage/movies.html', context)
    return render(request, 'homepage/index.html')
</code>```

models.py

```<code>from django.db import models

# Create your models here.

class MovieId(models.Model):
    movie_id = models.IntegerField()
    def __str__(self):
        return self.movie_id
</code>```

答:
Maybe introduce some javascript to make an ajax call to another view which adds to the Movie model (I'm making an assumption you are just adding a record). If I were you, I'd change that model to:

```<code>class MovieLinkClick(models.Model):
    movie_id = models.IntegerField()

    def __str__(self):
        return self.movie_id
</code>```

Change the link to:

```<code><a href="{{ movie_details }}" data-movieid={{id}} class="movielink"><img src="{{ poster }}" alt=""></a>
</code>```

then add some javascript in the template to watch for those clicks. If you've got jQuery loaded you can use the data attributes to easily get something like the movieid set in the a tag. (see https://api.jquery.com/data/). You'll likely also need a csrf_token if you are using a post method.

```<code>$(document).ready(function() {
  $('.movielink').on("click", function(e) {
    e.preventDefault();
    var link = $(this).attr("href");
    var id = $(this).data('movieid');
    $.ajax({
           url: "{% url 'movies:log_click' %}",
           type: "POST",
           data: {movie_id: id, csrfmiddlewaretoken: "{{ csrf_token }}" });
    window.location.href = link;  //redirect to the href
  });
});
</code>```

You'd need to create a suitable urls entry to handle the movies:log_click which accepts a post method. See https://docs.djangoproject.com/en/1.11/topics/http/urls/ for a refresher on that.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to get {{ id }} when user clicks on movie and save it to models. I can't use modelForm because id parameter comes from html template. Any suggestions?

Maybe, there is a different way to get an id of that movie user clicks?

Btw, I'm using tmdb api.

{% for id, poster in poster_id_zip %}

      <form class="add-movie-form" method="POST">
        {% csrf_token %}
        <input type="hidden" name="movie-id" value="{{ id }}">
        <button style="display: block; margin: 5px auto 0 auto;" type="submit" name="add">Add</button>
      </form>

{% endfor %}

views.py

def index(request):
    api_key = "api_key"
    image_base_url = "https://image.tmdb.org/t/p/"
    if request.method == "POST":
        user_query = request.POST.get('search-box', ' ')
        if user_query == '':
            user_query = ' '

        search_movies_url = "https://api.themoviedb.org/3/search/movie?api_key={}&query={}".format(api_key, user_query)

        search_results_data = requests.get(search_movies_url)

        total_results = search_results_data.json().get("total_results") # for handling no search results

        movie_ids, poster_path, poster_full_url = [], [], []

        for movie in search_results_data.json().get("results"):
            movie_ids.append(movie.get("id"))
            poster_path.append(movie.get("poster_path"))

        for poster in poster_path:
            poster_full_url.append(image_base_url+"{}{}".format("w185", poster))

        movie_details = "https://api.themoviedb.org/3/movie/{}?api_key={}".format(movie_ids, api_key)

        poster_id_zip = zip(movie_ids, poster_full_url) # grouping ids with poster images

        context = {"movie_ids": movie_ids, "poster_url": poster_full_url, "movie_details": movie_details, "poster_id_zip": poster_id_zip, "total_results": total_results,}

        return render(request, 'homepage/movies.html', context)
    return render(request, 'homepage/index.html')

models.py

from django.db import models

# Create your models here.

class MovieId(models.Model):
    movie_id = models.IntegerField()
    def __str__(self):
        return self.movie_id

Body:
Maybe introduce some javascript to make an ajax call to another view which adds to the Movie model (I'm making an assumption you are just adding a record). If I were you, I'd change that model to:

class MovieLinkClick(models.Model):
    movie_id = models.IntegerField()

    def __str__(self):
        return self.movie_id

Change the link to:

<a href="{{ movie_details }}" data-movieid={{id}} class="movielink"><img src="{{ poster }}" alt=""></a>

then add some javascript in the template to watch for those clicks. If you've got jQuery loaded you can use the data attributes to easily get something like the movieid set in the a tag. (see https://api.jquery.com/data/). You'll likely also need a csrf_token if you are using a post method.

$(document).ready(function() {
  $('.movielink').on("click", function(e) {
    e.preventDefault();
    var link = $(this).attr("href");
    var id = $(this).data('movieid');
    $.ajax({
           url: "{% url 'movies:log_click' %}",
           type: "POST",
           data: {movie_id: id, csrfmiddlewaretoken: "{{ csrf_token }}" });
    window.location.href = link;  //redirect to the href
  });
});

You'd need to create a suitable urls entry to handle the movies:log_click which accepts a post method. See https://docs.djangoproject.com/en/1.11/topics/http/urls/ for a refresher on that.


问:
Xaamrin Forms BoxView Width Too Long when using to Underline
I am using a BoxView to accomplish underlining in my app.  I have a couple of labels that are very short - Text such as Yes or No etc.  Here is the XAML for one of the labels with the BoxView for underlining:

```<code><StackLayout Orientation="Vertical" Grid.Row="5" Grid.Column="1" Margin="0,4,0,4" HorizontalOptions="Start" BackgroundColor="Purple" MinimumWidthRequest="1">
    <Label x:Name="txtUseMetric" TextColor="Blue" FontSize="Small" Text="{Binding UseMetricText}" BackgroundColor="Yellow">
    <Label.GestureRecognizers>
        <TapGestureRecognizer Tapped="Value_Tapped" CommandParameter="usemetric" />
    </Label.GestureRecognizers>
    </Label>
    <BoxView BackgroundColor="Green" HeightRequest="1" MinimumWidthRequest="1" />
</StackLayout>
</code>```

My problem is that the width of the BoxView is always extending past my text  I have tried overriding the MinWidthRequest in my App.Xaml file as seen below:

```<code><Style TargetType="BoxView">
    <Setter Property="MinimumWidthRequest" Value="3" />
</Style>
</code>```

But this has not effect.  I have included  screen shots for you to see.

FYI - The yellow is the width of the Label.  You don't see any purple (the background color of the StackLayout) because the StackLayout and Label are the same width.  The second screen shot shows what the screen looks like if I remove the BoxView - i.e. the Label and StackLayout are sized correctly.

Any suggestions on how to fix this?

Screen shot with BoxView Too Long making label and StackLayout too long

Screen shot with BoxView removed and Label and Stack Layout sizing correctly

答:
One option is to replace the label/box underline with a custom renderer that adds an underline capability to the label.

Here is how to do it:

User Control

```<code>public class CustomLabel : Label
{
    public static readonly BindableProperty IsUnderlinedProperty =
        BindableProperty.Create(nameof(IsUnderlined), typeof(bool), typeof(CustomLabel), false);

    public bool IsUnderlined
    {
        get { return (bool)GetValue(IsUnderlinedProperty); }
        set
        {
            SetValue(IsUnderlinedProperty, value);
        }
    }
}
</code>```

Android renderer

```<code>[assembly: ExportRenderer(typeof(CustomLabel), typeof(CustomLabelRenderer))]
namespace Incident.Droid.CustomRenderers
{
    public class CustomLabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);

            var view = (CustomLabel)Element;
            var control = Control;

            UpdateUi(view, control);
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            var view = (CustomLabel)Element;

            if (e.PropertyName == CustomLabel.IsUnderlinedProperty.PropertyName)
            {
                Control.PaintFlags = view.IsUnderlined ? Control.PaintFlags | PaintFlags.UnderlineText : Control.PaintFlags &= ~PaintFlags.UnderlineText;
            }

        }

        static void UpdateUi(CustomLabel view, TextView control)
        {
            if (view.FontSize > 0)
            {
                control.TextSize = (float)view.FontSize;
            }

            if (view.IsUnderlined)
            {
                control.PaintFlags = control.PaintFlags | PaintFlags.UnderlineText;
            }
        }
    }
}
</code>```

iOS Renderer

```<code>[assembly: ExportRenderer(typeof(CustomLabel), typeof(CustomLabelRenderer))]
namespace Incident.iOS.CustomRenderers
{
    public class CustomLabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);

            var view = (CustomLabel)Element;

            UpdateUi(view, Control);
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            var view = (CustomLabel)Element;

            if (e.PropertyName == CustomLabel.IsUnderlinedProperty.PropertyName)
            {
                UpdateUi(view, Control);
            }
        }

        private static void UpdateUi(CustomLabel view, UILabel control)
        {
            var attrString = new NSMutableAttributedString(control.Text);

            if (view != null && view.IsUnderlined)
            {
                attrString.AddAttribute(UIStringAttributeKey.UnderlineStyle,
                    NSNumber.FromInt32((int)NSUnderlineStyle.Single),
                    new NSRange(0, attrString.Length));
            }

            control.AttributedText = attrString;
        }
    }
}
</code>```

Body:
I am using a BoxView to accomplish underlining in my app.  I have a couple of labels that are very short - Text such as Yes or No etc.  Here is the XAML for one of the labels with the BoxView for underlining:

<StackLayout Orientation="Vertical" Grid.Row="5" Grid.Column="1" Margin="0,4,0,4" HorizontalOptions="Start" BackgroundColor="Purple" MinimumWidthRequest="1">

        <TapGestureRecognizer Tapped="Value_Tapped" CommandParameter="usemetric" />

    <BoxView BackgroundColor="Green" HeightRequest="1" MinimumWidthRequest="1" />
</StackLayout>

My problem is that the width of the BoxView is always extending past my text  I have tried overriding the MinWidthRequest in my App.Xaml file as seen below:

But this has not effect.  I have included  screen shots for you to see.

FYI - The yellow is the width of the Label.  You don't see any purple (the background color of the StackLayout) because the StackLayout and Label are the same width.  The second screen shot shows what the screen looks like if I remove the BoxView - i.e. the Label and StackLayout are sized correctly.

Any suggestions on how to fix this?

Screen shot with BoxView Too Long making label and StackLayout too long

Screen shot with BoxView removed and Label and Stack Layout sizing correctly

Body:
One option is to replace the label/box underline with a custom renderer that adds an underline capability to the label.

Here is how to do it:

User Control

public class CustomLabel : Label
{
    public static readonly BindableProperty IsUnderlinedProperty =
        BindableProperty.Create(nameof(IsUnderlined), typeof(bool), typeof(CustomLabel), false);

    public bool IsUnderlined
    {
        get { return (bool)GetValue(IsUnderlinedProperty); }
        set
        {
            SetValue(IsUnderlinedProperty, value);
        }
    }
}

Android renderer

[assembly: ExportRenderer(typeof(CustomLabel), typeof(CustomLabelRenderer))]
namespace Incident.Droid.CustomRenderers
{
    public class CustomLabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);

            var view = (CustomLabel)Element;
            var control = Control;

            UpdateUi(view, control);
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            var view = (CustomLabel)Element;

            if (e.PropertyName == CustomLabel.IsUnderlinedProperty.PropertyName)
            {
                Control.PaintFlags = view.IsUnderlined ? Control.PaintFlags | PaintFlags.UnderlineText : Control.PaintFlags &= ~PaintFlags.UnderlineText;
            }

        }

        static void UpdateUi(CustomLabel view, TextView control)
        {
            if (view.FontSize > 0)
            {
                control.TextSize = (float)view.FontSize;
            }

            if (view.IsUnderlined)
            {
                control.PaintFlags = control.PaintFlags | PaintFlags.UnderlineText;
            }
        }
    }
}

iOS Renderer

[assembly: ExportRenderer(typeof(CustomLabel), typeof(CustomLabelRenderer))]
namespace Incident.iOS.CustomRenderers
{
    public class CustomLabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);

            var view = (CustomLabel)Element;

            UpdateUi(view, Control);
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            var view = (CustomLabel)Element;

            if (e.PropertyName == CustomLabel.IsUnderlinedProperty.PropertyName)
            {
                UpdateUi(view, Control);
            }
        }

        private static void UpdateUi(CustomLabel view, UILabel control)
        {
            var attrString = new NSMutableAttributedString(control.Text);

            if (view != null && view.IsUnderlined)
            {
                attrString.AddAttribute(UIStringAttributeKey.UnderlineStyle,
                    NSNumber.FromInt32((int)NSUnderlineStyle.Single),
                    new NSRange(0, attrString.Length));
            }

            control.AttributedText = attrString;
        }
    }
}