问:
Help with Django ORM query
I have these two Django models (simplified):

```<code>class Movie(models.Model):
    title = models.CharField(max_length=255)
    year = models.IntegerField(max_length=4)
    rating = models.DecimalField(max_digits=2, decimal_places=1, default=0)

class Request(models.Model):
    movie = models.ForeignKey(Movie)
    user = models.ForeignKey(User)
    language = models.CharField(max_length=7, choices=settings.APP_LANGUAGES, db_index=True)
    notes = models.CharField(max_length=255, blank=True, null=True)
    added = models.DateTimeField(default=datetime.now)
</code>```

I want to get all Requests with a count by language for each movie. I actually come up with a solution with an ORM query, which gives me the results I am looking for:

reqs = Request.objects.values('movie', 'langauge').annotate(Count('language'))

However, I will need an access to other Movie attributes while I will be rendering the results in the template. Obviously, the above query returns ValueQuerySet like:

[{'movie': 460, 'language__count': 1, 'language': u'es-mx'}, {'movie': 458, 'language__count': 2, 'language': u'cs'}, {'movie': 459, 'language__count': 1, 'language': u'el'}]

Thus something like reqs[0].movie.rating won't work. So, how should I access other Movie attributes?

Thank you.

答:
You can do something like this:

```<code>reqs = Request.objects.values('movie', 'movie__rating', 'movie__title', 'movie__year', 'language').annotate(Count('language'))
print reqs
</code>```

here is sample output:

```<code>[
    {'movie__year': 2010, 'language': u'EN', 'movie__title': u'Foo', 'movie': 1, 'language__count': 1, 'movie__rating': Decimal('1')},
    {'movie__year': 2010, 'language': u'ES', 'movie__title': u'Foo', 'movie': 1, 'language__count': 1, 'movie__rating': Decimal('1')},
    {'movie__year': 2010, 'language': u'RU', 'movie__title': u'Foo', 'movie': 1, 'language__count': 1, 'movie__rating': Decimal('1')},
    {'movie__year': 1998, 'language': u'EN', 'movie__title': u'Bar', 'movie': 2, 'language__count': 3, 'movie__rating': Decimal('9')},
    {'movie__year': 1998, 'language': u'RU', 'movie__title': u'Bar', 'movie': 2, 'language__count': 1, 'movie__rating': Decimal('9')},
]
</code>```

you can see that returning extra movie attributes doesn't change the count, here is sample  output from your original query:

```<code>reqs = Request.objects.values('movie', 'language').annotate(Count('language'))
print reqs
</code>```

this produces output:

```<code>[
    {'movie': 1, 'language__count': 1, 'language': u'EN'},
    {'movie': 1, 'language__count': 1, 'language': u'ES'},
    {'movie': 1, 'language__count': 1, 'language': u'RU'},
    {'movie': 2, 'language__count': 3, 'language': u'EN'},
    {'movie': 2, 'language__count': 1, 'language': u'RU'},
]
</code>```

EDIT

If you want to be able to call methods on the movie then you want to select the movies with you query, not the requests:

```<code>movies = Movie.objects.annotate(num_lang=Count('request__language')).all()
</code>```

This will return all the movies, annotated by request's language count, which you can access via property *num_lang* on the movie. You will also be able to call all the methods on the movies objects

Title: Help with Django ORM query

Body:
I have these two Django models (simplified):

class Movie(models.Model):
    title = models.CharField(max_length=255)
    year = models.IntegerField(max_length=4)
    rating = models.DecimalField(max_digits=2, decimal_places=1, default=0)

class Request(models.Model):
    movie = models.ForeignKey(Movie)
    user = models.ForeignKey(User)
    language = models.CharField(max_length=7, choices=settings.APP_LANGUAGES, db_index=True)
    notes = models.CharField(max_length=255, blank=True, null=True)
    added = models.DateTimeField(default=datetime.now)

I want to get all Requests with a count by language for each movie. I actually come up with a solution with an ORM query, which gives me the results I am looking for:

reqs = Request.objects.values('movie', 'langauge').annotate(Count('language'))

However, I will need an access to other Movie attributes while I will be rendering the results in the template. Obviously, the above query returns ValueQuerySet like:

[{'movie': 460, 'language__count': 1, 'language': u'es-mx'}, {'movie': 458, 'language__count': 2, 'language': u'cs'}, {'movie': 459, 'language__count': 1, 'language': u'el'}]

Thus something like reqs[0].movie.rating won't work. So, how should I access other Movie attributes?

Thank you.

Body:
You can do something like this:

reqs = Request.objects.values('movie', 'movie__rating', 'movie__title', 'movie__year', 'language').annotate(Count('language'))
print reqs

here is sample output:

[
    {'movie__year': 2010, 'language': u'EN', 'movie__title': u'Foo', 'movie': 1, 'language__count': 1, 'movie__rating': Decimal('1')},
    {'movie__year': 2010, 'language': u'ES', 'movie__title': u'Foo', 'movie': 1, 'language__count': 1, 'movie__rating': Decimal('1')},
    {'movie__year': 2010, 'language': u'RU', 'movie__title': u'Foo', 'movie': 1, 'language__count': 1, 'movie__rating': Decimal('1')},
    {'movie__year': 1998, 'language': u'EN', 'movie__title': u'Bar', 'movie': 2, 'language__count': 3, 'movie__rating': Decimal('9')},
    {'movie__year': 1998, 'language': u'RU', 'movie__title': u'Bar', 'movie': 2, 'language__count': 1, 'movie__rating': Decimal('9')},
]

you can see that returning extra movie attributes doesn't change the count, here is sample  output from your original query:

reqs = Request.objects.values('movie', 'language').annotate(Count('language'))
print reqs

this produces output:

[
    {'movie': 1, 'language__count': 1, 'language': u'EN'},
    {'movie': 1, 'language__count': 1, 'language': u'ES'},
    {'movie': 1, 'language__count': 1, 'language': u'RU'},
    {'movie': 2, 'language__count': 3, 'language': u'EN'},
    {'movie': 2, 'language__count': 1, 'language': u'RU'},
]

EDIT

If you want to be able to call methods on the movie then you want to select the movies with you query, not the requests:

movies = Movie.objects.annotate(num_lang=Count('request__language')).all()

This will return all the movies, annotated by request's language count, which you can access via property *num_lang* on the movie. You will also be able to call all the methods on the movies objects


来源: stackexchange

问:
SVG markup in PDF as generated from Jasper Reports
Problem Statement

I have a SVG markup sent from front end javascript to back-end action classes. I am using Jasper Reports to generate PDF which will contain the SVG image( i have markup data only). How do i do that.

What i have tried

I have tried to embed SVG image( having the link to image file) to the PDF file while generating reports.

Looking for

How to embed svg markup so that i can see the image in PDF. Any other best approach to solve it.

答:
In later versions of jasper reports you no longer need to add class="net.sf.jasperreports.engine.JRRenderable" to the imageExpression.

It is the default in JasperReports 6+ and JasperSoftStudio (JSS) will remove it if you add it in the Source pane.

The Tomcat SVG file provided in the JasperSoft Community answer works nicely.  My own SVG file would show properly in MS Edge or Chrome but didn't appear in JSS.

When I added width, height, viewbox and overflow attributes to the svg element, it then did appear in JSS - so try the example first before trying the svg you actually want.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Many to many resource mapping restful api design
There are many other questions here which target the same problem many-to-many relationship url design for restful apis. I have somewhat the same, but it differs from other.
I couldn't find any better approach.

I have locations resource, and services resource`

```<code>GET /services                           //it should give you all services
GET /locations                          //it should give you all locations
GET /locations/:id/services             //it should give you all services offered by a location
</code>```

The problem that I have is I have to design a route which gives
All locations along with services offered by them

I went though a post on reddit that suggests.

GET /locations?include=services

I also went through another doc . It suggest.

GET  /locations-services

I am sure I am not the first one who is having such confusion.
 Please help, and if possible share some resources which I can go through to clear my doubts off.

答:
You can use any spelling you want.  You should choose a spelling that is consistent with the spellings you use for other identifiers, for the same reason that we choose spellings of variable names that are consistent with other local variable names.

But

```<code>/a1dadfcb-8fc6-4456-b05e-a0b91575e0ef
</code>```

is a perfectly satisfactory URI.

```<code>/locations?include=services
/locations?services
/locations-services
/locations/services
/service-directory
</code>```

These are all fine.  General-purpose components don't care, so long as you use a spelling consistent with the production rules defined by RFC 3986

Body:
There are many other questions here which target the same problem many-to-many relationship url design for restful apis. I have somewhat the same, but it differs from other.
I couldn't find any better approach.

I have locations resource, and services resource`

GET /services                           //it should give you all services
GET /locations                          //it should give you all locations
GET /locations/:id/services             //it should give you all services offered by a location

The problem that I have is I have to design a route which gives
All locations along with services offered by them

I went though a post on reddit that suggests.

GET /locations?include=services

I also went through another doc . It suggest.

GET  /locations-services

I am sure I am not the first one who is having such confusion.
 Please help, and if possible share some resources which I can go through to clear my doubts off.

Body:
You can use any spelling you want.  You should choose a spelling that is consistent with the spellings you use for other identifiers, for the same reason that we choose spellings of variable names that are consistent with other local variable names.

But

/a1dadfcb-8fc6-4456-b05e-a0b91575e0ef

is a perfectly satisfactory URI.

/locations?include=services
/locations?services
/locations-services
/locations/services
/service-directory

These are all fine.  General-purpose components don't care, so long as you use a spelling consistent with the production rules defined by RFC 3986


问:
how to change a button background and enable it after other buttons are pressed
How do I enable the "Next" button after 'Yes' or 'No' from each question is pressed? I want to make my "Next" button active (change the background and enable) only after all the questions have been answered. I don't know whether I should use loop or if it's possible by if-else. Any help is very appreciated.

I have developed my program in a way that users can either press the 'yes' or 'no' button and after answering all questions the "Next" button should get activated (change the background and enable).

```<code>int one = 0;
int two = 0;
int three = 0;
int four = 0;

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

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        String phone_price = extras.getString("phone_price");
        final String numonly = phone_price.replaceAll("[^0-9]", "");

        final int phoneprice = Integer.parseInt(numonly);

        final Button ques_one_yes = (Button)findViewById(R.id.ques_one_yes);
        final Button ques_one_no = (Button)findViewById(R.id.ques_one_no);
        final Button ques_two_yes = (Button)findViewById(R.id.ques_two_yes);
        final Button ques_two_no = (Button)findViewById(R.id.ques_two_no);
        final Button ques_three_yes = (Button)findViewById(R.id.ques_three_yes);
        final Button ques_three_no = (Button)findViewById(R.id.ques_three_no);
        final Button ques_four_yes = (Button)findViewById(R.id.ques_four_yes);
        final Button ques_four_no = (Button)findViewById(R.id.ques_four_no);
        final Button nextstep = (Button)findViewById(R.id.next_step);

        ques_one_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                one = 1;
                ques_one_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_one_yes.setBackground(getDrawable(R.drawable.button_background));
                ques_one_no.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_one_no.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_one_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                one = 1;
                ques_one_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_one_no.setBackground(getDrawable(R.drawable.button_background));
                ques_one_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_one_yes.setBackground(getDrawable(R.drawable.inactive_button_background));

            }
        });

        ques_two_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                two = 1;
                ques_two_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_two_yes.setBackground(getDrawable(R.drawable.button_background));
                ques_two_no.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_two_no.setBackground(getDrawable(R.drawable.inactive_button_background));

            }
        });

        ques_two_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                two = 1;
                ques_two_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_two_no.setBackground(getDrawable(R.drawable.button_background));
                ques_two_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_two_yes.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_three_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                three = 1;
                ques_three_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_three_yes.setBackground(getDrawable(R.drawable.button_background));
                ques_three_no.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_three_no.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_three_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                three = 1;
                ques_three_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_three_no.setBackground(getDrawable(R.drawable.button_background));
                ques_three_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_three_yes.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_four_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                four = 1;
                ques_four_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_four_yes.setBackground(getDrawable(R.drawable.button_background));
                ques_four_no.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_four_no.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_four_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                four = 1;
                ques_four_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_four_no.setBackground(getDrawable(R.drawable.button_background));
                ques_four_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_four_yes.setBackground(getDrawable(R.drawable.inactive_button_background));

            }
        });

    }
}
</code>```

Quesions

答:
you can try "RadioGroup" and "RadioButton"

```<code>radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener(){
    @Override
    public void onCheckedChanged(RadioGroup rb, int id){
            if (id == R.id.ques_one_yes)
    }
})
</code>```

and in layout file

```<code><RadioGroup
    android:id="@+id/radioGroup"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <RadioButton
        android:id="@+id/ques_one_yes"
        android:layout_width="wrap_content"
        android:BackGround="@drawable/rb_bg"
        android:layout_height="wrap_content"/>
</RadioGroup>
</code>```

and in drawable file rb_bg.xml

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_background"  android:state_checked="true"/>
    <item android:drawable="@drawable/inactive_button_background"/>
</selector>
</code>```

and the TextColor is other drawable file

Body:
How do I enable the "Next" button after 'Yes' or 'No' from each question is pressed? I want to make my "Next" button active (change the background and enable) only after all the questions have been answered. I don't know whether I should use loop or if it's possible by if-else. Any help is very appreciated.

I have developed my program in a way that users can either press the 'yes' or 'no' button and after answering all questions the "Next" button should get activated (change the background and enable).

int one = 0;
int two = 0;
int three = 0;
int four = 0;

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

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        String phone_price = extras.getString("phone_price");
        final String numonly = phone_price.replaceAll("[^0-9]", "");

        final int phoneprice = Integer.parseInt(numonly);

        final Button ques_one_yes = (Button)findViewById(R.id.ques_one_yes);
        final Button ques_one_no = (Button)findViewById(R.id.ques_one_no);
        final Button ques_two_yes = (Button)findViewById(R.id.ques_two_yes);
        final Button ques_two_no = (Button)findViewById(R.id.ques_two_no);
        final Button ques_three_yes = (Button)findViewById(R.id.ques_three_yes);
        final Button ques_three_no = (Button)findViewById(R.id.ques_three_no);
        final Button ques_four_yes = (Button)findViewById(R.id.ques_four_yes);
        final Button ques_four_no = (Button)findViewById(R.id.ques_four_no);
        final Button nextstep = (Button)findViewById(R.id.next_step);

        ques_one_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                one = 1;
                ques_one_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_one_yes.setBackground(getDrawable(R.drawable.button_background));
                ques_one_no.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_one_no.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_one_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                one = 1;
                ques_one_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_one_no.setBackground(getDrawable(R.drawable.button_background));
                ques_one_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_one_yes.setBackground(getDrawable(R.drawable.inactive_button_background));

            }
        });

        ques_two_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                two = 1;
                ques_two_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_two_yes.setBackground(getDrawable(R.drawable.button_background));
                ques_two_no.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_two_no.setBackground(getDrawable(R.drawable.inactive_button_background));

            }
        });

        ques_two_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                two = 1;
                ques_two_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_two_no.setBackground(getDrawable(R.drawable.button_background));
                ques_two_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_two_yes.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_three_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                three = 1;
                ques_three_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_three_yes.setBackground(getDrawable(R.drawable.button_background));
                ques_three_no.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_three_no.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_three_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                three = 1;
                ques_three_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_three_no.setBackground(getDrawable(R.drawable.button_background));
                ques_three_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_three_yes.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_four_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                four = 1;
                ques_four_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_four_yes.setBackground(getDrawable(R.drawable.button_background));
                ques_four_no.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_four_no.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_four_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                four = 1;
                ques_four_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_four_no.setBackground(getDrawable(R.drawable.button_background));
                ques_four_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_four_yes.setBackground(getDrawable(R.drawable.inactive_button_background));

            }
        });

    }
}

Quesions

Body:
you can try "RadioGroup" and "RadioButton"

radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener(){
    @Override
    public void onCheckedChanged(RadioGroup rb, int id){
            if (id == R.id.ques_one_yes)
    }
})

and in layout file

<RadioGroup
    android:id="@+id/radioGroup"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <RadioButton
        android:id="@+id/ques_one_yes"
        android:layout_width="wrap_content"
        android:BackGround="@drawable/rb_bg"
        android:layout_height="wrap_content"/>
</RadioGroup>

and in drawable file rb_bg.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_background"  android:state_checked="true"/>
    <item android:drawable="@drawable/inactive_button_background"/>
</selector>

and the TextColor is other drawable file


答:
Your are taking the initial values for all the options as 0 and making it 1 on OnClick.
Just give an if-else in your onCreate method like:

if(one = 1 && two = 1 && three = 1 && four = 1)
   button.setEnable(true);
else
   button.setEnable(false);

if all values are 1 then enable the button, else disable it.

Title: how to change a button background and enable it after other buttons are pressed


问:
How do I know which person released mobile app to AppCenter organization
Is there a way to find who released/uploaded Apk/ipa file to the AppCenter organization. I use Fastlane script to upload releases using the AppCenter Key.

However, I couldn't find a way who (user account) is releasing the Apps.

答:
I could not find any proper answer from anyone, however, I figured this out in below.

Navigate to YourOrganization >> YourAppName >> App settings >> People

The App uploader will be default get "Manager" role, he released the app to AppCenter.


问:
How to implement Di in WinForms properly
I am building a Winforms app.
I have few Projects
The main project is the winforms project
I have DB project (using EF core) and business project with my services
I am using Ninject for DI injection of the business services. I am initializing the StandartKernel in the main form with all my registered bindings.
So when i open a Form from the Main form i am passing the needed services from the kernel to the constructor of the form.
The problem is when i want to create a form from other form (not the main one)
Example:
From the Main Form i create ClientForm
But i want to add to the client's collection "Cars" a new object so I want to create a Car form directly from the ClientForm. And here is the problem: in the ClientForm i dont have CarService to pass to the new form, i have only ClientService.
What is the best solution to do the DI in such a project?
I am thinking to make all my services static but...
Any other solution?</p>

答:
Well, I was working with something like that these days. I was using the Unity Container to make my DI. The code is not entirely complete and not optimized at all.

If you've seen or used ASP.NET APIs, I tried to play the same operation in a windows forms application.

I used a extension method like below to add all my forms to the Unity Container.

```<code>    public static void AddForms(this IUnityContainer container, Assembly assembly = null)
    {
        if (assembly == null) assembly = Assembly.GetCallingAssembly();

        foreach (var form in assembly.GetTypes().Where(x => typeof(Form).IsAssignableFrom(x)))
        {
            var initForm = form.GetCustomAttribute<InitialFormAttribute>();
            if (initForm != null)
            {
                container.RegisterType(typeof(Form), form, "InitialForm", new TransientLifetimeManager());
            }
            else
            {
                container.RegisterType(form, new TransientLifetimeManager());
            }

        }
    }
</code>```

And use some coding to implements the startup just like in ASP.NET. At startup I added the EF Core DbContext to the container, just as I added everything I needed to be able to simply make the Unity Container create the instances of the forms for me, and I always have access to my services within the forms.

If you want to see the full code, comment below.

Body:
Well, I was working with something like that these days. I was using the Unity Container to make my DI. The code is not entirely complete and not optimized at all.

If you've seen or used ASP.NET APIs, I tried to play the same operation in a windows forms application.

I used a extension method like below to add all my forms to the Unity Container.

    public static void AddForms(this IUnityContainer container, Assembly assembly = null)
    {
        if (assembly == null) assembly = Assembly.GetCallingAssembly();

        foreach (var form in assembly.GetTypes().Where(x => typeof(Form).IsAssignableFrom(x)))
        {
            var initForm = form.GetCustomAttribute<InitialFormAttribute>();
            if (initForm != null)
            {
                container.RegisterType(typeof(Form), form, "InitialForm", new TransientLifetimeManager());
            }
            else
            {
                container.RegisterType(form, new TransientLifetimeManager());
            }

        }
    }

And use some coding to implements the startup just like in ASP.NET. At startup I added the EF Core DbContext to the container, just as I added everything I needed to be able to simply make the Unity Container create the instances of the forms for me, and I always have access to my services within the forms.

If you want to see the full code, comment below.


问:
Is it possible to select multiple offsets with SQL
I'd like to select multiple offsets with a single SELECT SQL query. Is this possible?

For example, let's say I have a table of non-continuous dates called dates.

```<code>date
----------
2020-01-01
2020-01-09
2020-01-16
2020-01-22
2020-01-29
2020-02-01
2020-02-04
2020-02-10
2020-02-13
</code>```

I'd like to select the 1st, 4th and 7th offsets from the most recent date. In this example, the query should return:

```<code>offset    date
------    -------
1         2020-02-10
4         2020-01-29
7         2020-01-09
</code>```

Ideally, I would like to write the query as follows:

```<code>SELECT
    *
FROM
    dates
ORDER BY
    date DESC
OFFSET
    (1, 4, 7)
</code>```

Obviously, this does not compile due to the LIMIT/OFFSET clause.

I could try a UNION, but not only is this extremely verbose it does not work because the LIMIT/OFFSET clause must come after the last UNION.

FAIL:

```<code>SELECT 1, date FROM dates ORDER BY date DESC LIMIT 1 OFFSET 1
UNION
SELECT 4, date FROM dates ORDER BY date DESC LIMIT 1 OFFSET 4
UNION
SELECT 7, date FROM dates ORDER BY date DESC LIMIT 1 OFFSET 7
</code>```

Is there an elegant query to do this? The other option I can think of is to use row_number() with a window function, and then do something like SELECT * WHERE row_number IN (1, 4, 7). HOWEVER, in some cases I am forced to use an older version of SQLite that does not support window functions.

答:
For earlier version of SQLite you can use a correlated query in the WHERE clause:

```<code>select t.date
from tablename t
where (select count(*) from tablename where date > t.date) in (1, 4, 7)
</code>```

See the demo.

Results:

```<code>| date       |
| ---------- |
| 2020-01-09 |
| 2020-01-29 |
| 2020-02-10 |
</code>```

If you also want the offset column:

```<code>select
  (select count(*) from tablename where date > t.date) offset,
  t.date
from tablename t
where offset in (1, 4, 7)
order by offset
</code>```

See the demo.

Results:

```<code>| offset | date       |
| ------ | ---------- |
| 1      | 2020-02-10 |
| 4      | 2020-01-29 |
| 7      | 2020-01-09 |
</code>```

Body:
I'd like to select multiple offsets with a single SELECT SQL query. Is this possible?

For example, let's say I have a table of non-continuous dates called dates.

date
----------
2020-01-01
2020-01-09
2020-01-16
2020-01-22
2020-01-29
2020-02-01
2020-02-04
2020-02-10
2020-02-13

I'd like to select the 1st, 4th and 7th offsets from the most recent date. In this example, the query should return:

offset    date
------    -------
1         2020-02-10
4         2020-01-29
7         2020-01-09

Ideally, I would like to write the query as follows:

SELECT
    *
FROM
    dates
ORDER BY
    date DESC
OFFSET
    (1, 4, 7)

Obviously, this does not compile due to the LIMIT/OFFSET clause.

I could try a UNION, but not only is this extremely verbose it does not work because the LIMIT/OFFSET clause must come after the last UNION.

FAIL:

SELECT 1, date FROM dates ORDER BY date DESC LIMIT 1 OFFSET 1
UNION
SELECT 4, date FROM dates ORDER BY date DESC LIMIT 1 OFFSET 4
UNION
SELECT 7, date FROM dates ORDER BY date DESC LIMIT 1 OFFSET 7

Is there an elegant query to do this? The other option I can think of is to use row_number() with a window function, and then do something like SELECT * WHERE row_number IN (1, 4, 7). HOWEVER, in some cases I am forced to use an older version of SQLite that does not support window functions.

Body:
For earlier version of SQLite you can use a correlated query in the WHERE clause:

select t.date
from tablename t
where (select count(*) from tablename where date > t.date) in (1, 4, 7)

See the demo.

Results:

| date       |
| ---------- |
| 2020-01-09 |
| 2020-01-29 |
| 2020-02-10 |

If you also want the offset column:

select
  (select count(*) from tablename where date > t.date) offset,
  t.date
from tablename t
where offset in (1, 4, 7)
order by offset

See the demo.

Results:

| offset | date       |
| ------ | ---------- |
| 1      | 2020-02-10 |
| 4      | 2020-01-29 |
| 7      | 2020-01-09 |


问:
Ionic 3 - App shows blank screen after build with --prod but working with development mode
After upgrade from app-scripts": "3.1.0" to "3.1.9", my app has broken with --prod flag, I've checked on inspecting device console, but I did not see any errors. Just a blank screen. It worked perfectly on develop mode without --prod flag.

Here is my package.json

```<code>{
    "name": "affiliates",
    "version": "0.0.232",
    "author": "Ionic Framework",
    "homepage": "http://ionicframework.com/",
    "private": true,
    "config": {
        "ionic_webpack": "./src/config/webpack.config.js",
        "ionic_generate_source_map": "true"
    },
    "scripts": {
        "clean": "ionic-app-scripts clean",
        "build": "ionic-app-scripts build",
        "lint": "ionic-app-scripts lint",
        "ionic:build": "ionic-app-scripts build",
        "ionic:serve": "ionic-app-scripts serve",
        "serve:test": "MY_ENV=test ionic-app-scripts serve",
        "serve:dev": "MY_ENV=dev_docker ionic-app-scripts serve",
        "serve:test_local": "MY_ENV=test_local ionic-app-scripts serve",
        "test": "karma start ./test-config/karma.conf.js",
        "test-ci": "karma start ./test-config/karma.conf.js --single-run",
        "test-coverage": "karma start ./test-config/karma.conf.js --coverage",
        "e2e": "npm run e2e-update && npm run e2e-test",
        "e2e-test": "protractor ./test-config/protractor.conf.js",
        "e2e-update": "webdriver-manager update --standalone false --gecko false --versions.chrome 2.44"
    },
    "dependencies": {
        "@angular/common": "5.0.0",
        "@angular/compiler": "5.0.0",
        "@angular/compiler-cli": "5.0.0",
        "@angular/core": "5.0.0",
        "@angular/forms": "5.0.0",
        "@angular/http": "5.0.0",
        "@angular/platform-browser": "5.0.0",
        "@angular/platform-browser-dynamic": "5.0.0",
        "@ionic-native/app-version": "^4.20.0",
        "@ionic-native/core": "4.3.2",
        "@ionic-native/geolocation": "^4.15.0",
        "@ionic-native/native-geocoder": "^4.15.0",
        "@ionic-native/splash-screen": "4.3.2",
        "@ionic-native/status-bar": "4.3.2",
        "@ionic/storage": "^2.1.3",
        "@ngx-translate/core": "^9.1.1",
        "@ngx-translate/http-loader": "^2.0.1",
        "analytics-node": "^3.3.0",
        "brmasker-ionic-3": "^1.0.9",
        "cordova-android": "7.1.4",
        "cordova-browser": "5.0.4",
        "cordova-ios": "4.5.5",
        "cordova-plugin-app-version": "^0.1.9",
        "cordova-plugin-device": "^1.1.4",
        "cordova-plugin-geolocation": "~4.0.1",
        "cordova-plugin-ionic-webview": "^2.3.1",
        "cordova-plugin-nativegeocoder": "^3.1.2",
        "cordova-plugin-splashscreen": "^4.0.3",
        "cordova-plugin-statusbar": "git+https://github.com/apache/cordova-plugin-statusbar.git",
        "cordova-plugin-whitelist": "^1.3.1",
        "cordova-sqlite-storage": "^2.6.0",
        "flag-icon-css": "^3.0.0",
        "ionic-angular": "^3.9.2",
        "ionic-plugin-keyboard": "^2.2.1",
        "ionic2-rating": "^1.2.2",
        "ionicons": "3.0.0",
        "jquery": "^3.3.1",
        "jquery-ui": "^1.12.1",
        "lodash": "^4.17.13",
        "moment": "^2.21.0",
        "ng-select": "^1.0.1",
        "ngx-bootstrap": "^2.0.5",
        "ngx-credit-cards": "^1.0.9",
        "raven-js": "^3.26.4",
        "rxjs": "5.5.2",
        "slick-carousel": "^1.8.1",
        "sw-toolbox": "3.6.0",
        "webpack": "^4.29.6",
        "zone.js": "^0.8.21"
    },
    "devDependencies": {
        "@ionic/app-scripts": "^3.1.9",
        "@ionic/cli-plugin-cordova": "1.6.2",
        "@types/jasmine": "2.8.6",
        "@types/node": "^10.1.2",
        "angular2-template-loader": "^0.6.2",
        "html-loader": "^0.5.5",
        "ionic": "3.20.0",
        "istanbul-instrumenter-loader": "^3.0.1",
        "jasmine": "^3.1.0",
        "jasmine-spec-reporter": "^4.2.1",
        "karma": "^2.0.2",
        "karma-chrome-launcher": "^2.2.0",
        "karma-coverage-istanbul-reporter": "^2.0.0",
        "karma-jasmine": "^1.1.2",
        "karma-jasmine-html-reporter": "^1.1.0",
        "karma-sourcemap-loader": "^0.3.7",
        "karma-webpack": "^3.0.0",
        "null-loader": "^0.1.1",
        "postcss": "6.0.14",
        "protractor": "^5.3.2",
        "ts-loader": "^3.5.0",
        "ts-node": "^6.0.3",
        "typescript": "^2.8.4",
        "ws": "3.3.2"
    },
    "description": "An Ionic project",
    "cordova": {
        "plugins": {
            "cordova-plugin-device": {},
            "cordova-plugin-splashscreen": {},
            "cordova-plugin-whitelist": {},
            "ionic-plugin-keyboard": {},
            "cordova-sqlite-storage": {},
            "cordova-plugin-app-version": {},
            "cordova-plugin-geolocation": {
                "GEOLOCATION_USAGE_DESCRIPTION": "To locate you"
            },
            "cordova-plugin-nativegeocoder": {},
            "cordova-plugin-ionic-webview": {},
            "cordova-plugin-statusbar": {}
        },
        "platforms": [
            "browser",
            "ios",
            "android"
        ]
    }
}
</code>```

The app does not show the issue, just a white screen, I guess that is having some incompatible plugins but I couldn't spot where is it.

答:
Try to type

chrome://inspect/#devices

inside your navbar in chrome and then ionic cordova run android --prod
Here is the mistake. Therefore empty values.

If it won't works, try downgrading your Typescript to 2.8.4.

Hope this help :)

Body:
After upgrade from app-scripts": "3.1.0" to "3.1.9", my app has broken with --prod flag, I've checked on inspecting device console, but I did not see any errors. Just a blank screen. It worked perfectly on develop mode without --prod flag.

Here is my package.json

{
    "name": "affiliates",
    "version": "0.0.232",
    "author": "Ionic Framework",
    "homepage": "http://ionicframework.com/",
    "private": true,
    "config": {
        "ionic_webpack": "./src/config/webpack.config.js",
        "ionic_generate_source_map": "true"
    },
    "scripts": {
        "clean": "ionic-app-scripts clean",
        "build": "ionic-app-scripts build",
        "lint": "ionic-app-scripts lint",
        "ionic:build": "ionic-app-scripts build",
        "ionic:serve": "ionic-app-scripts serve",
        "serve:test": "MY_ENV=test ionic-app-scripts serve",
        "serve:dev": "MY_ENV=dev_docker ionic-app-scripts serve",
        "serve:test_local": "MY_ENV=test_local ionic-app-scripts serve",
        "test": "karma start ./test-config/karma.conf.js",
        "test-ci": "karma start ./test-config/karma.conf.js --single-run",
        "test-coverage": "karma start ./test-config/karma.conf.js --coverage",
        "e2e": "npm run e2e-update && npm run e2e-test",
        "e2e-test": "protractor ./test-config/protractor.conf.js",
        "e2e-update": "webdriver-manager update --standalone false --gecko false --versions.chrome 2.44"
    },
    "dependencies": {
        "@angular/common": "5.0.0",
        "@angular/compiler": "5.0.0",
        "@angular/compiler-cli": "5.0.0",
        "@angular/core": "5.0.0",
        "@angular/forms": "5.0.0",
        "@angular/http": "5.0.0",
        "@angular/platform-browser": "5.0.0",
        "@angular/platform-browser-dynamic": "5.0.0",
        "@ionic-native/app-version": "^4.20.0",
        "@ionic-native/core": "4.3.2",
        "@ionic-native/geolocation": "^4.15.0",
        "@ionic-native/native-geocoder": "^4.15.0",
        "@ionic-native/splash-screen": "4.3.2",
        "@ionic-native/status-bar": "4.3.2",
        "@ionic/storage": "^2.1.3",
        "@ngx-translate/core": "^9.1.1",
        "@ngx-translate/http-loader": "^2.0.1",
        "analytics-node": "^3.3.0",
        "brmasker-ionic-3": "^1.0.9",
        "cordova-android": "7.1.4",
        "cordova-browser": "5.0.4",
        "cordova-ios": "4.5.5",
        "cordova-plugin-app-version": "^0.1.9",
        "cordova-plugin-device": "^1.1.4",
        "cordova-plugin-geolocation": "~4.0.1",
        "cordova-plugin-ionic-webview": "^2.3.1",
        "cordova-plugin-nativegeocoder": "^3.1.2",
        "cordova-plugin-splashscreen": "^4.0.3",
        "cordova-plugin-statusbar": "git+https://github.com/apache/cordova-plugin-statusbar.git",
        "cordova-plugin-whitelist": "^1.3.1",
        "cordova-sqlite-storage": "^2.6.0",
        "flag-icon-css": "^3.0.0",
        "ionic-angular": "^3.9.2",
        "ionic-plugin-keyboard": "^2.2.1",
        "ionic2-rating": "^1.2.2",
        "ionicons": "3.0.0",
        "jquery": "^3.3.1",
        "jquery-ui": "^1.12.1",
        "lodash": "^4.17.13",
        "moment": "^2.21.0",
        "ng-select": "^1.0.1",
        "ngx-bootstrap": "^2.0.5",
        "ngx-credit-cards": "^1.0.9",
        "raven-js": "^3.26.4",
        "rxjs": "5.5.2",
        "slick-carousel": "^1.8.1",
        "sw-toolbox": "3.6.0",
        "webpack": "^4.29.6",
        "zone.js": "^0.8.21"
    },
    "devDependencies": {
        "@ionic/app-scripts": "^3.1.9",
        "@ionic/cli-plugin-cordova": "1.6.2",
        "@types/jasmine": "2.8.6",
        "@types/node": "^10.1.2",
        "angular2-template-loader": "^0.6.2",
        "html-loader": "^0.5.5",
        "ionic": "3.20.0",
        "istanbul-instrumenter-loader": "^3.0.1",
        "jasmine": "^3.1.0",
        "jasmine-spec-reporter": "^4.2.1",
        "karma": "^2.0.2",
        "karma-chrome-launcher": "^2.2.0",
        "karma-coverage-istanbul-reporter": "^2.0.0",
        "karma-jasmine": "^1.1.2",
        "karma-jasmine-html-reporter": "^1.1.0",
        "karma-sourcemap-loader": "^0.3.7",
        "karma-webpack": "^3.0.0",
        "null-loader": "^0.1.1",
        "postcss": "6.0.14",
        "protractor": "^5.3.2",
        "ts-loader": "^3.5.0",
        "ts-node": "^6.0.3",
        "typescript": "^2.8.4",
        "ws": "3.3.2"
    },
    "description": "An Ionic project",
    "cordova": {
        "plugins": {
            "cordova-plugin-device": {},
            "cordova-plugin-splashscreen": {},
            "cordova-plugin-whitelist": {},
            "ionic-plugin-keyboard": {},
            "cordova-sqlite-storage": {},
            "cordova-plugin-app-version": {},
            "cordova-plugin-geolocation": {
                "GEOLOCATION_USAGE_DESCRIPTION": "To locate you"
            },
            "cordova-plugin-nativegeocoder": {},
            "cordova-plugin-ionic-webview": {},
            "cordova-plugin-statusbar": {}
        },
        "platforms": [
            "browser",
            "ios",
            "android"
        ]
    }
}

The app does not show the issue, just a white screen, I guess that is having some incompatible plugins but I couldn't spot where is it.


问:
serving both Vaadin and JSPs from the same webapp
I cannot get both my Vaadin app and some jsps using springmvc to work in the same webapp. The most promising approach seems to be doing the following:

```<code><servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>fluxtream</servlet-name>
    <url-pattern>/main/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>fluxtream</servlet-name>
    <url-pattern>/VAADIN/*</url-pattern>
</servlet-mapping>
</code>```

i.e. not serving the Vaadin app from the root of the webapp, but that gives me the following error:

```<code>java.lang.NullPointerException
org.vaadin.artur.icepush.ICEPushServlet.service(ICEPushServlet.java:52)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
</code>```

... which might be related to the fact that I'm using IcePush (a required dependency for me).

Anyhow, I would be grateful if someone could share their experience with serving an app alongside some jsps and springmvc.

答:
I would recommend this thread from Vaadin forums. Combine the discussed solution so that you have:

```<code><servlet>
        <servlet-name>VaadinApplicationRunner</servlet-name>
        <servlet-class>com.vaadin.terminal.gwt.server.ApplicationRunnerServlet</servlet-class>
</servlet>

<servlet-mapping>
        <servlet-name>VaadinApplicationRunner</servlet-name>
        <url-pattern>/VAADIN/*</url-pattern>
</servlet-mapping>

    <servlet-mapping>
      <servlet-name>Microblog</servlet-name>
      <url-pattern>/MicroblogApplicationServlet/*</url-pattern>
  </servlet-mapping>
</code>```

This is an example for icepush Microblog portlet. Other Vaadin portlets or icepush portlets can be with their own url patterns. Consult the tutorial for Spring integration, how it links with this.

Body:
I cannot get both my Vaadin app and some jsps using springmvc to work in the same webapp. The most promising approach seems to be doing the following:

<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>fluxtream</servlet-name>
    <url-pattern>/main/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>fluxtream</servlet-name>
    <url-pattern>/VAADIN/*</url-pattern>
</servlet-mapping>

i.e. not serving the Vaadin app from the root of the webapp, but that gives me the following error:

java.lang.NullPointerException
org.vaadin.artur.icepush.ICEPushServlet.service(ICEPushServlet.java:52)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

... which might be related to the fact that I'm using IcePush (a required dependency for me).

Anyhow, I would be grateful if someone could share their experience with serving an app alongside some jsps and springmvc.

Body:
I would recommend this thread from Vaadin forums. Combine the discussed solution so that you have:

<servlet>
        <servlet-name>VaadinApplicationRunner</servlet-name>
        <servlet-class>com.vaadin.terminal.gwt.server.ApplicationRunnerServlet</servlet-class>
</servlet>

<servlet-mapping>
        <servlet-name>VaadinApplicationRunner</servlet-name>
        <url-pattern>/VAADIN/*</url-pattern>
</servlet-mapping>

    <servlet-mapping>
      <servlet-name>Microblog</servlet-name>
      <url-pattern>/MicroblogApplicationServlet/*</url-pattern>
  </servlet-mapping>

This is an example for icepush Microblog portlet. Other Vaadin portlets or icepush portlets can be with their own url patterns. Consult the tutorial for Spring integration, how it links with this.


问:
How do I make my sizeof sum struct work with an empty parameter pack
I have this variadic struct for determining the sum of the sizeof all the types passed in:

```<code>template <typename U, typename... T> struct TotalSizeOf
    : std::integral_constant<size_t, sizeof(U) + TotalSizeOf<T...>::value> {};

template <typename U> struct TotalSizeOf<U>
    : std::integral_constant<size_t, sizeof(U)> {};
</code>```

Usage:
TotalSizeOf<double, int, char>::value

The question is, how do I modify this to allow it to work on an empty parameter pack, to return 0;

e.g. TotalSizeOf<>::value

Currently, I get the error error: wrong number of template arguments (0, should be at least 1)

I only have C++14 available.

答:
With C++17 you can get this without elaborate template metaprogramming, using fold expressions:

```<code>#include <iostream>
#include <type_traits>

template<class... T>
struct TotalSizeOf: std::integral_constant<std::size_t, (0 + ... + sizeof(T))> {};

int main()
{
    std::cout << TotalSizeOf< int, char>::value << std::endl;
    std::cout << TotalSizeOf< char>::value << std::endl;
    std::cout << TotalSizeOf< >::value << std::endl;
}
</code>```

This should also be more efficient when compiling (of course at runtime, these are the same).

PS: Just read, that you only have C++14, but will let this stand here, since I think it is nice to see, that we are less forced to do awkward TMP in newer C++ versions.

Addendum: Less elegant than C++17, but C++14 and pretty much tmp-free

```<code>#include <iostream>
#include <type_traits>
#include <initializer_list>

constexpr size_t sum(std::initializer_list<size_t> arr) {
    // Accumulate is sadly not constexpr in C++14
    auto ret = 0ul;
    for(auto i: arr) {
        ret += i;
    }
    return ret;
}

template<class... T>
struct TotalSizeOf: std::integral_constant<std::size_t, sum({sizeof(T)...})> {};

int main()
{
    std::cout << TotalSizeOf< int, char>::value << std::endl;
    std::cout << TotalSizeOf< char>::value << std::endl;
    std::cout << TotalSizeOf< >::value << std::endl;
}
</code>```

Body:
I have this variadic struct for determining the sum of the sizeof all the types passed in:

template <typename U, typename... T> struct TotalSizeOf
    : std::integral_constant<size_t, sizeof(U) + TotalSizeOf<T...>::value> {};

template <typename U> struct TotalSizeOf
    : std::integral_constant<size_t, sizeof(U)> {};

Usage:
TotalSizeOf<double, int, char>::value

The question is, how do I modify this to allow it to work on an empty parameter pack, to return 0;

e.g. TotalSizeOf<>::value

Currently, I get the error error: wrong number of template arguments (0, should be at least 1)

I only have C++14 available.

Body:
With C++17 you can get this without elaborate template metaprogramming, using fold expressions:

#include <iostream>
#include <type_traits>

template<class... T>
struct TotalSizeOf: std::integral_constant<std::size_t, (0 + ... + sizeof(T))> {};

int main()
{
    std::cout << TotalSizeOf< int, char>::value << std::endl;
    std::cout << TotalSizeOf< char>::value << std::endl;
    std::cout << TotalSizeOf< >::value << std::endl;
}

This should also be more efficient when compiling (of course at runtime, these are the same).

PS: Just read, that you only have C++14, but will let this stand here, since I think it is nice to see, that we are less forced to do awkward TMP in newer C++ versions.

Addendum: Less elegant than C++17, but C++14 and pretty much tmp-free

#include <iostream>
#include <type_traits>
#include <initializer_list>

constexpr size_t sum(std::initializer_list<size_t> arr) {
    // Accumulate is sadly not constexpr in C++14
    auto ret = 0ul;
    for(auto i: arr) {
        ret += i;
    }
    return ret;
}

template<class... T>
struct TotalSizeOf: std::integral_constant<std::size_t, sum({sizeof(T)...})> {};

int main()
{
    std::cout << TotalSizeOf< int, char>::value << std::endl;
    std::cout << TotalSizeOf< char>::value << std::endl;
    std::cout << TotalSizeOf< >::value << std::endl;
}


问:
How do I make a bot status that has memberCount on it?
I made a simple discord verify bot, but I want to make the bot status to watching # people verifying (the # is how many people in my server). I see some bots have it, but I don't know how to make it. Here is my current code for the bot status:

```<code>if (Object.keys(this.config.presence).length !== 0) {
        this.user.setPresence({
            game: {
                name: this.config.presence.name,
                type: this.config.presence.type
            },
            status: "online"
        }).catch(console.error);
    }
</code>```

答:
Welcome to StackOverflow!

client.users.size should return you all the users from all the guilds that the bot is into!

if (Object.keys(this.config.presence).length !== 0) {
    this.user.setPresence({
            game: {
                name: client.users.size + ' people verifying!',
                type: this.config.presence.type
            },
            status: "online"
        }).catch(console.error);
    }
```

You can also find this at discord.js documentation.

Body:
I made a simple discord verify bot, but I want to make the bot status to watching # people verifying (the # is how many people in my server). I see some bots have it, but I don't know how to make it. Here is my current code for the bot status:

if (Object.keys(this.config.presence).length !== 0) {
        this.user.setPresence({
            game: {
                name: this.config.presence.name,
                type: this.config.presence.type
            },
            status: "online"
        }).catch(console.error);
    }

Body:
Welcome to StackOverflow!

client.users.size should return you all the users from all the guilds that the bot is into!

if (Object.keys(this.config.presence).length !== 0) {
    this.user.setPresence({
            game: {
                name: client.users.size + ' people verifying!',
                type: this.config.presence.type
            },
            status: "online"
        }).catch(console.error);
    }

You can also find this at discord.js documentation.


问:
React-Native: Is it possible to get the layout positions of the FlatList

As I indicated in the Picture with arrow mark, I would like to get the top positions of FlatList. I tried onLayout props, But it return only null values.

Is there anyway to get the top positions of FlatList?

答:
Check below sample

```<code>import React, {Component} from 'react';
import {View, FlatList, StyleSheet, Text} from 'react-native';

const DATA = [
  {
    id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
    title: 'First Item',
  },
  {
    id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
    title: 'Second Item',
  },
  {
    id: '58694a0f-3da1-471f-bd96-145571e29d72',
    title: 'Third Item',
  },
];

export default class HomeScreen extends Component {
  findDimesions = layout => {
    const {x, y, width, height} = layout;
    console.log(x);
    console.log(y);
    console.log(width);
    console.log(height);
  };

  render() {
    return (
      <View
        onLayout={event => this.findDimesions(event.nativeEvent.layout)}
        style={styles.container}>
        <FlatList
          data={DATA}
          renderItem={({item}) => (
            <View style={styles.item}>
              <Text style={styles.title}>{item.title}</Text>
            </View>
          )}
          keyExtractor={item => item.id}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  item: {
    backgroundColor: '#f9c2ff',
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
  },
  title: {
    fontSize: 32,
  },
});
</code>```

Change this according to your requirements.

Hope this helps you. Feel free for doubts.

Body:
Check below sample

import React, {Component} from 'react';
import {View, FlatList, StyleSheet, Text} from 'react-native';

const DATA = [
  {
    id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
    title: 'First Item',
  },
  {
    id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
    title: 'Second Item',
  },
  {
    id: '58694a0f-3da1-471f-bd96-145571e29d72',
    title: 'Third Item',
  },
];

export default class HomeScreen extends Component {
  findDimesions = layout => {
    const {x, y, width, height} = layout;
    console.log(x);
    console.log(y);
    console.log(width);
    console.log(height);
  };

  render() {
    return (
      <View
        onLayout={event => this.findDimesions(event.nativeEvent.layout)}
        style={styles.container}>
        <FlatList
          data={DATA}
          renderItem={({item}) => (
            <View style={styles.item}>
              <Text style={styles.title}>{item.title}</Text>
            </View>
          )}
          keyExtractor={item => item.id}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  item: {
    backgroundColor: '#f9c2ff',
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
  },
  title: {
    fontSize: 32,
  },
});

Change this according to your requirements.

Hope this helps you. Feel free for doubts.


问:
Split SQL Server Column value
I have a SQL Server table which name is AbundanceImpact.

```<code>Monetary~50
Monetary~120
Monetary~200
Monetary~269.90
Monetary~125
Magnanimous~50
Monetary~22.05
Unlimited~500
Monetary~150
Monetary~300
Monetary~21.89
Monetary~10.95
</code>```

So I want the all integer values only with SUM.

答:
I would use stuff() for this:

```<code>select sum(try_convert(numeric(20, 4),
                       stuff(col, 1, charindex('~', col), '')
                      )
          )
</code>```

If you actually want to ignore the fractional components, then you would use numeric(20, 0) -- or something similar.  The 20 seems big enough for your data.

Title: Split SQL Server Column value

Body:
I have a SQL Server table which name is AbundanceImpact.

Monetary~50
Monetary~120
Monetary~200
Monetary~269.90
Monetary~125
Magnanimous~50
Monetary~22.05
Unlimited~500
Monetary~150
Monetary~300
Monetary~21.89
Monetary~10.95

So I want the all integer values only with SUM.

Body:
I would use stuff() for this:

select sum(try_convert(numeric(20, 4),
                       stuff(col, 1, charindex('~', col), '')
                      )
          )

If you actually want to ignore the fractional components, then you would use numeric(20, 0) -- or something similar.  The 20 seems big enough for your data.


问:
Django rest framework response items by category
I'm using Django rest framework serializer to return plans for a mobile application. For now my serializer response looks like this:

```<code>[
    {
        "id": 1,
        "nome": "Test",
        "localizacao": "Example - MG",
        "instituicao": "Example",
        "modalidade": "Example",
        "categoria": "Category 1",
        "frequencia_semanal": 1,
        "carga_horaria": 2,
        "quantidade_alunos": 2,
        "valor_unitario": "12.00",
        "taxa_matricula": "12.00",
        "informacoes_adicionais": ""
    }
]
</code>```

I need to separate plans by category so, response structure must look like this:

```<code>[
    "Category 1": [
        {
            "id": 1,
            "nome": "Test",
            "localizacao": "Example",
            "instituicao": "Example",
            "modalidade": "Example",
            "frequencia_semanal": 1,
            "carga_horaria": 2,
            "quantidade_alunos": 2,
            "valor_unitario": "12.00",
            "taxa_matricula": "12.00",
            "informacoes_adicionais": ""
        }
    ]
]
</code>```

The "categoria" value, must be keys and all plans belonging to that category must be contained in the key.

there is my models.py

```<code>class Plano(models.Model):
    PUBLICO_ALVO_MENORES = 1
    PUBLICO_ALVO_ADOLESCENTES = 2
    PUBLICO_ALVO_ADULTOS = 3
    PUBLICO_ALVO_TODOS = 4
    PUBLICO_ALVO_CHOICES = (
        (PUBLICO_ALVO_MENORES, 'Menores'),
        (PUBLICO_ALVO_ADOLESCENTES, 'Adolecentes'),
        (PUBLICO_ALVO_ADULTOS, 'Adultos'),
        (PUBLICO_ALVO_TODOS, 'Todas as idades'),
    )
    nome = models.CharField(max_length=200)
    localizacao = models.ForeignKey('Localizacao', on_delete=models.PROTECT)
    instituicao = models.ForeignKey('Instituicao', null=True, on_delete=models.PROTECT)
    modalidade = models.ForeignKey('PlanoModalidade', verbose_name='Modalidades', on_delete=models.PROTECT)
    categoria = models.ForeignKey('PlanoCategoria', verbose_name='Categorias', on_delete=models.PROTECT)
    publico_alvo = models.SmallIntegerField(choices=PUBLICO_ALVO_CHOICES, null=True)
    frequencia_semanal = models.PositiveSmallIntegerField(verbose_name='Frequência semanal')
    carga_horaria = models.PositiveSmallIntegerField(verbose_name='Carga horária diária')
    quantidade_alunos = models.PositiveSmallIntegerField(verbose_name='Quantidade de alunos')
    valor_unitario = models.DecimalField(decimal_places=2, max_digits=18, verbose_name='Valor unitário')
    taxa_matricula = models.DecimalField(decimal_places=2, max_digits=18, verbose_name='Taxa matrícula')
    informacoes_adicionais = models.TextField(max_length=200, blank=True)
</code>```

DRF serializers.py

```<code>class PlanosSerializer(serializers.ModelSerializer):
    categoria = serializers.StringRelatedField()
    modalidade = serializers.StringRelatedField()
    localizacao = serializers.StringRelatedField()
    instituicao = serializers.StringRelatedField()

    class Meta:
        model = Plano
        fields = [
            'id', 'nome', 'localizacao', 'instituicao', 'modalidade', 'categoria',
            'frequencia_semanal', 'carga_horaria', 'quantidade_alunos', 'valor_unitario',
            'taxa_matricula', 'informacoes_adicionais',
        ]
</code>```

Please help me haha.

答:
I recoment change your JSON to anything similar to:

```<code>[{
     "category_id":1,
     "category_name":"Category 1",
     "category_items":[
        {
           "id":1,
           "nome":"Test",
           "localizacao":"Example",
           "instituicao":"Example",
           "modalidade":"Example",
           "frequencia_semanal":1,
           "carga_horaria":2,
           "quantidade_alunos":2,
           "valor_unitario":"12.00",
           "taxa_matricula":"12.00",
           "informacoes_adicionais":""
        }
     ]
  }]
</code>```

And is more easy, create using neested serializer.
https://www.django-rest-framework.org/api-guide/relations/#nested-relationships

Body:
I'm using Django rest framework serializer to return plans for a mobile application. For now my serializer response looks like this:

[
    {
        "id": 1,
        "nome": "Test",
        "localizacao": "Example - MG",
        "instituicao": "Example",
        "modalidade": "Example",
        "categoria": "Category 1",
        "frequencia_semanal": 1,
        "carga_horaria": 2,
        "quantidade_alunos": 2,
        "valor_unitario": "12.00",
        "taxa_matricula": "12.00",
        "informacoes_adicionais": ""
    }
]

I need to separate plans by category so, response structure must look like this:

[
    "Category 1": [
        {
            "id": 1,
            "nome": "Test",
            "localizacao": "Example",
            "instituicao": "Example",
            "modalidade": "Example",
            "frequencia_semanal": 1,
            "carga_horaria": 2,
            "quantidade_alunos": 2,
            "valor_unitario": "12.00",
            "taxa_matricula": "12.00",
            "informacoes_adicionais": ""
        }
    ]
]

The "categoria" value, must be keys and all plans belonging to that category must be contained in the key.

there is my models.py

class Plano(models.Model):
    PUBLICO_ALVO_MENORES = 1
    PUBLICO_ALVO_ADOLESCENTES = 2
    PUBLICO_ALVO_ADULTOS = 3
    PUBLICO_ALVO_TODOS = 4
    PUBLICO_ALVO_CHOICES = (
        (PUBLICO_ALVO_MENORES, 'Menores'),
        (PUBLICO_ALVO_ADOLESCENTES, 'Adolecentes'),
        (PUBLICO_ALVO_ADULTOS, 'Adultos'),
        (PUBLICO_ALVO_TODOS, 'Todas as idades'),
    )
    nome = models.CharField(max_length=200)
    localizacao = models.ForeignKey('Localizacao', on_delete=models.PROTECT)
    instituicao = models.ForeignKey('Instituicao', null=True, on_delete=models.PROTECT)
    modalidade = models.ForeignKey('PlanoModalidade', verbose_name='Modalidades', on_delete=models.PROTECT)
    categoria = models.ForeignKey('PlanoCategoria', verbose_name='Categorias', on_delete=models.PROTECT)
    publico_alvo = models.SmallIntegerField(choices=PUBLICO_ALVO_CHOICES, null=True)
    frequencia_semanal = models.PositiveSmallIntegerField(verbose_name='Frequência semanal')
    carga_horaria = models.PositiveSmallIntegerField(verbose_name='Carga horária diária')
    quantidade_alunos = models.PositiveSmallIntegerField(verbose_name='Quantidade de alunos')
    valor_unitario = models.DecimalField(decimal_places=2, max_digits=18, verbose_name='Valor unitário')
    taxa_matricula = models.DecimalField(decimal_places=2, max_digits=18, verbose_name='Taxa matrícula')
    informacoes_adicionais = models.TextField(max_length=200, blank=True)

DRF serializers.py

class PlanosSerializer(serializers.ModelSerializer):
    categoria = serializers.StringRelatedField()
    modalidade = serializers.StringRelatedField()
    localizacao = serializers.StringRelatedField()
    instituicao = serializers.StringRelatedField()

    class Meta:
        model = Plano
        fields = [
            'id', 'nome', 'localizacao', 'instituicao', 'modalidade', 'categoria',
            'frequencia_semanal', 'carga_horaria', 'quantidade_alunos', 'valor_unitario',
            'taxa_matricula', 'informacoes_adicionais',
        ]

Please help me haha.

Body:
I recoment change your JSON to anything similar to:

[{
     "category_id":1,
     "category_name":"Category 1",
     "category_items":[
        {
           "id":1,
           "nome":"Test",
           "localizacao":"Example",
           "instituicao":"Example",
           "modalidade":"Example",
           "frequencia_semanal":1,
           "carga_horaria":2,
           "quantidade_alunos":2,
           "valor_unitario":"12.00",
           "taxa_matricula":"12.00",
           "informacoes_adicionais":""
        }
     ]
  }]

And is more easy, create using neested serializer.
https://www.django-rest-framework.org/api-guide/relations/#nested-relationships


问:
Reading scores from txt and displaying highest score and records of it
Starting Out with Python chapter 6 exercise:

High Score
Assume that a file named scores.txt exists on the computer’s disk. It contains a series of records, each with two fields – a name, followed by a score (an integer between 1 and 100). Write a program that displays the name and score of the record with the highest score, as well as the number of records in the file. (Hint: Use a variable and an “if” statement to keep track of the highest score found as you read through the records, and a variable to keep count of the number of records.)

Data in grades.txt
Jennifer 89
Pearson 90
Nancy 95
Gina 100
Harvey 98
Mike 99
Ross 15
Test 90
```

<hr>

```file=open('grades.txt','r')
my_list=[]

num_of_records=0
highest_score=1
highest_score_name=''

for line in file:
    name,score=line.strip().split()
    if int(score)>highest_score:
        highest_score=int(score)
        highest_score_name=name

    num_of_records=num_of_records+1

print('the name and score of the record with highest score:')
print('Name:',highest_score_name)
print('Score:',highest_score)

print('\nNumber of records:',num_of_records)

file.close()
```

<p>Total starter with python here and trying to get through the book
however hitting error with this question.</p>

<p>Error:</p>

```line 9, in <module> name,score=line.strip().split()
  ValueError: not enough values to unpack (expected 2, got 0)
```

Any guides is appreciated.

答:
According to your comment you hit this error:

```<code>line 9, in <module> name,score=line.strip().split() ValueError: not enough values to unpack (expected 2, got 0)
</code>```

This indicates a problem in one line of the file. I assume there's an empty line in your file. You could either check for that before unpacking the value or do an error handling with try/except. As you're quite early in, I think checking if the line contains anything is on par with the learning progress:

```<code>if line.strip():
    name,score=line.split()
</code>```

This way you're only unpacking the line if the variable isn't empty after removing whitespaces.

Body:
Starting Out with Python chapter 6 exercise:

High Score
Assume that a file named scores.txt exists on the computer’s disk. It contains a series of records, each with two fields – a name, followed by a score (an integer between 1 and 100). Write a program that displays the name and score of the record with the highest score, as well as the number of records in the file. (Hint: Use a variable and an “if” statement to keep track of the highest score found as you read through the records, and a variable to keep count of the number of records.)

Data in grades.txt
Jennifer 89
Pearson 90
Nancy 95
Gina 100
Harvey 98
Mike 99
Ross 15
Test 90

file=open('grades.txt','r')
my_list=[]

num_of_records=0
highest_score=1
highest_score_name=''

for line in file:
    name,score=line.strip().split()
    if int(score)>highest_score:
        highest_score=int(score)
        highest_score_name=name

    num_of_records=num_of_records+1

print('the name and score of the record with highest score:')
print('Name:',highest_score_name)
print('Score:',highest_score)

print('\nNumber of records:',num_of_records)

file.close()

Total starter with python here and trying to get through the book
however hitting error with this question.

Error:

line 9, in <module> name,score=line.strip().split()
  ValueError: not enough values to unpack (expected 2, got 0)

Any guides is appreciated.

Body:
According to your comment you hit this error:

line 9, in <module> name,score=line.strip().split() ValueError: not enough values to unpack (expected 2, got 0)

This indicates a problem in one line of the file. I assume there's an empty line in your file. You could either check for that before unpacking the value or do an error handling with try/except. As you're quite early in, I think checking if the line contains anything is on par with the learning progress:

if line.strip():
    name,score=line.split()

This way you're only unpacking the line if the variable isn't empty after removing whitespaces.


问:
How to redirect to another component after checking conditions in angular 8?
I am new to Angular 8 and i am making a login component and after entering username password i want to redirect to another component using route thats my code i have done this much :

my login component.ts:

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

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  myForm:FormGroup
  submitted=false;
  _baseURL : string;
  formvalid: boolean;
   user:string;
   pwd:string;
  constructor(private formbuilder:FormBuilder){}

  ngOnInit(){
    this.myForm = this.formbuilder.group({
    username:['',Validators.required],
    password:['',[Validators.required,Validators.pattern("^(?=.*?[a-z])(.{13,}|(?=.*?[A-Z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,12})$")]]
    });
    this._baseURL="";
    this.formvalid=false;
  }

  Submitme(){
    this.submitted = true;

    if (this.myForm.invalid) {
      this.formvalid=false;
        return;
    }
    if (this.myForm.valid) {
      this.formvalid=true;
    this._baseURL= 'Welcome'+" "+ this.myForm.controls.username.value;
  }
  this.user=this.myForm.controls.username.value;
  this.pwd=this.myForm.controls.password.value;
}
rest(){
  this.myForm.reset();
  this.submitted = false;
}
}
</code>```

my login component html is:

```<code>        <h1 class="text-center" [hidden]="formvalid">Login</h1>
          <form [formGroup]="myForm" (ngSubmit)="Submitme()" class="text-center">
           <div class="container bg-dark" [hidden]="formvalid" style="border: 1px solid black;">
         <div class="row mt-3">
           <div class="col-lg-5">
         <label for="name" class="text-white">Username :</label>
         </div>
         <input type="text" formControlName="username" class="col-lg-4 form-control"
           [ngClass]="{ 'is-invalid': submitted && myForm.controls.username.errors }">
          <div *ngIf="submitted && myForm.controls.username.errors" class="text-danger">
            <div *ngIf="myForm.controls.username.errors.required">First Name is required</div>
        </div>
       </div>
     <div class="row mt-2">
           <div class="col-lg-5">
       <label for="pwd" class="text-white">Password :</label>
         </div>
      <input type="password" formControlName="password" class="col-lg-4 form-control"
      [ngClass]="{ 'is-invalid': submitted && myForm.controls.password.errors }">
       <div *ngIf="submitted && myForm.controls.password.errors" class="text-danger">
     <div *ngIf="myForm.controls.password.errors.required">password is required</div>
      <div *ngIf="myForm.controls.password.errors.pattern">Pwd must contain atleast one upper and
    lower case character one special character one digit and 8 characters in length  </div>
   </div>
    </div>
     <button class="btn btn-primary mt-2 mb-3" type="submit"
   [routerLink]="'/afterlog'">Submit</button>
     <input type="button" (click)="rest()" value="Reset" class="btn btn-primary mt-2 mb-3">
 </div>
      </form>
</code>```

After login i want to redirect to another component with welcome message using routing in angular 8:
Thanks in advance!!!!

答:
So if I understand correctly you want to navigate to a new page after they submit the form?

First you need to inject the Router class in your constructor.
Add this in your constructor:
private router: Router

And add this import: import { Router } from '@angular/router';

Now you can make use of the Router class in your TS file.

to navigate to an other page you use this syntax: this.router.navigate(['/']);
The example above would to to the home page.

You can also navigate relative to some path like this:
First add this to your constructor: private route: ActivatedRoute
And import ActivatedRoute
Then you can navigate relative to the current route like this: this.router.navigate(['../../'], { relativeTo: this.route });

this.route is the ActivatedRoute reference

For more on routing and navigation check: https://angular.io/guide/router

Body:
I am new to Angular 8 and i am making a login component and after entering username password i want to redirect to another component using route thats my code i have done this much :

my login component.ts:

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

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  myForm:FormGroup
  submitted=false;
  _baseURL : string;
  formvalid: boolean;
   user:string;
   pwd:string;
  constructor(private formbuilder:FormBuilder){}

  ngOnInit(){
    this.myForm = this.formbuilder.group({
    username:['',Validators.required],
    password:['',[Validators.required,Validators.pattern("^(?=.*?[a-z])(.{13,}|(?=.*?[A-Z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,12})$")]]
    });
    this._baseURL="";
    this.formvalid=false;
  }

  Submitme(){
    this.submitted = true;

    if (this.myForm.invalid) {
      this.formvalid=false;
        return;
    }
    if (this.myForm.valid) {
      this.formvalid=true;
    this._baseURL= 'Welcome'+" "+ this.myForm.controls.username.value;
  }
  this.user=this.myForm.controls.username.value;
  this.pwd=this.myForm.controls.password.value;
}
rest(){
  this.myForm.reset();
  this.submitted = false;
}
}

my login component html is:

Login

          <form [formGroup]="myForm" (ngSubmit)="Submitme()" class="text-center">

         Username :

         <input type="text" formControlName="username" class="col-lg-4 form-control"
           [ngClass]="{ 'is-invalid': submitted && myForm.controls.username.errors }">

First Name is required

       Password :

      <input type="password" formControlName="password" class="col-lg-4 form-control"
      [ngClass]="{ 'is-invalid': submitted && myForm.controls.password.errors }">

password is required

Pwd must contain atleast one upper and
    lower case character one special character one digit and 8 characters in length

     <button class="btn btn-primary mt-2 mb-3" type="submit"
   [routerLink]="'/afterlog'">Submit</button>
     <input type="button" (click)="rest()" value="Reset" class="btn btn-primary mt-2 mb-3">

      </form>

After login i want to redirect to another component with welcome message using routing in angular 8:
Thanks in advance!!!!


问:
How to stop java replaceAll() from removing backslash?
I am writing some simple java code that looks in a string to find a value called REPLACEALL. Once it finds that string I have it replace it with a path name as a value (ex:D:\test\path\something). However, when I run the code it replace it fine but it removes the single  \. I am not sure why and have set up  a debug to see where it is happening. The original string gets passed in fine, its only when the string goes through the replaceAll() that it causes this issue.

Java:

```<code>String path = "D:\test\path\something";
String s1="select * from Webserver WHERE data= REPLCAEME";
String replaceString=s1.replaceAll("REPLACEME"," ' " + path + " ' ");
System.out.println(replaceString);
</code>```

答: The backslash is used as an escape character in strings, which means that you have to escape it itself as \\. Otherwise, it denotes special characters, e.g., \t denotes a tab space, so in your example \test effectively means <tab>est.

Body:
I am writing some simple java code that looks in a string to find a value called REPLACEALL. Once it finds that string I have it replace it with a path name as a value (ex:D:\test\path\something). However, when I run the code it replace it fine but it removes the single  \. I am not sure why and have set up  a debug to see where it is happening. The original string gets passed in fine, its only when the string goes through the replaceAll() that it causes this issue.

Java:

String path = "D:\test\path\something";
String s1="select * from Webserver WHERE data= REPLCAEME";
String replaceString=s1.replaceAll("REPLACEME"," ' " + path + " ' ");
System.out.println(replaceString);


问:
Why EventTarget subclass instances lose their names?
The current version of JavaScript implements EventTarget as a class instead of an interface, so you can create an instance of EventTarget with all the expected methods.

I tried to copy/paste the EventTarget example in the console (on both Chrome and Firefox) but when I inspect the myEventTarget object (that is build as a subclass of EventTarget named MyEventTarget), the console says that myEventTarget is an EventTarget, not a MyEventTarget.

This is the code

//this is the MDN example
class MyEventTarget extends EventTarget {
  constructor(mySecret) {
    super();
    this._secret = mySecret;
  }

  get secret() { return this._secret; }
};

let myEventTarget = new MyEventTarget(5);
let value = myEventTarget.secret;  // == 5
myEventTarget.addEventListener("foo", function(e) {
  this._secret = e.detail;
});

let event = new CustomEvent("foo", { detail: 7 });
myEventTarget.dispatchEvent(event);
let newValue = myEventTarget.secret; // == 7

// the following is the code I have added
// everything seems to work as usual, ie
console.log(myEventTarget instanceof MyEventTarget)
// the console says that is true

// but if I try to print the instance...
console.log(myEventTarget)
// EventTarget { _secret: 7 }
```

<p>Why the console says that myEventTarget is just an EventTarget?</p>

<p>I found this thing quite uncommon because if I type the following code the console says that myEventTarget is actually a MyEventTarget instance</p>

<pre class="lang-js prettyprint-override"><code>class MyEventTarget extends class SomeOtherClass{} {
  constructor(mySecret) {
    super();
    this._secret = mySecret;
  }

  get secret() { return this._secret; }
};

let myEventTarget = new MyEventTarget(5);

console.log(myEventTarget instanceof MyEventTarget)
// the console diligently says that is true

// and if I try to print the instance...
console.log(myEventTarget)
// ...the console correcly says
// MyEventTarget { _secret: 5 }
</code>```

so if I use EventTarget as superclass, the instances lose their constructor name?
I understand that is not a big deal, I think that print class names is just for debugging purpose but there is a reason for this?

答:
This happens because EventTarget overrides Symbol.toStringTag and you inherit this behaviour. You can override it to be whatever you want.

class MyEventTarget extends EventTarget {
  constructor(mySecret) {
    super();
    this._secret = mySecret;
  }

  get secret() { return this._secret; }

  get [Symbol.toStringTag]() {
    return this.constructor.name
  }
};

let myEventTarget = new MyEventTarget(5);
let value = myEventTarget.secret;  // == 5
myEventTarget.addEventListener("foo", function(e) {
  this._secret = e.detail;
});

let event = new CustomEvent("foo", { detail: 7 });
myEventTarget.dispatchEvent(event);
let newValue = myEventTarget.secret; // == 7

// the following is the code I have added
// everything seems to work as usual, ie
console.log(myEventTarget instanceof MyEventTarget)
// the console says that is true

// but if I try to print the instance...
console.log(myEventTarget)
// MyEventTarget { _secret: 7 }

console.log(Object.prototype.toString.call(myEventTarget))
// [object MyEventTarget]```

Body:
The current version of JavaScript implements EventTarget as a class instead of an interface, so you can create an instance of EventTarget with all the expected methods.

I tried to copy/paste the EventTarget example in the console (on both Chrome and Firefox) but when I inspect the myEventTarget object (that is build as a subclass of EventTarget named MyEventTarget), the console says that myEventTarget is an EventTarget, not a MyEventTarget.

This is the code

//this is the MDN example
class MyEventTarget extends EventTarget {
  constructor(mySecret) {
    super();
    this._secret = mySecret;
  }

  get secret() { return this._secret; }
};

let myEventTarget = new MyEventTarget(5);
let value = myEventTarget.secret;  // == 5
myEventTarget.addEventListener("foo", function(e) {
  this._secret = e.detail;
});

let event = new CustomEvent("foo", { detail: 7 });
myEventTarget.dispatchEvent(event);
let newValue = myEventTarget.secret; // == 7

// the following is the code I have added
// everything seems to work as usual, ie
console.log(myEventTarget instanceof MyEventTarget)
// the console says that is true

// but if I try to print the instance...
console.log(myEventTarget)
// EventTarget { _secret: 7 }

Why the console says that myEventTarget is just an EventTarget?

I found this thing quite uncommon because if I type the following code the console says that myEventTarget is actually a MyEventTarget instance

class MyEventTarget extends class SomeOtherClass{} {
  constructor(mySecret) {
    super();
    this._secret = mySecret;
  }

  get secret() { return this._secret; }
};

let myEventTarget = new MyEventTarget(5);

console.log(myEventTarget instanceof MyEventTarget)
// the console diligently says that is true

// and if I try to print the instance...
console.log(myEventTarget)
// ...the console correcly says
// MyEventTarget { _secret: 5 }

so if I use EventTarget as superclass, the instances lose their constructor name?
I understand that is not a big deal, I think that print class names is just for debugging purpose but there is a reason for this?


问:
How to create an empty java trust store?
I want to make a https client in java which initially does not have any CA certs to trust. Since I don't want the JVM to use the default cacerts file I should make an empty trust store and point it to the JVM.

How can I make an empty trust store?

答:
Using keytool, create a random key pair:

```<code>keytool -genkeypair -alias boguscert -storepass storePassword -keypass secretPassword -keystore emptyStore.keystore -dname "CN=Developer, OU=Department, O=Company, L=City, ST=State, C=CA"
</code>```

then delete it

```<code>keytool -delete -alias boguscert -storepass storePassword -keystore emptyStore.keystore
</code>```

review its contents:

```<code>$ keytool -list -keystore emptyStore.keystore -storepass storePassword
Keystore type: JKS
Keystore provider: SUN
Your keystore contains 0 entries
</code>```

Body:
Using keytool, create a random key pair:

keytool -genkeypair -alias boguscert -storepass storePassword -keypass secretPassword -keystore emptyStore.keystore -dname "CN=Developer, OU=Department, O=Company, L=City, ST=State, C=CA"

then delete it

keytool -delete -alias boguscert -storepass storePassword -keystore emptyStore.keystore

review its contents:

$ keytool -list -keystore emptyStore.keystore -storepass storePassword
Keystore type: JKS
Keystore provider: SUN
Your keystore contains 0 entries


问:
How do I handle the "don't ask again" checkbox in Android Runtime Permission?
I want to handle this checkbox and take action accordingly.
The process I want to do is as follows;
User triggers permission,

Dont do anything if the user denied permission

User triggers permission again

This time checkbox marks.

Again, there is no action.

The user triggers permission again.

This time the dialog show to go to the settings.

Most apps show the go to settings dialog after the second rejection. I dont want this.

答: if check box is checked store it using shared pref</p>


问:
rundeck question - enable auto-refresh on activity - its disabled by default
Running into an inconvenience of a default and not settable via the gui. The subject says it all. Auto-refresh in Activity pane of rundeck GUI is off by default. How to set it for an all-user default of 60 seconds?</p>

答: Right now doesn't exist a way to enable by default and set a custom interval for Activity panel, you can suggest that here. </p>


问:
Is there a way to do groupby in pandas such that same feature is used in both row and columns?
Input table:

```<code>person    cat1    cat2
   P1        A    X
   P1        B    X
   P2        A    X
   P2        B    Y
   P3        A    X
   P3        B    Y
</code>```

Required table:

```<code>             B
        X    Y    Z
     X  1    2    0
A    Y  0    0    0
     Z  0    0    0
</code>```

The aggregation function can be unique persons - nunique()

Code till now:
df.groupby(['cat1','cat2']).person.nunique().unstack()

But this does not give the right table. Any help on how to do this?

答:
This is fairly ugly, but seems to do the job:

```<code>df1 = df.groupby('person').apply(lambda g:
    g.pivot_table('cat2', None, 'cat1', aggfunc=lambda x: x)
)
df2 = df1.reset_index().drop('level_1', axis=1)
df3 = df2.pivot_table(None, 'A', 'B', aggfunc=lambda x: len(x))
</code>```

Now sure how efficient it is on "Big Data" (TM).

Essentially, df1 contains as many columns as the values for cat1, filled with the value in cat2:

```<code>cat1         A  B
person
p1     cat2  X  X
p2     cat2  X  Y
p3     cat2  X  Y
</code>```

df2 is the same with clutter removed:

```<code>cat1 person  A  B
0        p1  X  X
1        p2  X  Y
2        p3  X  Y
</code>```

and df3 contains the result:

```<code>  person
B      X  Y
A
X      1  2
</code>```

Body:
Input table:

person    cat1    cat2
   P1        A    X
   P1        B    X
   P2        A    X
   P2        B    Y
   P3        A    X
   P3        B    Y

Required table:

             B
        X    Y    Z
     X  1    2    0
A    Y  0    0    0
     Z  0    0    0

The aggregation function can be unique persons - nunique()

Code till now:
df.groupby(['cat1','cat2']).person.nunique().unstack()

But this does not give the right table. Any help on how to do this?

Body:
This is fairly ugly, but seems to do the job:

df1 = df.groupby('person').apply(lambda g:
    g.pivot_table('cat2', None, 'cat1', aggfunc=lambda x: x)
)
df2 = df1.reset_index().drop('level_1', axis=1)
df3 = df2.pivot_table(None, 'A', 'B', aggfunc=lambda x: len(x))

Now sure how efficient it is on "Big Data" (TM).

Essentially, df1 contains as many columns as the values for cat1, filled with the value in cat2:

cat1         A  B
person
p1     cat2  X  X
p2     cat2  X  Y
p3     cat2  X  Y

df2 is the same with clutter removed:

cat1 person  A  B
0        p1  X  X
1        p2  X  Y
2        p3  X  Y

and df3 contains the result:

  person
B      X  Y
A
X      1  2


问:
Jquery clone original HTML not DOM
I need to clone a section of markup that has already been modified in the DOM. I want to get the original HTML source - what is seen in View > Source.

clone() uses what's in the DOM

答:
You can't.

If you need it, store the original markup in a JavaScript var before making any modifications.

Title: Jquery clone original HTML not DOM


问:
How to support both vcxproj to cmake on a project?
I'm developing cross-platform c++ project. The original idea is to work with msvc2010 and later compile for other systems with the help of CMake and Hudson.
It doesn't seem to be convenient manually change CMake files after changes in studio settings.

So, what’s the easiest way: to write parser for vcxproj and vcxproj.filters, or there is another good solution?

答: The best tool for this purprose is cmake-converter</p>


问:
Service Workers - selectively choose resources
I have a simple Service Worker implementation like this:

```<code>var CACHE_NAME = "app-cache-v1";
var urlsToCache = ["./style/main.css", "./app.ts.js"];

self.addEventListener("install", function(event) {
    event.waitUntil(
        caches.open(CACHE_NAME).then(function(cache) {
            return cache.addAll(urlsToCache);
        })
    );
});
self.addEventListener("activate", function(event) {
    event.waitUntil(
        caches.keys().then(function(cacheNames) {
            return Promise.all(
                cacheNames.map(function(cacheName) {
                    return caches.delete(cacheName);
                })
            );
        })
    );
});

self.addEventListener("fetch", function(event) {
    event.respondWith(
        fetch(event.request).catch(function() {
            return caches.match(event.request);
        })
    );
});
</code>```

My goal is to cache all resources except the two files indicated in the urlsToCache variable, these two files should ALWAYS be requested from the network.. How can i achieve this? How can I then verify that it is actually so?

答:
You can check the url of the request in fetch event handler before deciding what caching strategy to use:</p>

```<code>self.addEventListener("fetch", function(event) {
  const url = new URL(event.request.clone().url);
  if (urlsToCache.indexOf(url.pathname) !== -1) { // check if current url exists in your array
     event.respondWith(
         // without cacheing
     );
  } else {
     event.respondWith(
        // with cacheing
     );
  }
</code>```

Body:
I have a simple Service Worker implementation like this:

var CACHE_NAME = "app-cache-v1";
var urlsToCache = ["./style/main.css", "./app.ts.js"];

self.addEventListener("install", function(event) {
    event.waitUntil(
        caches.open(CACHE_NAME).then(function(cache) {
            return cache.addAll(urlsToCache);
        })
    );
});
self.addEventListener("activate", function(event) {
    event.waitUntil(
        caches.keys().then(function(cacheNames) {
            return Promise.all(
                cacheNames.map(function(cacheName) {
                    return caches.delete(cacheName);
                })
            );
        })
    );
});

self.addEventListener("fetch", function(event) {
    event.respondWith(
        fetch(event.request).catch(function() {
            return caches.match(event.request);
        })
    );
});

My goal is to cache all resources except the two files indicated in the urlsToCache variable, these two files should ALWAYS be requested from the network.. How can i achieve this? How can I then verify that it is actually so?

Body:
You can check the url of the request in fetch event handler before deciding what caching strategy to use:

self.addEventListener("fetch", function(event) {
  const url = new URL(event.request.clone().url);
  if (urlsToCache.indexOf(url.pathname) !== -1) { // check if current url exists in your array
     event.respondWith(
         // without cacheing
     );
  } else {
     event.respondWith(
        // with cacheing
     );
  }


问:
App Build Failed with an Exception in react native, A problem occur in evaluating script
i m new in react native.. when i was run my app following error occurred in command line. Kindly guide me with an appropriate solution... Thanks.

FAILURE: Build failed with an exception.

Where:
Script 'E:\My Final Year Project\Home_Page\node_modules@react-native-community\cli-platform-android\native_modules.gradle' line: 170

What went wrong:
A problem occurred evaluating script.

internal/modules/cjs/loader.js:797    throw err;    ^Error: Cannot find module '@react-native-community/cli'Require stack:- E:\My Final Year Project\Home_Page\android[eval]    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:794:15)    at Function.Module._load (internal/modules/cjs/loader.js:687:27)    at Module.require (internal/modules/cjs/loader.js:849:19)    at require (internal/modules/cjs/helpers.js:74:18)    at [eval]:1:13    at Script.runInThisContext (vm.js:116:20)    at Object.runInThisContext (vm.js:306:38)    at Object. ([eval]-wrapper:9:26)    at Module._compile (internal/modules/cjs/loader.js:956:30)    at evalScript (internal/process/execution.js:80:25) {  code: 'MODULE_NOT_FOUND',  requireStack: [ 'E:\My Final Year Project\Home_Page\android\[eval]' ]}

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 36s

error Failed to install the app. Make sure you have the Android development environment set up: https://facebook.github.io/react-native/docs/getting-started.html#android-development-environment. Run CLI with --verbose flag for more details.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081
:ReactNative:Unexpected empty result of running 'node -e console.log(require('@react-native-community/cli').bin);' command.
:ReactNative:Running 'node -e console.log(require('@react-native-community/cli').bin);' command failed.

答:
This happened to me with react-native 0.61.5 and cli version 1.0.9.

Updating @react-native-community/cli worked for me.

$ npm install @react-native-community/cli@4.0.1


问:
Merge query to distribute equal number of records between 100 users
I have two tables in Oracle, in first table I have 100 users and in second table I have 100000 records. I want to distribute equal amount of records between them.....

Instead of writing updating and using rownum <= 1000 to distribute data....I want to write merge statement that can divide equal number of records between 100 users.

Table 1

```<code>column A Column B  column c
  1       Pre      90008765
  2      Pre      90008766 and so on like this
</code>```

Table 2

```<code>column a Column B column C Column d
1         null     null    null
2          null    null    null
And so on will have 100000 records
</code>```

and between these two tables column a will be common in which we can apply join condition..... please guide me with merge query

答:
If I understand correctly these words "write merge statement that can divide equal number of records between 100 users", you want this:

```<code>merge into table2 tgt
using (
select tb.rwd, ta.a
  from (select rownum rn, a, b, c, count(1) over () cnt from table1) ta
  join (select rowid rwd, rownum rn, a, b, c, d from table2) tb
    on mod(ta.rn, cnt) = mod(tb.rn, cnt)) src
on (tgt.rowid = src.rwd)
when matched then update set a = src.a
</code>```

dbfiddle

This statement assigns rows from T1 to rows in T2 in sequence 1-2-3-...-1-2-3-..., using function mod(). Of course you can update other columns if you need, not only A.

Body:
I have two tables in Oracle, in first table I have 100 users and in second table I have 100000 records. I want to distribute equal amount of records between them.....

Instead of writing updating and using rownum <= 1000 to distribute data....I want to write merge statement that can divide equal number of records between 100 users.

Table 1

column A Column B  column c
  1       Pre      90008765
  2      Pre      90008766 and so on like this

Table 2

column a Column B column C Column d
1         null     null    null
2          null    null    null
And so on will have 100000 records

and between these two tables column a will be common in which we can apply join condition..... please guide me with merge query

Body:
If I understand correctly these words "write merge statement that can divide equal number of records between 100 users", you want this:

merge into table2 tgt
using (
select tb.rwd, ta.a
  from (select rownum rn, a, b, c, count(1) over () cnt from table1) ta
  join (select rowid rwd, rownum rn, a, b, c, d from table2) tb
    on mod(ta.rn, cnt) = mod(tb.rn, cnt)) src
on (tgt.rowid = src.rwd)
when matched then update set a = src.a

dbfiddle

This statement assigns rows from T1 to rows in T2 in sequence 1-2-3-...-1-2-3-..., using function mod(). Of course you can update other columns if you need, not only A.