问:
CSS Bootstrap overrides my own CSS
I am trying to create a split-button in my website (ASPNET WebForms). So far the only split-button implementation I like is the one from Bootstrap. I am not using any other feature of their framework. However, as soon as I insert:

```<code><link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css">
</code>```

My own css is a mess. I tried to isolate only the classes I would need for splitbutton, but I was not able to successfully do it.

This is my html code for the splitbutton with the requiered classes

```<code><div class="btn-group">
                          <button type="button" onclick="NewPost();return false;" class="btn btn-primary">Enviar</button>
                          <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown"><span class="caret"></span><span class="sr-only">Toggle Dropdown</span></button>
                          <ul class="dropdown-menu" role="menu">
                                <li><a href="#">Enviar con notificaciones</a></li>
                          </ul>
                    </div>
</code>```

Does anybody know a way to isolate the desire classes? Or may be point me to another implementation of a splitbutton that is similar to this one and cross-browser? I googled a lot but the only usable one I found was bootstrap.

答:
As they said before, the bootstrap css importation must be before the custom css.
Like this:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" >
<link rel="stylesheet" href="css/styles.css">
```

Title: CSS Bootstrap overrides my own CSS

Body:
I am trying to create a split-button in my website (ASPNET WebForms). So far the only split-button implementation I like is the one from Bootstrap. I am not using any other feature of their framework. However, as soon as I insert:

<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css">

My own css is a mess. I tried to isolate only the classes I would need for splitbutton, but I was not able to successfully do it.

This is my html code for the splitbutton with the requiered classes

                          <button type="button" onclick="NewPost();return false;" class="btn btn-primary">Enviar</button>
                          <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Toggle Dropdown</button>

Enviar con notificaciones

Does anybody know a way to isolate the desire classes? Or may be point me to another implementation of a splitbutton that is similar to this one and cross-browser? I googled a lot but the only usable one I found was bootstrap.


来源: stackexchange

问:
How can I have access into *argv[ ] in C?
Say that I have this part of code. If user does not enter the file names as command line arguments I want to ask him again so as to enter them now but as it seems I cannot have access in argv[1] and argv[2]. For example when the first scanf is executed segmentation fault occurs. But in this case how can I read the arguments and place them into argv[1] and argv[2]?
Thanks in advance for your help!</p>

```<code>int main (int argc, char **argv)
{
    if (argc != 3)
    {
        printf("You did not enter two files.\n");
        printf("You can now enter those two files.\n");
        printf("file 1: ");
        scanf("%s", argv[1]);
        printf("file 2: ");
        scanf("%s ", argv[2]);
    }

    printf("%s\n", argv[1]);
    printf("%s\n", argv[2]);

    FILE *file1 = fopen(argv[1], "r");
    FILE *file2 = fopen(argv[2], "r");
}
</code>```

答:
Argv is passed from console and you pass it while executing your program.

First, you have to compile it with, for example:

gcc program.c -o program

And then execute it with arguments, for example:

./program arg1 arg2

If you wish to wait for a user to enter parameters for your program through the console you should use regular variables.

ContentLicense: CC BY-SA 4.0

Body:
Say that I have this part of code. If user does not enter the file names as command line arguments I want to ask him again so as to enter them now but as it seems I cannot have access in argv[1] and argv[2]. For example when the first scanf is executed segmentation fault occurs. But in this case how can I read the arguments and place them into argv[1] and argv[2]?
Thanks in advance for your help!

int main (int argc, char **argv)
{
    if (argc != 3)
    {
        printf("You did not enter two files.\n");
        printf("You can now enter those two files.\n");
        printf("file 1: ");
        scanf("%s", argv[1]);
        printf("file 2: ");
        scanf("%s ", argv[2]);
    }

    printf("%s\n", argv[1]);
    printf("%s\n", argv[2]);

    FILE *file1 = fopen(argv[1], "r");
    FILE *file2 = fopen(argv[2], "r");
}


问:
Trouble in installing fast debugger on Netbeans IDE 6.9 for rails 3.0.1
I am trying to install the  fast debugger on netbeans IDE in ubuntu natty narwahl.I am receiving this error.How can i fix this?

```<code>    Building native extensions.  This could take a while...
    ERROR:  Error installing ruby-debug-ide:
        ERROR: Failed to build gem native extension.

            /home/roger/.rvm/rubies/ruby-1.9.2-p180/bin/ruby mkrf_conf.rb
    Building native extensions.  This could take a while...

rake RUBYARCHDIR=/home/roger/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/gems/1.9.1/gems/ruby-debug-ide-0.4.9/lib RUBYLIBDIR=/home/roger/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/gems/1.9.1/gems/ruby-debug-ide-0.4.9/lib
/home/roger/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems.rb:388:in `bin_path': can't find gem rake ([">= 0"]) with executable rake (Gem::GemNotFoundException)
    from /home/roger/.rvm/gems/ruby-1.9.2-p180/bin/rake:19:in `<main>'
</code>```

Thanks

P.s. :I have already checked out the link Cannot install Fast debugger in Netbeans 6.8 for Ruby 1.9 but i am not able to exactly comprehend how they have fixed this issue.

答:
I have found the solution.

hit 'gem env' on the command line and take note of the GEM paths

(1)GO to project properties.

(2)Select Rails

(3)Click on 'Manage' button corresponding to the ruby platform

(4)Now change the gem paths  & home path provided in the netbeans IDE for gems to the one you noted before.

This would solve your problem!!

ContentLicense: CC BY-SA 3.0

Body:
I am trying to install the  fast debugger on netbeans IDE in ubuntu natty narwahl.I am receiving this error.How can i fix this?

    Building native extensions.  This could take a while...
    ERROR:  Error installing ruby-debug-ide:
        ERROR: Failed to build gem native extension.

            /home/roger/.rvm/rubies/ruby-1.9.2-p180/bin/ruby mkrf_conf.rb
    Building native extensions.  This could take a while...

rake RUBYARCHDIR=/home/roger/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/gems/1.9.1/gems/ruby-debug-ide-0.4.9/lib RUBYLIBDIR=/home/roger/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/gems/1.9.1/gems/ruby-debug-ide-0.4.9/lib
/home/roger/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems.rb:388:in `bin_path': can't find gem rake ([">= 0"]) with executable rake (Gem::GemNotFoundException)
    from /home/roger/.rvm/gems/ruby-1.9.2-p180/bin/rake:19:in `'

Thanks

P.s. :I have already checked out the link Cannot install Fast debugger in Netbeans 6.8 for Ruby 1.9 but i am not able to exactly comprehend how they have fixed this issue.


问:
google test PrintTo for std::set<std::string>
In the google test Advanced documentation they say to write PrintTo in the same namespace that defines the value to be printed, which is great if it's your own class in your own namespace, but if it's std::set you aren't supposed to add new members to namespace std.

So how do you customize the PrintTo behavior for std::set<std::string>?  The default printer in google test stops printing after a certain number of values which isn't useful when the values that differ come after the ones emitted by the default printer.

```<code>#include <set>
#include <string>
#include <gtest/gtest.h>

void PrintTo(const std::set<std::string> &value, std::ostream *str)
{
    *str << "Got here!\n";
}

TEST(MapPrint, custom_printer)
{
    std::set<std::string> one{"foo"};
    std::set<std::string> two{"bar"};

    ASSERT_EQ(one, two); // doesn't print 'Got here!'
}
</code>```

答: What works is to define PrintTo in namespace testing::internal.  This still feels a little dirty to me.  Presumably the internal namespace is so that google test can change whatever implementation details they like in there without regard to backwards compatibility.  At least it doesn't result in undefined behavior as would defining PrintTo in namespace std.

Body:
In the google test Advanced documentation they say to write PrintTo in the same namespace that defines the value to be printed, which is great if it's your own class in your own namespace, but if it's std::set you aren't supposed to add new members to namespace std.

So how do you customize the PrintTo behavior for std::set<std::string>?  The default printer in google test stops printing after a certain number of values which isn't useful when the values that differ come after the ones emitted by the default printer.

#include <set>
#include <string>
#include <gtest/gtest.h>

void PrintTo(const std::set<std::string> &value, std::ostream *str)
{
    *str << "Got here!\n";
}

TEST(MapPrint, custom_printer)
{
    std::set<std::string> one{"foo"};
    std::set<std::string> two{"bar"};

    ASSERT_EQ(one, two); // doesn't print 'Got here!'
}


问:
Microsoft.AspNet.Web.Optimization JavaScript bundling fails to minify template literals
Using the latest version of Microsoft.AspNet.Web.Optimization v1.1.3 I am unable to get bundling to minify the JavaScript if it includes template literals. For example if I include the following in one of my bundle scripts:

```<code>var name = 'Bob';
var formattedName = `${name} says hello`;
</code>```

The resulting bundle will join all files but it won't minify code, and gives me this error:

```<code>/* Minification failed. Returning unminified contents.
(2,13-14): run-time error JS1014: Invalid character: `
(2,15-16): run-time error JS1004: Expected ';': {
(2,30-31): run-time error JS1014: Invalid character: `
(3,1-2): run-time error JS1107: Expecting more source characters
*/
</code>```

I understand this feature was only introduced in ECMAScript2015 and it's clearly not supported but is there a clean workaround other than reverting back to the old string concatenation methods?

```<code>var name = 'Bob';
var formattedName = name + ' says hello';
</code>```

Also, will template literal support go into future versions of Microsoft.AspNet.Web.Optimization?

答:
I am using the bundleconfig.json method for minifying some script files and I encountered similar errors when running the appropriate task:

```<code>Illegal assignment: =
Expected ';'
Expected ';'
Expected expression
Expected '}'
</code>```

I managed to change the literal from this:

```<code>style.textContent = `
...
`;
</code>```

To this:

```<code>style.textContent = `
...`;
</code>```

It will probably not answer your specific question (as you used Gulp), but might help someone out there, that doesn't want to start using npm's various packages for the same objective.

Body:
Using the latest version of Microsoft.AspNet.Web.Optimization v1.1.3 I am unable to get bundling to minify the JavaScript if it includes template literals. For example if I include the following in one of my bundle scripts:

var name = 'Bob';
var formattedName = `${name} says hello`;

The resulting bundle will join all files but it won't minify code, and gives me this error:

/* Minification failed. Returning unminified contents.
(2,13-14): run-time error JS1014: Invalid character: `
(2,15-16): run-time error JS1004: Expected ';': {
(2,30-31): run-time error JS1014: Invalid character: `
(3,1-2): run-time error JS1107: Expecting more source characters
*/

I understand this feature was only introduced in ECMAScript2015 and it's clearly not supported but is there a clean workaround other than reverting back to the old string concatenation methods?

var name = 'Bob';
var formattedName = name + ' says hello';

Also, will template literal support go into future versions of Microsoft.AspNet.Web.Optimization?

Body:
I am using the bundleconfig.json method for minifying some script files and I encountered similar errors when running the appropriate task:

Illegal assignment: =
Expected ';'
Expected ';'
Expected expression
Expected '}'

I managed to change the literal from this:

style.textContent = `
...
`;

To this:

style.textContent = `
...`;

It will probably not answer your specific question (as you used Gulp), but might help someone out there, that doesn't want to start using npm's various packages for the same objective.


问:
Pandas does not append rows within a loop
I have a following loop:

```<code>lines = []

for dicom in mydicoms:

    dcm1 = pydicom.dcmread(dicom)

    identity = dcm1.PatientID
    age = dcm1.PatientAge
    sex = dcm1.PatientSex
    modality = dcm1.Modality
    finding = dcm1.StudyDescription
    rows = dcm1.Rows
    columns = dcm1.Columns

    new_row = {'id':identity, 'age':age, 'sex':sex, 'modality':modality, 'finding':finding, 'rows':rows, 'columns':columns}
    df.append(new_row, ignore_index = True)

    lines.append(new_row)
</code>```

When I check df afterwards it is empty.

When I copy and paste parts of the code from the loop or do any of the following in another Jupyter cell:

```<code>df.append(new_row, ignore_index=True)

df.append(lines, ignore_index = True)
</code>```

it appends it correctly, just not inside the loop.

What am I missing?

答:
as mentioned by anky, you should assign it back to the df variable.

Here's your code with the correction:

```<code>lines = []

for dicom in mydicoms:

    dcm1 = pydicom.dcmread(dicom)

    identity = dcm1.PatientID
    age = dcm1.PatientAge
    sex = dcm1.PatientSex
    modality = dcm1.Modality
    finding = dcm1.StudyDescription
    rows = dcm1.Rows
    columns = dcm1.Columns

    new_row = {'id':identity, 'age':age, 'sex':sex, 'modality':modality, 'finding':finding, 'rows':rows, 'columns':columns}
    df = df.append(new_row, ignore_index = True)

    lines.append(new_row)
</code>```

Body:
I have a following loop:

lines = []

for dicom in mydicoms:

    dcm1 = pydicom.dcmread(dicom)

    identity = dcm1.PatientID
    age = dcm1.PatientAge
    sex = dcm1.PatientSex
    modality = dcm1.Modality
    finding = dcm1.StudyDescription
    rows = dcm1.Rows
    columns = dcm1.Columns

    new_row = {'id':identity, 'age':age, 'sex':sex, 'modality':modality, 'finding':finding, 'rows':rows, 'columns':columns}
    df.append(new_row, ignore_index = True)

    lines.append(new_row)

When I check df afterwards it is empty.

When I copy and paste parts of the code from the loop or do any of the following in another Jupyter cell:

df.append(new_row, ignore_index=True)

df.append(lines, ignore_index = True)

it appends it correctly, just not inside the loop.

What am I missing?

Body:
as mentioned by anky, you should assign it back to the df variable.

Here's your code with the correction:

lines = []

for dicom in mydicoms:

    dcm1 = pydicom.dcmread(dicom)

    identity = dcm1.PatientID
    age = dcm1.PatientAge
    sex = dcm1.PatientSex
    modality = dcm1.Modality
    finding = dcm1.StudyDescription
    rows = dcm1.Rows
    columns = dcm1.Columns

    new_row = {'id':identity, 'age':age, 'sex':sex, 'modality':modality, 'finding':finding, 'rows':rows, 'columns':columns}
    df = df.append(new_row, ignore_index = True)

    lines.append(new_row)


问:
How do I manage identities with ETL?
I need help figuring out a workflow and I'm not sure how to go about it... Let's say I'm transforming (ETL?) data from Table A to Table B. Table A has a composite primary key A.a+A.b+A.c, while Table B has just an automatically populated identity column. How can I map the composite keys from A back to the identities created when inserting into B?

Preferably I would like to not have any columns in table B related to A's composite key because there are many other tables that need to undergo the same operation but don't have the same composite key structure.

答:
Ask yourself exactly what you need the original keys for. The answer may vary depending on the source system. This may lead you to maintain a "source system" column and a "original source keys" column. The latter may need to be a comma-delimited list of the original keys.

Or, you may find that you never actually need to map back, so don't need to keep anything.

ContentLicense: CC BY-SA 2.5

Title: How do I manage identities with ETL?

OwnerDisplayName: John Saunders


问:
PHP MySQL insert values from multiple checkboxes into one column in table
I have a form that a user would fill out while creating a ticket for a bug they have found on our website.  In the form there is currently an input field where the user would enter in the designs that the bug is affecting (ex., "Design1, Design2, Design3, Design4" ...etc).  When the form is submitted the value is stored in a table column named affectedDesigns.

What i am wanting to do is create several checkboxes (one check box for each design we have) that a user would select instead of using the input field.  They would be able to select all that apply.  If possible i would still like to store all of the values into the affectedDesigns column in one record.  I'm thinking that i can gather the selected checkboxes values and create an array or some comma delimited value that contains all of the selected items and submit that to the databasein the one record in the affectedDesigns column.  How can i achieve this?

Also, how would i then pull that data and re-populate the checkboxes if they would like to go back later and edit the ticket?  Thanks for any help!

答: You'll end up using explode() and implode() to convert between string and array.


问:
How to Dynamically (Hard Coded) the context menu
I am trying to Dynamically (Hard Code) the Context menu in my .cs file instead of defining it inside my .xaml file.

So far I have defined the datagrid inside .cs file like this:

```<code>        DataGrid dgCM = new DataGrid();
        dgCM.Style = (Style)FindResource("DgCustomStyle");
        dgCM.ItemsSource = MainWindow.m_DtTagList.DefaultView;

        dgCM.GridLinesVisibility = DataGridGridLinesVisibility.All;
        dgCM.VerticalGridLinesBrush = Brushes.Black;
        dgCM.AutoGenerateColumns = true;
        dgCM.CanUserAddRows = true;
        dgCM.CanUserDeleteRows = true;
        dgCM.IsReadOnly = false;

        dgCM.SelectionMode = DataGridSelectionMode.Extended;
        dgCM.SelectionUnit = DataGridSelectionUnit.FullRow;

        dgCM.MouseDoubleClick += DgCM_Row_DoubleClick;

        dgCM.Margin = new Thickness(0, 10, 0, 0);
</code>```

Now My aim is to define in similar way the Context menu for it having 3 options Copy, paste and delete when I right click.
Could someone suggest me a solution for it?
Looking forward for your replies.
Thank you

答:
You do that by adding following code:</p>

```<code> MenuItem copy = new MenuItem() { Header = "_Copy" };
 copy.Click += (s, e) =>
 {
    // Do something
 };
 MenuItem paste = new MenuItem() { Header = "_Paste" };
 paste.Click += (s, e) =>
 {
    // Do something
 };
 MenuItem cut = new MenuItem() { Header = "_Cut" };
 cut.Click += (s, e) =>
 {
    // Do something
 };
 dgCM.ContextMenu = new ContextMenu();
 dgCM.ContextMenu.Items.Add(copy);
 dgCM.ContextMenu.Items.Add(paste);
 dgCM.ContextMenu.Items.Add(cut);
</code>```

Body:
I am trying to Dynamically (Hard Code) the Context menu in my .cs file instead of defining it inside my .xaml file.

So far I have defined the datagrid inside .cs file like this:

        DataGrid dgCM = new DataGrid();
        dgCM.Style = (Style)FindResource("DgCustomStyle");
        dgCM.ItemsSource = MainWindow.m_DtTagList.DefaultView;

        dgCM.GridLinesVisibility = DataGridGridLinesVisibility.All;
        dgCM.VerticalGridLinesBrush = Brushes.Black;
        dgCM.AutoGenerateColumns = true;
        dgCM.CanUserAddRows = true;
        dgCM.CanUserDeleteRows = true;
        dgCM.IsReadOnly = false;

        dgCM.SelectionMode = DataGridSelectionMode.Extended;
        dgCM.SelectionUnit = DataGridSelectionUnit.FullRow;

        dgCM.MouseDoubleClick += DgCM_Row_DoubleClick;

        dgCM.Margin = new Thickness(0, 10, 0, 0);

Now My aim is to define in similar way the Context menu for it having 3 options Copy, paste and delete when I right click.
Could someone suggest me a solution for it?
Looking forward for your replies.
Thank you

Body:
You do that by adding following code:

 MenuItem copy = new MenuItem() { Header = "_Copy" };
 copy.Click += (s, e) =>
 {
    // Do something
 };
 MenuItem paste = new MenuItem() { Header = "_Paste" };
 paste.Click += (s, e) =>
 {
    // Do something
 };
 MenuItem cut = new MenuItem() { Header = "_Cut" };
 cut.Click += (s, e) =>
 {
    // Do something
 };
 dgCM.ContextMenu = new ContextMenu();
 dgCM.ContextMenu.Items.Add(copy);
 dgCM.ContextMenu.Items.Add(paste);
 dgCM.ContextMenu.Items.Add(cut);


问:
Django: Can't get current logged in user in DRF RetrieveUpdateDestroyAPIView
I want to return the reports written by the currently logged in author. I have defined a custom user model through AbstractBaseUser. I want to use RetrieveUpdateDestroyAPIView so that the author can retrieve as well as edit and delete reports.

I defined these models: CustomUser, used as default user model and for authentication. ReporterProfile, users need to fill this model when they promote themselves as authors. . The Report model stores all submitted reports. The reporterprofile field in Report model has a ForeignKey relationship with the ReporterProfile model, which in turn, has a ForeignKey relation with CustomUser model.

My model definitions:

```<code>class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(default=timezone.now)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

class ReporterProfile(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    dob = models.DateField(auto_now=False, blank=True, help_text="YYYY-MM-DD")
    sex = models.CharField(max_length=22, choices=SEX_CHOICES)
    avatar = models.ImageField(upload_to=user_directory_path)
</code>```

This is my view:

```<code>class MyReportsView(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = (permissions.IsAuthenticated,)
    serializer_class = ReportSerializer(request.user)
    queryset = Report.objects.all()  # need to get the currently logged in user
</code>```

With this, I am getting the error: NameError: name 'request' is not defined.

This is my serializer:

```<code>class ReportSerializer(serializers.ModelSerializer):
    class Meta:
        model = Report
        fields = ('reporterprofile', 'slug', 'title', 'column', 'summary', 'body', 'created', 'modified', 'published',)
</code>```

How do I fetch the reports submitted by the currently logged in user?

答:
Override the get_queryset() method

```<code>class MyReportsView(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = (permissions.IsAuthenticated,)
    <b>serializer_class = ReportSerializer

    def get_queryset(self):
        return Report.objects.filter(reporterprofile__user=self.request.user)</b></code>```

You can access the current logged-in user by calling self.request.user in anywhere in the view class.

Note: The expression filter(user=self.request.user) probably make some field error since there is no direct relation with Auth user model in Report

Body:
I want to return the reports written by the currently logged in author. I have defined a custom user model through AbstractBaseUser. I want to use RetrieveUpdateDestroyAPIView so that the author can retrieve as well as edit and delete reports.

I defined these models: CustomUser, used as default user model and for authentication. ReporterProfile, users need to fill this model when they promote themselves as authors. . The Report model stores all submitted reports. The reporterprofile field in Report model has a ForeignKey relationship with the ReporterProfile model, which in turn, has a ForeignKey relation with CustomUser model.

My model definitions:

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(default=timezone.now)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

class ReporterProfile(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    dob = models.DateField(auto_now=False, blank=True, help_text="YYYY-MM-DD")
    sex = models.CharField(max_length=22, choices=SEX_CHOICES)
    avatar = models.ImageField(upload_to=user_directory_path)

This is my view:

class MyReportsView(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = (permissions.IsAuthenticated,)
    serializer_class = ReportSerializer(request.user)
    queryset = Report.objects.all()  # need to get the currently logged in user

With this, I am getting the error: NameError: name 'request' is not defined.

This is my serializer:

class ReportSerializer(serializers.ModelSerializer):
    class Meta:
        model = Report
        fields = ('reporterprofile', 'slug', 'title', 'column', 'summary', 'body', 'created', 'modified', 'published',)

How do I fetch the reports submitted by the currently logged in user?

Body:
Override the get_queryset() method

class MyReportsView(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = (permissions.IsAuthenticated,)
    serializer_class = ReportSerializer

    def get_queryset(self):
        return Report.objects.filter(reporterprofile__user=self.request.user)

You can access the current logged-in user by calling self.request.user in anywhere in the view class.

Note: The expression filter(user=self.request.user) probably make some field error since there is no direct relation with Auth user model in Report


问:
dplyr filter removing NA when that was not specified
Consider the following data:

```<code>library(tidyverse)
df <- tibble(col1 = c("A", "", NA),
             col2 = 5:7)
#> # A tibble: 3 x 2
#>   col1   col2
#>   <chr> <int>
#> 1 "A"       5
#> 2 ""        6
#> 3  NA       7
</code>```

I'm trying to filter out blanks from the data frame above with the following code

```<code>df %>% filter(col1 != "")
#> # A tibble: 1 x 2
#>   col1   col2
#>   <chr> <int>
#> 1 A         5
</code>```

Why are NA removed in addition to blanks? I did not include df %>% filter(!is.na(col1)), nor drop_na(), nor na.exclude(), etc. in my filter call, so I wouldn't think the NA row should be filtered out of the data frame.

How do I filter out blanks, but keep the NA? An explanation would be preferred as well. Thank you.

答: I don't know why that is happening, it shouldn't, but why don't you just assing a value to NA's, remove blanks and then assing those values to NA's again</p>

Body:
Consider the following data:

library(tidyverse)
df <- tibble(col1 = c("A", "", NA),
             col2 = 5:7)
#> # A tibble: 3 x 2
#>   col1   col2
#>   <chr> <int>
#> 1 "A"       5
#> 2 ""        6
#> 3  NA       7

I'm trying to filter out blanks from the data frame above with the following code

df %>% filter(col1 != "")
#> # A tibble: 1 x 2
#>   col1   col2
#>   <chr> <int>
#> 1 A         5

Why are NA removed in addition to blanks? I did not include df %>% filter(!is.na(col1)), nor drop_na(), nor na.exclude(), etc. in my filter call, so I wouldn't think the NA row should be filtered out of the data frame.

How do I filter out blanks, but keep the NA? An explanation would be preferred as well. Thank you.


问:
How to make change email address form in profile in Laravel
I did password change successfully but i had troubles for email change which i think it would be easier but for some reason couldn't think how to do it.

Old email:

New email:

Confirm new email:

This is the form i wanna make it but cant solve the Controllers function.

This is how i tried to solve it

```<code>public function changeemailPost(Request $request)
    {

        if (!(Hash::check($request->get('email'), Auth::user()->email))) {
            return redirect()->back()->with("error","Your current e-mail does not matches with the e-mail you provided. Please try again.");
        }

        if(strcmp($request->get('email'), $request->get('new-email')) == 0){
            return redirect()->back()->with("error","New e-mail cannot be same as your current e-mail. Please choose a different e-mail.");
        }

            $validate = $request->validate([
                'email' => 'required',
                'new-email' => 'required|string|min:6|confirmed',
            ]);
            $user = Auth::user();
            $user->email = $request['new-email'];
            $user->save();
            Auth::logout();
            return view('auth.login');
        }
</code>```

This is the html

```<code><form method="POST" action="{{ route('change-emailPost') }}">
                            @csrf
                            <label>Enter your old e-mail:</label>

                            <fieldset class="youplay-input">
                                <input id="current-email" type="email" class="form-control" placeholder="Current E-Mail" name="email" required>
                            </fieldset>

                            <label>Enter your new e-mail:</label>

                            <fieldset class="youplay-input">
                                <input id="new-email" type="email" placeholder="New E-Mail" class="form-control" name="new-email" required>
                            </fieldset>

                            <fieldset class="youplay-input">
                                <input id="new-email-confirm" type="email" class="form-control" placeholder="Confirm New E-Mail" name="new-email-confirmation" required>
                            </fieldset>
                            <button type="submit" class="btn btn-default db">
                                Change E-Mail
                            </button>
                        </form>
</code>```

But i only get this error

Your current e-mail does not matches with the e-mail you provided. Please try again

The problem got fixed thanks to the answer below but one thing you should change is the Hash checks for errors in email, instead of:

```<code>if (!(Hash::check($request->get('email'), Auth::user()->email))) {
            return redirect()->back()->with("error","Your current e-mail does not matches with the e-mail you provided. Please try again.");
        }

        if(strcmp($request->get('email'), $request->get('new-email')) == 0){
            return redirect()->back()->with("error","New e-mail cannot be same as your current e-mail. Please choose a different e-mail.");
        }
</code>```

Use this:

```<code>if(Auth::user()->email != $request['email']){
            return redirect()->back()->with("error","Your email doesnt not match with what you provided");
        }
        if(Auth::user()->email === $request['new-email']){
            return redirect()->back()->with("error", "Your new email cannot be the same as the old email");
        }
</code>```

答:
You need change your changeemailPost function. Try this -

```<code>public function changeemailPost(Request $request)
{

    if (!(Hash::check($request->get('email'), Auth::user()->email))) {
        return redirect()->back()->with("error","Your current e-mail does not matches with the e-mail you provided. Please try again.");
    }

    if(strcmp($request->get('email'), $request->get('new-email')) == 0){
        return redirect()->back()->with("error","New e-mail cannot be same as your current e-mail. Please choose a different e-mail.");
    }

        $validate = $request->validate([
            'new-email' => 'required|string|min:6|confirmed',
            'new-email_confirmation' => 'required|string|min:6',
        ]);
        $user = Auth::user();
        $user->email = $request['new-email'];
        $user->save();
        Auth::logout();
        return view('auth.login');
    }
</code>```

And your HTML like below -

```<code><form method="POST" action="{{ route('change-emailPost') }}">
                        @csrf
                        <label>Enter your old e-mail:</label>

                        <fieldset class="youplay-input">
                            <input id="current-email" type="email" class="form-control" placeholder="Current E-Mail" name="email" required>
                        </fieldset>

                        <label>Enter your new e-mail:</label>

                        <fieldset class="youplay-input">
                            <input id="new-email" type="email" placeholder="New E-Mail" class="form-control" name="new-email" required>
                        </fieldset>

                        <fieldset class="youplay-input">
                            <input id="new-email-confirm" type="email" class="form-control" placeholder="Confirm New E-Mail" name="new-email_confirmation" required>
                        </fieldset>
                        <button type="submit" class="btn btn-default db">
                            Change E-Mail
                        </button>
                    </form>
</code>```

If you want to compare two input field a & b with value with confirmed validation rules b field should be renamed as b_confirmation.

Reference - https://laravel.com/docs/7.x/validation#rule-confirmed

Body:
I did password change successfully but i had troubles for email change which i think it would be easier but for some reason couldn't think how to do it.

Old email:

New email:

Confirm new email:

This is the form i wanna make it but cant solve the Controllers function.

This is how i tried to solve it

public function changeemailPost(Request $request)
    {

        if (!(Hash::check($request->get('email'), Auth::user()->email))) {
            return redirect()->back()->with("error","Your current e-mail does not matches with the e-mail you provided. Please try again.");
        }

        if(strcmp($request->get('email'), $request->get('new-email')) == 0){
            return redirect()->back()->with("error","New e-mail cannot be same as your current e-mail. Please choose a different e-mail.");
        }

            $validate = $request->validate([
                'email' => 'required',
                'new-email' => 'required|string|min:6|confirmed',
            ]);
            $user = Auth::user();
            $user->email = $request['new-email'];
            $user->save();
            Auth::logout();
            return view('auth.login');
        }

This is the html

<form method="POST" action="{{ route('change-emailPost') }}">
                            @csrf
                            Enter your old e-mail:

                            <fieldset class="youplay-input">
                                <input id="current-email" type="email" class="form-control" placeholder="Current E-Mail" name="email" required>
                            </fieldset>

                            Enter your new e-mail:

                            <fieldset class="youplay-input">
                                <input id="new-email" type="email" placeholder="New E-Mail" class="form-control" name="new-email" required>
                            </fieldset>

                            <fieldset class="youplay-input">
                                <input id="new-email-confirm" type="email" class="form-control" placeholder="Confirm New E-Mail" name="new-email-confirmation" required>
                            </fieldset>
                            <button type="submit" class="btn btn-default db">
                                Change E-Mail
                            </button>
                        </form>

But i only get this error

Your current e-mail does not matches with the e-mail you provided. Please try again

The problem got fixed thanks to the answer below but one thing you should change is the Hash checks for errors in email, instead of:

if (!(Hash::check($request->get('email'), Auth::user()->email))) {
            return redirect()->back()->with("error","Your current e-mail does not matches with the e-mail you provided. Please try again.");
        }

        if(strcmp($request->get('email'), $request->get('new-email')) == 0){
            return redirect()->back()->with("error","New e-mail cannot be same as your current e-mail. Please choose a different e-mail.");
        }

Use this:

if(Auth::user()->email != $request['email']){
            return redirect()->back()->with("error","Your email doesnt not match with what you provided");
        }
        if(Auth::user()->email === $request['new-email']){
            return redirect()->back()->with("error", "Your new email cannot be the same as the old email");
        }

Body:
You need change your changeemailPost function. Try this -

public function changeemailPost(Request $request)
{

    if (!(Hash::check($request->get('email'), Auth::user()->email))) {
        return redirect()->back()->with("error","Your current e-mail does not matches with the e-mail you provided. Please try again.");
    }

    if(strcmp($request->get('email'), $request->get('new-email')) == 0){
        return redirect()->back()->with("error","New e-mail cannot be same as your current e-mail. Please choose a different e-mail.");
    }

        $validate = $request->validate([
            'new-email' => 'required|string|min:6|confirmed',
            'new-email_confirmation' => 'required|string|min:6',
        ]);
        $user = Auth::user();
        $user->email = $request['new-email'];
        $user->save();
        Auth::logout();
        return view('auth.login');
    }

And your HTML like below -

<form method="POST" action="{{ route('change-emailPost') }}">
                        @csrf
                        <label>Enter your old e-mail:</label>

                        <fieldset class="youplay-input">
                            <input id="current-email" type="email" class="form-control" placeholder="Current E-Mail" name="email" required>
                        </fieldset>

                        <label>Enter your new e-mail:</label>

                        <fieldset class="youplay-input">
                            <input id="new-email" type="email" placeholder="New E-Mail" class="form-control" name="new-email" required>
                        </fieldset>

                        <fieldset class="youplay-input">
                            <input id="new-email-confirm" type="email" class="form-control" placeholder="Confirm New E-Mail" name="new-email_confirmation" required>
                        </fieldset>
                        <button type="submit" class="btn btn-default db">
                            Change E-Mail
                        </button>
                    </form>

If you want to compare two input field a & b with value with confirmed validation rules b field should be renamed as b_confirmation.

Reference - https://laravel.com/docs/7.x/validation#rule-confirmed


问:
Image isn't uploading to database from form django
images which are collected through the form are not uploaded to the database

how to fix this issue

please help me

views.py

```<code>class club(ListView):
    model = UserProfile
    template_name = "club.html"
    def post(self, *args ,**kwargs):
        if self.request.method == 'POST':
            self.request.user.userprofile.userphoto = self.request.FILES.get('image')
            self.request.user.userprofile.phone_number = self.request.POST.get('userphonenumber')
            self.request.user.userprofile.Isclubmem = True
            self.request.user.userprofile.save()
            return redirect('core:home')
</code>```

club.html

```<code><div class="container">
            <form action="." method="POST">
                {%csrf_token%}
                <b>Register:<br><br></b>
                Profile Pic:
                <input name="image" accept=".png,.jpg,.jpeg" type="file" value=selectimage><br><br>
                Phonenumber:
                <input name="userphonenumber" type="number" placeholder="+91 9876543210" ><br><br>
                <input type="submit" value="submit" class="btn btn-success">
            </form>
        </div>
</code>```

models.py

```<code>class UserProfile(models.Model):
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    stripe_customer_id = models.CharField(max_length=50, blank=True, null=True)
    Isclubmem = models.BooleanField(default=False)
    one_click_purchasing = models.BooleanField(default=False)
    userphoto = models.ImageField(upload_to='images/', null=True)
    phone_number = models.IntegerField(default=False)
    usermoney = models.FloatField(default=0.0)
    def __str__(self):
        return self.user.username
</code>```

答:
The form should specify enctype="multipart/form-data" if you want to upload files, so:

```<code><form action="." method="POST" <b>enctype="multipart/form-data"</b>>
    …
</form></code>```

Body:
images which are collected through the form are not uploaded to the database

how to fix this issue

please help me

views.py

class club(ListView):
    model = UserProfile
    template_name = "club.html"
    def post(self, *args ,**kwargs):
        if self.request.method == 'POST':
            self.request.user.userprofile.userphoto = self.request.FILES.get('image')
            self.request.user.userprofile.phone_number = self.request.POST.get('userphonenumber')
            self.request.user.userprofile.Isclubmem = True
            self.request.user.userprofile.save()
            return redirect('core:home')

club.html

            <form action="." method="POST">
                {%csrf_token%}
                Register:

                Profile Pic:
                <input name="image" accept=".png,.jpg,.jpeg" type="file" value=selectimage>

                Phonenumber:
                <input name="userphonenumber" type="number" placeholder="+91 9876543210" >

                <input type="submit" value="submit" class="btn btn-success">
            </form>

models.py

class UserProfile(models.Model):
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    stripe_customer_id = models.CharField(max_length=50, blank=True, null=True)
    Isclubmem = models.BooleanField(default=False)
    one_click_purchasing = models.BooleanField(default=False)
    userphoto = models.ImageField(upload_to='images/', null=True)
    phone_number = models.IntegerField(default=False)
    usermoney = models.FloatField(default=0.0)
    def __str__(self):
        return self.user.username

Body:
The form should specify enctype="multipart/form-data" if you want to upload files, so:

<form action="." method="POST" enctype="multipart/form-data">
    …
</form>


问:
How to share large set of files between kuberntes pods
I have a large set of read-only configuration files (around 4k) which is used by the microservice to process some XML files and supposed to be read via Apache Commons Configuration.

These files are of the following types:

Properties file

XML

dtd

xfo

xslt

5 of these files will need some environment variables to be substituted in their content, such as third party software location, or different services URL based on the environment the files are deployed in.

Now, I need to make these files available for 4 microservices at run time.

I'm using fabric8.io maven docker plugin with dockerfile for image generation.
Kubernetes, helm, Jenkinsfile, and ArgoCD for the spring-boot microservices CD/CI.

The 2 challenges that I'm facing is how to substitute the variables inside of these static files, and how to make these files available for each pod.

I have three solutions in mind but I would like to know what is the best/optimal 12-factor approach for this problem.

Solution 1: is to deploy the files as a separate pod and allow other pods to access to some volume mount that it provides.

Solution  2: Add the files to the microservice image during the docker image build.

Solution  3: Add the files as a container of each microservice pod.

答:
There is another solution: mounting the files as a volume (backed by cloud storage) and substituting values on-access within the service and that's a solution I'd go with by default.

Solutions 1 and especially 3 add a lot of complexity. Solution 2 may be a good choice too, however to choose the best option you really need to answer another question - how are the config files and env substitutions changing with respect to the application container versions?

i.e. When you change the files, should all of the services get new versions?


问:
How do I handle a ManyToMany relationship in JSON?
This is a follow-up question to my previous question on "Managing employee contracts in a many-to-many relationship?" and this question

I have a relationship that can be explained thusly:

company --< contracts >-- employees

I am importing the data through JSON.  For simplicity sake it is shown below.

```<code>{
  "companies" : [
    {
      "name" : "Company A",
      "employees" : [
        {
          "name" : "Tom",
          "contract" : {
            "length" : "10",
            "salary" : "10000"
          }
        }
      ]
    }
  ]
}
</code>```

The problem is, I am not sure if this is correct.

In my Model relationship the contract sits between company and employees whereas in my above code I've put it as an object and it sits as a child under the employees.

Therefore, my question is, where should a junction table sit within the JSON feed?

Should it sit as a parent to employees, or is it okay where it is?

I'm not sure if I am doing it right and would welcome any help/thoughts on the best way to structure/layout a JSON feed that is reliant upon a junction table.

I know it may seem silly, but I'm trying to ascertain best standards when dealing with junction tables.

Thanks.

Edit.

Purpose/Context

I am attempting to read in JSON into Core data using TouchJSON.  Apologies for not clarifying the context earlier.  Updated tags.

I read the JSON into a NSDictionary.  If I start to separate the objects out I am not sure how to make TouchJSON/iOS understand the context of each relationship when it comes to parse/read the data into memory.

答:
The only way to accomplish this without foreign keys is to duplicate one side of the 'many' entities in your relationship.  Based on your example above, this would mean duplicating employees throughout the data structure.

You can really only get around this problem the same way that your relational database gets around the problem - with a mapping table and foreign keys.

```<code>{
  "companies" : [
    {
      "id" : 1,
      "name" : "Company A"
    }
  ],

  "employees" : [
    {
      "id" : 1,
      "name" : "Fred"
    }
  ],

  "contracts" : [
    {
      "id" : 123,
      "company_id" : 1,
      "employee_id": 1
      "length" : 10,
      "salary" : 10000
    }
  ]
}
</code>```

(As an aside, numerical values are valid in JSON, they do not need to be quoted)

The question, then, is if you have those keys available to you at the time of serialization.  If not, then you may need to assign some, if even temporarily for the purposes of the JSON, to accomplish your goal.

Body:
This is a follow-up question to my previous question on "Managing employee contracts in a many-to-many relationship?" and this question

I have a relationship that can be explained thusly:

company --< contracts >-- employees

I am importing the data through JSON.  For simplicity sake it is shown below.

{
  "companies" : [
    {
      "name" : "Company A",
      "employees" : [
        {
          "name" : "Tom",
          "contract" : {
            "length" : "10",
            "salary" : "10000"
          }
        }
      ]
    }
  ]
}

The problem is, I am not sure if this is correct.

In my Model relationship the contract sits between company and employees whereas in my above code I've put it as an object and it sits as a child under the employees.

Therefore, my question is, where should a junction table sit within the JSON feed?

Should it sit as a parent to employees, or is it okay where it is?

I'm not sure if I am doing it right and would welcome any help/thoughts on the best way to structure/layout a JSON feed that is reliant upon a junction table.

I know it may seem silly, but I'm trying to ascertain best standards when dealing with junction tables.

Thanks.

Edit.

Purpose/Context

I am attempting to read in JSON into Core data using TouchJSON.  Apologies for not clarifying the context earlier.  Updated tags.

I read the JSON into a NSDictionary.  If I start to separate the objects out I am not sure how to make TouchJSON/iOS understand the context of each relationship when it comes to parse/read the data into memory.

Body:
The only way to accomplish this without foreign keys is to duplicate one side of the 'many' entities in your relationship.  Based on your example above, this would mean duplicating employees throughout the data structure.

You can really only get around this problem the same way that your relational database gets around the problem - with a mapping table and foreign keys.

{
  "companies" : [
    {
      "id" : 1,
      "name" : "Company A"
    }
  ],

  "employees" : [
    {
      "id" : 1,
      "name" : "Fred"
    }
  ],

  "contracts" : [
    {
      "id" : 123,
      "company_id" : 1,
      "employee_id": 1
      "length" : 10,
      "salary" : 10000
    }
  ]
}

(As an aside, numerical values are valid in JSON, they do not need to be quoted)

The question, then, is if you have those keys available to you at the time of serialization.  If not, then you may need to assign some, if even temporarily for the purposes of the JSON, to accomplish your goal.


问:
Typo3 9 Routing config generating 404 error
We have a Typo3 9 server with a number of websites running on it. We also have the news plugin to facilitate the addition of blog posts.

With Typo3 9 the old RealURL system has been depricated in favour of a built in system. This is working for the normal pages but is not working for the news articles.

We have implemented the following YAML confic file which is based off the examples provided by the news plugin and a number of other stack overflow posts. The problem is that while we can confirm that the config is loaded, we get a 404 error:

```<code>404 Page not found!

Reason: The requested page does not exist

Current URL: /blog/2020-january/
</code>```

We then commenced in depth, line by line examinantion of the code to understand what is going wrong. We did manage to render the /blog/2020-january/ page, but it had no content. None of the individual blog pages resolve either.

Are there other configurations that we should look for to enable this functionality? We have had another Typo3 person look at the problem without success.

```<code>rootPageId: 156
base: 'https://example.site'
baseVariants: {  }
languages:
  -
    title: English
    enabled: true
    languageId: '0'
    base: /
    typo3Language: default
    locale: en_AU
    iso-639-1: en
    navigationTitle: ''
    hreflang: ''
    direction: ''
    flag: au
errorHandling: {  }
routes: {  }
routeEnhancers:
    PageTypeSuffix:
      type: PageType
      default: '/'
      index: '/'
      map:
        '/': 0
    NewsPlugin:
        type: Extbase
        extension: News
        plugin: Pi1
        limitToPages:
          - 187
          - 201
        routes:
          # Detail view:
          - routePath: '/{news_title}'
            _controller: 'News::detail'
            _arguments: {'news_title': 'news'}
          # Categories:
          - routePath: '/{category}'
            _controller: 'News::list'
            _arguments: {'category': 'overwriteDemand/categories'}
          # Tags:
          - routePath: '/{tag_name}'
            _controller: 'News::list'
            _arguments: {'tag_name': 'overwriteDemand/tags'}
          # Pagination:
          - routePath: '/{page}'
            _controller: 'News::list'
            _arguments: {'page': '@widget_0/currentPage'}
          # Archive:
          - routePath: '/{localized_archive}/{year}/{month}'
            _controller: 'News::archive'
          # Date:
          - routePath: '/{year}-{month}'
            _controller: 'News::list'
            _arguments:
              year: overwriteDemand/year
              month: overwriteDemand/month
        defaultController: 'News::list'
        defaults:
            page: '0'
            year: ''
            month: ''
        requirements:
            page: '\d+'
            news_title: '^[a-zA-Z0-9].*$'
        aspects:
            page:
                type: StaticRangeMapper
                start: '1'
                end: '100'
            news_title:
                type: PersistedPatternMapper
                tableName: tx_news_domain_model_news
                routeFieldPattern: '^(?P<path_segment>.+)$'
                routeFieldResult: '{path_segment}'
            category:
                type: PersistedAliasMapper
                tableName: 'sys_category'
                routeFieldName: 'title'
            tag_name:
                type: PersistedAliasMapper
                tableName: 'tx_news_domain_model_tag'
                routeFieldName: 'title'
            localized_archive:
                type: LocaleModifier
                default: 'archive'
                routeFieldName: 'title'
                localeMap:
                  - languageId: 'de_.*'
                    value: 'archiv'
                  - languageId: 'fr_.*'
                    value: 'archives'
            year:
                type: StaticRangeMapper
                start: '1970'
                end: '2099'
            month:
                type: StaticValueMapper
                map:
                  january: '01'
                  february: '02'
                  march: '03'
                  april: '04'
                  may: '05'
                  june: '06'
                  july: '07'
                  august: '08'
                  september: '09'
                  october: 10
                  november: 11
                  december: 12
</code>```

答:
```<code>Please check your code see below code of news_title
</code>```

routeEnhancers: News: type: Extbase extension: News plugin: Pi1 routes: - routePath: '/{news-title}' _controller: 'News::detail' _arguments: news-title: news aspects: news-title: type: PersistedAliasMapper tableName: tx_news_domain_model_news routeFieldName: path_segment

Remove curly braces from path_segment, remove do it as above or in docs thank you

Please see the official documents https://docs.typo3.org/p/georgringer/news/7.2/en-us/AdministratorManual/BestPractice/Routing/Index.html

Body:
We have a Typo3 9 server with a number of websites running on it. We also have the news plugin to facilitate the addition of blog posts.

With Typo3 9 the old RealURL system has been depricated in favour of a built in system. This is working for the normal pages but is not working for the news articles.

We have implemented the following YAML confic file which is based off the examples provided by the news plugin and a number of other stack overflow posts. The problem is that while we can confirm that the config is loaded, we get a 404 error:

404 Page not found!

Reason: The requested page does not exist

Current URL: /blog/2020-january/

We then commenced in depth, line by line examinantion of the code to understand what is going wrong. We did manage to render the /blog/2020-january/ page, but it had no content. None of the individual blog pages resolve either.

Are there other configurations that we should look for to enable this functionality? We have had another Typo3 person look at the problem without success.

rootPageId: 156
base: 'https://example.site'
baseVariants: {  }
languages:
  -
    title: English
    enabled: true
    languageId: '0'
    base: /
    typo3Language: default
    locale: en_AU
    iso-639-1: en
    navigationTitle: ''
    hreflang: ''
    direction: ''
    flag: au
errorHandling: {  }
routes: {  }
routeEnhancers:
    PageTypeSuffix:
      type: PageType
      default: '/'
      index: '/'
      map:
        '/': 0
    NewsPlugin:
        type: Extbase
        extension: News
        plugin: Pi1
        limitToPages:
          - 187
          - 201
        routes:
          # Detail view:
          - routePath: '/{news_title}'
            _controller: 'News::detail'
            _arguments: {'news_title': 'news'}
          # Categories:
          - routePath: '/{category}'
            _controller: 'News::list'
            _arguments: {'category': 'overwriteDemand/categories'}
          # Tags:
          - routePath: '/{tag_name}'
            _controller: 'News::list'
            _arguments: {'tag_name': 'overwriteDemand/tags'}
          # Pagination:
          - routePath: '/{page}'
            _controller: 'News::list'
            _arguments: {'page': '@widget_0/currentPage'}
          # Archive:
          - routePath: '/{localized_archive}/{year}/{month}'
            _controller: 'News::archive'
          # Date:
          - routePath: '/{year}-{month}'
            _controller: 'News::list'
            _arguments:
              year: overwriteDemand/year
              month: overwriteDemand/month
        defaultController: 'News::list'
        defaults:
            page: '0'
            year: ''
            month: ''
        requirements:
            page: '\d+'
            news_title: '^[a-zA-Z0-9].*$'
        aspects:
            page:
                type: StaticRangeMapper
                start: '1'
                end: '100'
            news_title:
                type: PersistedPatternMapper
                tableName: tx_news_domain_model_news
                routeFieldPattern: '^(?P<path_segment>.+)$'
                routeFieldResult: '{path_segment}'
            category:
                type: PersistedAliasMapper
                tableName: 'sys_category'
                routeFieldName: 'title'
            tag_name:
                type: PersistedAliasMapper
                tableName: 'tx_news_domain_model_tag'
                routeFieldName: 'title'
            localized_archive:
                type: LocaleModifier
                default: 'archive'
                routeFieldName: 'title'
                localeMap:
                  - languageId: 'de_.*'
                    value: 'archiv'
                  - languageId: 'fr_.*'
                    value: 'archives'
            year:
                type: StaticRangeMapper
                start: '1970'
                end: '2099'
            month:
                type: StaticValueMapper
                map:
                  january: '01'
                  february: '02'
                  march: '03'
                  april: '04'
                  may: '05'
                  june: '06'
                  july: '07'
                  august: '08'
                  september: '09'
                  october: 10
                  november: 11
                  december: 12

Body:
Please check your code see below code of news_title

routeEnhancers: News: type: Extbase extension: News plugin: Pi1 routes: - routePath: '/{news-title}' _controller: 'News::detail' _arguments: news-title: news aspects: news-title: type: PersistedAliasMapper tableName: tx_news_domain_model_news routeFieldName: path_segment

Remove curly braces from path_segment, remove do it as above or in docs thank you

Please see the official documents https://docs.typo3.org/p/georgringer/news/7.2/en-us/AdministratorManual/BestPractice/Routing/Index.html


问:
Display message on screen of iframe src is empty
I want to display a message "Please click on a match to get started" when there is no match link clicked. i.e. the iframe is without an src. I am using django at the backend. Here is my html:</p>

```<code>  </form><br>
      {% for match in all_matches %}
      <li style="list-style:none; text-align: center"><a style="padding: 6px 8px 6px 16px;text-decoration: none;font-size: 18px;color: #ffffff;display: block;" href="{{match.url}}" target="iframe1">{{match.name}}</a></li>
      <hr class="new1">
      {% endfor %}
    </div>

  <div class="col-sm-9 col-xs-9 col-md-9 col-lg-9" id="frameContainer">

  <iframe name="iframe1" id="fr" style="display: block;" width=100% height=100% frameborder="0" allowFullScreen="true"></iframe>
  </div>
</code>```

答: Probably the simplest way to do this is to have a static HTML file as the initial iframe source, which contains the message.</p>

Body:
I want to display a message "Please click on a match to get started" when there is no match link clicked. i.e. the iframe is without an src. I am using django at the backend. Here is my html:

  </form>

      {% for match in all_matches %}

{{match.name}}

      {% endfor %}


问:
FormBuilder in reactiveForms in Angular 9 with Clarity work but send error
I have a problem with my angular reactive forms in Angular with clarity. Everything works perfectly but if I click few times I have a some error in my console and my first input showing nothing.

I don't know why...

My code component.ts :

```<code>    import { Component, OnInit, ViewChild } from '@angular/core';
    import { FormGroup, Validators, FormBuilder } from '@angular/forms';
    import { ClrForm } from '@clr/angular';

    import { Entreprise } from '@models/entreprise-model';
    import { EntrepriseService } from '@services/entreprise.service';
    import { Router } from '@angular/router';

    @Component({
        selector: 'app-entreprise-edit',
        templateUrl: './entreprise-edit.component.html',
        styleUrls: ['./entreprise-edit.component.scss']
    })
    export class EntrepriseEditComponent implements OnInit {
     @ViewChild(ClrForm, {static: true}) clrForm;

     updateEntForm: FormGroup;
     entreprise: Entreprise;
     loading = false;

     constructor(
       private entrepriseService: EntrepriseService,
       private formBuilder: FormBuilder,
       private router: Router,
       ) { }

  ngOnInit() {
    this.entrepriseService.findEnt()
      .subscribe(
        (ent) => {
        this.entreprise = ent.data;
        this.initForm();
      });
  }

  initForm() {
    this.updateEntForm = this.formBuilder.group({
      nameEnt: [this.entreprise.nameEnt, [Validators.required]],
      ville: [this.entreprise.ville, [Validators.required]],
      numSiret: [this.entreprise.numSiret, [Validators.required, Validators.minLength(14), Validators.maxLength(14)]],
      nbr_couvert: [this.entreprise.nbr_couvert, [Validators.required]],
    });
  }

  onSubmit() {
    if (!this.updateEntForm.valid) {
      this.clrForm.markAsTouched();
      return;
    }
    this.loading = true;
    this.entrepriseService.updateEnt(this.entreprise.id, this.updateEntForm.value)
    .subscribe(
      (ent) => {
        this.loading = false;
        this.entreprise = ent.data;
        this.router.navigate(['/dashboard/entreprise']);
      },
      (error: Error) => {
        this.loading = false;
        console.log(error);
      });
  }

}
</code>```

My code component.html :

```<code><form clrForm clrLayout="horizontal" [formGroup]="updateEntForm" class="form form--no-cols"
                (ngSubmit)="onSubmit()">

                <clr-input-container class="input-icon input-icon--nameEnt">
                    <label for="nameEnt">Le nom</label>
                    <input clrInput id="nameEnt" type="text" formControlName="nameEnt" name="nameEnt" required />
                    <clr-control-error *clrIfError="required">Ce champs est obligatoire!</clr-control-error>
                </clr-input-container>

                <clr-input-container class="input-icon input-icon--letter">
                    <label for="ville">La ville</label>
                    <input id="ville" clrInput type="text" formControlName="ville" name="ville" required />
                    <clr-control-error *clrIfError="required">Ce champs est obligatoire!</clr-control-error>
                </clr-input-container>

                <clr-input-container class="input-icon input-icon--nameEnt">
                    <label for="numSiret">Votre numéro de Siret:</label>
                    <input clrInput id="numSiret" type="number" formControlName="numSiret" name="numSiret"
                        required />
                    <clr-control-error *clrIfError="required">Ce champs est obligatoire!
                    </clr-control-error>
                </clr-input-container>

                <clr-input-container class="input-icon input-icon--letter">
                    <label for="nbr_couvert">Le nombre de couvert:</label>
                    <input clrInput id="nbr_couvert" type="number" formControlName="nbr_couvert" name="nbr_couvert"
                         required>
                    <clr-control-error *clrIfError="required">Ce champs est obligatoire!
                    </clr-control-error>
                </clr-input-container>

            </form>
</code>```

The differents error I have :

```<code>ERROR Error: "formGroup expects a FormGroup instance. Please pass one in.

       Example:

    <div [formGroup]="myGroup">
      <input formControlName="firstName">
    </div>

    In your class:

    this.myGroup = new FormGroup({
       firstName: new FormControl()
    });"
</code>```

```<code>ERROR TypeError: "ctx.ent is undefined"
</code>```

```<code>ERROR TypeError: "this.form is undefined"
</code>```

```<code>ERROR TypeError: "this.control.statusChanges is null"
</code>```

If someone have a idea...

答:
Today I gave a fairly good example of the use of recreational forms, and also indicated what 3 elements make up reactive forms

Theme

As for assigning data to a form, it’s better to use it like this

```<code>constructor(private appService: appService) {
    if (this.route.snapshot.paramMap.get('id')) {
        this.id = Number(this.route.snapshot.paramMap.get('id'));
        this.appService.getData(this.id).subscribe(result => {
            this.model = result;
            this.formBasic.controls['id'].setValue(this.model.id);
            this.formBasic.controls['name'].setValue(this.model.name);
    }
}
</code>```

Body:
I have a problem with my angular reactive forms in Angular with clarity. Everything works perfectly but if I click few times I have a some error in my console and my first input showing nothing.

I don't know why...

My code component.ts :

    import { Component, OnInit, ViewChild } from '@angular/core';
    import { FormGroup, Validators, FormBuilder } from '@angular/forms';
    import { ClrForm } from '@clr/angular';

    import { Entreprise } from '@models/entreprise-model';
    import { EntrepriseService } from '@services/entreprise.service';
    import { Router } from '@angular/router';

    @Component({
        selector: 'app-entreprise-edit',
        templateUrl: './entreprise-edit.component.html',
        styleUrls: ['./entreprise-edit.component.scss']
    })
    export class EntrepriseEditComponent implements OnInit {
     @ViewChild(ClrForm, {static: true}) clrForm;

     updateEntForm: FormGroup;
     entreprise: Entreprise;
     loading = false;

     constructor(
       private entrepriseService: EntrepriseService,
       private formBuilder: FormBuilder,
       private router: Router,
       ) { }

  ngOnInit() {
    this.entrepriseService.findEnt()
      .subscribe(
        (ent) => {
        this.entreprise = ent.data;
        this.initForm();
      });
  }

  initForm() {
    this.updateEntForm = this.formBuilder.group({
      nameEnt: [this.entreprise.nameEnt, [Validators.required]],
      ville: [this.entreprise.ville, [Validators.required]],
      numSiret: [this.entreprise.numSiret, [Validators.required, Validators.minLength(14), Validators.maxLength(14)]],
      nbr_couvert: [this.entreprise.nbr_couvert, [Validators.required]],
    });
  }

  onSubmit() {
    if (!this.updateEntForm.valid) {
      this.clrForm.markAsTouched();
      return;
    }
    this.loading = true;
    this.entrepriseService.updateEnt(this.entreprise.id, this.updateEntForm.value)
    .subscribe(
      (ent) => {
        this.loading = false;
        this.entreprise = ent.data;
        this.router.navigate(['/dashboard/entreprise']);
      },
      (error: Error) => {
        this.loading = false;
        console.log(error);
      });
  }

}

My code component.html :

<form clrForm clrLayout="horizontal" [formGroup]="updateEntForm" class="form form--no-cols"
                (ngSubmit)="onSubmit()">

                <clr-input-container class="input-icon input-icon--nameEnt">
                    Le nom
                    <input clrInput id="nameEnt" type="text" formControlName="nameEnt" name="nameEnt" required />
                    <clr-control-error *clrIfError="required">Ce champs est obligatoire!</clr-control-error>
                </clr-input-container>

                <clr-input-container class="input-icon input-icon--letter">
                    La ville
                    <input id="ville" clrInput type="text" formControlName="ville" name="ville" required />
                    <clr-control-error *clrIfError="required">Ce champs est obligatoire!</clr-control-error>
                </clr-input-container>

                <clr-input-container class="input-icon input-icon--nameEnt">
                    Votre numéro de Siret:
                    <input clrInput id="numSiret" type="number" formControlName="numSiret" name="numSiret"
                        required />
                    <clr-control-error *clrIfError="required">Ce champs est obligatoire!
                    </clr-control-error>
                </clr-input-container>

                <clr-input-container class="input-icon input-icon--letter">
                    Le nombre de couvert:
                    <input clrInput id="nbr_couvert" type="number" formControlName="nbr_couvert" name="nbr_couvert"
                         required>
                    <clr-control-error *clrIfError="required">Ce champs est obligatoire!
                    </clr-control-error>
                </clr-input-container>

            </form>

The differents error I have :

ERROR Error: "formGroup expects a FormGroup instance. Please pass one in.

       Example:

      <input formControlName="firstName">

    In your class:

    this.myGroup = new FormGroup({
       firstName: new FormControl()
    });"

ERROR TypeError: "ctx.ent is undefined"

ERROR TypeError: "this.form is undefined"

ERROR TypeError: "this.control.statusChanges is null"

If someone have a idea...

Body:
Today I gave a fairly good example of the use of recreational forms, and also indicated what 3 elements make up reactive forms

Theme

As for assigning data to a form, it’s better to use it like this

constructor(private appService: appService) {
    if (this.route.snapshot.paramMap.get('id')) {
        this.id = Number(this.route.snapshot.paramMap.get('id'));
        this.appService.getData(this.id).subscribe(result => {
            this.model = result;
            this.formBasic.controls['id'].setValue(this.model.id);
            this.formBasic.controls['name'].setValue(this.model.name);
    }
}


问:
How can this MYSQL query be better
I have a table that has all the photos from a user. For some reason (dont care why) some users can be deleted (using DELETE FROM) from the users table, but the photos are kept on the photos tables.

I need to know how many photos are from users that actually exists on the users table.

The first solution I came up with is this:

```<code>SELECT COUNT(DISTINCT user_id) FROM photos WHERE user_id IN (SELECT id FROM users)
</code>```

But I'm not sure if doing two Queries is the best one. Is there a better way to do this?

答:
If you want to find out how many non-orphaned pictures you have, you don't need DISTINCT at all.

```<code>SELECT COUNT(*)
FROM users u
INNER JOIN photos p ON (p.user_id = p.id)
</code>```

Title: How can this MYSQL query be better

Body:
I have a table that has all the photos from a user. For some reason (dont care why) some users can be deleted (using DELETE FROM) from the users table, but the photos are kept on the photos tables.

I need to know how many photos are from users that actually exists on the users table.

The first solution I came up with is this:

SELECT COUNT(DISTINCT user_id) FROM photos WHERE user_id IN (SELECT id FROM users)

But I'm not sure if doing two Queries is the best one. Is there a better way to do this?

Body:
If you want to find out how many non-orphaned pictures you have, you don't need DISTINCT at all.

SELECT COUNT(*)
FROM users u
INNER JOIN photos p ON (p.user_id = p.id)


问:
Excel mutual pairing
How can I pair members of a list such that if the pair of member 'a' is member 'b' then the pair of 'b' is 'a', in MS Excel?

Ideally, the pairing randomizes at each calculation.

Attempt:

1) I have a list of names in a column, (column B).

2) I put the natural numbers up to the list length in column A:

```<code>=ROW(B2)-1
</code>```

3) Random numbers in column C:

```<code>=RAND()
</code>```

4) I ranked ordered the randoms in column D.

```<code>=RANK(C2, $C$2:$C$178)
</code>```

Thus I have two orderings. The order of appearance in comumn A and a random order in D.

However, for example, row by row the "pair of 11" does not have 11 as its pair, in turn. How can I achieve a mutual pairing? If 11 is paired with 27 I need 27 to be paired with 11 also.

(I can then VLOOKUP to pull the names.)

```<code>=VLOOKUP(D2,$A$2:$B$178,2,0)
</code>```

EDIT:

Bellow is my output. You can see that 'c' is the pair of 'a' but 'a' is not pair of 'c'. (The F column checks if someone is paired to themselves.)

So basicly in the output E column I am taking the name corresponding to the random rank ordering. I would like to acheve mutual pairs in some way.

答:
Here is another approach. In your column E you have a permutation of the names. Keep this as an intermediate column. In this case it is c,b,d,a. Simply match c to b and d to a. Index and Match can be used to extract the pairings like this:

The crucial formula in F2 is

```<code>=IF(MOD(MATCH(B2,$E$2:$E$5,0),2) = 0,INDEX($E$2:$E$5,MATCH(B2,$E$2:$E$5,0)-1),INDEX($E$2:$E$5,MATCH(B2,$E$2:$E$5,0)+1))
</code>```

The formulas in columns D, E are exactly as you gave them.

Title: Excel mutual pairing

Body:
How can I pair members of a list such that if the pair of member 'a' is member 'b' then the pair of 'b' is 'a', in MS Excel?

Ideally, the pairing randomizes at each calculation.

Attempt:

1) I have a list of names in a column, (column B).

2) I put the natural numbers up to the list length in column A:

=ROW(B2)-1

3) Random numbers in column C:

=RAND()

4) I ranked ordered the randoms in column D.

=RANK(C2, $C$2:$C$178)

Thus I have two orderings. The order of appearance in comumn A and a random order in D.

However, for example, row by row the "pair of 11" does not have 11 as its pair, in turn. How can I achieve a mutual pairing? If 11 is paired with 27 I need 27 to be paired with 11 also.

(I can then VLOOKUP to pull the names.)

=VLOOKUP(D2,$A$2:$B$178,2,0)

EDIT:

Bellow is my output. You can see that 'c' is the pair of 'a' but 'a' is not pair of 'c'. (The F column checks if someone is paired to themselves.)

So basicly in the output E column I am taking the name corresponding to the random rank ordering. I would like to acheve mutual pairs in some way.

Body:
Here is another approach. In your column E you have a permutation of the names. Keep this as an intermediate column. In this case it is c,b,d,a. Simply match c to b and d to a. Index and Match can be used to extract the pairings like this:

The crucial formula in F2 is

=IF(MOD(MATCH(B2,$E$2:$E$5,0),2) = 0,INDEX($E$2:$E$5,MATCH(B2,$E$2:$E$5,0)-1),INDEX($E$2:$E$5,MATCH(B2,$E$2:$E$5,0)+1))

The formulas in columns D, E are exactly as you gave them.


问:
How to Inspect the Queue Processing a Celery Task
I'm currently leveraging celery for periodic tasks. I am new to celery. I have two workers running two different queues. One for slow background jobs and one for jobs user's queue up in the application.

I am monitoring my tasks on datadog because it's an easy way to confirm my workers a running appropriately.

What I want to do is after each task completes, record which queue the task was completed on.

```<code>@after_task_publish.connect()
def on_task_publish(sender=None, headers=None, body=None, **kwargs):
    statsd.increment("celery.on_task_publish.start.increment")

    task = celery.tasks.get(sender)
    queue_name = task.queue

    statsd.increment("celery.on_task_publish.increment", tags=[f"{queue_name}:{task}"])
</code>```

The following function is something that I implemented after researching the celery docs and some StackOverflow posts, but it's not working as intended. I get the first statsd increment but the remaining code does not execute.

I am wondering if there is a simpler way to inspect inside/after each task completes, what queue processed the task.

答:
Since your question says is there a way to inspect inside/after each task completes - I'm assuming you haven't tried this celery-result-backend stuff. So you could check out this feature which is provided by Celery itself : Celery-Result-Backend / Task-result-Backend .
It is very useful for storing results of your celery tasks.
Read through this => https://docs.celeryproject.org/en/stable/userguide/configuration.html#task-result-backend-settings

Once you get an idea of how to setup this result-backend, Search for result_extended key (in the same link) to be able to add queue-names in your task return values.

Number of options are available - Like you can setup these results to go to any of these :

```<code>Sql-DB / NoSql-DB / S3 / Azure / Elasticsearch / etc
</code>```

I have made use of this Result-Backend feature with Elasticsearch and this how my task results are stored :

It is just a matter of adding few configurations in settings.py file as per your requirements. Worked really well for my application. And I have a weekly cron that clears only successful results of tasks - since we don't need the results anymore - and I can see only failed results (like the one in image).

These were main keys for my requirement : task_track_started and task_acks_late along with result_backend

Body:
I'm currently leveraging celery for periodic tasks. I am new to celery. I have two workers running two different queues. One for slow background jobs and one for jobs user's queue up in the application.

I am monitoring my tasks on datadog because it's an easy way to confirm my workers a running appropriately.

What I want to do is after each task completes, record which queue the task was completed on.

@after_task_publish.connect()
def on_task_publish(sender=None, headers=None, body=None, **kwargs):
    statsd.increment("celery.on_task_publish.start.increment")

    task = celery.tasks.get(sender)
    queue_name = task.queue

    statsd.increment("celery.on_task_publish.increment", tags=[f"{queue_name}:{task}"])

The following function is something that I implemented after researching the celery docs and some StackOverflow posts, but it's not working as intended. I get the first statsd increment but the remaining code does not execute.

I am wondering if there is a simpler way to inspect inside/after each task completes, what queue processed the task.

Body:
Since your question says is there a way to inspect inside/after each task completes - I'm assuming you haven't tried this celery-result-backend stuff. So you could check out this feature which is provided by Celery itself : Celery-Result-Backend / Task-result-Backend .
It is very useful for storing results of your celery tasks.
Read through this => https://docs.celeryproject.org/en/stable/userguide/configuration.html#task-result-backend-settings

Once you get an idea of how to setup this result-backend, Search for result_extended key (in the same link) to be able to add queue-names in your task return values.

Number of options are available - Like you can setup these results to go to any of these :

Sql-DB / NoSql-DB / S3 / Azure / Elasticsearch / etc

I have made use of this Result-Backend feature with Elasticsearch and this how my task results are stored :

It is just a matter of adding few configurations in settings.py file as per your requirements. Worked really well for my application. And I have a weekly cron that clears only successful results of tasks - since we don't need the results anymore - and I can see only failed results (like the one in image).

These were main keys for my requirement : task_track_started and task_acks_late along with result_backend


问:
The specified child already has a parent. You must call removeView() on the child's parent first
I am doing a little exercise about a application you that put your name, and it returns "hello (the name you put)". But after i push the button i get the error "The specified child already has a parent. You must call removeView() on the child's parent first"

MainActivity.java

package com.example.holaamigos;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
    public final static String EXTRA_SALUDO = "com.example.holaamigos.SALUDO";

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

        final EditText txtNombre = (EditText)findViewById(R.id.TxtNombre);
        final Button btnHola = (Button)findViewById(R.id.BtnHola);

            btnHola.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MainActivity.this, ActivitySaludo.class);
                    String saludo = txtNombre.getText().toString();
                    intent.putExtra(EXTRA_SALUDO, saludo);
                    startActivity(intent);
        }

    });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}
```
<p><strong>ActivitySaludo.java</strong></p>
<pre class="lang-java prettyprint-override"><code>package com.example.holaamigos;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class ActivitySaludo extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_saludo);

        Intent intent = getIntent();
        String saludo = intent.getStringExtra(MainActivity.EXTRA_SALUDO);

        //TextView txt = new TextView(this);
        //txt.setText(20);
        //txt.setText(saludo);

        TextView txtCambiado = (TextView) findViewById(R.id.TxtSaludo);
        txtCambiado.setText(saludo);
        setContentView(txtCambiado);
    }

}
</code>```

activity_saludo.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/TxtSaludo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

</LinearLayout>
```
<p><strong>activity_main.xml</strong></p>

```<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/LblNombre"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/nombre" />

    <EditText
        android:id="@+id/TxtNombre"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text" />

    <Button
        android:id="@+id/BtnHola"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hola_apy"
        android:onClick="enviarSaludo"/>

</LinearLayout>
```
<p><strong>LogCat</strong></p>
<pre class="lang-java prettyprint-override"><code>10-10 16:12:18.470: D/AndroidRuntime(810): Shutting down VM
10-10 16:12:18.470: W/dalvikvm(810): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
10-10 16:12:18.586: E/AndroidRuntime(810): FATAL EXCEPTION: main
10-10 16:12:18.586: E/AndroidRuntime(810): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.holaamigos/com.example.holaamigos.ActivitySaludo}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.os.Handler.dispatchMessage(Handler.java:99)
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.os.Looper.loop(Looper.java:137)
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.app.ActivityThread.main(ActivityThread.java:5041)
10-10 16:12:18.586: E/AndroidRuntime(810):  at java.lang.reflect.Method.invokeNative(Native Method)
10-10 16:12:18.586: E/AndroidRuntime(810):  at java.lang.reflect.Method.invoke(Method.java:511)
10-10 16:12:18.586: E/AndroidRuntime(810):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-10 16:12:18.586: E/AndroidRuntime(810):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-10 16:12:18.586: E/AndroidRuntime(810):  at dalvik.system.NativeStart.main(Native Method)
10-10 16:12:18.586: E/AndroidRuntime(810): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.view.ViewGroup.addViewInner(ViewGroup.java:3339)
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.view.ViewGroup.addView(ViewGroup.java:3210)
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.view.ViewGroup.addView(ViewGroup.java:3186)
10-10 16:12:18.586: E/AndroidRuntime(810):  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:289)
10-10 16:12:18.586: E/AndroidRuntime(810):  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:279)
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.app.Activity.setContentView(Activity.java:1901)
10-10 16:12:18.586: E/AndroidRuntime(810):  at com.example.holaamigos.ActivitySaludo.onCreate(ActivitySaludo.java:25)
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.app.Activity.performCreate(Activity.java:5104)
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
10-10 16:12:18.586: E/AndroidRuntime(810):  ... 11 more
10-10 16:12:18.856: D/dalvikvm(810): GC_CONCURRENT freed 134K, 10% free 2630K/2908K, paused 73ms+83ms, total 237ms
</code>```

答: In my case i just pass the wrong view to the Method

Body:
I am doing a little exercise about a application you that put your name, and it returns "hello (the name you put)". But after i push the button i get the error "The specified child already has a parent. You must call removeView() on the child's parent first"

MainActivity.java

package com.example.holaamigos;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
    public final static String EXTRA_SALUDO = "com.example.holaamigos.SALUDO";

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

        final EditText txtNombre = (EditText)findViewById(R.id.TxtNombre);
        final Button btnHola = (Button)findViewById(R.id.BtnHola);

            btnHola.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MainActivity.this, ActivitySaludo.class);
                    String saludo = txtNombre.getText().toString();
                    intent.putExtra(EXTRA_SALUDO, saludo);
                    startActivity(intent);
        }

    });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

ActivitySaludo.java

package com.example.holaamigos;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class ActivitySaludo extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_saludo);

        Intent intent = getIntent();
        String saludo = intent.getStringExtra(MainActivity.EXTRA_SALUDO);

        //TextView txt = new TextView(this);
        //txt.setText(20);
        //txt.setText(saludo);

        TextView txtCambiado = (TextView) findViewById(R.id.TxtSaludo);
        txtCambiado.setText(saludo);
        setContentView(txtCambiado);
    }

}

activity_saludo.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/TxtSaludo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

</LinearLayout>

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/LblNombre"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/nombre" />

    <EditText
        android:id="@+id/TxtNombre"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text" />

    <Button
        android:id="@+id/BtnHola"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hola_apy"
        android:onClick="enviarSaludo"/>

</LinearLayout>

LogCat

10-10 16:12:18.470: D/AndroidRuntime(810): Shutting down VM
10-10 16:12:18.470: W/dalvikvm(810): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
10-10 16:12:18.586: E/AndroidRuntime(810): FATAL EXCEPTION: main
10-10 16:12:18.586: E/AndroidRuntime(810): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.holaamigos/com.example.holaamigos.ActivitySaludo}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.os.Handler.dispatchMessage(Handler.java:99)
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.os.Looper.loop(Looper.java:137)
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.app.ActivityThread.main(ActivityThread.java:5041)
10-10 16:12:18.586: E/AndroidRuntime(810):  at java.lang.reflect.Method.invokeNative(Native Method)
10-10 16:12:18.586: E/AndroidRuntime(810):  at java.lang.reflect.Method.invoke(Method.java:511)
10-10 16:12:18.586: E/AndroidRuntime(810):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-10 16:12:18.586: E/AndroidRuntime(810):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-10 16:12:18.586: E/AndroidRuntime(810):  at dalvik.system.NativeStart.main(Native Method)
10-10 16:12:18.586: E/AndroidRuntime(810): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.view.ViewGroup.addViewInner(ViewGroup.java:3339)
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.view.ViewGroup.addView(ViewGroup.java:3210)
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.view.ViewGroup.addView(ViewGroup.java:3186)
10-10 16:12:18.586: E/AndroidRuntime(810):  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:289)
10-10 16:12:18.586: E/AndroidRuntime(810):  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:279)
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.app.Activity.setContentView(Activity.java:1901)
10-10 16:12:18.586: E/AndroidRuntime(810):  at com.example.holaamigos.ActivitySaludo.onCreate(ActivitySaludo.java:25)
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.app.Activity.performCreate(Activity.java:5104)
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
10-10 16:12:18.586: E/AndroidRuntime(810):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
10-10 16:12:18.586: E/AndroidRuntime(810):  ... 11 more
10-10 16:12:18.856: D/dalvikvm(810): GC_CONCURRENT freed 134K, 10% free 2630K/2908K, paused 73ms+83ms, total 237ms


问:
Iteration in Logic Apps terminates prematurely
I'm using the Loop Until control in a Logic App, controlled by a simple counter. However, I find the loop terminates prematurely, so far fairly consistently after about 30 iterations, when I'm looking for much more (365 in fact - days of a year). The App doesn't fail, and looking at the run, it's clear the counter is working fine. Presumably the App has run up against an internal limit. I'm currently trying to use Analytics to dig deeper; will revert if any useful result. The only other thing worth mentioning is that I've set all loops to run sequentially i.e. no concurrency

答:
How do you set the count and Timeout limit in the Until connector?

Default limits are 60 iterations and one hour for timeout, if you exceed that limits, the until loop end before the condition is true.


Title: How to create a list from a string

Body:
I have the following question;

Given this string:

(-9.1801505 38.7320159, -9.1800081 38.7316384, -9.1760106 38.7280334, -9.175614100000001 38.7277934, -9.174941499999999 38.7276969, -9.174286 38.7273452, -9.1739754 38.7269114, -9.173853299999999 38.7266373, -9.173908000000001 38.726382, -9.174462200000001 38.725427, -9.174693700000001 38.7252121, -9.1753494 38.7249695, -9.1772258 38.724483, -9.177979300000001 38.7241841, -9.1781305 38.7240326, -9.178122200000001 38.7237591, -9.174915199999999 38.7229978, -9.172651999999999 38.7224599, -9.1716237 38.7223014, -9.170840099999999 38.7223315, -9.1661269 38.7232445, -9.1631047 38.7238009, -9.1621644 38.7239822, -9.1611914 38.7241708, -9.161030500000001 38.7242016, -9.1606402 38.7242798, -9.1605509 38.7242976, -9.1597224 38.7244719, -9.1588452 38.7246248, -9.1574752 38.7248025, -9.1563748 38.7248708, -9.157024399999999 38.7252864, -9.160008299999999 38.7284055, -9.158204400000001 38.7296856, -9.1554751 38.7316224, -9.158455399999999 38.7338999, -9.159123599999999 38.7336254, -9.159243399999999 38.733823, -9.1590688 38.734304, -9.1587736 38.7343032, -9.1585287 38.7344595, -9.1584726 38.7346586, -9.158265099999999 38.7346166, -9.157652300000001 38.7361352, -9.1579041 38.7362527, -9.1576316 38.7366198, -9.1577363 38.7366731, -9.1574563 38.7371094, -9.1564187 38.737462, -9.157724699999999 38.7388573, -9.1598056 38.7379811, -9.1602277 38.73791, -9.165917800000001 38.738966, -9.166425500000001 38.7392131, -9.167036400000001 38.7396749, -9.168542199999999 38.7416702, -9.169788499999999 38.740959, -9.170749499999999 38.7402073, -9.171019899999999 38.7398203, -9.1712919 38.7392233, -9.1716798 38.7391685, -9.1719215 38.7391826, -9.172312700000001 38.7392701, -9.1727472 38.7394396, -9.1738649 38.7388609, -9.174271299999999 38.7365449, -9.174486099999999 38.7343981, -9.1743024 38.734297, -9.174186000000001 38.7341419, -9.1741347 38.7338797, -9.174625199999999 38.7332609, -9.1749603 38.7329354, -9.175330799999999 38.7327162, -9.1756046 38.7326312, -9.176090200000001 38.7325687, -9.1776274 38.7328163, -9.177988300000001 38.7328404, -9.178248099999999 38.7328097, -9.1799505 38.7322568, -9.1801505 38.7320159)

How can I turn it into a list of lists?

For instance this string:(-9.1801505 38.7320159, -9.1800081 38.7316384, -9.1760106 38.7280334) would become this:

[[-9.1801505, 38.7320159], [-9.1800081, 38.7316384], [-9.1760106, 38.7280334]]

Body:
Given that this is a string you can do it like this:

string = '(-9.1801505 38.7320159, -9.1800081 38.7316384, -9.1760106 38.7280334)'
l = []
for tup in string[1:-1].split(','):
    l.append([float(val) for val in tup.split()])
print(l)

Output:

[[-9.1801505, 38.7320159], [-9.1800081, 38.7316384], [-9.1760106, 38.7280334]]