问:
Avoid username field creation in custom user model for django allauth
I'm using a custom user model with allauth and I need to have the username field omitted. I've already seen the docs and a whole bunch of stackoverflow answers about using ACCOUNT_USER_MODEL_USERNAME_FIELD = None but all of this still leads my database to have an username field.

Now since the db still has an username field with the unique constraint set on and allauth will not put a username in the field with the aforementioned setting set to None, this causes me to face IntegrityError after the very first user creation. I know I can solve this by just having the aforementioned setting be set to 'username' but I'm curious, how do I just not make the username, because I'm never using it.

My model:

class CustomUser(AbstractUser):
    # Custom user model for django-allauth
    first_name = None
    last_name = None

    def delete(self):
        # Custom delete - make sure user storage is also purged
        # Purge the user storage
        purge_userstore(self.email)
        # Call the original delete method to take care of everything else
        super(CustomUser, self).delete()

```

<p>It doesn't really do much except override the <code>delete</code> function. This override is irrelevant in this topic but I included it just for the sake of completeness. It also sets <code>first_name</code> and <code>last_name</code> to <code>None</code>, which works perfectly and removes those fields from the database as expected. I've tried setting <code>user</code> to <code>None</code> but that does nothing. I've also tried setting <code>username</code> to <code>None</code> but that will raise a <code>FieldNotFound</code> error with <code>ACCOUNT_USER_MODEL_USERNAME_FIELD = None</code></p>

<p>My settings (the relevant bit):</p>

<pre class="lang-py prettyprint-override"><code>AUTHENTICATION_BACKENDS = (
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend",
)
AUTH_USER_MODEL = 'custom_account.CustomUser'
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_AUTHENTICATION_METHOD = 'email'
</code>```

My migration file:

migrations.CreateModel(
            name='CustomUser',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('password', models.CharField(max_length=128, verbose_name='password')),
                ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
                ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
                ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
                ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
                ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
                ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
                ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
                ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
                ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
            ],
....
```

This migration generation confuses me to no end. Why is the username field still there? Why is it set to be the only unique constraint even though I've clearly set ACCOUNT_UNIQUE_EMAIL = True?

Note: This migration file is generated from a clean slate, this is the first and only migration file generated from the code I have presented.

At first I thought, my settings were simply not being read. But I checked django.conf.settings and allauth.account.app_settings (in the shell) for these changes and they were all updated. What's going on here?

Note: Amongst the many stackoverflow questions I've searched, this question in particular seems to explain my issue perfectly. With one small problem, the answer by the creator of allauth himself suggested to use ACCOUNT_USER_MODEL_USERNAME_FIELD = "username" as the model in question was "clearly using the username field". But the answer does not explain what to do when you don't want to use the username field at all.

答:
Looks like the only way to get rid of the username field is to override the AbstractUser's username field and/or use a completely custom model from the ground up. Thought overriding AbstractBaseUser should work too, albeit AbstractBaseUser provides less functionality.

class CustomUser(AbstractUser):
    # Custom user model for django-allauth
    # Remove unnecessary fields
    username = None
    first_name = None
    last_name = None
    # Set the email field to unique
    email = models.EmailField(_('email address'), unique=True)
    # Get rid of all references to the username field
    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
```

<p>This model will remove the <code>username</code> field and make the <code>email</code> field unique, as well as change all references to the <code>USERNAME_FIELD</code> to <code>'email'</code>. Do note that <code>REQUIRED_FIELDS</code> should be empty as the <code>USERNAME_FIELD</code> cannot be in there. When using allauth, this is not a problem, the email and password requirement are managed by allauth anyway.</p>

<p>The settings that I've mentioned in the question should remain the same, specifically-</p>

<pre class="lang-py prettyprint-override"><code>ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_REQUIRED = True
</code>```

Body:
I'm using a custom user model with allauth and I need to have the username field omitted. I've already seen the docs and a whole bunch of stackoverflow answers about using ACCOUNT_USER_MODEL_USERNAME_FIELD = None but all of this still leads my database to have an username field.

Now since the db still has an username field with the unique constraint set on and allauth will not put a username in the field with the aforementioned setting set to None, this causes me to face IntegrityError after the very first user creation. I know I can solve this by just having the aforementioned setting be set to 'username' but I'm curious, how do I just not make the username, because I'm never using it.

My model:

class CustomUser(AbstractUser):
    # Custom user model for django-allauth
    first_name = None
    last_name = None

    def delete(self):
        # Custom delete - make sure user storage is also purged
        # Purge the user storage
        purge_userstore(self.email)
        # Call the original delete method to take care of everything else
        super(CustomUser, self).delete()

It doesn't really do much except override the delete function. This override is irrelevant in this topic but I included it just for the sake of completeness. It also sets first_name and last_name to None, which works perfectly and removes those fields from the database as expected. I've tried setting user to None but that does nothing. I've also tried setting username to None but that will raise a FieldNotFound error with ACCOUNT_USER_MODEL_USERNAME_FIELD = None

My settings (the relevant bit):

AUTHENTICATION_BACKENDS = (
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend",
)
AUTH_USER_MODEL = 'custom_account.CustomUser'
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_AUTHENTICATION_METHOD = 'email'

My migration file:

migrations.CreateModel(
            name='CustomUser',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('password', models.CharField(max_length=128, verbose_name='password')),
                ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
                ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
                ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
                ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
                ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
                ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
                ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
                ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
                ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
            ],
....

This migration generation confuses me to no end. Why is the username field still there? Why is it set to be the only unique constraint even though I've clearly set ACCOUNT_UNIQUE_EMAIL = True?

Note: This migration file is generated from a clean slate, this is the first and only migration file generated from the code I have presented.

At first I thought, my settings were simply not being read. But I checked django.conf.settings and allauth.account.app_settings (in the shell) for these changes and they were all updated. What's going on here?

Note: Amongst the many stackoverflow questions I've searched, this question in particular seems to explain my issue perfectly. With one small problem, the answer by the creator of allauth himself suggested to use ACCOUNT_USER_MODEL_USERNAME_FIELD = "username" as the model in question was "clearly using the username field". But the answer does not explain what to do when you don't want to use the username field at all.

Body:
Looks like the only way to get rid of the username field is to override the AbstractUser's username field and/or use a completely custom model from the ground up. Thought overriding AbstractBaseUser should work too, albeit AbstractBaseUser provides less functionality.

class CustomUser(AbstractUser):
    # Custom user model for django-allauth
    # Remove unnecessary fields
    username = None
    first_name = None
    last_name = None
    # Set the email field to unique
    email = models.EmailField(_('email address'), unique=True)
    # Get rid of all references to the username field
    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

This model will remove the username field and make the email field unique, as well as change all references to the USERNAME_FIELD to 'email'. Do note that REQUIRED_FIELDS should be empty as the USERNAME_FIELD cannot be in there. When using allauth, this is not a problem, the email and password requirement are managed by allauth anyway.

The settings that I've mentioned in the question should remain the same, specifically-

ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_REQUIRED = True


来源: stackexchange

问:
How to deploy Blazor untouched DemoApp BUT with working Authorization (BlazorServer)
I can't come up with a solution by myself ... for the following Task!

I try to deploy the untouched Blazor template from Visual Studio (Blazor Server (not WebAssembly) with Authentication ON (individual users).

If I start the app locally on my PC everything works fine. I can register a Account log in etc.

But If I "Publish" the Blazor App and upload it to my Hosting Side I cant use the Authentication Register/Login etc.
(Hosting on interserver.net / ASP.NET Web Hosting (0 of 25 MSSQL used)  / config with plesk)

I get a Server Status 500 Error.

Some points to mention. I set the App Template to work with "App will store User internal".

I am pretty much a noob to Databases, SQL etc..

My thoughts are that the problem is that I use the "App store User internal" Option right at the creation of the Project. True?

Do I need to also publish my SQLDatabase that is auto created with the Template (locally) to my server?
(yes then -> how ?)

Do I use the DB Connection String from appsetting.json and create a DB on my Server with the same name as the local db? But at my hoster if I want to add a SQL db I have to create a User and a Password. At the local Project I didn't have to enter a User or a passwordd so how to do that then?

Extremely sorry for my lack of knowledge. Please share your knowledge to help me find some peace after all...

答:
When you create a Blazor application using Identity with local user accounts, it defaults to using Entity Framework and Microsoft SQL Server, specifically SQLexpress on your development machine. If you check Startup.cs you should see:

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

As your hosting service is providing MySql, that's not going to work, so you need to replace this. It makes sense to remove SqlServer from your template and switch to using MySql on your development machine so the two use the same code.

When you run locally the connection string used comes from appsettings.json. When you publish, if there is a file called appsettings.Production.json any settings in here will be used instead, so you can put the connection string to connect to the hosted MySQL database in there.

I'm not an expert on setting up MySQL so I'd suggest you look at ".NET Core 3 — Blazor App and Security with Identity and MySql" which should help in the process.

ContentLicense: CC BY-SA 4.0

Body:
When you create a Blazor application using Identity with local user accounts, it defaults to using Entity Framework and Microsoft SQL Server, specifically SQLexpress on your development machine. If you check Startup.cs you should see:

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

As your hosting service is providing MySql, that's not going to work, so you need to replace this. It makes sense to remove SqlServer from your template and switch to using MySql on your development machine so the two use the same code.

When you run locally the connection string used comes from appsettings.json. When you publish, if there is a file called appsettings.Production.json any settings in here will be used instead, so you can put the connection string to connect to the hosted MySQL database in there.

I'm not an expert on setting up MySQL so I'd suggest you look at ".NET Core 3 — Blazor App and Security with Identity and MySql" which should help in the process.


问:
Wordpress Avada Theme remove border
How do I remove in Wordpress Avada Theme the top borders, which automatically appear everywhere and look like this:

I can remove them in Chrome dev tools just like this:

But if I put e.g. this css code inside the Avada themes custom css, it is still there:

```<code>#main .fusion-row {
    border-top: 0px !important;
}
</code>```

答:
```<code> #main .fusion-row {
       display: none !important;
   }
</code>```

Use this CSS line in your additional CSS field

Or

You can go to the theme editor and look for header.php file look for header code remove it.

Title: Wordpress Avada Theme remove border

Body:
How do I remove in Wordpress Avada Theme the top borders, which automatically appear everywhere and look like this:

I can remove them in Chrome dev tools just like this:

But if I put e.g. this css code inside the Avada themes custom css, it is still there:

#main .fusion-row {
    border-top: 0px !important;
}

Body:
 #main .fusion-row {
       display: none !important;
   }

Use this CSS line in your additional CSS field

Or

You can go to the theme editor and look for header.php file look for header code remove it.


问:
Import .py with .ipynb within VSCode
Within the same project directory, I have one file solution.ipynb and other called model.py. In the file solution.ipynb I have to import the module model.py.

Altough both files are in the same directory, when I use the below code:

```<code>import import_ipynb
import model
</code>```

I still get the error: ModuleNotFoundError: No module named 'model'

Please note: I'm using the VSCode to open and write on the .ipynb file. Strangely enough, when I open the .ipynb file with Jupyter lab, the module model.py can be imported without problems.

What I've already tried: (1) install the import-ipynb and reference it above (as seen in the first line of the code) and (2) add a __init__.py file within the directory where the .ipynb is located.

答:
You can use this</p>

```<code>% run "model.py"
</code>```

Title: Import .py with .ipynb within VSCode

Body:
Within the same project directory, I have one file solution.ipynb and other called model.py. In the file solution.ipynb I have to import the module model.py.

Altough both files are in the same directory, when I use the below code:

import import_ipynb
import model

I still get the error: ModuleNotFoundError: No module named 'model'

Please note: I'm using the VSCode to open and write on the .ipynb file. Strangely enough, when I open the .ipynb file with Jupyter lab, the module model.py can be imported without problems.

What I've already tried: (1) install the import-ipynb and reference it above (as seen in the first line of the code) and (2) add a __init__.py file within the directory where the .ipynb is located.

Body:
You can use this

% run "model.py"


问:
Make a global minor mode buffer-local
Another Elisp package defines a minor mode as global. In other words, the package defines the minor mode with:

```<code>(define-minor-mode some-minor-mode
  ;; ... other stuff ...
  :global t)
</code>```

I'd like to make it buffer-local so that when I activate it, it only applies to the buffer in which it is activated. How do I do this?

答:
You can't.  Or at least, you can't in a generic way.

When a minor mode is defined as global, the logic of the mode will undoubtedly make that exact same assumption, and there's no generic change you could make which would cause any arbitrary global minor mode to have only buffer-local effects.

Furthermore, for some global modes a buffer-local variant wouldn't even make sense, such as modes which affect window configurations or frame parameters.

Global modes have to be treated on a case-by-case basis, looking at their specific implementation details.  Depending on the code in question, you might be able to achieve your goal for some particular mode; but that same approach would not be guaranteed to work for all global modes.

It's worth mentioning that there are "globalized" minor modes which blend the other two concepts, by taking an existing buffer-local minor mode, and then defining a global mode which enables or disables the buffer-local mode en masse in all of the applicable buffers.  You can't go in the other direction, though -- if you don't already have a buffer-local mode, then you would have to write that first.

Title: Make a global minor mode buffer-local

Body:
Another Elisp package defines a minor mode as global. In other words, the package defines the minor mode with:

(define-minor-mode some-minor-mode
  ;; ... other stuff ...
  :global t)

I'd like to make it buffer-local so that when I activate it, it only applies to the buffer in which it is activated. How do I do this?


问:
Reactor Flux: how to parse file with header
Recently I started using project reactor 3.3 and I don't know what is the best way to handle flux of lines, with first line as column names, then use those column names to process/convert all other lines. Right now I'm doing this way:

Flux<String> lines = ....;
Mono<String[]> columns = Mono.from(lines.take(1).map(header -> header.split(";"))); //getting first line
Flux<SomeDto> objectFlux = lines.skip(1) //skip first line
  .flatMapIterable(row -> //iterating over lines
      columns.map(cols -> convert(cols, row)));  //convert line into SomeDto object

```

So is it the right way?

答:
So is it the right way?

There's always more than one way to cook an egg - but the code you have there seems odd / suboptimal for two main reasons:

I'd assume it's one line per record / DTO you want to extract, so it's a bit odd you're using flatMapIterable() rather than flatMap()

You're going to resubscribe to lines once for each line, when you re-evaluate that Mono. That's almost certainly not what you want to do. (Caching the Mono helps, but you'd still resubscribe at least twice.)

Instead you may want to look at using switchOnFirst(), which will enable you to dynamically transform the Flux based on the first element (the header in your case.) This means you can do something like so:

```<code>lines
        .switchOnFirst((signal, flux) -> flux.zipWith(Flux.<String[]>just(signal.get().split(";")).repeat()))
        .map(row -> convert(row.getT1(), row.getT2()))
</code>```

Note this is a bear-bones example, in real-world use you'll need to check whether the signal actually has a value as per the docs:

Note that the source might complete or error immediately instead of emitting, in which case the Signal would be onComplete or onError. It is NOT necessarily an onNext Signal, and must be checked accordingly.

Body:
Recently I started using project reactor 3.3 and I don't know what is the best way to handle flux of lines, with first line as column names, then use those column names to process/convert all other lines. Right now I'm doing this way:

Flux<String> lines = ....;
Mono<String[]> columns = Mono.from(lines.take(1).map(header -> header.split(";"))); //getting first line
Flux<SomeDto> objectFlux = lines.skip(1) //skip first line
  .flatMapIterable(row -> //iterating over lines
      columns.map(cols -> convert(cols, row)));  //convert line into SomeDto object

So is it the right way?

Body:
So is it the right way?

There's always more than one way to cook an egg - but the code you have there seems odd / suboptimal for two main reasons:

I'd assume it's one line per record / DTO you want to extract, so it's a bit odd you're using flatMapIterable() rather than flatMap()

You're going to resubscribe to lines once for each line, when you re-evaluate that Mono. That's almost certainly not what you want to do. (Caching the Mono helps, but you'd still resubscribe at least twice.)

Instead you may want to look at using switchOnFirst(), which will enable you to dynamically transform the Flux based on the first element (the header in your case.) This means you can do something like so:

lines
        .switchOnFirst((signal, flux) -> flux.zipWith(Flux.<String[]>just(signal.get().split(";")).repeat()))
        .map(row -> convert(row.getT1(), row.getT2()))

Note this is a bear-bones example, in real-world use you'll need to check whether the signal actually has a value as per the docs:

Note that the source might complete or error immediately instead of emitting, in which case the Signal would be onComplete or onError. It is NOT necessarily an onNext Signal, and must be checked accordingly.


问:
Capture optional Group
I want to capture the values of some keys which may be optional, specifically consider the string below

```<code>@Foo1:dog|a=5|b=6|c=10|d=12|e=2
@Foo2:cat|a=12|c=10|d=11|e=123
@Foo1:bat|a=213123|b=10
@Foo3:pet|c=346
</code>```

Now I want to capture the strings between @ and :, : and |, and the value of keys b, d which may be optional.
I should the following captured

```<code>Foo1, dog, 6, 12
Foo2, cat, 11
Foo1, bat, 10
Foo3, pet
</code>```

I am using this regex
^@(\w+):(\w+).*(?:b=(\d+)).*(?:d=(\d+)) but it only works when both b and d are present.

答:
You may use

```<code>^@(\w+):(\w+)(?:.*?\|b=(\d+))?(?:.*?\|d=(\d+))?
</code>```

See the regex demo

Details

^ - start of string

@ - a @ char

(\w+) - Group 1: one or more word chars

: - a colon

(\w+) - Group 2: one or more word chars

(?:.*?\|b=(\d+))? - an optional non-capturing group matching any 0+ chars other than line break chars, as few as possible, then |b= and then capturing 1+ digits into Group 3

(?:.*?\|d=(\d+))? - an optional non-capturing group matching any 0+ chars other than line break chars, as few as possible, then |d= and then capturing 1+ digits into Group 4

Title: Capture optional Group

Body:
I want to capture the values of some keys which may be optional, specifically consider the string below

@Foo1:dog|a=5|b=6|c=10|d=12|e=2
@Foo2:cat|a=12|c=10|d=11|e=123
@Foo1:bat|a=213123|b=10
@Foo3:pet|c=346

Now I want to capture the strings between @ and :, : and |, and the value of keys b, d which may be optional.
I should the following captured

Foo1, dog, 6, 12
Foo2, cat, 11
Foo1, bat, 10
Foo3, pet

I am using this regex
^@(\w+):(\w+).*(?:b=(\d+)).*(?:d=(\d+)) but it only works when both b and d are present.

Body:
You may use

^@(\w+):(\w+)(?:.*?\|b=(\d+))?(?:.*?\|d=(\d+))?

See the regex demo

Details

^ - start of string

@ - a @ char

(\w+) - Group 1: one or more word chars

: - a colon

(\w+) - Group 2: one or more word chars

(?:.*?\|b=(\d+))? - an optional non-capturing group matching any 0+ chars other than line break chars, as few as possible, then |b= and then capturing 1+ digits into Group 3

(?:.*?\|d=(\d+))? - an optional non-capturing group matching any 0+ chars other than line break chars, as few as possible, then |d= and then capturing 1+ digits into Group 4


问:
How to call parent non virtual function in c++ multi inheritance?
```<code>class VA {
 public:
  virtual void print() = 0;
};
class VB : public VA {
 public:
  virtual void bprint() = 0;
};
class SA : public VA {
 public:
  void print() override { std::cout << "SA" << std::endl; };
};
class SB : public SA, public VB {
 public:
  virtual void bprint() { std::cout << "SB" << std::endl; };
};
int main() {
  SB sb;
  sb.bprint();
  sb.print();
}
</code>```

What is the correct way to call sb.print()?

```<code>class SB : public SA, public VB {
 public:
  virtual void bprint() { std::cout << "SB" << std::endl; };
  void print() override { SA::print(); };
};
</code>```

I know this kind of override will work, but I am considering is there a way that no extra code in class SB?

答:
It looks like you are trying to make VA an interface in Java sense: no data, only some methods which have to be implemented only once in the hierarchy.

Short version: use virtual inheritance for VA: : public virtual VA.

Long version follows.

Multiple inheritance in C++ by default creates independent paths to all base objects. In your case, SB actually has two VA bases: one from SA, and one from VB. The former has an implementation of print, the latter does not, hence the first compilation error:

```<code>a.cpp: In function 'int main()':
a.cpp:20:6: error: cannot declare variable 'sb' to be of abstract type 'SB'
   20 |   SB sb;
      |      ^~
a.cpp:15:7: note:   because the following virtual functions are pure within 'SB':
   15 | class SB : public SA, public VB {
      |       ^~
a.cpp:5:16: note:     'virtual void VA::print()'
    5 |   virtual void print() = 0;
      |                ^~~~~
a.cpp:22:6: error: request for member 'print' is ambiguous
   22 |   sb.print();
      |      ^~~~~
a.cpp:5:16: note: candidates are: 'virtual void VA::print()'
    5 |   virtual void print() = 0;
      |                ^~~~~
a.cpp:13:8: note:                 'virtual void SA::print()'
   13 |   void print() override { std::cout << "SA" << std::endl; };
      |        ^~~~~
</code>```

However, there is also the second error. It becomes more visible if you implement print both in SA and VB: there are actually two prints:

```<code>a.cpp: In function 'int main()':
a.cpp:23:6: error: request for member 'print' is ambiguous
   23 |   sb.print();
      |      ^~~~~
a.cpp:5:16: note: candidates are: 'virtual void VA::print()'
    5 |   virtual void print() = 0;
      |                ^~~~~
a.cpp:10:8: note:                 'virtual void VB::print()'
   10 |   void print() override { std::cout << "VB" << std::endl; };  // Tried to add another implementation
      |        ^~~~~
a.cpp:14:8: note:                 'virtual void SA::print()'
   14 |   void print() override { std::cout << "SA" << std::endl; };
      |        ^~~~~
</code>```

In C++ corresponding mechanics is provided by virtual inheritance: every base which should be deduplicated should be marked as virtual:

#include <iostream>

class VA {
 public:
  virtual void print() = 0;
};
class VB : public virtual VA {  // 'virtual' ~ 'please ensure there is only one VA base'
 public:
  virtual void bprint() = 0;
};
class SA : public virtual VA {  // 'virtual' ~ 'please ensure there is only one VA base'
 public:
  void print() override { std::cout << "SA" << std::endl; };
};
class SB : public SA, public VB {
 public:
  virtual void bprint() { std::cout << "SB" << std::endl; };
};
int main() {
  SB sb;
  sb.bprint();
  sb.print();
}
```

Now the compiler knows that there is only one VA base, and successfully finds its print implementation unambiguously in SA. It's important that SA is derived from VA, though, otherwise SA::print won't have any connection to VA::print whatsoever.

Body:
class VA {
 public:
  virtual void print() = 0;
};
class VB : public VA {
 public:
  virtual void bprint() = 0;
};
class SA : public VA {
 public:
  void print() override { std::cout << "SA" << std::endl; };
};
class SB : public SA, public VB {
 public:
  virtual void bprint() { std::cout << "SB" << std::endl; };
};
int main() {
  SB sb;
  sb.bprint();
  sb.print();
}

What is the correct way to call sb.print()?

class SB : public SA, public VB {
 public:
  virtual void bprint() { std::cout << "SB" << std::endl; };
  void print() override { SA::print(); };
};

I know this kind of override will work, but I am considering is there a way that no extra code in class SB?

Body:
It looks like you are trying to make VA an interface in Java sense: no data, only some methods which have to be implemented only once in the hierarchy.

Short version: use virtual inheritance for VA: : public virtual VA.

Long version follows.

Multiple inheritance in C++ by default creates independent paths to all base objects. In your case, SB actually has two VA bases: one from SA, and one from VB. The former has an implementation of print, the latter does not, hence the first compilation error:

a.cpp: In function 'int main()':
a.cpp:20:6: error: cannot declare variable 'sb' to be of abstract type 'SB'
   20 |   SB sb;
      |      ^~
a.cpp:15:7: note:   because the following virtual functions are pure within 'SB':
   15 | class SB : public SA, public VB {
      |       ^~
a.cpp:5:16: note:     'virtual void VA::print()'
    5 |   virtual void print() = 0;
      |                ^~~~~
a.cpp:22:6: error: request for member 'print' is ambiguous
   22 |   sb.print();
      |      ^~~~~
a.cpp:5:16: note: candidates are: 'virtual void VA::print()'
    5 |   virtual void print() = 0;
      |                ^~~~~
a.cpp:13:8: note:                 'virtual void SA::print()'
   13 |   void print() override { std::cout << "SA" << std::endl; };
      |        ^~~~~

However, there is also the second error. It becomes more visible if you implement print both in SA and VB: there are actually two prints:

a.cpp: In function 'int main()':
a.cpp:23:6: error: request for member 'print' is ambiguous
   23 |   sb.print();
      |      ^~~~~
a.cpp:5:16: note: candidates are: 'virtual void VA::print()'
    5 |   virtual void print() = 0;
      |                ^~~~~
a.cpp:10:8: note:                 'virtual void VB::print()'
   10 |   void print() override { std::cout << "VB" << std::endl; };  // Tried to add another implementation
      |        ^~~~~
a.cpp:14:8: note:                 'virtual void SA::print()'
   14 |   void print() override { std::cout << "SA" << std::endl; };
      |        ^~~~~

In C++ corresponding mechanics is provided by virtual inheritance: every base which should be deduplicated should be marked as virtual:

#include <iostream>

class VA {
 public:
  virtual void print() = 0;
};
class VB : public virtual VA {  // 'virtual' ~ 'please ensure there is only one VA base'
 public:
  virtual void bprint() = 0;
};
class SA : public virtual VA {  // 'virtual' ~ 'please ensure there is only one VA base'
 public:
  void print() override { std::cout << "SA" << std::endl; };
};
class SB : public SA, public VB {
 public:
  virtual void bprint() { std::cout << "SB" << std::endl; };
};
int main() {
  SB sb;
  sb.bprint();
  sb.print();
}

Now the compiler knows that there is only one VA base, and successfully finds its print implementation unambiguously in SA. It's important that SA is derived from VA, though, otherwise SA::print won't have any connection to VA::print whatsoever.


问:
Need a Regular expresssion that should not allow only space in string, It can allow spaces along with characters
Need a Regular expresssion that should not allow  only space  in string, It can allow spaces along  with characters.

e.g: space+char+space  is  allowed  where  as  only  space  is not allowed

答:
Try this:

```<code>/^\s+$\
</code>```

Any string that matches the above expression is invalid as per your criteria.

ContentLicense: CC BY-SA 3.0

Body:
Try this:

/^\s+$\

Any string that matches the above expression is invalid as per your criteria.


问:
Return non-nullable type
I'm sure, my code gets not null value for return:

    fun getBitmap(id: Int): Bitmap{
        if (!(id in bitmapStorage))
            bitmapStorage.put(id, BitmapFactory.decodeResource(resources, id))
        return bitmapStorage.get(id)
    }
```

What's the right way to return Bitmap type instead of Bitmap??

!!, as Bitmap or something else?

答:
Given the operations you're performing on bitmapStorage I'm assuming it's an instance of MutableMap. If that's the case, I think there's an even more idiomatic way to achieve the same result, and it involves using getOrPut method. Basically, it returns the value associated to a given key, if it exists, otherwise it associates whatever value you want to the given key and returns that value.

Example:

```<code>val myMap = mutableMapOf<String, String>(
        "key1" to "value1"
)

fun complexMethodToComputeValue(): String {
    // do something complex
    return "I will be called"
}

val value1 = myMap.getOrPut("key1") {
    // this will not be called
    "I won't be called"
}
val value2 = myMap.getOrPut("key2", ::complexMethodToComputeValue)

println(value1)
println(value2)
</code>```

This prints:

```<code>value1
I will be called
</code>```

So, to come back to your code, it could be rewritten as:

```<code>fun getBitmap(id: Int) =  bitmapStorage.getOrPut(id) {
    BitmapFactory.decodeResource(resources, id)
}
</code>```

Title: Return non-nullable type

Body:
I'm sure, my code gets not null value for return:

    fun getBitmap(id: Int): Bitmap{
        if (!(id in bitmapStorage))
            bitmapStorage.put(id, BitmapFactory.decodeResource(resources, id))
        return bitmapStorage.get(id)
    }

What's the right way to return Bitmap type instead of Bitmap??

!!, as Bitmap or something else?

Body:
Given the operations you're performing on bitmapStorage I'm assuming it's an instance of MutableMap. If that's the case, I think there's an even more idiomatic way to achieve the same result, and it involves using getOrPut method. Basically, it returns the value associated to a given key, if it exists, otherwise it associates whatever value you want to the given key and returns that value.

Example:

val myMap = mutableMapOf<String, String>(
        "key1" to "value1"
)

fun complexMethodToComputeValue(): String {
    // do something complex
    return "I will be called"
}

val value1 = myMap.getOrPut("key1") {
    // this will not be called
    "I won't be called"
}
val value2 = myMap.getOrPut("key2", ::complexMethodToComputeValue)

println(value1)
println(value2)

This prints:

value1
I will be called

So, to come back to your code, it could be rewritten as:

fun getBitmap(id: Int) =  bitmapStorage.getOrPut(id) {
    BitmapFactory.decodeResource(resources, id)
}


问:
separate lines according to a string in them in python
I have a file containing (~1000) lines of data in the following -simplified- form:

```<code>movej(p[-0.2875, -0.4, 0.05, -0.0004, 3.1415, 0.0002],a=5.000000,v=5.000000,r=0.000000)
movej([-1.3615, -2.0244, -1.5691, -2.6895, 0.2092, 1.2197],a=5.000000,v=5.000000,r=0.050000)
movel(p[-0.2875, -0.375, 0.0, -0.0004, 3.1415, 0.0002],a=0.500000,v=0.300000,r=0.000000)
movel([-1.2437, -1.9458, -2.0485, -2.2887, 0.0128, 1.2197],a=5.000000,v=5.000000,r=0.050000)
# Various comments
## Various comments
### Various comments
</code>```

And I need to separate the lines in two sets (for later conversion to pandas dataframes), one set consisting of the lines with the p -starting with "movej(p[" or "movel(p[" and the other consisting of the lines without the p -starting with "movej([" or "movel([".

```<code>movej(p[-0.2875, -0.4, 0.05, -0.0004, 3.1415, 0.0002],a=5.000000,v=5.000000,r=0.000000)
movel(p[-0.2875, -0.375, 0.0, -0.0004, 3.1415, 0.0002],a=0.500000,v=0.300000,r=0.000000)

and

movej([-1.3615, -2.0244, -1.5691, -2.6895, 0.2092, 1.2197],a=5.000000,v=5.000000,r=0.050000)
movel([-1.2437, -1.9458, -2.0485, -2.2887, 0.0128, 1.2197],a=5.000000,v=5.000000,r=0.050000)
</code>```

To do so, I have created the following code that almost does the job.

The issue I am experiencing is that it stops or doesn't store everything in the TCP_lines and joint_lines strings.
I have also tried using list with the same result.

```<code>with open("SRP_Assemble all BUSH_BEARING onto HPC_FRONT_BOTTOM.script", "r") as f:
    lines = f.readlines()
    TCP_lines = ""
    joint_lines = ""

    for line in lines:
        if line.startswith(("movej(p" ,"movel(p")):
            TCP_lines += line
        elif line.startswith(("movej(" ,"movel(")):
            joint_lines += line

print (TCP_lines)
print (joint_lines)
</code>```

EDIT:
Does the console have a limited space to print results?
So it only prints the first couple of rows?

I used a redirector to print the results in a text box and it looks fine...

Body:
I have a file containing (~1000) lines of data in the following -simplified- form:

movej(p[-0.2875, -0.4, 0.05, -0.0004, 3.1415, 0.0002],a=5.000000,v=5.000000,r=0.000000)
movej([-1.3615, -2.0244, -1.5691, -2.6895, 0.2092, 1.2197],a=5.000000,v=5.000000,r=0.050000)
movel(p[-0.2875, -0.375, 0.0, -0.0004, 3.1415, 0.0002],a=0.500000,v=0.300000,r=0.000000)
movel([-1.2437, -1.9458, -2.0485, -2.2887, 0.0128, 1.2197],a=5.000000,v=5.000000,r=0.050000)
# Various comments
## Various comments
### Various comments

And I need to separate the lines in two sets (for later conversion to pandas dataframes), one set consisting of the lines with the p -starting with "movej(p[" or "movel(p[" and the other consisting of the lines without the p -starting with "movej([" or "movel([".

movej(p[-0.2875, -0.4, 0.05, -0.0004, 3.1415, 0.0002],a=5.000000,v=5.000000,r=0.000000)
movel(p[-0.2875, -0.375, 0.0, -0.0004, 3.1415, 0.0002],a=0.500000,v=0.300000,r=0.000000)

and

movej([-1.3615, -2.0244, -1.5691, -2.6895, 0.2092, 1.2197],a=5.000000,v=5.000000,r=0.050000)
movel([-1.2437, -1.9458, -2.0485, -2.2887, 0.0128, 1.2197],a=5.000000,v=5.000000,r=0.050000)

To do so, I have created the following code that almost does the job.

The issue I am experiencing is that it stops or doesn't store everything in the TCP_lines and joint_lines strings.
I have also tried using list with the same result.

with open("SRP_Assemble all BUSH_BEARING onto HPC_FRONT_BOTTOM.script", "r") as f:
    lines = f.readlines()
    TCP_lines = ""
    joint_lines = ""

    for line in lines:
        if line.startswith(("movej(p" ,"movel(p")):
            TCP_lines += line
        elif line.startswith(("movej(" ,"movel(")):
            joint_lines += line

print (TCP_lines)
print (joint_lines)

EDIT:
Does the console have a limited space to print results?
So it only prints the first couple of rows?

I used a redirector to print the results in a text box and it looks fine...

Body:
I tried to simulate what you are doing. The below outputs the correct lines. What output do you get?

lines = ["movej(p[-0.2875, -0.4, 0.05, -0.0004, 3.1415, 0.0002],a=5.000000,v=5.000000,r=0.000000)",
"movej([-1.3615, -2.0244, -1.5691, -2.6895, 0.2092, 1.2197],a=5.000000,v=5.000000,r=0.050000)",
"movel(p[-0.2875, -0.375, 0.0, -0.0004, 3.1415, 0.0002],a=0.500000,v=0.300000,r=0.000000)",
"movel([-1.2437, -1.9458, -2.0485, -2.2887, 0.0128, 1.2197],a=5.000000,v=5.000000,r=0.050000)",]

TCP_lines = ""
joint_lines = ""

for line in lines:
    if line.startswith(("movej(p" ,"movel(p")):
        TCP_lines += line
    elif line.startswith(("movej(" ,"movel(")):
        joint_lines += line

print (TCP_lines)
print (joint_lines)

OUT:

movej(p[-0.2875, -0.4, 0.05, -0.0004, 3.1415,
0.0002],a=5.000000,v=5.000000,r=0.000000)movel(p[-0.2875, -0.375, 0.0, -0.0004, 3.1415, 0.0002],a=0.500000,v=0.300000,r=0.000000)

movej([-1.3615, -2.0244, -1.5691, -2.6895, 0.2092,
1.2197],a=5.000000,v=5.000000,r=0.050000)movel([-1.2437, -1.9458, -2.0485, -2.2887, 0.0128, 1.2197],a=5.000000,v=5.000000,r=0.050000)


问:
Left join two datatables with certain parameters
I have two datatables t1 and t2. Imported them to SQL, tested with SQL command LEFT JOIN and it is working. However as amount of data is not so big I am wondering is it possible to perform the same action directly to datatables without exporting them to SQL?

Here I have two tables in SQL LFI = t1 and LSE = t2.

Table LFI in database:

```<code>NRO   SNAME  NAMEA   NAMEB   IADDRESS  POSTA   POSTN   POSTADR   COMPANYN   COUNTRY   BID
123   Fiat   Punto   500     J5        K4      O3      P4        O2         JT        S1
133   Opel   Meriva  FTG     J5        K4      O3      P4        O2         JO        T3
153   MB     E200    C25     JN        KI      OP      PY        OR         JD        Y5
183   BMW    E64     SE0     JR        KE      OT      PG        OL         J8        U9
103   Audi   S6      700     JP        KU      OU      PN        OH         J6        I11
</code>```

Table LSE in database:

```<code>NRO   SNAME  NAMEA   NAMEB   IADDRESS  POSTA   POSTN   POSTADR   COMPANYN   COUNTRY   BID
423   Fiat   Punto   500     J5        K4      O3      P4        O2         JT        S1
463   BMW    E64     SE0     JR        KE      OT      PG        OL         J8        U9
483   KIA    E89     S78     J7        K7      O9      P6        O5         J4        U6
</code>```

Below code is capable of doing what is expected:

```<code>SELECT *
FROM LFI
LEFT JOIN LSE
ON CAST(LFI.SNAME AS VARCHAR(50)) = CAST(LSE.SNAME AS VARCHAR(50));
</code>```

How to perform the same directly to datatables so that joined result would go to temporary datatable with LEFT JOIN?

Current code:

```<code>                var results = from table1 in t1.AsEnumerable()
                              join table2 in t2.AsEnumerable()
                              on (string)table1["SNAME"] equals (string)table2["SNAME"]
                              //into temp
                              //from row in temp.DefaultIfEmpty()
                              select new
                              {
                                  NRO = (string)table1["NRO"],
                                  SNAME = (string)table1["SNAME"],
                                  NAMEA = (string)table1["NAMEA"],
                                  NAMEB = (string)table1["NAMEB"],
                                  ADDRESS = (string)table1["ADDRESS"],
                                  POSTA = (string)table1["POSTA"],
                                  POSTN = (string)table1["POSTN"],
                                  POSTITP = (string)table1["POSTITP"],
                                  COMPANYN = (string)table1["COMPANYN"],
                                  COUNTRY = (string)table1["COUNTRY"],
                                  BID = (string)table1["BID"]
                              };

                foreach (var item in results)
                {
                    Console.WriteLine(String.Format("NRO = {0}, SNAME = {1}, NAMEA = {2}, NAMEB = {3}, KAYNTIOS = {4}, ADDRESS = {5}, POSTA = {6}, POSTN = {7}, COMPANYN = {8}, COUNTRY = {9}, BID = {10}", item.NRO, item.SNAME,
                        item.NAMEA, item.NAMEB, item.KAYNTIOS, item.ADDRESS, item.POSTA, item.POSTN, item.COMPANYN,
                        item.COUNTRY, item.BID));
                }
</code>```

My current code is outputting only matching results:

```<code>NRO  SNAME  NAMEA   NAMEB   IADDRESS  POSTA   POSTN   POSTADR   COMPANYN   COUNTRY   BID
123  Fiat   Punto   500     J5        K4      O3      P4        O2         JT        S1
183  BMW    E64     SE0     JR        KE      OT      PG        OL         J8        U9
</code>```

Joined output should look like this (Column order doesn't really matter as long as it is the same all the time):

```<code>NRO  NRO1   SNAME  NAMEA   NAMEB   IADDRESS  POSTA   POSTN   POSTADR   COMPANYN   COUNTRY   BID
123  423    Fiat   Punto   500     J5        K4      O3      P4        O2         JT        S1
133         Opel   Meriva  FTG     J5        K4      O3      P4        O2         JO        T3
153         MB     E200    C25     JN        KI      OP      PY        OR         JD        Y5
183  463    BMW    E64     SE0     JR        KE      OT      PG        OL         J8        U9
103         Audi   S6      700     JP        KU      OU      PN        OH         J6        I11
     483    KIA    E89     S78     J7        K7      O9      P6        O5         J4        U6
</code>```

答:
What you need here is Full Outer Join in Sql. But because it doesn't have direct equivalent in Linq, you should implement it this way : T1 ⋃ (T2 - T1)

T1 : Is achieved by T1 Left Join T2

(T2 - T1) : Is achieved by T2 Left Join T1 Where T1 is null

This should results what you're looking for:

```<code>// T1
var firstPart = from table1 in t1.AsEnumerable()
                join table2 in t2.AsEnumerable()
                    on (string)table1["SNAME"] equals (string)table2["SNAME"] into temp
                from table2 in temp.DefaultIfEmpty()
                select new
                {
                    NRO = (string)table1["NRO"],
                    NRO1 = table2 != null ? (string)table2["NRO"] : string.Empty,
                    SNAME = (string)table1["SNAME"],
                    NAMEA = (string)table1["NAMEA"],
                    NAMEB = (string)table1["NAMEB"],
                    ADDRESS = (string)table1["ADDRESS"],
                    POSTA = (string)table1["POSTA"],
                    POSTN = (string)table1["POSTN"],
                    POSTITP = (string)table1["POSTITP"],
                    COMPANYN = (string)table1["COMPANYN"],
                    COUNTRY = (string)table1["COUNTRY"],
                    BID = (string)table1["BID"]
                };

// (T2 -T1)
var secndPart = from table2 in t2.AsEnumerable()
                join table1 in t1.AsEnumerable()
                    on (string)table2["SNAME"] equals (string)table1["SNAME"] into temp
                from table1 in temp.DefaultIfEmpty()
                where table1 == null
                select new
                {
                    NRO = string.Empty,
                    NRO1 = (string)table2["NRO"],
                    SNAME = (string)table2["SNAME"],
                    NAMEA = (string)table2["NAMEA"],
                    NAMEB = (string)table2["NAMEB"],
                    ADDRESS = (string)table2["ADDRESS"],
                    POSTA = (string)table2["POSTA"],
                    POSTN = (string)table2["POSTN"],
                    POSTITP = (string)table2["POSTITP"],
                    COMPANYN = (string)table2["COMPANYN"],
                    COUNTRY = (string)table2["COUNTRY"],
                    BID = (string)table2["BID"]
                };

// T1 ⋃ (T2 - T1)
var results = firstPart.Concat(secndPart);

foreach (var item in results)
{
    Console.WriteLine(
        $"NRO = {item.NRO}, " +
        $"NRO1 = {item.NRO1}, " +
        $"SNAME = {item.SNAME}, " +
        $"NAMEA = {item.NAMEA}, " +
        $"NAMEB = {item.NAMEB}, " +
        $"ADDRESS = {item.ADDRESS}, " +
        $"POSTA = {item.POSTA}, " +
        $"POSTN = {item.POSTN}, " +
        $"POSTITP = {item.POSTITP}, " +
        $"COMPANYN = {item.COMPANYN}, " +
        $"COUNTRY = {item.COUNTRY}, " +
        $"BID = {item.BID}"
        );
}
</code>```

Body:
I have two datatables t1 and t2. Imported them to SQL, tested with SQL command LEFT JOIN and it is working. However as amount of data is not so big I am wondering is it possible to perform the same action directly to datatables without exporting them to SQL?

Here I have two tables in SQL LFI = t1 and LSE = t2.

Table LFI in database:

NRO   SNAME  NAMEA   NAMEB   IADDRESS  POSTA   POSTN   POSTADR   COMPANYN   COUNTRY   BID
123   Fiat   Punto   500     J5        K4      O3      P4        O2         JT        S1
133   Opel   Meriva  FTG     J5        K4      O3      P4        O2         JO        T3
153   MB     E200    C25     JN        KI      OP      PY        OR         JD        Y5
183   BMW    E64     SE0     JR        KE      OT      PG        OL         J8        U9
103   Audi   S6      700     JP        KU      OU      PN        OH         J6        I11

Table LSE in database:

NRO   SNAME  NAMEA   NAMEB   IADDRESS  POSTA   POSTN   POSTADR   COMPANYN   COUNTRY   BID
423   Fiat   Punto   500     J5        K4      O3      P4        O2         JT        S1
463   BMW    E64     SE0     JR        KE      OT      PG        OL         J8        U9
483   KIA    E89     S78     J7        K7      O9      P6        O5         J4        U6

Below code is capable of doing what is expected:

SELECT *
FROM LFI
LEFT JOIN LSE
ON CAST(LFI.SNAME AS VARCHAR(50)) = CAST(LSE.SNAME AS VARCHAR(50));

How to perform the same directly to datatables so that joined result would go to temporary datatable with LEFT JOIN?

Current code:

                var results = from table1 in t1.AsEnumerable()
                              join table2 in t2.AsEnumerable()
                              on (string)table1["SNAME"] equals (string)table2["SNAME"]
                              //into temp
                              //from row in temp.DefaultIfEmpty()
                              select new
                              {
                                  NRO = (string)table1["NRO"],
                                  SNAME = (string)table1["SNAME"],
                                  NAMEA = (string)table1["NAMEA"],
                                  NAMEB = (string)table1["NAMEB"],
                                  ADDRESS = (string)table1["ADDRESS"],
                                  POSTA = (string)table1["POSTA"],
                                  POSTN = (string)table1["POSTN"],
                                  POSTITP = (string)table1["POSTITP"],
                                  COMPANYN = (string)table1["COMPANYN"],
                                  COUNTRY = (string)table1["COUNTRY"],
                                  BID = (string)table1["BID"]
                              };

                foreach (var item in results)
                {
                    Console.WriteLine(String.Format("NRO = {0}, SNAME = {1}, NAMEA = {2}, NAMEB = {3}, KAYNTIOS = {4}, ADDRESS = {5}, POSTA = {6}, POSTN = {7}, COMPANYN = {8}, COUNTRY = {9}, BID = {10}", item.NRO, item.SNAME,
                        item.NAMEA, item.NAMEB, item.KAYNTIOS, item.ADDRESS, item.POSTA, item.POSTN, item.COMPANYN,
                        item.COUNTRY, item.BID));
                }

My current code is outputting only matching results:

NRO  SNAME  NAMEA   NAMEB   IADDRESS  POSTA   POSTN   POSTADR   COMPANYN   COUNTRY   BID
123  Fiat   Punto   500     J5        K4      O3      P4        O2         JT        S1
183  BMW    E64     SE0     JR        KE      OT      PG        OL         J8        U9

Joined output should look like this (Column order doesn't really matter as long as it is the same all the time):

NRO  NRO1   SNAME  NAMEA   NAMEB   IADDRESS  POSTA   POSTN   POSTADR   COMPANYN   COUNTRY   BID
123  423    Fiat   Punto   500     J5        K4      O3      P4        O2         JT        S1
133         Opel   Meriva  FTG     J5        K4      O3      P4        O2         JO        T3
153         MB     E200    C25     JN        KI      OP      PY        OR         JD        Y5
183  463    BMW    E64     SE0     JR        KE      OT      PG        OL         J8        U9
103         Audi   S6      700     JP        KU      OU      PN        OH         J6        I11
     483    KIA    E89     S78     J7        K7      O9      P6        O5         J4        U6

Body:
What you need here is Full Outer Join in Sql. But because it doesn't have direct equivalent in Linq, you should implement it this way : T1 ⋃ (T2 - T1)

T1 : Is achieved by T1 Left Join T2

(T2 - T1) : Is achieved by T2 Left Join T1 Where T1 is null

This should results what you're looking for:

// T1
var firstPart = from table1 in t1.AsEnumerable()
                join table2 in t2.AsEnumerable()
                    on (string)table1["SNAME"] equals (string)table2["SNAME"] into temp
                from table2 in temp.DefaultIfEmpty()
                select new
                {
                    NRO = (string)table1["NRO"],
                    NRO1 = table2 != null ? (string)table2["NRO"] : string.Empty,
                    SNAME = (string)table1["SNAME"],
                    NAMEA = (string)table1["NAMEA"],
                    NAMEB = (string)table1["NAMEB"],
                    ADDRESS = (string)table1["ADDRESS"],
                    POSTA = (string)table1["POSTA"],
                    POSTN = (string)table1["POSTN"],
                    POSTITP = (string)table1["POSTITP"],
                    COMPANYN = (string)table1["COMPANYN"],
                    COUNTRY = (string)table1["COUNTRY"],
                    BID = (string)table1["BID"]
                };

// (T2 -T1)
var secndPart = from table2 in t2.AsEnumerable()
                join table1 in t1.AsEnumerable()
                    on (string)table2["SNAME"] equals (string)table1["SNAME"] into temp
                from table1 in temp.DefaultIfEmpty()
                where table1 == null
                select new
                {
                    NRO = string.Empty,
                    NRO1 = (string)table2["NRO"],
                    SNAME = (string)table2["SNAME"],
                    NAMEA = (string)table2["NAMEA"],
                    NAMEB = (string)table2["NAMEB"],
                    ADDRESS = (string)table2["ADDRESS"],
                    POSTA = (string)table2["POSTA"],
                    POSTN = (string)table2["POSTN"],
                    POSTITP = (string)table2["POSTITP"],
                    COMPANYN = (string)table2["COMPANYN"],
                    COUNTRY = (string)table2["COUNTRY"],
                    BID = (string)table2["BID"]
                };

// T1 ⋃ (T2 - T1)
var results = firstPart.Concat(secndPart);

foreach (var item in results)
{
    Console.WriteLine(
        $"NRO = {item.NRO}, " +
        $"NRO1 = {item.NRO1}, " +
        $"SNAME = {item.SNAME}, " +
        $"NAMEA = {item.NAMEA}, " +
        $"NAMEB = {item.NAMEB}, " +
        $"ADDRESS = {item.ADDRESS}, " +
        $"POSTA = {item.POSTA}, " +
        $"POSTN = {item.POSTN}, " +
        $"POSTITP = {item.POSTITP}, " +
        $"COMPANYN = {item.COMPANYN}, " +
        $"COUNTRY = {item.COUNTRY}, " +
        $"BID = {item.BID}"
        );
}


问:
Angular material date picker return Moment object instead of Date
I have a strange problem, in my html I defined-

```<code>    <mat-radio-button value="embargoed">
        <div>Everyone, limited by date</div>
        <mat-form-field *ngIf="data.selected === 'embargoed'">
            <mat-label>Available from date</mat-label>
            <input matInput [matDatepicker]="picker" #input [(ngModel)]="date">
            <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
            <mat-datepicker #picker></mat-datepicker>
        </mat-form-field>
    </mat-radio-button>
</code>```

in my comonent I initialized-

```<code>date = new Date();
</code>```

I have an OnSubmit function that does-

```<code>onSubmit(){
    if (this.data.selected === 'embargoed') {
        this.data.date = this.date;
    }
}
</code>```

In debud I can see that this.date is a Moment object instead of a Date object, any idea why?

答:
```<code>this.date = new Date(this.date);
</code>```

Body:
I have a strange problem, in my html I defined-

    <mat-radio-button value="embargoed">

Everyone, limited by date

        <mat-form-field *ngIf="data.selected === 'embargoed'">
            <mat-label>Available from date</mat-label>
            <input matInput [matDatepicker]="picker" #input [(ngModel)]="date">
            <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
            <mat-datepicker #picker></mat-datepicker>
        </mat-form-field>
    </mat-radio-button>

in my comonent I initialized-

date = new Date();

I have an OnSubmit function that does-

onSubmit(){
    if (this.data.selected === 'embargoed') {
        this.data.date = this.date;
    }
}

In debud I can see that this.date is a Moment object instead of a Date object, any idea why?

Body: this.date = new Date(this.date);


问:
Unicode problem when using cppimport/pybind11
I am trying to use cppimport, an lib based on pybind11, to import some *.cpp files directly into python, according to the author's example.

I am using Pycharm and python 3.7, installed both cppimport and pybind11, win10.

The import code is quite easy using cppimport.

```<code>import cppimport.import_hook
import DemoTrade
</code>```

Then I got an error

```<code>mako.exceptions.CompileException: Unicode decode operation of encoding 'ascii' failed in file 'C:\Users\...\DemoTrade.cpp' at line: 0 char: 0
</code>```

The files address is right, otherwise it will give another error

The problem seems in the coding of files, I changed other encoding, but nothing improved.

I don't know how to deal with this. Thank you for your help.

答:
Since cppimport is based on pybind11 and mako,  this is a mako problem.

in cppimport lib, find templating.py.

Then add the encode you want in mako.template.Template(). Following is an example

```<code>mako.template.Template(filename = filepath, lookup = lookup,
                      input_encoding='gb2312', output_encoding='gb2312')
</code>```

Then it is solved.

Body:
I am trying to use cppimport, an lib based on pybind11, to import some *.cpp files directly into python, according to the author's example.

I am using Pycharm and python 3.7, installed both cppimport and pybind11, win10.

The import code is quite easy using cppimport.

import cppimport.import_hook
import DemoTrade

Then I got an error

mako.exceptions.CompileException: Unicode decode operation of encoding 'ascii' failed in file 'C:\Users\...\DemoTrade.cpp' at line: 0 char: 0

The files address is right, otherwise it will give another error

The problem seems in the coding of files, I changed other encoding, but nothing improved.

I don't know how to deal with this. Thank you for your help.

Body:
Since cppimport is based on pybind11 and mako,  this is a mako problem.

in cppimport lib, find templating.py.

Then add the encode you want in mako.template.Template(). Following is an example

mako.template.Template(filename = filepath, lookup = lookup,
                      input_encoding='gb2312', output_encoding='gb2312')

Then it is solved.


问:
How to prevent highcharts from shortening labels with ellipsis
Highcharts is truncating an x-axis label on a bullet chart. I want to prevent this happening and always show the full text without shortening.

I have tried

```<code>.highcharts-container { overflow: visible !important; }
.highcharts-axis-labels text
    {
    overflow: visible !important;
}
</code>```

but it seems like the SVG is doing the truncation and ellipsis, not CSS as you can tell by seeing the rendered markup.

```<code><text x="229.0625" style="color: rgb(96, 96, 96); cursor: default;     font-size: 9px; padding: 0px; fill: rgb(96, 96, 96);" text-anchor="middle"   transform="translate(0,0)" y="32" opacity="1">
<tspan>47…</tspan>
<title>47.5k</title>
</text>
</code>```

I have tried adding the following property in the javascript:

```<code>labels: {
    autoRotation: false,
    style: {
    width: '200px',
    'min-width': '200px'
},
</code>```

But it does not work. How can I prevent highcharts from truncating the label text?

答:
You only need to add textOverflow property as none like the given code below to get the first and last tick value fully visible.</p>

```<code>xAxis: {
        labels: {
                 style: {
                         fontSize: '9px',
                         color: '#a1a5aa',
                         textOverflow: 'none'
                        }
                }
       }
</code>```

Body:
Highcharts is truncating an x-axis label on a bullet chart. I want to prevent this happening and always show the full text without shortening.

I have tried

.highcharts-container { overflow: visible !important; }
.highcharts-axis-labels text
    {
    overflow: visible !important;
}

but it seems like the SVG is doing the truncation and ellipsis, not CSS as you can tell by seeing the rendered markup.

<text x="229.0625" style="color: rgb(96, 96, 96); cursor: default;     font-size: 9px; padding: 0px; fill: rgb(96, 96, 96);" text-anchor="middle"   transform="translate(0,0)" y="32" opacity="1">
<tspan>47…</tspan>
<title>47.5k</title>
</text>

I have tried adding the following property in the javascript:

labels: {
    autoRotation: false,
    style: {
    width: '200px',
    'min-width': '200px'
},

But it does not work. How can I prevent highcharts from truncating the label text?

Body:
You only need to add textOverflow property as none like the given code below to get the first and last tick value fully visible.

xAxis: {
        labels: {
                 style: {
                         fontSize: '9px',
                         color: '#a1a5aa',
                         textOverflow: 'none'
                        }
                }
       }


问:
Import Python module with PyImport_ImportModuleEx for a gedit plugin
I'm learning Python and I try to use Python Markdown in a gedit plugin. Here's how my files are organized:

```<code>~/.gnome2/gedit/plugins/mytest.gedit-plugin
~/.gnome2/gedit/plugins/mytest/
~/.gnome2/gedit/plugins/mytest/__init__.py
~/.gnome2/gedit/plugins/mytest/markdown/
~/.gnome2/gedit/plugins/mytest/markdown/__init__.py
~/.gnome2/gedit/plugins/mytest/markdown/preprocessors.py
~/.gnome2/gedit/plugins/mytest/markdown/OTHER_FILES
~/.gnome2/gedit/plugins/mytest/markdown/extensions/
~/.gnome2/gedit/plugins/mytest/markdown/extensions/__init__.py
~/.gnome2/gedit/plugins/mytest/markdown/extensions/headerid.py
~/.gnome2/gedit/plugins/mytest/markdown/extensions/OTHER_FILES
</code>```

Explication:

My file mytest.gedit-plugin only contains minimal code to declare the plugin:

```<code>[Gedit Plugin]
Loader=python
Module=mytest
IAge=2
Name=My test
</code>```

My plugin has its own subfolder (mytest). The file mytest/__init__.py contains:

```<code>#!/usr/bin/python
# -*- coding: utf-8 -*-

import gedit
import markdown

class MyTestPlugin(gedit.Plugin):
    def __init__(self):
        gedit.Plugin.__init__(self)

    def activate(self, window):
        texte = "# Header 1 {#id}"
        print markdown.markdown(texte, extensions=['headerid'])
</code>```

Finally, the folder mytest/markdown contains default Python Markdown code.

When I activate my plugin in gedit (Edit > Preferences > Plugins), output in the terminal is:

```<code>Traceback (most recent call last):
  File "/home/moi/.gnome2/gedit/plugins/mytest/__init__.py", line 5, in <module>
    import markdown
  File "/home/moi/.gnome2/gedit/plugins/mytest/markdown/__init__.py", line 161, in <module>
    import preprocessors
  File "/home/moi/.gnome2/gedit/plugins/mytest/markdown/preprocessors.py", line 11, in <module>
    import markdown
ImportError: No module named markdown

** (gedit:8790): WARNING **: Error loading plugin 'My test'
</code>```

However, I successfully use Python Markdown outside gedit. For example, the following file works great when I run it in a terminal in the same location as the Python Markdown main folder:

```<code>#!/usr/bin/python
# -*- coding: utf-8 -*-

import markdown

texte = "# Header 1 {#id}"
print markdown.markdown(texte, extensions=['headerid'])
</code>```

I found that if I change import markdown in Python Markdown files for import __init__ as markdown, I can use Python Markdown without its extensions (mytest/markdown/extensions/), but anyway, it still doesn't work with my example:

```<code>/home/moi/.gnome2/gedit/plugins/mytest/markdown/__init__.py:114: MarkdownWarning: Failed loading extension 'headerid' from 'markdown.extensions.headerid' or 'mdx_headerid'
  warnings.warn(text, MarkdownWarning)
<h1>Header 1 {#id}</h1>
</code>```

So, my question is how could I modify import for extensions, or how could I install Python Markdown in a local emplacement (so in $HOME, without root access) to be able to use Python Markdown in a gedit plugin?

Thanks a lot.

Note: I think gedit uses PyImport_ImportModuleEx() to load plugins, so that's why I put it in the title of my question.

Edit 1: 2 details: no root installation and possible to modify Python Markdown files.

Edit 2: Extensions are loaded with the following code in mytest/markdown/__init__.py (about line 525):

```<code># Setup the module names
ext_module = 'markdown.extensions'
module_name_new_style = '.'.join([ext_module, ext_name])
module_name_old_style = '_'.join(['mdx', ext_name])

# Try loading the extention first from one place, then another
try: # New style (markdown.extensons.<extension>)
    module = __import__(module_name_new_style, {}, {}, [ext_module])
except ImportError:
    try: # Old style (mdx.<extension>)
        module = __import__(module_name_old_style)
    except ImportError:
       message(WARN, "Failed loading extension '%s' from '%s' or '%s'"
           % (ext_name, module_name_new_style, module_name_old_style))
       # Return None so we don't try to initiate none-existant extension
       return None
</code>```

Maybe there's a way to import with relative path. I'm really beginner with Python.

答: If you want to use markdown without modifying it then you're going to have to put it somewhere where the Python library expects it, such as in site-packages/. Otherwise, you will have to modify it to use relative imports instead of absolute imports.

Body:
I'm learning Python and I try to use Python Markdown in a gedit plugin. Here's how my files are organized:

~/.gnome2/gedit/plugins/mytest.gedit-plugin
~/.gnome2/gedit/plugins/mytest/
~/.gnome2/gedit/plugins/mytest/__init__.py
~/.gnome2/gedit/plugins/mytest/markdown/
~/.gnome2/gedit/plugins/mytest/markdown/__init__.py
~/.gnome2/gedit/plugins/mytest/markdown/preprocessors.py
~/.gnome2/gedit/plugins/mytest/markdown/OTHER_FILES
~/.gnome2/gedit/plugins/mytest/markdown/extensions/
~/.gnome2/gedit/plugins/mytest/markdown/extensions/__init__.py
~/.gnome2/gedit/plugins/mytest/markdown/extensions/headerid.py
~/.gnome2/gedit/plugins/mytest/markdown/extensions/OTHER_FILES

Explication:

My file mytest.gedit-plugin only contains minimal code to declare the plugin:

[Gedit Plugin]
Loader=python
Module=mytest
IAge=2
Name=My test

My plugin has its own subfolder (mytest). The file mytest/__init__.py contains:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import gedit
import markdown

class MyTestPlugin(gedit.Plugin):
    def __init__(self):
        gedit.Plugin.__init__(self)

    def activate(self, window):
        texte = "# Header 1 {#id}"
        print markdown.markdown(texte, extensions=['headerid'])

Finally, the folder mytest/markdown contains default Python Markdown code.

When I activate my plugin in gedit (Edit > Preferences > Plugins), output in the terminal is:

Traceback (most recent call last):
  File "/home/moi/.gnome2/gedit/plugins/mytest/__init__.py", line 5, in <module>
    import markdown
  File "/home/moi/.gnome2/gedit/plugins/mytest/markdown/__init__.py", line 161, in <module>
    import preprocessors
  File "/home/moi/.gnome2/gedit/plugins/mytest/markdown/preprocessors.py", line 11, in <module>
    import markdown
ImportError: No module named markdown

** (gedit:8790): WARNING **: Error loading plugin 'My test'

However, I successfully use Python Markdown outside gedit. For example, the following file works great when I run it in a terminal in the same location as the Python Markdown main folder:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import markdown

texte = "# Header 1 {#id}"
print markdown.markdown(texte, extensions=['headerid'])

I found that if I change import markdown in Python Markdown files for import __init__ as markdown, I can use Python Markdown without its extensions (mytest/markdown/extensions/), but anyway, it still doesn't work with my example:

/home/moi/.gnome2/gedit/plugins/mytest/markdown/__init__.py:114: MarkdownWarning: Failed loading extension 'headerid' from 'markdown.extensions.headerid' or 'mdx_headerid'
  warnings.warn(text, MarkdownWarning)

Header 1 {#id}

So, my question is how could I modify import for extensions, or how could I install Python Markdown in a local emplacement (so in $HOME, without root access) to be able to use Python Markdown in a gedit plugin?

Thanks a lot.

Note: I think gedit uses PyImport_ImportModuleEx() to load plugins, so that's why I put it in the title of my question.

Edit 1: 2 details: no root installation and possible to modify Python Markdown files.

Edit 2: Extensions are loaded with the following code in mytest/markdown/__init__.py (about line 525):

# Setup the module names
ext_module = 'markdown.extensions'
module_name_new_style = '.'.join([ext_module, ext_name])
module_name_old_style = '_'.join(['mdx', ext_name])

# Try loading the extention first from one place, then another
try: # New style (markdown.extensons.<extension>)
    module = __import__(module_name_new_style, {}, {}, [ext_module])
except ImportError:
    try: # Old style (mdx.<extension>)
        module = __import__(module_name_old_style)
    except ImportError:
       message(WARN, "Failed loading extension '%s' from '%s' or '%s'"
           % (ext_name, module_name_new_style, module_name_old_style))
       # Return None so we don't try to initiate none-existant extension
       return None

Maybe there's a way to import with relative path. I'm really beginner with Python.


问:
Radio button global state for name attribute
I need to be able to have radion buttons or checkboxes to show / hide content if its checked. There will be more radio buttons and checkboxes to show content in the same form, so to distinguish them from each other, it could be based on the name attribute.

So far i can show the hidden fields when i check the radio buttons, but i want one to cancel out the other, but only if it has the same name attribute (something else can also work).

Is there a react genius who can figure this out? I would be forever in your debt :)

```<code>class PartnerRoute extends Component {
    constructor(props) {
        super(props)
        this.state = {
            showOneTimeFee: '',
            showSubscription: ''
        };
    }

    toggleOneTimeFee = () => {
        const currentState = this.state.showOneTimeFee;
        this.setState({
            showOneTimeFee: !currentState
        })
    }
    toggleSubscription = () => {
        const currentState = this.state.showSubscription;
        this.setState({
            showSubscription: !currentState
        })
    }

    render() {
        return (
            <div className="partner-route">
                <ContentContainer>
                    <div className="form--create-event">
                        <form>
                            <h3>Event information</h3>
                            <GridContainer columnCount="one">
                                <CustomInput type="text" placeholder="Event name" />
                            </GridContainer>

                            <GridContainer columnCount="one">
                                <CustomTextarea type="text" placeholder="Event description" />
                            </GridContainer>

                            <h3>Event date</h3>
                            <GridContainer columnCount="three">
                                <CustomInput type="text" placeholder="Day" />
                                <CustomInput type="text" placeholder="Month" />
                                <CustomInput type="text" placeholder="Year" />
                            </GridContainer>

                            <h3>Payment</h3>
                            <GridContainer columnCount="one">
                                <CustomRadio
                                    type="radio"
                                    name="payment"
                                    id="rb1"
                                    value="1"
                                    label="Free, no payment needed"
                                />
                                <CustomRadio
                                    type="radio"
                                    name="payment"
                                    id="rb2"
                                    value="2"
                                    label="1 time fee"
                                    onChange={this.toggleOneTimeFee}
                                />
                                {this.state.showOneTimeFee &&
                                    <div className="hidden-field">
                                        <CustomInput type="text" placeholder="Price" />
                                    </div>
                                }

                                <CustomRadio
                                    type="radio"
                                    name="payment"
                                    id="rb3"
                                    value="3"
                                    label="Subscription"
                                    onChange={this.toggleSubscription}
                                />
                                {this.state.showSubscription &&
                                    <div className="hidden-field">
                                        <CustomInput type="text" placeholder="Price" />
                                    </div>
                                }
                            </GridContainer>
                        </form>
                    </div>
                </ContentContainer>

            </div>
        )
    }
}

export default PartnerRoute
</code>```

答:
Please check this example where I used setState with prevState that is important and also I used changeHandler for all three radio. Moreover, to run this code in my side I changed all Custom input with generic input for ex CustomInput to input. Please revert this your side.

```<code>import React, {Component} from "react";

export default class PartnerRoute extends Component {
    constructor(props) {
        super(props);
        this.state = {
            showOneTimeFee: false,
            showSubscription: false
        };
    }
    handleChange = (event) => {
        if (event.target.value == 2) // One Time Fee
            this.setState(prevState => {
                return {
                    showOneTimeFee: !prevState.showOneTimeFee,
                    showSubscription: false
                };
            });
        else if (event.target.value == 3) // Subscription
            this.setState(prevState => {
                return {
                    showOneTimeFee: false,
                    showSubscription: !prevState.showSubscription
                };
            });
        else // Free, no payment needed
            this.setState({
                showOneTimeFee: false,
                showSubscription: false
            });
    };

    render() {
        return (
            <div className="partner-route">
                <div>
                    <div className="form--create-event">
                        <form>
                            <h3>Event information</h3>
                            <div>
                                <input type="text" placeholder="Event name"/>
                            </div>
                            <div>
                                <input type="text" multiline="true" placeholder="Event description"/>
                            </div>
                            <h3>Event date</h3>
                            <div>
                                <input type="text" placeholder="Day"/>
                                <input type="text" placeholder="Month"/>
                                <input type="text" placeholder="Year"/>
                            </div>
                            <h3>Payment</h3>
                            <div>
                                <input type="radio" name="payment" id="rb1" value="1" label="Free, no payment needed"
                                       onChange={this.handleChange}/>
                                <label htmlFor="rb1">Free, no payment needed</label><br/>
                                <input type="radio" name="payment" id="rb2" value="2" label="1 time fee"
                                       onChange={this.handleChange}/>
                                <label htmlFor="rb2">1 time fee</label><br/>
                                {this.state.showOneTimeFee &&
                                <div className="hidden-field">
                                    <input type="text" placeholder="One Time Price"/>
                                </div>
                                }
                                <input type="radio" name="payment" id="rb3" value="3" label="Subscription"
                                       onChange={this.handleChange}/>
                                <label htmlFor="rb3">Subscription</label><br/>
                                {this.state.showSubscription &&
                                <div className="hidden-field">
                                    <input type="text" placeholder="Subscription Price"/>
                                </div>
                                }
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        )
    }
}
</code>```

Body:
I need to be able to have radion buttons or checkboxes to show / hide content if its checked. There will be more radio buttons and checkboxes to show content in the same form, so to distinguish them from each other, it could be based on the name attribute.

So far i can show the hidden fields when i check the radio buttons, but i want one to cancel out the other, but only if it has the same name attribute (something else can also work).

Is there a react genius who can figure this out? I would be forever in your debt :)

class PartnerRoute extends Component {
    constructor(props) {
        super(props)
        this.state = {
            showOneTimeFee: '',
            showSubscription: ''
        };
    }

    toggleOneTimeFee = () => {
        const currentState = this.state.showOneTimeFee;
        this.setState({
            showOneTimeFee: !currentState
        })
    }
    toggleSubscription = () => {
        const currentState = this.state.showSubscription;
        this.setState({
            showSubscription: !currentState
        })
    }

    render() {
        return (

                <ContentContainer>

                        <form>

Event information

                            <GridContainer columnCount="one">
                                <CustomInput type="text" placeholder="Event name" />
                            </GridContainer>

                            <GridContainer columnCount="one">
                                <CustomTextarea type="text" placeholder="Event description" />
                            </GridContainer>

Event date

                            <GridContainer columnCount="three">
                                <CustomInput type="text" placeholder="Day" />
                                <CustomInput type="text" placeholder="Month" />
                                <CustomInput type="text" placeholder="Year" />
                            </GridContainer>

Payment

                            <GridContainer columnCount="one">
                                <CustomRadio
                                    type="radio"
                                    name="payment"
                                    id="rb1"
                                    value="1"
                                    label="Free, no payment needed"
                                />
                                <CustomRadio
                                    type="radio"
                                    name="payment"
                                    id="rb2"
                                    value="2"
                                    label="1 time fee"
                                    onChange={this.toggleOneTimeFee}
                                />
                                {this.state.showOneTimeFee &&

                                        <CustomInput type="text" placeholder="Price" />

                                }

                                <CustomRadio
                                    type="radio"
                                    name="payment"
                                    id="rb3"
                                    value="3"
                                    label="Subscription"
                                    onChange={this.toggleSubscription}
                                />
                                {this.state.showSubscription &&

                                        <CustomInput type="text" placeholder="Price" />

                                }
                            </GridContainer>
                        </form>

                </ContentContainer>

        )
    }
}

export default PartnerRoute

Body:
Please check this example where I used setState with prevState that is important and also I used changeHandler for all three radio. Moreover, to run this code in my side I changed all Custom input with generic input for ex CustomInput to input. Please revert this your side.

import React, {Component} from "react";

export default class PartnerRoute extends Component {
    constructor(props) {
        super(props);
        this.state = {
            showOneTimeFee: false,
            showSubscription: false
        };
    }
    handleChange = (event) => {
        if (event.target.value == 2) // One Time Fee
            this.setState(prevState => {
                return {
                    showOneTimeFee: !prevState.showOneTimeFee,
                    showSubscription: false
                };
            });
        else if (event.target.value == 3) // Subscription
            this.setState(prevState => {
                return {
                    showOneTimeFee: false,
                    showSubscription: !prevState.showSubscription
                };
            });
        else // Free, no payment needed
            this.setState({
                showOneTimeFee: false,
                showSubscription: false
            });
    };

    render() {
        return (
            <div className="partner-route">
                <div>
                    <div className="form--create-event">
                        <form>
                            <h3>Event information</h3>
                            <div>
                                <input type="text" placeholder="Event name"/>
                            </div>
                            <div>
                                <input type="text" multiline="true" placeholder="Event description"/>
                            </div>
                            <h3>Event date</h3>
                            <div>
                                <input type="text" placeholder="Day"/>
                                <input type="text" placeholder="Month"/>
                                <input type="text" placeholder="Year"/>
                            </div>
                            <h3>Payment</h3>
                            <div>
                                <input type="radio" name="payment" id="rb1" value="1" label="Free, no payment needed"
                                       onChange={this.handleChange}/>
                                <label htmlFor="rb1">Free, no payment needed</label><br/>
                                <input type="radio" name="payment" id="rb2" value="2" label="1 time fee"
                                       onChange={this.handleChange}/>
                                <label htmlFor="rb2">1 time fee</label><br/>
                                {this.state.showOneTimeFee &&
                                <div className="hidden-field">
                                    <input type="text" placeholder="One Time Price"/>
                                </div>
                                }
                                <input type="radio" name="payment" id="rb3" value="3" label="Subscription"
                                       onChange={this.handleChange}/>
                                <label htmlFor="rb3">Subscription</label><br/>
                                {this.state.showSubscription &&
                                <div className="hidden-field">
                                    <input type="text" placeholder="Subscription Price"/>
                                </div>
                                }
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        )
    }
}


问:
ngModel cannot be used to register form controls with a parent formGroup directive at runtime
I don't know why I get this error message. This is my html:

```<code> <form [formGroup]="insert" (ngSubmit)="onSubmit(insert.value)">

            <div class="ui-g-12 ui-md-12 ui-lg-12">
                <div class="ui-g-5 ui-g-offset-1  ui-md-4 ui-md-offset-1 ui-lg-4 ui-lg-offset-1">
                    <span >name</span>
                </div>
                <div class="ui-g-6 ui-md-4 ui-lg-4">
                    <input type="text" pInputText [(ngModel)]="name_student" formControlName="name_student" />
                </div>
            </div>
...
</form>
</code>```

In y .ts I do:

```<code>  insert: FormGroup;

 ngOnInit(): void {
    //gestione degli errori dopo il submit
    this.insert= this.fb.group({
      'name_student': new FormControl('', Validators.required)
    });
</code>```

I obtain:

```<code>ngModel cannot be used to register form controls with a parent formGroup directive.  Try using       formGroup's partner directive "formControlName" instead.  Example:
</code>```

Anyone can help me?

答:
try this

```<code><form [formGroup]="insert" (ngSubmit)="onSubmit(insert.value)">

            <div class="ui-g-12 ui-md-12 ui-lg-12">
                <div class="ui-g-5 ui-g-offset-1  ui-md-4 ui-md-offset-1 ui-lg-4 ui-lg-offset-1">
                    <span >name</span>
                </div>
                <div class="ui-g-6 ui-md-4 ui-lg-4">
                    <input type="text" pInputText [(ngModel)]="name_student" formControlName="name_student" [ngModelOptions]="{standalone: true />
                </div>
            </div>
...
</form>
</code>```

you should put [ngModelOptions]="{standalone: true

Body:
I don't know why I get this error message. This is my html:

 <form [formGroup]="insert" (ngSubmit)="onSubmit(insert.value)">

                    name

                    <input type="text" pInputText [(ngModel)]="name_student" formControlName="name_student" />

...
</form>

In y .ts I do:

  insert: FormGroup;

 ngOnInit(): void {
    //gestione degli errori dopo il submit
    this.insert= this.fb.group({
      'name_student': new FormControl('', Validators.required)
    });

I obtain:

ngModel cannot be used to register form controls with a parent formGroup directive.  Try using       formGroup's partner directive "formControlName" instead.  Example:

Anyone can help me?

Body:
try this

<form [formGroup]="insert" (ngSubmit)="onSubmit(insert.value)">

            <div class="ui-g-12 ui-md-12 ui-lg-12">
                <div class="ui-g-5 ui-g-offset-1  ui-md-4 ui-md-offset-1 ui-lg-4 ui-lg-offset-1">
                    <span >name</span>
                </div>
                <div class="ui-g-6 ui-md-4 ui-lg-4">
                    <input type="text" pInputText [(ngModel)]="name_student" formControlName="name_student" [ngModelOptions]="{standalone: true />
                </div>
            </div>
...
</form>

you should put [ngModelOptions]="{standalone: true


问:
Docker / PHP / Apache - File permissions lost when created inside container
i'm trying to set up a docker app with Apache and Php stack.
But when i create a new file inside my project container, the permissions losted because root user is connected by default.
How can I connect my host user ?

docker-compose.yml

```<code>version: '3'
services:
  web:
    container_name: web
    build:
      context: docker/web
    volumes:
      - ./app/:/var/www/app
      - ./docker/web/apache/log:/var/log/apache2/app
    working_dir: /var/www/app
    ports:
      - 80:80
</code>```

dockerfile

```<code>FROM php:7.4-apache

ENV APACHE_DOCUMENT_ROOT /var/www

RUN apt-get update && apt-get install -y \
        libfreetype6-dev \
        libjpeg62-turbo-dev \
        libpng-dev \
        libzip-dev \
        git \
        zip \
        unzip \
    && docker-php-ext-configure gd --with-freetype --with-jpeg \
    && docker-php-ext-install -j$(nproc) gd \
    && docker-php-ext-install zip pdo pdo_mysql opcache \
    && apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

RUN rm /etc/localtime
RUN ln -s /usr/share/zoneinfo/Europe/Paris /etc/localtime
RUN "date"

RUN sed -ri -e 's!/var/www/html!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/sites-available/*.conf
RUN sed -ri -e 's!/var/www/!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/apache2.conf /etc/apache2/conf-available/*.conf

COPY php/php.ini /usr/local/etc/php/conf.d/app.ini
COPY apache/app.conf /etc/apache2/sites-available/000-default.conf

RUN groupadd dev -g 1000
RUN useradd dev -g dev -d /home/dev -m
RUN echo '%dev ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
</code>```

I tried to create a dev user in my Dockerfile but not working.

答:
I solved the problem by adding my dev user to sudoers and then running apache2ctl in sudo.</p>

```<code>FROM php:7.4-apache

RUN apt-get update && apt-get install -y \
        sudo \
        libfreetype6-dev \
        libjpeg62-turbo-dev \
        libpng-dev \
        libzip-dev \
        git \
        zip \
        unzip \
    && docker-php-ext-configure gd --with-freetype --with-jpeg \
    && docker-php-ext-install -j$(nproc) gd \
    && docker-php-ext-install zip pdo pdo_mysql opcache \
    && apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

RUN rm /etc/localtime
RUN ln -s /usr/share/zoneinfo/Europe/Paris /etc/localtime
RUN "date"

RUN sed -ri -e 's!/var/www/html!/var/www!g' /etc/apache2/sites-available/*.conf
RUN sed -ri -e 's!/var/www/!/var/www!g' /etc/apache2/apache2.conf /etc/apache2/conf-available/*.conf

COPY php/php.ini /usr/local/etc/php/conf.d/app.ini
COPY apache/app.conf /etc/apache2/sites-available/000-default.conf

RUN groupadd dev -g 1000
RUN useradd dev -g dev -d /home/dev -m
RUN echo '%dev ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
USER dev:dev

CMD ["sudo", "/usr/sbin/apache2ctl", "-D", "FOREGROUND"]
</code>```

Body:
i'm trying to set up a docker app with Apache and Php stack.
But when i create a new file inside my project container, the permissions losted because root user is connected by default.
How can I connect my host user ?

docker-compose.yml

version: '3'
services:
  web:
    container_name: web
    build:
      context: docker/web
    volumes:
      - ./app/:/var/www/app
      - ./docker/web/apache/log:/var/log/apache2/app
    working_dir: /var/www/app
    ports:
      - 80:80

dockerfile

FROM php:7.4-apache

ENV APACHE_DOCUMENT_ROOT /var/www

RUN apt-get update && apt-get install -y \
        libfreetype6-dev \
        libjpeg62-turbo-dev \
        libpng-dev \
        libzip-dev \
        git \
        zip \
        unzip \
    && docker-php-ext-configure gd --with-freetype --with-jpeg \
    && docker-php-ext-install -j$(nproc) gd \
    && docker-php-ext-install zip pdo pdo_mysql opcache \
    && apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

RUN rm /etc/localtime
RUN ln -s /usr/share/zoneinfo/Europe/Paris /etc/localtime
RUN "date"

RUN sed -ri -e 's!/var/www/html!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/sites-available/*.conf
RUN sed -ri -e 's!/var/www/!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/apache2.conf /etc/apache2/conf-available/*.conf

COPY php/php.ini /usr/local/etc/php/conf.d/app.ini
COPY apache/app.conf /etc/apache2/sites-available/000-default.conf

RUN groupadd dev -g 1000
RUN useradd dev -g dev -d /home/dev -m
RUN echo '%dev ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers

I tried to create a dev user in my Dockerfile but not working.

Body:
I solved the problem by adding my dev user to sudoers and then running apache2ctl in sudo.

FROM php:7.4-apache

RUN apt-get update && apt-get install -y \
        sudo \
        libfreetype6-dev \
        libjpeg62-turbo-dev \
        libpng-dev \
        libzip-dev \
        git \
        zip \
        unzip \
    && docker-php-ext-configure gd --with-freetype --with-jpeg \
    && docker-php-ext-install -j$(nproc) gd \
    && docker-php-ext-install zip pdo pdo_mysql opcache \
    && apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

RUN rm /etc/localtime
RUN ln -s /usr/share/zoneinfo/Europe/Paris /etc/localtime
RUN "date"

RUN sed -ri -e 's!/var/www/html!/var/www!g' /etc/apache2/sites-available/*.conf
RUN sed -ri -e 's!/var/www/!/var/www!g' /etc/apache2/apache2.conf /etc/apache2/conf-available/*.conf

COPY php/php.ini /usr/local/etc/php/conf.d/app.ini
COPY apache/app.conf /etc/apache2/sites-available/000-default.conf

RUN groupadd dev -g 1000
RUN useradd dev -g dev -d /home/dev -m
RUN echo '%dev ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
USER dev:dev

CMD ["sudo", "/usr/sbin/apache2ctl", "-D", "FOREGROUND"]