问:
.net transient database context being disposed prematurely
I am moving an asp.net mvc5 application using EF6 to asp.net core MVC 3.0 using EF Core.

In my mvc5 application I have some administrative operation that modify the database and take a long time, so I use a pattern when I create a new DBContext that is not the one that is associated with the request context and then run the task in the background using Task.Run.  This has been working fine for years.

In converting to .net core it was unclear how to create a new DBContext in the way that I was doing it in my old codebase.  It seems like I should be able to create a Transient DBContext in these cases and all should be fine.

So I created a subclass of MyDbContext called MyTransientDbContex and in my Configure class I  added this service:

```<code>            services.AddDbContext<MyTransientDbContex>(options =>
                options.UseSqlServer(
                    context.Configuration.GetConnectionString("MyContextConnection")),
                ServiceLifetime.Transient, ServiceLifetime.Transient);
</code>```

In my controller I inject the context in the action that needs the transient service and spawn a thread to do something with it:

```<code>public ActionResult Update([FromServices] MyTransientContext context) {

    Task.Run(() =>
    {
        try {
            // Do some long running operation with context
        }
        Catch (Exception e) {
            // Report Exception
        }
        finally {
            context.Dispose();
        }
    }

    return RedirectToAction("Status");
}
</code>```

I would not expect my transient context to be disposed until the finally block.  But I am getting this exception when attempting to access the context on the background thread:

```<code>Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'MyTransientContext'.'
</code>```

And indeed the _disposed flag is set to true on the context object.

I put a breakpoint on the constructer for MyTransientContext and "Made an Object ID" of the this pointer so that I could track the object.  This transient object is being created and is the same one that is inject into my controller action.  It's also the same object that I'm trying to reference when the exception is thrown.

I tried setting a data breakpoint on the _disposed member in order to get a callstack on when disposed is being set to true, but the breakpoint won't bind.

I also tried overriding the Dispose method on MyTransientContext, and it isn't called until my explicit dispose in the finally block, which is after the exception is thrown and caught.

I feel like I'm missing something fundamental here.  Isn't this what the transient services are for?  What would dispose a Transient service?

One last detail - MyTransientContext is derived from MyContext, which is in turn derived from IdentityDbContext (Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityDbContex)

Edit: The reason that I went down the path of using a Transient was because of this ef core document page: https://learn.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext.  It states that "...any code that explicitly executes multiple threads in parallel should ensure that DbContext instances aren't ever accessed concurrently.  Using dependency injection,  this can be achieved by either registering the context as scoped and creating scopes (using IServiceScopeFactory) for each thread, or by registering the DbContext as transient (using the overload of AddDbContext which takes a ServiceLifetime parameter)."

As xabikos pointed out, this seems to be overriden by the scoping of the asp.net DI system, where it looks like anything created by that system is scoped to the request context, including Transient objects.  Can someone point out where that's documented so that I can better understand how to work with the limitations?

答:
You mixed the concepts of transient objects that are created by internal DI container asp.net core provides.

You configure the MyTransientContext to be transient in the internal DI system. This practically means that every time a scope is created then a new instance is returned. For asp.net application this scope matches an HTTP request. When the requests ends then all the objects are disposed if applicable.

Now in your code, that is a synchronous action method you spawn a Task with Task.Run. This is an async operation and you don't await for this. Practically during execution this will be started but not wait to finish, the redirect will happen and the request will end. At this point if you try to use the injected instance you will get the exception.

If you would like to solve this you need change to an async action and await on the Task.Run. And most likely you don't need to spawn a new Task. But you need to understand that this is not probably the best way as it will need for the long operation to finish before the redirect takes place.

An alternative to this would be to use a messaging mechanism, and send a message that triggers this operation. And you have another component, like worker service that listens for those messages and process them.

Body:
I am moving an asp.net mvc5 application using EF6 to asp.net core MVC 3.0 using EF Core.

In my mvc5 application I have some administrative operation that modify the database and take a long time, so I use a pattern when I create a new DBContext that is not the one that is associated with the request context and then run the task in the background using Task.Run.  This has been working fine for years.

In converting to .net core it was unclear how to create a new DBContext in the way that I was doing it in my old codebase.  It seems like I should be able to create a Transient DBContext in these cases and all should be fine.

So I created a subclass of MyDbContext called MyTransientDbContex and in my Configure class I  added this service:

            services.AddDbContext<MyTransientDbContex>(options =>
                options.UseSqlServer(
                    context.Configuration.GetConnectionString("MyContextConnection")),
                ServiceLifetime.Transient, ServiceLifetime.Transient);

In my controller I inject the context in the action that needs the transient service and spawn a thread to do something with it:

public ActionResult Update([FromServices] MyTransientContext context) {

    Task.Run(() =>
    {
        try {
            // Do some long running operation with context
        }
        Catch (Exception e) {
            // Report Exception
        }
        finally {
            context.Dispose();
        }
    }

    return RedirectToAction("Status");
}

I would not expect my transient context to be disposed until the finally block.  But I am getting this exception when attempting to access the context on the background thread:

Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'MyTransientContext'.'

And indeed the _disposed flag is set to true on the context object.

I put a breakpoint on the constructer for MyTransientContext and "Made an Object ID" of the this pointer so that I could track the object.  This transient object is being created and is the same one that is inject into my controller action.  It's also the same object that I'm trying to reference when the exception is thrown.

I tried setting a data breakpoint on the _disposed member in order to get a callstack on when disposed is being set to true, but the breakpoint won't bind.

I also tried overriding the Dispose method on MyTransientContext, and it isn't called until my explicit dispose in the finally block, which is after the exception is thrown and caught.

I feel like I'm missing something fundamental here.  Isn't this what the transient services are for?  What would dispose a Transient service?

One last detail - MyTransientContext is derived from MyContext, which is in turn derived from IdentityDbContext (Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityDbContex)

Edit: The reason that I went down the path of using a Transient was because of this ef core document page: https://learn.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext.  It states that "...any code that explicitly executes multiple threads in parallel should ensure that DbContext instances aren't ever accessed concurrently.  Using dependency injection,  this can be achieved by either registering the context as scoped and creating scopes (using IServiceScopeFactory) for each thread, or by registering the DbContext as transient (using the overload of AddDbContext which takes a ServiceLifetime parameter)."

As xabikos pointed out, this seems to be overriden by the scoping of the asp.net DI system, where it looks like anything created by that system is scoped to the request context, including Transient objects.  Can someone point out where that's documented so that I can better understand how to work with the limitations?


来源: stackexchange

问:
From where value of intent is coming on which I am calling getAction() function? (This is overridden method of BroadcastReceiver class)
I have created a broadcast receiver class Which is working fine. I am confused about from where the value of intent comes in onReceive method.

```<code> @Override
    public void onReceive(Context context, Intent intent) {

       String action = intent.getAction();

       if(wifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action))
       {
           int state=intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE,-1);

           if(state==WifiP2pManager.WIFI_P2P_STATE_ENABLED){
               Toast.makeText(context,"Wifi is ON",Toast.LENGTH_SHORT).show();
           }
           else
           {
               Toast.makeText(context,"Wifi is OFF",Toast.LENGTH_SHORT).show();
           }
        }
}
</code>```

Main Activity code where I have made an Intent Filter, where I have added an action.

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

        wifiP2pManager =  (WifiP2pManager)

getSystemService(Context.WIFI_P2P_SERVICE);
    channel = wifiP2pManager.initialize(this,getMainLooper(),null);

        broadcastReceiver = new WiFiDirectBroadcastReceiver(wifiP2pManager, channel, this);

      intentFilter =  new IntentFilter();
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);

        }
</code>```

答:
If your BroadcastReceiver works, then you must have initialized wifiP2pManager and called a function on the object. When tbe state changes an intent is being broadcasted. With the receiver you subscribe to those intents.

You can read in more detail about the WifiP2pManager in the Android documentation Wi-Fi Direct (peer-to-peer or P2P) overview

ContentLicense: CC BY-SA 4.0

Body:
I have created a broadcast receiver class Which is working fine. I am confused about from where the value of intent comes in onReceive method.

 @Override
    public void onReceive(Context context, Intent intent) {

       String action = intent.getAction();

       if(wifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action))
       {
           int state=intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE,-1);

           if(state==WifiP2pManager.WIFI_P2P_STATE_ENABLED){
               Toast.makeText(context,"Wifi is ON",Toast.LENGTH_SHORT).show();
           }
           else
           {
               Toast.makeText(context,"Wifi is OFF",Toast.LENGTH_SHORT).show();
           }
        }
}

Main Activity code where I have made an Intent Filter, where I have added an action.

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

        wifiP2pManager =  (WifiP2pManager)

getSystemService(Context.WIFI_P2P_SERVICE);
    channel = wifiP2pManager.initialize(this,getMainLooper(),null);

        broadcastReceiver = new WiFiDirectBroadcastReceiver(wifiP2pManager, channel, this);

      intentFilter =  new IntentFilter();
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);

        }


问:
How to test validation annotations of a class using JUnit?
I need to test the validation annotations but it looks like they do not work. I am not sure if the JUnit is also correct. Currently, the test will be passed but as you can see the specified email address is wrong.

JUnit

```<code>public static void testContactSuccess() {
        Contact contact = new Contact();
        contact.setEmail("Jackyahoo.com");
        contact.setName("Jack");
        System.err.println(contact);
    }
</code>```

Class to be tested

```<code>public class Contact {

    @NotNull
    @Size(min = 1, max = 10)
    String name;

    @NotNull
    @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\."
            +"[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@"
            +"(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?",
                 message="{invalid.email}")
    String email;

    @Digits(fraction = 0, integer = 10)
    @Size(min = 10, max = 10)
    String phone;

    getters and setters

}
</code>```

答:
A simple way to test validation annotations using javax:

Declare the Validator at Class level:

```<code>private final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
</code>```

Then in your test simply call it on the object you require validation on, with what exception you are validating:

```<code>Set<TheViolation<TheClassYouAreValidating> violations = validator.validate(theInstanceOfTheClassYouAreValidating);
</code>```

Then simply assert the number of expected violations:

```<code>assertThat(violations.size()).isEqualTo(1);
</code>```

You will need to add this to your dependencies (gradle):

compile group: 'javax.validation', name: 'validation-api', version: '2.0.1.Final'

ContentLicense: CC BY-SA 3.0

Body:
I need to test the validation annotations but it looks like they do not work. I am not sure if the JUnit is also correct. Currently, the test will be passed but as you can see the specified email address is wrong.

JUnit

public static void testContactSuccess() {
        Contact contact = new Contact();
        contact.setEmail("Jackyahoo.com");
        contact.setName("Jack");
        System.err.println(contact);
    }

Class to be tested

public class Contact {

    @NotNull
    @Size(min = 1, max = 10)
    String name;

    @NotNull
    @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\."
            +"[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@"
            +"(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?",
                 message="{invalid.email}")
    String email;

    @Digits(fraction = 0, integer = 10)
    @Size(min = 10, max = 10)
    String phone;

    getters and setters

}

Body:
A simple way to test validation annotations using javax:

Declare the Validator at Class level:

private final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

Then in your test simply call it on the object you require validation on, with what exception you are validating:

Set<TheViolation<TheClassYouAreValidating> violations = validator.validate(theInstanceOfTheClassYouAreValidating);

Then simply assert the number of expected violations:

assertThat(violations.size()).isEqualTo(1);

You will need to add this to your dependencies (gradle):

compile group: 'javax.validation', name: 'validation-api', version: '2.0.1.Final'


问:
Select Statement inside a procedure in Oracle
sorry for asking this question but it's because none of the answers given before are enough for me to understand. I want to write a stored procedure that returns all the columns in a table.As an ad hod query I just write

```<code>SELECT * FROM EMPLOYEES
</code>```

but here, I get an error which prompts me to provide INTO clause which I don't understand why and how.Could someone explain how would I do that both in the above case and when I want to return just one column values(multiple rows).

答:
People with a SQL Server background are used to writing stored procedures that return whole query results and so try to write PL/SQL procedures something like this:

```<code>procedure get_emps is
begin
    -- this will NOT work!
    select * from emp;
end;
</code>```

Unfortunately it's not that simple.  Probably the nearest equivalent in PL/SQL is a function returning a ref cursor:

```<code>function get_emps return sys_refcursor is
    rc sys_refcursor;
begin
    open rc for
        select * from emp;
    return rc;
end;
</code>```

You could call this from a calling program like this:

```<code>declare
    cur sys_refcursor;
    emp_rec emp%rowtype;
begin
    cur := get_emps;
    loop
        fetch cur into emp_rec;
        exit when cur%notfound;
    end loop;
    close cur;
end;
</code>```

or in SQL Plus you could do:

```<code>var rc refcursor
:rc := get_emps;
print rc
</code>```

Body:
sorry for asking this question but it's because none of the answers given before are enough for me to understand. I want to write a stored procedure that returns all the columns in a table.As an ad hod query I just write

SELECT * FROM EMPLOYEES

but here, I get an error which prompts me to provide INTO clause which I don't understand why and how.Could someone explain how would I do that both in the above case and when I want to return just one column values(multiple rows).

Body:
People with a SQL Server background are used to writing stored procedures that return whole query results and so try to write PL/SQL procedures something like this:

procedure get_emps is
begin
    -- this will NOT work!
    select * from emp;
end;

Unfortunately it's not that simple.  Probably the nearest equivalent in PL/SQL is a function returning a ref cursor:

function get_emps return sys_refcursor is
    rc sys_refcursor;
begin
    open rc for
        select * from emp;
    return rc;
end;

You could call this from a calling program like this:

declare
    cur sys_refcursor;
    emp_rec emp%rowtype;
begin
    cur := get_emps;
    loop
        fetch cur into emp_rec;
        exit when cur%notfound;
    end loop;
    close cur;
end;

or in SQL Plus you could do:

var rc refcursor
:rc := get_emps;
print rc


问:
Kafka Mysql CDC to Elastic search
I was trying to outsource my MySql db changes to kafka topic via source-connector and that works. Now I want to send those data to elastic search instance.

To do that, I was following this Kafka Connect Elasticsearch: Consuming and Indexing with Kafka Connect and this one Kafka Connect and Elasticsearch.

For CDC of mysql to kafka, I can see the changes I made in mysql and read it creating a source-connector, but when I create another connector elasticsearch-sink connector, source-connectr task.state shown Failed! And hence database changes are not going into ES though index is created there as setup in es-config.properties file.

I have put the jar/s inside kafka-dir where for source-connector's lib worked(to avoid further problem regarding classpath problem).

When creating elaticsearch-sink-connector I get this error(though for soure, I have no error, and all libs are in same directory!):

ERROR Plugin class loader for connector:
  'io.confluent.connect.elasticsearch.ElasticsearchSinkConnector' was
  not found. Returning:
  org.apache.kafka.connect.runtime.isolation.DelegatingClassLoader@5cc126dc
  (org.apache.kafka.connect.runtime.isolation.DelegatingClassLoader:165)

I am running my connector by this:

```<code>bin/connect-standalone.sh config/connect-standalone.properties config/elasticsearch-connect.properties
</code>```

In brief, only one of my connectors task.state remains RUNNING at a time

Edit:
plugin.path for connect-standablone.properties file:

```<code>plugin.path=/media/***/projects/playground/kafka/kafka_2.12-2.4.0, /media/***/projects/playground/kafka/kafka-connect-elasticsearch/target/kafka-connect-elasticsearch-3.2.0-SNAPSHOT-package/share/java
</code>```

both of them contains the  es-connector jar.Last one added later as but still same

What should I do now?

答:
The thing work like charm when I just change schema.enable to false

```<code>key.converter.schemas.enable=false
value.converter.schemas.enable=false
</code>```

and added extra / after the plugin.path  though without / it worked for source-connector!

Edit: I forgot to mention that I have replaced my connector version with 5.4.0 release too as cricket_007 mentioned

Edit-2:
I later investigated more and found that, extra / issue along with the new key properties mentioned below helped me to get rid of FAILED state of connectors(only one connector was RUNNING at a time):

```<code>internal.key.converter=org.apache.kafka.connect.json.JsonConverter
internal.value.converter=org.apache.kafka.connect.json.JsonConverter
internal.key.converter.schemas.enable=false
internal.value.converter.schemas.enable=false
</code>```

in connect-standalone.properties file

Thanks

Title: Kafka Mysql CDC to Elastic search

Body:
I was trying to outsource my MySql db changes to kafka topic via source-connector and that works. Now I want to send those data to elastic search instance.

To do that, I was following this Kafka Connect Elasticsearch: Consuming and Indexing with Kafka Connect and this one Kafka Connect and Elasticsearch.

For CDC of mysql to kafka, I can see the changes I made in mysql and read it creating a source-connector, but when I create another connector elasticsearch-sink connector, source-connectr task.state shown Failed! And hence database changes are not going into ES though index is created there as setup in es-config.properties file.

I have put the jar/s inside kafka-dir where for source-connector's lib worked(to avoid further problem regarding classpath problem).

When creating elaticsearch-sink-connector I get this error(though for soure, I have no error, and all libs are in same directory!):

ERROR Plugin class loader for connector:
  'io.confluent.connect.elasticsearch.ElasticsearchSinkConnector' was
  not found. Returning:
  org.apache.kafka.connect.runtime.isolation.DelegatingClassLoader@5cc126dc
  (org.apache.kafka.connect.runtime.isolation.DelegatingClassLoader:165)

I am running my connector by this:

bin/connect-standalone.sh config/connect-standalone.properties config/elasticsearch-connect.properties

In brief, only one of my connectors task.state remains RUNNING at a time

Edit:
plugin.path for connect-standablone.properties file:

plugin.path=/media/***/projects/playground/kafka/kafka_2.12-2.4.0, /media/***/projects/playground/kafka/kafka-connect-elasticsearch/target/kafka-connect-elasticsearch-3.2.0-SNAPSHOT-package/share/java

both of them contains the  es-connector jar.Last one added later as but still same

What should I do now?

Body:
The thing work like charm when I just change schema.enable to false

key.converter.schemas.enable=false
value.converter.schemas.enable=false

and added extra / after the plugin.path  though without / it worked for source-connector!

Edit: I forgot to mention that I have replaced my connector version with 5.4.0 release too as cricket_007 mentioned

Edit-2:
I later investigated more and found that, extra / issue along with the new key properties mentioned below helped me to get rid of FAILED state of connectors(only one connector was RUNNING at a time):

internal.key.converter=org.apache.kafka.connect.json.JsonConverter
internal.value.converter=org.apache.kafka.connect.json.JsonConverter
internal.key.converter.schemas.enable=false
internal.value.converter.schemas.enable=false

in connect-standalone.properties file

Thanks


问:
/bin/sh: jlink: not found. command '/bin/sh -c jlink' returned a non-zero code: 127
the dockerfile used -

```<code>FROM azul/zulu-openjdk-alpine:11 as jdk

RUN jlink \
    --module-path /usr/lib/jvm/*/jmods/ \
    --verbose \
    --add-modules java.base,jdk.unsupported,java.sql,java.desktop \
    --compress 2 \
    --no-header-files \
    --no-man-pages \
    --output /opt/jdk-11-minimal

FROM alpine:3.10
ENV JAVA_HOME=/opt/jdk-11-minimal
ENV PATH=$PATH:/opt/jdk-11-minimal/bin
COPY --from=jdk /opt/jdk-11-minimal /opt/jdk-11-minimal
</code>```

why jlink can't be found in azul/zulu-openjdk-alpine:11?

答:
The simple answer is jlink is not on the PATH so can't be found.

If you change the RUN line to

```<code>RUN /usr/lib/jvm/zulu11/bin/jlink
</code>```

then it can be found.

However, you still have an error using the wildcard in the module path.  Change this to

```<code>--module-path /usr/lib/jvm/zulu11/jmods/
</code>```

and the docker command will complete successfully.

Body:
the dockerfile used -

FROM azul/zulu-openjdk-alpine:11 as jdk

RUN jlink \
    --module-path /usr/lib/jvm/*/jmods/ \
    --verbose \
    --add-modules java.base,jdk.unsupported,java.sql,java.desktop \
    --compress 2 \
    --no-header-files \
    --no-man-pages \
    --output /opt/jdk-11-minimal

FROM alpine:3.10
ENV JAVA_HOME=/opt/jdk-11-minimal
ENV PATH=$PATH:/opt/jdk-11-minimal/bin
COPY --from=jdk /opt/jdk-11-minimal /opt/jdk-11-minimal

why jlink can't be found in azul/zulu-openjdk-alpine:11?

Body:
The simple answer is jlink is not on the PATH so can't be found.

If you change the RUN line to

RUN /usr/lib/jvm/zulu11/bin/jlink

then it can be found.

However, you still have an error using the wildcard in the module path.  Change this to

--module-path /usr/lib/jvm/zulu11/jmods/

and the docker command will complete successfully.


问:
Yii2 Forms Automatically Submit on completion of a single field
I have an issue where, when I complete one field on a form and move to another field, either by using the Tab key or the mouse, the form automatically submits and goes to the page specified in actionCreate or actionEdit (as appropriate). If I reopen the form, that single data element was saved, and I can enter one more data element only to have the form automatically resubmit again as soon as I move to another field.

Some background information:

This behavior occurs with Google Chrome v.56.x and Firefox v.52.x. It does not occur with Microsoft Edge. (In Edge, the forms work as they should. Unfortunately, I really need the much more robust development tools in Chrome and Firefox.)

I am using a localhost with an XAMPP stack (Apache 2.4.23 (Win32), PHP 5.6.28, Yii 2.0.11.2)

This issue occurs on all forms (many) generated by gii.

This behavior occurs whether I use the standard Yii ActiveForm or the Kartik-V ActiveForm.

Apache logs show no errors whatsoever. Yii runtime/logs/app.log also shows no errors.

This behavior has been going on for a very long time; I've just been working around it. Now, it's reached the point where I really need to do something about it. I've tried Googling to see if anyone had identified the issue and haven't been able find any potential resolutions online.

I'm kind of at a loss as to where to go next on this thing. Given that the forms are very standard and do work in Edge, I'm kind of thinking that this may be more a Chrme/Firefox/localhost issue than a Yii issue, but I can't find anything on the behavior.

I'd greatly appreciate any thoughts, ideas, and especially resolutions that anyone might have to offer.

An example controller (one of many associated with this behavior:

```<code><?php
// This class was automatically generated by a giiant build task
// You should not change it manually as it will be overwritten on next build

    namespace backend\controllers\base;

    use common\models\PaletteColors;
    use common\models\search\PaletteColorsSearch;
    use yii\web\Controller;
    use yii\web\HttpException;
    use yii\helpers\Url;
    use yii\filters\AccessControl;
    use dmstr\bootstrap\Tabs;

    /**
     * PaletteColorsController implements the CRUD actions for PaletteColors model.
     */
    class PaletteColorsController extends Controller
    {

        /**
         * @var boolean whether to enable CSRF validation for the actions in this controller.
         * CSRF validation is enabled only when both this property and [[Request::enableCsrfValidation]] are true.
         */
        public $enableCsrfValidation = false;

        /**
         * Lists all PaletteColors models.
         *
         * @return mixed
         */
        public function actionIndex()
        {
            $searchModel  = new PaletteColorsSearch;
            $dataProvider = $searchModel->search($_GET);

            Tabs::clearLocalStorage();

            Url::remember();
            \Yii::$app->session['__crudReturnUrl'] = null;

            return $this->render('index', [
                'dataProvider' => $dataProvider,
                'searchModel'  => $searchModel,
            ]);
        }

        /**
         * Displays a single PaletteColors model.
         *
         * @param integer $id
         *
         * @return mixed
         */
        public function actionView($id)
        {
            \Yii::$app->session['__crudReturnUrl'] = Url::previous();
            Url::remember();
            Tabs::rememberActiveState();

            return $this->render('view', [
                'model' => $this->findModel($id),
            ]);
        }

        /**
         * Creates a new PaletteColors model.
         * If creation is successful, the browser will be redirected to the 'view' page.
         *
         * @return mixed
         */
        public function actionCreate()
        {
            $model = new PaletteColors;

            try {
                if ($model->load($_POST) && $model->save()) {
                    return $this->redirect(['view', 'id' => $model->id]);
                } elseif (!\Yii::$app->request->isPost) {
                    $model->load($_GET);
                }
            } catch (\Exception $e) {
                $msg = (isset($e->errorInfo[2])) ? $e->errorInfo[2] : $e->getMessage();
                $model->addError('_exception', $msg);
            }

            return $this->render('create', ['model' => $model]);
        }

        /**
         * Updates an existing PaletteColors model.
         * If update is successful, the browser will be redirected to the 'view' page.
         *
         * @param integer $id
         *
         * @return mixed
         */
        public function actionUpdate($id)
        {
            $model = $this->findModel($id);

            if ($model->load($_POST) && $model->save()) {
                return $this->redirect(Url::previous());
            } else {
                return $this->render('update', [
                    'model' => $model,
                ]);
            }
        }

        /**
         * Deletes an existing PaletteColors model.
         * If deletion is successful, the browser will be redirected to the 'index' page.
         *
         * @param integer $id
         *
         * @return mixed
         */
        public function actionDelete($id)
        {
            try {
                $this->findModel($id)->delete();
            } catch (\Exception $e) {
                $msg = (isset($e->errorInfo[2])) ? $e->errorInfo[2] : $e->getMessage();
                \Yii::$app->getSession()->addFlash('error', $msg);

                return $this->redirect(Url::previous());
            }

// TODO: improve detection
            $isPivot = strstr('$id', ',');
            if ($isPivot == true) {
                return $this->redirect(Url::previous());
            } elseif (isset(\Yii::$app->session['__crudReturnUrl']) && \Yii::$app->session['__crudReturnUrl'] != '/') {
                Url::remember(null);
                $url                                   = \Yii::$app->session['__crudReturnUrl'];
                \Yii::$app->session['__crudReturnUrl'] = null;

                return $this->redirect($url);
            } else {
                return $this->redirect(['index']);
            }
        }

        /**
         * Finds the PaletteColors model based on its primary key value.
         * If the model is not found, a 404 HTTP exception will be thrown.
         *
         * @param integer $id
         *
         * @return PaletteColors the loaded model
         * @throws HttpException if the model cannot be found
         */
        protected function findModel($id)
        {
            if (($model = PaletteColors::findOne($id)) !== null) {
                return $model;
            } else {
                throw new HttpException(404, 'The requested page does not exist.');
            }
        }
    }
</code>```

The _form.php file associated with this controller:

```<code><?php

    use kartik\helpers\Html;
    use kartik\icons\Icon;
    use kartik\tabs\TabsX;
    use kartik\widgets\ActiveForm;

    // Initialize framework as per <code>icon-framework</code> param in Yii config
    Icon::map($this);

    // Initialize a specific framework - e.g. Web Hosting Hub Glyphs
    Icon::map($this, Icon::FA);

    /**
     * @var yii\web\View                $this
     * @var common\models\PaletteColors $model
     * @var yii\widgets\ActiveForm      $form
     */

?>

<div class="palette-colors-form">

    <?php $form = ActiveForm::begin([
                                        'id'                   => 'PaletteColors',
                                        'type'                 => ActiveForm::TYPE_VERTICAL,
                                        // 'enctype' => 'multipart/form-data',
                                        'enableAjaxValidation' => true,
                                        'fieldConfig'          => [
                                            'autoPlaceholder' => false,
                                            'showErrors'      => true,
                                        ],
                                    ]
    );
    ?>

    <div class="">
        <?php $this->beginBlock('main'); ?>

        <p>

            <!-- attribute palette_id -->
            <?= // generated by schmunk42\giiant\generators\crud\providers\core\RelationProvider::activeField
                $form->field($model, 'palette_id')->dropDownList(
                    \yii\helpers\ArrayHelper::map(common\models\Palettes::find()->all(), 'id', 'name'),
                    [
                        'prompt'   => 'Select',
                        'disabled' => (isset($relAttributes) && isset($relAttributes['palette_id'])),
                    ]
                ); ?>

            <!-- attribute palette_color_group_id -->
            <?= // generated by schmunk42\giiant\generators\crud\providers\core\RelationProvider::activeField
                $form->field($model, 'palette_color_group_id')->dropDownList(
                    \yii\helpers\ArrayHelper::map(common\models\PaletteColorGroups::find()->all(), 'id', 'name'),
                    [
                        'prompt'   => 'Select',
                        'disabled' => (isset($relAttributes) && isset($relAttributes['palette_color_group_id'])),
                    ]
                ); ?>

            <!-- attribute rgba_red -->
            <?= $form->field($model, 'rgba_red')->textInput() ?>

            <!-- attribute rgba_green -->
            <?= $form->field($model, 'rgba_green')->textInput() ?>

            <!-- attribute rgba_blue -->
            <?= $form->field($model, 'rgba_blue')->textInput() ?>

            <!-- attribute hsla_hue -->
            <?= $form->field($model, 'hsla_hue')->textInput() ?>

            <!-- attribute hsla_saturation -->
            <?= $form->field($model, 'hsla_saturation')->textInput() ?>

            <!-- attribute hsla_luminosity -->
            <?= $form->field($model, 'hsla_luminosity')->textInput() ?>

            <!-- attribute name_common -->
            <?= $form->field($model, 'name_common')->textInput(['maxlength' => true]) ?>

            <!-- attribute rgba_alpha -->
            <?= $form->field($model, 'rgba_alpha')->textInput() ?>

            <!-- attribute hsla_alpha -->
            <?= $form->field($model, 'hsla_alpha')->textInput() ?>

            <!-- attribute cmyk_cyan -->
            <?= $form->field($model, 'cmyk_cyan')->textInput() ?>

            <!-- attribute cmyk_magenta -->
            <?= $form->field($model, 'cmyk_magenta')->textInput() ?>

            <!-- attribute cmyk_yellow -->
            <?= $form->field($model, 'cmyk_yellow')->textInput() ?>

            <!-- attribute cmyk_key -->
            <?= $form->field($model, 'cmyk_key')->textInput() ?>

            <!-- attribute radial_gradient -->
            <?= $form->field($model, 'radial_gradient')->textarea(['rows' => 6]) ?>

            <!-- attribute description -->
            <?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>

            <!-- attribute comments -->
            <?= $form->field($model, 'comments')->textarea(['rows' => 6]) ?>

            <!-- attribute twb_variable -->
            <?= $form->field($model, 'twb_variable')->textInput(['maxlength' => true]) ?>

            <!-- attribute name_variant -->
            <?= $form->field($model, 'name_variant')->textInput(['maxlength' => true]) ?>

            <!-- attribute hex -->
            <?= $form->field($model, 'hex')->textInput(['maxlength' => true]) ?>

            <!-- attribute hex_web_safe -->
            <?= $form->field($model, 'hex_web_safe')->textInput(['maxlength' => true]) ?>

            <!-- attribute hex_inverted -->
            <?= $form->field($model, 'hex_inverted')->textInput(['maxlength' => true]) ?>

            <!-- attribute hex_complement -->
            <?= $form->field($model, 'hex_complement')->textInput(['maxlength' => true]) ?>
        </p>
        <?php $this->endBlock(); ?>

        <?=
            TabsX::widget(
                [
                    'encodeLabels' => false,
                    'items'        => [
                        [
                            'label'   => '<i class="fa fa-home"></i> Palette Colors',
                            'content' => $this->blocks['main'],
                            'active'  => true,
                        ],
                    ],
                    'position'     => TabsX::POS_ABOVE,
                    'encodeLabels' => false
                ]
            );
        ?>
        <hr/>

        <?php echo $form->errorSummary($model); ?>

        <div class="row">
            <div class="col-md-12 text-right">
                <?= Html::submitButton(
                    '<span class="glyphicon glyphicon-check"></span> ' .
                    ($model->isNewRecord ? 'Create' : 'Save'),
                    [
                        'id'    => 'save-' . $model->formName(),
                        'class' => 'btn btn-success'
                    ]
                );
                ?>
            </div>
        </div>

        <?php ActiveForm::end(); ?>

    </div>

</div>
</code>```

答:
For some reason it did the same for me in activeForm, what seemed to help albeit I don't know exactly why, was chaging:

```<code><?php $form = ActiveForm::begin([
    'enableClientValidation' => false,
    'enableAjaxValidation' => true,
]) ?>
</code>```

to

```<code><?php $form = ActiveForm::begin([
//    'enableClientValidation' => false,
//    'enableAjaxValidation' => true,
]) ?>
</code>```

Body:
I have an issue where, when I complete one field on a form and move to another field, either by using the Tab key or the mouse, the form automatically submits and goes to the page specified in actionCreate or actionEdit (as appropriate). If I reopen the form, that single data element was saved, and I can enter one more data element only to have the form automatically resubmit again as soon as I move to another field.

Some background information:

This behavior occurs with Google Chrome v.56.x and Firefox v.52.x. It does not occur with Microsoft Edge. (In Edge, the forms work as they should. Unfortunately, I really need the much more robust development tools in Chrome and Firefox.)

I am using a localhost with an XAMPP stack (Apache 2.4.23 (Win32), PHP 5.6.28, Yii 2.0.11.2)

This issue occurs on all forms (many) generated by gii.

This behavior occurs whether I use the standard Yii ActiveForm or the Kartik-V ActiveForm.

Apache logs show no errors whatsoever. Yii runtime/logs/app.log also shows no errors.

This behavior has been going on for a very long time; I've just been working around it. Now, it's reached the point where I really need to do something about it. I've tried Googling to see if anyone had identified the issue and haven't been able find any potential resolutions online.

I'm kind of at a loss as to where to go next on this thing. Given that the forms are very standard and do work in Edge, I'm kind of thinking that this may be more a Chrme/Firefox/localhost issue than a Yii issue, but I can't find anything on the behavior.

I'd greatly appreciate any thoughts, ideas, and especially resolutions that anyone might have to offer.

An example controller (one of many associated with this behavior:

<?php
// This class was automatically generated by a giiant build task
// You should not change it manually as it will be overwritten on next build

    namespace backend\controllers\base;

    use common\models\PaletteColors;
    use common\models\search\PaletteColorsSearch;
    use yii\web\Controller;
    use yii\web\HttpException;
    use yii\helpers\Url;
    use yii\filters\AccessControl;
    use dmstr\bootstrap\Tabs;

    /**
     * PaletteColorsController implements the CRUD actions for PaletteColors model.
     */
    class PaletteColorsController extends Controller
    {

        /**
         * @var boolean whether to enable CSRF validation for the actions in this controller.
         * CSRF validation is enabled only when both this property and [[Request::enableCsrfValidation]] are true.
         */
        public $enableCsrfValidation = false;

        /**
         * Lists all PaletteColors models.
         *
         * @return mixed
         */
        public function actionIndex()
        {
            $searchModel  = new PaletteColorsSearch;
            $dataProvider = $searchModel->search($_GET);

            Tabs::clearLocalStorage();

            Url::remember();
            \Yii::$app->session['__crudReturnUrl'] = null;

            return $this->render('index', [
                'dataProvider' => $dataProvider,
                'searchModel'  => $searchModel,
            ]);
        }

        /**
         * Displays a single PaletteColors model.
         *
         * @param integer $id
         *
         * @return mixed
         */
        public function actionView($id)
        {
            \Yii::$app->session['__crudReturnUrl'] = Url::previous();
            Url::remember();
            Tabs::rememberActiveState();

            return $this->render('view', [
                'model' => $this->findModel($id),
            ]);
        }

        /**
         * Creates a new PaletteColors model.
         * If creation is successful, the browser will be redirected to the 'view' page.
         *
         * @return mixed
         */
        public function actionCreate()
        {
            $model = new PaletteColors;

            try {
                if ($model->load($_POST) && $model->save()) {
                    return $this->redirect(['view', 'id' => $model->id]);
                } elseif (!\Yii::$app->request->isPost) {
                    $model->load($_GET);
                }
            } catch (\Exception $e) {
                $msg = (isset($e->errorInfo[2])) ? $e->errorInfo[2] : $e->getMessage();
                $model->addError('_exception', $msg);
            }

            return $this->render('create', ['model' => $model]);
        }

        /**
         * Updates an existing PaletteColors model.
         * If update is successful, the browser will be redirected to the 'view' page.
         *
         * @param integer $id
         *
         * @return mixed
         */
        public function actionUpdate($id)
        {
            $model = $this->findModel($id);

            if ($model->load($_POST) && $model->save()) {
                return $this->redirect(Url::previous());
            } else {
                return $this->render('update', [
                    'model' => $model,
                ]);
            }
        }

        /**
         * Deletes an existing PaletteColors model.
         * If deletion is successful, the browser will be redirected to the 'index' page.
         *
         * @param integer $id
         *
         * @return mixed
         */
        public function actionDelete($id)
        {
            try {
                $this->findModel($id)->delete();
            } catch (\Exception $e) {
                $msg = (isset($e->errorInfo[2])) ? $e->errorInfo[2] : $e->getMessage();
                \Yii::$app->getSession()->addFlash('error', $msg);

                return $this->redirect(Url::previous());
            }

// TODO: improve detection
            $isPivot = strstr('$id', ',');
            if ($isPivot == true) {
                return $this->redirect(Url::previous());
            } elseif (isset(\Yii::$app->session['__crudReturnUrl']) && \Yii::$app->session['__crudReturnUrl'] != '/') {
                Url::remember(null);
                $url                                   = \Yii::$app->session['__crudReturnUrl'];
                \Yii::$app->session['__crudReturnUrl'] = null;

                return $this->redirect($url);
            } else {
                return $this->redirect(['index']);
            }
        }

        /**
         * Finds the PaletteColors model based on its primary key value.
         * If the model is not found, a 404 HTTP exception will be thrown.
         *
         * @param integer $id
         *
         * @return PaletteColors the loaded model
         * @throws HttpException if the model cannot be found
         */
        protected function findModel($id)
        {
            if (($model = PaletteColors::findOne($id)) !== null) {
                return $model;
            } else {
                throw new HttpException(404, 'The requested page does not exist.');
            }
        }
    }

The _form.php file associated with this controller:

<?php

    use kartik\helpers\Html;
    use kartik\icons\Icon;
    use kartik\tabs\TabsX;
    use kartik\widgets\ActiveForm;

    // Initialize framework as per icon-framework param in Yii config
    Icon::map($this);

    // Initialize a specific framework - e.g. Web Hosting Hub Glyphs
    Icon::map($this, Icon::FA);

    /**
     * @var yii\web\View                $this
     * @var common\models\PaletteColors $model
     * @var yii\widgets\ActiveForm      $form
     */

?>

    <?php $form = ActiveForm::begin([
                                        'id'                   => 'PaletteColors',
                                        'type'                 => ActiveForm::TYPE_VERTICAL,
                                        // 'enctype' => 'multipart/form-data',
                                        'enableAjaxValidation' => true,
                                        'fieldConfig'          => [
                                            'autoPlaceholder' => false,
                                            'showErrors'      => true,
                                        ],
                                    ]
    );
    ?>

        <?php $this->beginBlock('main'); ?>

            <?= // generated by schmunk42\giiant\generators\crud\providers\core\RelationProvider::activeField
                $form->field($model, 'palette_id')->dropDownList(
                    \yii\helpers\ArrayHelper::map(common\models\Palettes::find()->all(), 'id', 'name'),
                    [
                        'prompt'   => 'Select',
                        'disabled' => (isset($relAttributes) && isset($relAttributes['palette_id'])),
                    ]
                ); ?>

            <?= // generated by schmunk42\giiant\generators\crud\providers\core\RelationProvider::activeField
                $form->field($model, 'palette_color_group_id')->dropDownList(
                    \yii\helpers\ArrayHelper::map(common\models\PaletteColorGroups::find()->all(), 'id', 'name'),
                    [
                        'prompt'   => 'Select',
                        'disabled' => (isset($relAttributes) && isset($relAttributes['palette_color_group_id'])),
                    ]
                ); ?>

            <?= $form->field($model, 'rgba_red')->textInput() ?>

            <?= $form->field($model, 'rgba_green')->textInput() ?>

            <?= $form->field($model, 'rgba_blue')->textInput() ?>

            <?= $form->field($model, 'hsla_hue')->textInput() ?>

            <?= $form->field($model, 'hsla_saturation')->textInput() ?>

            <?= $form->field($model, 'hsla_luminosity')->textInput() ?>

            <?= $form->field($model, 'name_common')->textInput(['maxlength' => true]) ?>

            <?= $form->field($model, 'rgba_alpha')->textInput() ?>

            <?= $form->field($model, 'hsla_alpha')->textInput() ?>

            <?= $form->field($model, 'cmyk_cyan')->textInput() ?>

            <?= $form->field($model, 'cmyk_magenta')->textInput() ?>

            <?= $form->field($model, 'cmyk_yellow')->textInput() ?>

            <?= $form->field($model, 'cmyk_key')->textInput() ?>

            <?= $form->field($model, 'radial_gradient')->textarea(['rows' => 6]) ?>

            <?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>

            <?= $form->field($model, 'comments')->textarea(['rows' => 6]) ?>

            <?= $form->field($model, 'twb_variable')->textInput(['maxlength' => true]) ?>

            <?= $form->field($model, 'name_variant')->textInput(['maxlength' => true]) ?>

            <?= $form->field($model, 'hex')->textInput(['maxlength' => true]) ?>

            <?= $form->field($model, 'hex_web_safe')->textInput(['maxlength' => true]) ?>

            <?= $form->field($model, 'hex_inverted')->textInput(['maxlength' => true]) ?>

            <?= $form->field($model, 'hex_complement')->textInput(['maxlength' => true]) ?>

        <?php $this->endBlock(); ?>

        <?=
            TabsX::widget(
                [
                    'encodeLabels' => false,
                    'items'        => [
                        [
                            'label'   => ' Palette Colors',
                            'content' => $this->blocks['main'],
                            'active'  => true,
                        ],
                    ],
                    'position'     => TabsX::POS_ABOVE,
                    'encodeLabels' => false
                ]
            );
        ?>

        <?php echo $form->errorSummary($model); ?>

                <?= Html::submitButton(
                    ' ' .
                    ($model->isNewRecord ? 'Create' : 'Save'),
                    [
                        'id'    => 'save-' . $model->formName(),
                        'class' => 'btn btn-success'
                    ]
                );
                ?>

        <?php ActiveForm::end(); ?>

Body:
For some reason it did the same for me in activeForm, what seemed to help albeit I don't know exactly why, was chaging:

<?php $form = ActiveForm::begin([
    'enableClientValidation' => false,
    'enableAjaxValidation' => true,
]) ?>

to

<?php $form = ActiveForm::begin([
//    'enableClientValidation' => false,
//    'enableAjaxValidation' => true,
]) ?>


问:
SwiftUI - How do I change the text color of a Textfield?
I'm trying to change the textcolor of Textfield (the text that user write) in SwiftUI. I'm trying with foregroundColor but it changes the placeholder's text color.

How do you do this in SwiftUI?

```<code> TextField($variable, placeholder: Text("a text"))
            .foregroundColor(.green)
</code>```

答:
Text color should be changed for using the Property of text field .foreground color
Updated for Xcode Version 11.1 (11A1027)

SwiftUI

```<code>TextField("Email", text: $email)
                .textContentType(.emailAddress)
                .padding(.init(top: 0, leading: 15, bottom:0 , trailing: 15))
                .foregroundColor(.blue)
                .textFieldStyle(RoundedBorderTextFieldStyle.init())
</code>```

Body:
I'm trying to change the textcolor of Textfield (the text that user write) in SwiftUI. I'm trying with foregroundColor but it changes the placeholder's text color.

How do you do this in SwiftUI?

 TextField($variable, placeholder: Text("a text"))
            .foregroundColor(.green)

Body:
Text color should be changed for using the Property of text field .foreground color
Updated for Xcode Version 11.1 (11A1027)

SwiftUI

TextField("Email", text: $email)
                .textContentType(.emailAddress)
                .padding(.init(top: 0, leading: 15, bottom:0 , trailing: 15))
                .foregroundColor(.blue)
                .textFieldStyle(RoundedBorderTextFieldStyle.init())


问:
How to get charges(transactions) details in Stripe based on date range
I wanted to get a list of charges(Transactions) based on date range I specify, ie all transactions between my specified Start date and End date.

But in CHARGES API, I can not see any Start date nor End Date arguments.

How can I get this?

答:
To get particular date data  code is like

```<code>$mydata= \Stripe\Charge::all(array('limit'=>50,'starting_after'=>null ,"created" => array("gt" => strtotime("2020-02-17"),"lt" => strtotime("2020-02-19"))));

print_r($mydata);
</code>```

It will give you data of 2020-02-18 with limit 50, If you want more record add last charge id in starting_after parameter

Body:
To get particular date data  code is like

$mydata= \Stripe\Charge::all(array('limit'=>50,'starting_after'=>null ,"created" => array("gt" => strtotime("2020-02-17"),"lt" => strtotime("2020-02-19"))));

print_r($mydata);

It will give you data of 2020-02-18 with limit 50, If you want more record add last charge id in starting_after parameter


问:
Swift UI: Disable a button if a text field is empty
How I can disable button if a text field is empty for Swift UI. My code:

```<code>struct AddTask: View {
  @Binding var isOpen: Bool
  @State var text = ""
  let tint: Color
  let done: (String) -> ()

  var body: some View {
    VStack() {
      HStack {
        Text("What tasks are you planning to do?")
          .font(.custom("Avenir", size: 14))
          .foregroundColor(.gray)
        Spacer()
      }

        CustomTextField(text: $text, isFirstResponder: true)
        .frame(height: 30)

      HStack {
        Spacer()
        Button(action: { self.done(self.text); self.isOpen.toggle() }) { Text("Done") }
          .foregroundColor(self.tint)
      }
      Spacer()
    }
    .padding(.all, 30)
  }
}
</code>```

I want to disable button if CustomTextField is empty.

答:
Use .disabled modifier like in following

```<code>    Button(action: { self.done(self.text); self.isOpen.toggle() }) { Text("Done") }
      .foregroundColor(self.tint)
      .disabled(self.text.isEmpty)
</code>```

Body:
How I can disable button if a text field is empty for Swift UI. My code:

struct AddTask: View {
  @Binding var isOpen: Bool
  @State var text = ""
  let tint: Color
  let done: (String) -> ()

  var body: some View {
    VStack() {
      HStack {
        Text("What tasks are you planning to do?")
          .font(.custom("Avenir", size: 14))
          .foregroundColor(.gray)
        Spacer()
      }

        CustomTextField(text: $text, isFirstResponder: true)
        .frame(height: 30)

      HStack {
        Spacer()
        Button(action: { self.done(self.text); self.isOpen.toggle() }) { Text("Done") }
          .foregroundColor(self.tint)
      }
      Spacer()
    }
    .padding(.all, 30)
  }
}

I want to disable button if CustomTextField is empty.

Body:
Use .disabled modifier like in following

    Button(action: { self.done(self.text); self.isOpen.toggle() }) { Text("Done") }
      .foregroundColor(self.tint)
      .disabled(self.text.isEmpty)


问:
How to prevent CSS from displaying the ::after content on a new line?
I'm trying to display a list of names, separated by a comma, using CSS:

a:after {
  content: ', \00a0';
  display: inline-block;
  text-decoration: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Foo
Bar</code>```

The problem is that the result looks something like this:

```<code>Foo, Baz
, Bar
</code>```

答:
Add these properties to the a selector:</p>

```<code>display: block;
float: left;
</code>```

Body:
I'm trying to display a list of names, separated by a comma, using CSS:

a:after {
  content: ', \00a0';
  display: inline-block;
  text-decoration: none;
}

Foo
Bar

The problem is that the result looks something like this:

Foo, Baz
, Bar

Body:
Add these properties to the a selector:

display: block;
float: left;


问:
How to add images side-by-side responsively in Markdown Mdxjs in a Gatsby site?
I want to put images side-by-side responsively using Markdown Mdxjs (for a Gatsby site).

Tables did not work for me, because:

it's necessary to add titles to columns (I just want to display images, no text).

it's not responsive for mobile (if images are too large, they should display in the next row)

image size cannot be adapted

答:
You can pass an object of custom react components to your MDXProvider, then use them in the MDX file.

```<code>import image1 from "./7.jpg"
import image2 from "./6.jpg"
import image3 from "./3.jpg"

## Big ol pupper blep

<cols num="3">
  <image-card src={image1} title="Shooberino waggy">
    Pupperino dat tungg tho floofs big ol doggorino thicc pupperino
  </image-card>
  <image-card src={image2} title="Biscit corgo">
    Maximum borkdrive floofs very jealous pupper
  </image-card>
  <image-card src={image3} title="Long bois shoob">
    What a nice floof
  </image-card>
</cols>
</code>```

Body:
You can pass an object of custom react components to your MDXProvider, then use them in the MDX file.

import image1 from "./7.jpg"
import image2 from "./6.jpg"
import image3 from "./3.jpg"

## Big ol pupper blep

<cols num="3">
  <image-card src={image1} title="Shooberino waggy">
    Pupperino dat tungg tho floofs big ol doggorino thicc pupperino
  </image-card>
  <image-card src={image2} title="Biscit corgo">
    Maximum borkdrive floofs very jealous pupper
  </image-card>
  <image-card src={image3} title="Long bois shoob">
    What a nice floof
  </image-card>
</cols>


问:
DBGrid get selected cell
I need to get the value of the selected cell of a DBGrid in Delphi.

I have no idea how to do it. I tried dbGrid's OnMouseMove

```<code>pt : TGridCoord;
...
pt:=dbGrid.MouseCoord(x, y);
</code>```

[Edited]
I can use the OnCellClick to get the value of the cell with "Column.Field.AsString", but I want to get the value from the first column when I click on any column of that row.

答:
```<code>procedure TForm1.DBGrid_DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumnEh;  State: TGridDrawState);
const defaultCheckBoxFieldNumber = 1;
begin
  if DBGrid.SelectedField.FieldNo = defaultCheckBoxFieldNumber then
    ....;
  else
    ...;
end;
</code>```

DBGrid.SelectedField.FieldNo gets selected field on event DrawColumnCell in TDBGrid.

Title: DBGrid get selected cell

Body:
I need to get the value of the selected cell of a DBGrid in Delphi.

I have no idea how to do it. I tried dbGrid's OnMouseMove

pt : TGridCoord;
...
pt:=dbGrid.MouseCoord(x, y);

[Edited]
I can use the OnCellClick to get the value of the cell with "Column.Field.AsString", but I want to get the value from the first column when I click on any column of that row.

Body:
procedure TForm1.DBGrid_DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumnEh;  State: TGridDrawState);
const defaultCheckBoxFieldNumber = 1;
begin
  if DBGrid.SelectedField.FieldNo = defaultCheckBoxFieldNumber then
    ....;
  else
    ...;
end;

DBGrid.SelectedField.FieldNo gets selected field on event DrawColumnCell in TDBGrid.


问:
Windriver compiler linker file regex
is there a way to use regex to add all C object files starting with foo for example to the linker file bss section with Windriver compiler instead of adding them manually one by one

```<code>SECTIONS {
      outputa 0x10000 :
        {
        foo1.o (.bss)
        foo2.o (.bss)
        ......
        foon.o (.bss)
        }
</code>```

Imagined solution

```<code>SECTIONS {
          outputa 0x10000 :
            {
            foo*.o (.bss)
</code>```

答:
Yes, it is possible to use regex in linker script.
    GROUP : {
        .sectionname:{"foo*"(.bss) }
....
}</p>

Title: Windriver compiler linker file regex

Body:
is there a way to use regex to add all C object files starting with foo for example to the linker file bss section with Windriver compiler instead of adding them manually one by one

SECTIONS {
      outputa 0x10000 :
        {
        foo1.o (.bss)
        foo2.o (.bss)
        ......
        foon.o (.bss)
        }

Imagined solution

SECTIONS {
          outputa 0x10000 :
            {
            foo*.o (.bss)


问:
How to disable button in nav component
I have a nav component where you can navigate back en for. But on a certain condition I want to disable the navigation buttons. So I try it like this:

```<code>
<app-echeq-progress-nav
      *ngIf="!submitting"
      [currentPage]="currentEcheqPageIdx + 1"
      [totalPages]="currentEcheqPath.length"
      (next)="next()"
      (previous)="prev()"
      [disabled]="status === EcheqSubmissionStatus.EXPIRED"
      [conditionals]="{
        isFirst: currentEcheqPager.isFirst,
        sending: sending
      }"

    ></app-echeq-progress-nav>

</code>```

and this is the component:

```<code>export class EcheqProgressNavComponent implements OnInit {
  @Input() currentPage: number;
  @Input() totalPages: number;
  @Input() conditionals: { isFirst?: boolean; sending?: boolean };

  @Output() previous = new EventEmitter<void>();
  @Output() next = new EventEmitter<void>();

  constructor() {}

  ngOnInit() {}
}
</code>```

But I get an error like this:

```<code>
Can't bind to 'disabled' since it isn't a known property of 'app-echeq-progress-nav'.

</code>```

So what I have to fix?

Thank you

Oke, I try it like this:

```<code><div class="echeq-progress-nav">
  <button
    type="button"
    class="echeq-progress-button echeq-progress-button-back"
    (click)="previous.emit()"
    [ngClass]="{ disabled: conditionals && (conditionals.isFirst || conditionals.sending) }"
    [disabled]="status === EcheqSubmissionStatus.EXPIRED"

  >
    <span class="fa fa-caret-left"></span>
  </button>
  <div class="echeq-progress-pages">Vraag {{ currentPage }} / {{ totalPages }}</div>
  <button
    type="button"
    class="echeq-progress-button echeq-progress-button-forward"
    (click)="next.emit()"
    [ngClass]="{ disabled: conditionals && conditionals.sending }"
    [disabled]="status === EcheqSubmissionStatus.EXPIRED"
  >
    <span class="fa fa-caret-right"></span>
  </button>
</div>
</code>```

I have it like this:

```<code>  <app-echeq-progress-nav
      *ngIf="!submitting"
      [currentPage]="currentEcheqPageIdx + 1"
      [totalPages]="currentEcheqPath.length"
      (next)="next()"
      (previous)="prev()"

      [isbtnDisabled]="currentEcheqSubmission.status === EcheqSubmissionStatus.EXPIRED"

      [conditionals]="{
        isFirst: currentEcheqPager.isFirst,
        sending: sending
      }"

    ></app-echeq-progress-nav>
</code>```

but here :

```<code> <app-echeq-progress-nav
      *ngIf="!submitting"
      [currentPage]="currentEcheqPageIdx + 1"
      [totalPages]="currentEcheqPath.length"
      (next)="next()"
      (previous)="prev()"

      [isbtnDisabled]="currentEcheqSubmission.status === EcheqSubmissionStatus.EXPIRED"

      [conditionals]="{
        isFirst: currentEcheqPager.isFirst,
        sending: sending
      }"

    ></app-echeq-progress-nav>
</code>```

I dont have directly access with status

答:
You should add in ...component.ts

```<code>@Input() buttonIsDisabled: boolean
</code>```

and bind this input to the relative button in the component template:

```<code><button [disabled]="buttonIsDisabled">Some button in the template</button>
</code>```

Title: How to disable button in nav component

Body:
I have a nav component where you can navigate back en for. But on a certain condition I want to disable the navigation buttons. So I try it like this:

<app-echeq-progress-nav
      *ngIf="!submitting"
      [currentPage]="currentEcheqPageIdx + 1"
      [totalPages]="currentEcheqPath.length"
      (next)="next()"
      (previous)="prev()"
      [disabled]="status === EcheqSubmissionStatus.EXPIRED"
      [conditionals]="{
        isFirst: currentEcheqPager.isFirst,
        sending: sending
      }"

    ></app-echeq-progress-nav>

and this is the component:

export class EcheqProgressNavComponent implements OnInit {
  @Input() currentPage: number;
  @Input() totalPages: number;
  @Input() conditionals: { isFirst?: boolean; sending?: boolean };

  @Output() previous = new EventEmitter<void>();
  @Output() next = new EventEmitter<void>();

  constructor() {}

  ngOnInit() {}
}

But I get an error like this:

Can't bind to 'disabled' since it isn't a known property of 'app-echeq-progress-nav'.

So what I have to fix?

Thank you

Oke, I try it like this:

  <button
    type="button"
    class="echeq-progress-button echeq-progress-button-back"
    (click)="previous.emit()"
    [ngClass]="{ disabled: conditionals && (conditionals.isFirst || conditionals.sending) }"
    [disabled]="status === EcheqSubmissionStatus.EXPIRED"

  >

  </button>

Vraag {{ currentPage }} / {{ totalPages }}

  <button
    type="button"
    class="echeq-progress-button echeq-progress-button-forward"
    (click)="next.emit()"
    [ngClass]="{ disabled: conditionals && conditionals.sending }"
    [disabled]="status === EcheqSubmissionStatus.EXPIRED"
  >

  </button>

I have it like this:

  <app-echeq-progress-nav
      *ngIf="!submitting"
      [currentPage]="currentEcheqPageIdx + 1"
      [totalPages]="currentEcheqPath.length"
      (next)="next()"
      (previous)="prev()"

      [isbtnDisabled]="currentEcheqSubmission.status === EcheqSubmissionStatus.EXPIRED"

      [conditionals]="{
        isFirst: currentEcheqPager.isFirst,
        sending: sending
      }"

    ></app-echeq-progress-nav>

but here :

 <app-echeq-progress-nav
      *ngIf="!submitting"
      [currentPage]="currentEcheqPageIdx + 1"
      [totalPages]="currentEcheqPath.length"
      (next)="next()"
      (previous)="prev()"

      [isbtnDisabled]="currentEcheqSubmission.status === EcheqSubmissionStatus.EXPIRED"

      [conditionals]="{
        isFirst: currentEcheqPager.isFirst,
        sending: sending
      }"

    ></app-echeq-progress-nav>

I dont have directly access with status

Body:
You should add in ...component.ts

@Input() buttonIsDisabled: boolean

and bind this input to the relative button in the component template:

<button [disabled]="buttonIsDisabled">Some button in the template</button>


问:
Excel file not being downloaded when function is called via ajax method
Situation

I am working on an application where I can have a grid with X items, and each item has a print button. Clicking this print button allows me to call an ajax function which passes the ID of the grid item to a controller. I retrieve the relevant data based on that ID and then download it in an excel file. (The retrieving of the specific item is not yet done)

What I have so far

So far, I have the basic code that downloads an excel file, along with my grid .

Problem

The problem I am facing is, if I click the "Print" button...nothing happens, even with a breakpoint in my exporttoexcel  functions shows me that the function is entered and I can step thru it and despite no errors, nothing occurs. However, I added  random button that called the same function and when i clicked that button, the excel file was downloaded. As a result, I believe the issue has something to do with aJax.

Code

<input type="button" value="Test" onclick="location.href='@Url.Action("ExportToExcel", "Profile")'" />
```

<p>This is the code which downloads the file. It was a simple button I added.</p>

<pre class="lang-js prettyprint-override"><code>function ExportToExcel(id) {
    $.ajax({
        type: "POST",
        url: "@Url.Action("ExportToExcel", "Profile")",
        data: { "id": id },
        dataType: "json"

    });
}
</code>```

This is the function that I want to work, but it does not work and I cannot see what i've got wrong.

Export to Excel Code

public void ExportToExcelx()
{
    var products = new System.Data.DataTable("teste");
    products.Columns.Add("col1", typeof(int));
    products.Columns.Add("col2", typeof(string));

    products.Rows.Add(1, "product 1");
    products.Rows.Add(2, "product 2");
    products.Rows.Add(3, "product 3");
    products.Rows.Add(4, "product 4");
    products.Rows.Add(5, "product 5");
    products.Rows.Add(6, "product 6");
    products.Rows.Add(7, "product 7");

    var grid = new GridView();
    grid.DataSource = products;
    grid.DataBind();

    Response.ClearContent();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
    Response.ContentType = "application/ms-excel";

    Response.Charset = "";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);

    grid.RenderControl(htw);

    //Response.Output.Write(sw.ToString());
    //Response.Flush();
    //Response.End();
    // =============

    //Open a memory stream that you can use to write back to the response
    byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
    MemoryStream s = new MemoryStream(byteArray);
    StreamReader sr = new StreamReader(s, Encoding.ASCII);

    //Write the stream back to the response
    Response.Write(sr.ReadToEnd());
    Response.End();

    //  return View("MyView");
}
```

Theory

I believe the error is somehow tied in to aJax, I am also creating the button in the controller like this.
"<button type='button' class='btn btn-warning' onclick='ExportToExcel(" + c.id + ");'>Print</button>",

Since location.href='@Url.Action works, I was wondering if attempting to redo my dynamic button would solve my issue.

Appreciate any insight that could be offered.

答:
ANSWER:

You need to include success in your ajax call.

```<code>    function ExportToExcel(id) {
        $.ajax({
            type: "POST",
            url: "@Url.Action("ExportToExcel", "Profile")",
            data: { "id": id },
            dataType: "json"
            success: function () {
                 window.location = '@Url.Action("ExportExcel", "Profile")?id='+id;
            }
        });
    }
</code>```

For Duplicate headers received from the server

Duplicate headers received from server

Body:
Situation

I am working on an application where I can have a grid with X items, and each item has a print button. Clicking this print button allows me to call an ajax function which passes the ID of the grid item to a controller. I retrieve the relevant data based on that ID and then download it in an excel file. (The retrieving of the specific item is not yet done)

What I have so far

So far, I have the basic code that downloads an excel file, along with my grid .

Problem

The problem I am facing is, if I click the "Print" button...nothing happens, even with a breakpoint in my exporttoexcel  functions shows me that the function is entered and I can step thru it and despite no errors, nothing occurs. However, I added  random button that called the same function and when i clicked that button, the excel file was downloaded. As a result, I believe the issue has something to do with aJax.

Code

<input type="button" value="Test" onclick="location.href='@Url.Action("ExportToExcel", "Profile")'" />

This is the code which downloads the file. It was a simple button I added.

function ExportToExcel(id) {
    $.ajax({
        type: "POST",
        url: "@Url.Action("ExportToExcel", "Profile")",
        data: { "id": id },
        dataType: "json"

    });
}

This is the function that I want to work, but it does not work and I cannot see what i've got wrong.

Export to Excel Code

public void ExportToExcelx()
{
    var products = new System.Data.DataTable("teste");
    products.Columns.Add("col1", typeof(int));
    products.Columns.Add("col2", typeof(string));

    products.Rows.Add(1, "product 1");
    products.Rows.Add(2, "product 2");
    products.Rows.Add(3, "product 3");
    products.Rows.Add(4, "product 4");
    products.Rows.Add(5, "product 5");
    products.Rows.Add(6, "product 6");
    products.Rows.Add(7, "product 7");

    var grid = new GridView();
    grid.DataSource = products;
    grid.DataBind();

    Response.ClearContent();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
    Response.ContentType = "application/ms-excel";

    Response.Charset = "";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);

    grid.RenderControl(htw);

    //Response.Output.Write(sw.ToString());
    //Response.Flush();
    //Response.End();
    // =============

    //Open a memory stream that you can use to write back to the response
    byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
    MemoryStream s = new MemoryStream(byteArray);
    StreamReader sr = new StreamReader(s, Encoding.ASCII);

    //Write the stream back to the response
    Response.Write(sr.ReadToEnd());
    Response.End();

    //  return View("MyView");
}

Theory

I believe the error is somehow tied in to aJax, I am also creating the button in the controller like this.
"<button type='button' class='btn btn-warning' onclick='ExportToExcel(" + c.id + ");'>Print</button>",

Since location.href='@Url.Action works, I was wondering if attempting to redo my dynamic button would solve my issue.

Appreciate any insight that could be offered.

Body:
ANSWER:

You need to include success in your ajax call.

    function ExportToExcel(id) {
        $.ajax({
            type: "POST",
            url: "@Url.Action("ExportToExcel", "Profile")",
            data: { "id": id },
            dataType: "json"
            success: function () {
                 window.location = '@Url.Action("ExportExcel", "Profile")?id='+id;
            }
        });
    }

For Duplicate headers received from the server

Duplicate headers received from server


问:
Python count column values by other column
I have the table such that:

```<code>no  Order   materials   status
1   1000    100         available
2   1000    200         not available
3   1001    500         Feb-20
4   1002    400         available
5   1002    300         not available
6   1002    600         available
7   1002    900         available
8   1003    700         available
9   1003    800         available
</code>```

And I'd like to have columns that shows:

Total number of materials per Order

Total number of materials with their status per Order

I was able to get the total number of materials per Order:

```<code>ds.groupby('Order').count()
ds['Total Materials'] = ds.groupby('Order')['Order'].transform('count')
</code>```

But not sure how to add a new columns based on conditions where status equals to each status, So that it will look like this:

```<code>no  Order   materials   status         Total Materials  available   not available   Feb-20
1   1000    100         available       2                    1            1           0
2   1000    200         not available   2                    1            1           0
3   1001    500         Feb-20          1                    0            0           1
4   1002    400         available       4                    3            1           0
5   1002    300         not available   4                    3            1           0
6   1002    600         available       4                    3            1           0
7   1002    900         available       4                    3            1           0
8   1003    700         available       2                    2            0           0
9   1003    800         available       2                    2            0           0
</code>```

Basically trying to figure out how to get the rest of the columns. Would appreciate your help!

答:
I would do a combination of pivot table and merge:

```<code>ds_final = ds.merge(ds.pivot_table(values='Total Materials',index=['Order'],columns='status',aggfunc='count',fill_value=0).reset_index(),how='left',on='Order')
print(ds_final)
</code>```

Output:

```<code>   no  Order  materiales  status  Total Materials  A  Feb-20  not A
0   1   1000         100       A                2  1       0      1
1   2   1000         200   not A                2  1       0      1
2   3   1001         500  Feb-20                1  0       1      0
3   4   1002         400       A                4  3       0      1
4   5   1002         300   not A                4  3       0      1
5   6   1002         600       A                4  3       0      1
6   7   1002         900       A                4  3       0      1
7   8   1003         700       A                2  2       0      0
8   9   1003         800       A                2  2       0      0
</code>```

Some extra explanation:

The pivot table helps to generate the columns from the status column. So here's the output of the pivot_table alone:

```<code>status  Order  A  Feb-20  not A
0        1000  1       0      1
1        1001  0       1      0
2        1002  3       0      1
3        1003  2       0      0
</code>```

Finally with this output, we can use merge or concat to generate the desired output.

Body:
I have the table such that:

no  Order   materials   status
1   1000    100         available
2   1000    200         not available
3   1001    500         Feb-20
4   1002    400         available
5   1002    300         not available
6   1002    600         available
7   1002    900         available
8   1003    700         available
9   1003    800         available

And I'd like to have columns that shows:

Total number of materials per Order

Total number of materials with their status per Order

I was able to get the total number of materials per Order:

ds.groupby('Order').count()
ds['Total Materials'] = ds.groupby('Order')['Order'].transform('count')

But not sure how to add a new columns based on conditions where status equals to each status, So that it will look like this:

no  Order   materials   status         Total Materials  available   not available   Feb-20
1   1000    100         available       2                    1            1           0
2   1000    200         not available   2                    1            1           0
3   1001    500         Feb-20          1                    0            0           1
4   1002    400         available       4                    3            1           0
5   1002    300         not available   4                    3            1           0
6   1002    600         available       4                    3            1           0
7   1002    900         available       4                    3            1           0
8   1003    700         available       2                    2            0           0
9   1003    800         available       2                    2            0           0

Basically trying to figure out how to get the rest of the columns. Would appreciate your help!

Body:
I would do a combination of pivot table and merge:

ds_final = ds.merge(ds.pivot_table(values='Total Materials',index=['Order'],columns='status',aggfunc='count',fill_value=0).reset_index(),how='left',on='Order')
print(ds_final)

Output:

   no  Order  materiales  status  Total Materials  A  Feb-20  not A
0   1   1000         100       A                2  1       0      1
1   2   1000         200   not A                2  1       0      1
2   3   1001         500  Feb-20                1  0       1      0
3   4   1002         400       A                4  3       0      1
4   5   1002         300   not A                4  3       0      1
5   6   1002         600       A                4  3       0      1
6   7   1002         900       A                4  3       0      1
7   8   1003         700       A                2  2       0      0
8   9   1003         800       A                2  2       0      0

Some extra explanation:

The pivot table helps to generate the columns from the status column. So here's the output of the pivot_table alone:

status  Order  A  Feb-20  not A
0        1000  1       0      1
1        1001  0       1      0
2        1002  3       0      1
3        1003  2       0      0

Finally with this output, we can use merge or concat to generate the desired output.


问:
Transaction Manager don't assume the transaction
i'm facing a problem i really dunno how to catch the cat tail (if you hollow me the joke :o))

i have a webapp in war, deploy in tomcat. the war contains 4 Jars.
4 jars have 4 applicationContext, with 4 entityManager, and 4 TransactionManager.

declare like this (change the number 1..):

```<code>      <bean id="entityManagerFactory1"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
    p:dataSource-ref="dataSource1"
    p:persistence-unit-name="com.xxxxxx.domain"     >

    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
        p:databasePlatform="${ds1.dbdialect}" p:generate-ddl="false"
            p:showSql="${ds1.showsql}"  />
    </property>
    <property name="loadTimeWeaver">
        <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
    </property>
</bean>

  <bean id="transactionManager1" class="org.springframework.orm.jpa.JpaTransactionManager"
    p:entityManagerFactory-ref="entityManagerFactory1">
    depends-on="entityManagerFactory1" name="transactionManager1"/>

   <tx:annotation-driven  transaction-manager="transactionManager1" />
</code>```

the context is load like this :

my problem i discover that when i'm using a BO of 3, the transaction is open with the datasource of 2.

moreover, if i do a persist i have the message :

AbstractSaveEventListener - delaying identity-insert due to no transaction in progress

BUT if i launch the jar 1 alone (for example), everything is working perfectly.

thanks a lot for your enlightement.

答:
Let me guess:

in your servlet-context.xml, do you import the contexts? e.g.:

```<code><import location="classpath:context1.xml" />
<import location="classpath:context2.xml" />
</code>```

etc.

If you do, all bean definitions are copied from the imported context into the root context, which means that you have four different <tx:annotation-driven /> declarations, with different transaction managers. Probably the last one wins.

Possible solutions: Either use Qualifiers or use the XML style of transaction declaration.

What I'd do is probably to introduce a custom @Transactional annotation per context:

```<code>@Transactional("tx1")
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})
public @interface Transactional1 {}
</code>```

Now annotate all methods in jar 1 with @Transactional1, in jar 2 with @Transactional2 etc. This mechanism is documented in the Section 10.5.6.3 Custom shortcut annotations

Body:
i'm facing a problem i really dunno how to catch the cat tail (if you hollow me the joke :o))

i have a webapp in war, deploy in tomcat. the war contains 4 Jars.
4 jars have 4 applicationContext, with 4 entityManager, and 4 TransactionManager.

declare like this (change the number 1..):

      <bean id="entityManagerFactory1"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
    p:dataSource-ref="dataSource1"
    p:persistence-unit-name="com.xxxxxx.domain"     >

    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
        p:databasePlatform="${ds1.dbdialect}" p:generate-ddl="false"
            p:showSql="${ds1.showsql}"  />
    </property>
    <property name="loadTimeWeaver">
        <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
    </property>
</bean>

  <bean id="transactionManager1" class="org.springframework.orm.jpa.JpaTransactionManager"
    p:entityManagerFactory-ref="entityManagerFactory1">
    depends-on="entityManagerFactory1" name="transactionManager1"/>

   <tx:annotation-driven  transaction-manager="transactionManager1" />

the context is load like this :

my problem i discover that when i'm using a BO of 3, the transaction is open with the datasource of 2.

moreover, if i do a persist i have the message :

AbstractSaveEventListener - delaying identity-insert due to no transaction in progress

BUT if i launch the jar 1 alone (for example), everything is working perfectly.

thanks a lot for your enlightement.

Body:
Let me guess:

in your servlet-context.xml, do you import the contexts? e.g.:

<import location="classpath:context1.xml" />
<import location="classpath:context2.xml" />

etc.

If you do, all bean definitions are copied from the imported context into the root context, which means that you have four different <tx:annotation-driven /> declarations, with different transaction managers. Probably the last one wins.

Possible solutions: Either use Qualifiers or use the XML style of transaction declaration.

What I'd do is probably to introduce a custom @Transactional annotation per context:

@Transactional("tx1")
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})
public @interface Transactional1 {}

Now annotate all methods in jar 1 with @Transactional1, in jar 2 with @Transactional2 etc. This mechanism is documented in the Section 10.5.6.3 Custom shortcut annotations


问:
How to convert a directory to a ZIP?
I wanted to know how to convert a file (x) directly to a ZIP (x.zip), and convert it back into a normal file, using python (3.7)

答:
To crack a ZIP file has been protected:</p>

```<code>import threading
from zipfile import ZipFile

def ext(f, pw):
    try:
        f.extractall(pwd=pw)
        print('Cracked the .zip file')
        print(':::::  %s' % pw)
    except:
        pass

f = 'file.zip'

pw = open('password.txt', 'r').readline()
for p in pw:
    crack=threading.Thread(target=ext, args=[f, p])
    crack.start()
</code>```

Title: How to convert a directory to a ZIP?

Body:
To crack a ZIP file has been protected:

import threading
from zipfile import ZipFile

def ext(f, pw):
    try:
        f.extractall(pwd=pw)
        print('Cracked the .zip file')
        print(':::::  %s' % pw)
    except:
        pass

f = 'file.zip'

pw = open('password.txt', 'r').readline()
for p in pw:
    crack=threading.Thread(target=ext, args=[f, p])
    crack.start()


问:
Set a variable equal to null if it is not included in an array?
If I have something like,

```<code>const {
  someProperty,
  anotherProperty,
  thirdProperty
} = someObject;

const includeProperties = ['someProperty', 'thirdProperty']
</code>```

Is it possible to make anotherProperty = null?

答:
```<code>    let someProperty = someObject,
       anotherProperty = someObject,
       thirdProperty = someObject;

    const includeProperties = [someProperty, thirdProperty];

if (!includeProperties.include(someVariable))
    someVariable= null;
}
</code>```

This is a possible way to do what you asked.

Body:
If I have something like,

const {
  someProperty,
  anotherProperty,
  thirdProperty
} = someObject;

const includeProperties = ['someProperty', 'thirdProperty']

Is it possible to make anotherProperty = null?

Body:
    let someProperty = someObject,
       anotherProperty = someObject,
       thirdProperty = someObject;

    const includeProperties = [someProperty, thirdProperty];

if (!includeProperties.include(someVariable))
    someVariable= null;
}

This is a possible way to do what you asked.


问:
How to read the value from web config in AngularJs Controller
```<code><configuration>
    <appSettings>
            <add key="var1" value="SomeValue"/>
      </appSettings>
<configuration>
</code>```

I want to read this var1 in angularJS controller
Like this...

```<code>function ReadConfigurationSettings()
    {
        var k = '<%=ConfigurationManager.AppSettings["var1"].ToString() %>'
        alert(k);
    }
</code>```

but its not working..

答:
You cannot get a value from web config directly. One option is to put the value into a meta tag in your index html for example like this:

```<code><meta name="var1" content="@ConfigurationManager.AppSettings["var1"]" />
</code>```

Then you can get that value from angular like this:

```<code>var var1 = angular.element(document).find('meta[name=var1]').prop("content");
</code>```

Body:
<configuration>
    <appSettings>
            <add key="var1" value="SomeValue"/>
      </appSettings>
<configuration>

I want to read this var1 in angularJS controller
Like this...

function ReadConfigurationSettings()
    {
        var k = '<%=ConfigurationManager.AppSettings["var1"].ToString() %>'
        alert(k);
    }

but its not working..

Body:
You cannot get a value from web config directly. One option is to put the value into a meta tag in your index html for example like this:

<meta name="var1" content="@ConfigurationManager.AppSettings["var1"]" />

Then you can get that value from angular like this:

var var1 = angular.element(document).find('meta[name=var1]').prop("content");


问:
TypeScript Array of Tuples
So I have this simple example:

```<code>type SomeTuple = [string, number];

const foo = (options: SomeTuple[]) => console.log(options);

const options = [
    ['first', 1],
    ['second', 2],
];

const otherOptions: SomeTuple[] = [
    ['first', 1],
    ['second', 2],
];

foo(options); // Error

foo(otherOptions); // OK
</code>```

Basically there no more much to tell, I just can't figure out why TS keeps showing me error in case where I'am not providing type for options explicitly;

Playground

Thank you for your time!

答:
It looks like Tuple declaration is inferred incorrectly, so you can declare explicitly your type:

```<code>foo = (options: SomeTuple[]) => console.log(options);

options: SomeTuple[] = [
    ['first', 1],
    ['second', 2],
];

otherOptions: SomeTuple[] = [
    ['first', 1],
    ['second', 2],
];
</code>```

A work stackblitz example can be seen here.

Title: TypeScript Array of Tuples

Body:
So I have this simple example:

type SomeTuple = [string, number];

const foo = (options: SomeTuple[]) => console.log(options);

const options = [
    ['first', 1],
    ['second', 2],
];

const otherOptions: SomeTuple[] = [
    ['first', 1],
    ['second', 2],
];

foo(options); // Error

foo(otherOptions); // OK

Basically there no more much to tell, I just can't figure out why TS keeps showing me error in case where I'am not providing type for options explicitly;

Playground

Thank you for your time!

Body:
It looks like Tuple declaration is inferred incorrectly, so you can declare explicitly your type:

foo = (options: SomeTuple[]) => console.log(options);

options: SomeTuple[] = [
    ['first', 1],
    ['second', 2],
];

otherOptions: SomeTuple[] = [
    ['first', 1],
    ['second', 2],
];

A work stackblitz example can be seen here.


问:
MSN (message sequence number) in response for a retransmitted RDMA Read
While running ib_read_bw test for 64K message sizes from Mellanox CX-4 (request initiator) to another RNIC, re-transmissions are happening from Mellanox for the 5th RDMA-READ on-wards for 50KB of data (first 12KBs has been ACKed successfully), after which it continuously re-transmitting the same request for remaining 50KB data, though the target RNIC is responding.

One observation the target RNIC is responding with a MSN of 11 instead of 5 int the first RDMA READ response, for the re-transmitted (for 50KB) read request.

The infiniband spec says, for duplicate requests RNIC should not increment the MSN, does this mean that, the RNIC should respond with whatever MSN it has (it may have responded for all the incoming requests received and having a MSN of 16 and then re-transmission being seen) or should it respond with proper MSN for the re-transmitted RDMA READ.

答:
The InfiniBand spec says that:

For RDMA READ requests, the responder
  may increment its MSN after it has completed validating the request and
  before it has begun transmitting any of the requested data, and may return
  the incremented MSN in the AETH of the first response packet.

and

The MSN shall not be incremented for duplicate requests.

(C9-148)

I believe this means the MSN should remain unchanged when retransmission occurs.


问:
Rails for Zombies Level 5 Challenge 5
The problem statement is
Create a named route. It should generate a path like '/zombies/:name' where :name is a parameter, and points to the index action in ZombiesController. Name the route 'graveyard'

the resources are
Resources

```<code>zombies
id  name    graveyard
1   Ash     Glen Haven Memorial Cemetary
2   Bob     Chapel Hill Cemetary
3   Jim     My Fathers Basement
</code>```

my solution is

```<code>TwitterForZombies::Application.routes.draw do
  match ':name' => 'Zombies#index', :as => 'graveyard'
end
</code>```

i also tried

```<code>TwitterForZombies::Application.routes.draw do
      match ':name' => 'Zombie#index', :as => 'graveyard'
    end
</code>```

the error that i get in both cases is

```<code>Sorry, Try Again
Did not route to ZombiesController index action with :name parameter
</code>```

What am i doing wrong??

答:
Try this</p>

```<code>match '/zombies/:name' => 'zombies#index', :as => 'graveyard'
</code>```

Title: Rails for Zombies Level 5 Challenge 5

Body:
The problem statement is
Create a named route. It should generate a path like '/zombies/:name' where :name is a parameter, and points to the index action in ZombiesController. Name the route 'graveyard'

the resources are
Resources

zombies
id  name    graveyard
1   Ash     Glen Haven Memorial Cemetary
2   Bob     Chapel Hill Cemetary
3   Jim     My Fathers Basement

my solution is

TwitterForZombies::Application.routes.draw do
  match ':name' => 'Zombies#index', :as => 'graveyard'
end

i also tried

TwitterForZombies::Application.routes.draw do
      match ':name' => 'Zombie#index', :as => 'graveyard'
    end

the error that i get in both cases is

Sorry, Try Again
Did not route to ZombiesController index action with :name parameter

What am i doing wrong??

Body:
Try this

match '/zombies/:name' => 'zombies#index', :as => 'graveyard'


问:
How to read pfx file's thumbprint without prompt for password
I have a need to obtain a thumbprint from a pfx file on the filesystem without being prompted for a password that requires manual input.

I'm running this as part of an installer where the user specifies the path to the certificate on the filesystem (Not in the store). And the user specifies the password for the certificate. From that point, i need the thumbprint.

So this is simply a matter of discovering a tool which i can pass a path and password to a pfx file and return the thumbprint.  I've tried several tools, but even OpenSSL compiled for windows, and it still prompts for the password and gives back a lot more info than just the thumbprint. It needs to be 100% programmatic and without further user intervention.

I'd love to hear any ideas on how to do this. This will be on Windows Server machines only. Thanks!

答:
When creating .pfx (pkcs#12) file, the internal storage containers, called "SafeBags", may also be encrypted and signed.

By default, OpenSSL encrypts the certificate along with its private key, which means it is not possible to get its thumbprint without knowing password.

When creating a new pfx, you can explicitly add -certpbe NONE to avoid encrypting the certificate.
For more details check -certpbe OpenSSL's man page


问:
How can i create this Curved Bottom ImageView?
Target Image View

I want to create an image view like the one in the design. I have no idea how to go about it. I'm hoping someone can point me int the right direction. A library or what I can do to get it.

答: If you want this, you can use toolbar. I am suggesting you. I think, you should use ArcLayout 3rd party library. You can find in github.</p>