问:
How to view committed kafka message only
I am currently using Kadeck community and sometimes commands on docker to view messages saved on kafka, but now I am testing transactional semantics and I want only to view committed messages. I am having a hard time to do this. Anyone know how to view committed messages only even using other 3rd party application such as Kadeck. Thanks! </p>

答:
You can do it using the kafka tools:

```<code>kafka-consumer-groups  --bootstrap-server broker01.example.com:9092 --describe --group your_group
</code>```

This command shows the state of topics of a consumer-group:

```<code>GROUP        TOPIC  PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG     OWNER
your-group   t1     0          1               3               2       test-consumer
</code>```

To see the committed messages you must read from the beginning until the current-offset with kafka-console-consumer or another kafka client.

Body:
You can do it using the kafka tools:

kafka-consumer-groups  --bootstrap-server broker01.example.com:9092 --describe --group your_group

This command shows the state of topics of a consumer-group:

GROUP        TOPIC  PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG     OWNER
your-group   t1     0          1               3               2       test-consumer

To see the committed messages you must read from the beginning until the current-offset with kafka-console-consumer or another kafka client.


来源: stackexchange

问:
Why does my PHP string comparison fail?
I have the following snippet of code

```<code>if ($summary == "CFD funding Interest Paid" ||
    $summary == "Commissions" ||
    $summary == "Closing trades") {
    print $summary.",".$date.",".$reference.",".$description.",".$amount."<br>";
}
else {
    print $summary."*<br>";
}
</code>```

It outputs the following

```
Commissions*
Commissions*
Closing trades*
Commissions*
Closing trades*
```

How come the strings do not appear to be matching?

答: Use the strcmp(str1, str2) function instead.

ContentLicense: CC BY-SA 3.0

Title: Why does my PHP string comparison fail?

Body:
I have the following snippet of code

if ($summary == "CFD funding Interest Paid" ||
    $summary == "Commissions" ||
    $summary == "Closing trades") {
    print $summary.",".$date.",".$reference.",".$description.",".$amount."
";
}
else {
    print $summary."*
";
}

It outputs the following

Commissions*
Commissions*
Closing trades*
Commissions*
Closing trades*

How come the strings do not appear to be matching?


问:
Python strings, algorithms (like (as in facebook like) system)
Here's what I need to do:
Implement a function likes :: [String] -> String, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples:

```<code>likes [] // must be "no one likes this"
likes ["Peter"] // must be "Peter likes this"
likes ["Jacob", "Alex"] // must be "Jacob and Alex like this"
likes ["Max", "John", "Mark"] // must be "Max, John and Mark like this"
likes ["Alex", "Jacob", "Mark", "Max"] // must be "Alex, Jacob and 2 others like this"
</code>```

Here's my code so far, only the 1st and second examples are correct, and I can't figure out how to convert ['Peter'] to 'Peter' and how to only put 'and' in the end(between last two people/values:

```<code>def likes(names):
    if names == []:
        return str("no one likes this")
    elif len(names) == 1:
        return (str(names)) + " likes this"
    elif 1<len(names)<=3:
        return " and ".join(map(str,names)) + " like this"
    else:
        return ", ".join(map(str,names)) + " and " + str(len(names)-2)+" others like this"
</code>```

The output for the first case is:
     "['Peter'] likes this" (should equal 'Peter likes this')
and for the last 2 cases:
    'Max and John and Mark like this' (should equal 'Max, John and Mark like this'),
    'Alex and Jacob and Mark and Max and 2 others like this' (should equal 'Alex, Jacob and 2 others like
    this')

I think I am quite close and would greatly appreciate any clarification!

答:
You can access the first item of the List with names[0].
I've also removed the unneeded map call.</p>

```<code>def likes(names):
    if len(names) == 0:
        return "no one likes this"
    elif len(names) == 1:
        return names[0] + " likes this"
    elif 1 < len(names) <= 3:
        return " and ".join(names) + " like this"
    else:
        return ", ".join(names[0:2]) + f" and {str(len(names)-2)} others like this"

print(likes([]))                  # must be "no one likes this"
print(likes(["Peter"]))            # must be "Peter likes this"
print(likes(["Jacob", "Alex"]))    # must be "Jacob and Alex like this"
print(likes(["Max", "John", "Mark"]))          # must be "Max, John and Mark like this"
print(likes(["Alex", "Jacob", "Mark", "Max"])) # must be "Alex, Jacob and 2 others like this"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here's what I need to do:
Implement a function likes :: [String] -> String, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples:

likes [] // must be "no one likes this"
likes ["Peter"] // must be "Peter likes this"
likes ["Jacob", "Alex"] // must be "Jacob and Alex like this"
likes ["Max", "John", "Mark"] // must be "Max, John and Mark like this"
likes ["Alex", "Jacob", "Mark", "Max"] // must be "Alex, Jacob and 2 others like this"

Here's my code so far, only the 1st and second examples are correct, and I can't figure out how to convert ['Peter'] to 'Peter' and how to only put 'and' in the end(between last two people/values:

def likes(names):
    if names == []:
        return str("no one likes this")
    elif len(names) == 1:
        return (str(names)) + " likes this"
    elif 1<len(names)<=3:
        return " and ".join(map(str,names)) + " like this"
    else:
        return ", ".join(map(str,names)) + " and " + str(len(names)-2)+" others like this"

The output for the first case is:
     "['Peter'] likes this" (should equal 'Peter likes this')
and for the last 2 cases:
    'Max and John and Mark like this' (should equal 'Max, John and Mark like this'),
    'Alex and Jacob and Mark and Max and 2 others like this' (should equal 'Alex, Jacob and 2 others like
    this')

I think I am quite close and would greatly appreciate any clarification!

Body:
You can access the first item of the List with names[0].
I've also removed the unneeded map call.

def likes(names):
    if len(names) == 0:
        return "no one likes this"
    elif len(names) == 1:
        return names[0] + " likes this"
    elif 1 < len(names) <= 3:
        return " and ".join(names) + " like this"
    else:
        return ", ".join(names[0:2]) + f" and {str(len(names)-2)} others like this"

print(likes([]))                  # must be "no one likes this"
print(likes(["Peter"]))            # must be "Peter likes this"
print(likes(["Jacob", "Alex"]))    # must be "Jacob and Alex like this"
print(likes(["Max", "John", "Mark"]))          # must be "Max, John and Mark like this"
print(likes(["Alex", "Jacob", "Mark", "Max"])) # must be "Alex, Jacob and 2 others like this"


问:
mysql query prints data of different rows in one row
I am using MySQL version 8.0 and popSQL as the editor.

Table:

```<code>create table account (no int, salary int);

insert into account values
(901,25000),
(902,30000),
(903,21000),
(904,40000),
(905,27000);
</code>```

Now, I want no and salary of person with highest salary.
Highest salary is 40000 and corresponding no is 904.
But, this query is giving me different output.

```<code>-- no and salary of max salary
select no, max(salary)
from account ;
</code>```

The output is:
no  max(salary)
901 40000

It is printing the first no and the max salary.
i.e. data of different rows are shown in a same row.
How to fix this???

Same type of problem for my next query.

```<code>-- no and salary of second highest salary.
select no, max(salary)
from account
where salary not in
(select max(salary) from account);
</code>```

The output is:
no  max(salary)
901 30000

Whereas expected is 902,30000.

I searched through the stack overflow for issue where data of different rows are shown in one but didn't get any help.

Thanking you in advance.

答:
MySQL version 5.7.5 and older is notorious for accepting malformed SQL queries.

In standard SQL when there's no GROUP BY clause, all columns must be aggregated or not. You, however, chose to aggregate one, but not the other. This is illegal in SQL and can lead to non-deterministic results. But... MySQL accepts it.

Use it at your own risk.

Note: This bad behavior can be enabled in future versions of MySQL for compatibility reasons. I would encourage you not to do such a thing.

Body:
I am using MySQL version 8.0 and popSQL as the editor.

Table:

create table account (no int, salary int);

insert into account values
(901,25000),
(902,30000),
(903,21000),
(904,40000),
(905,27000);

Now, I want no and salary of person with highest salary.
Highest salary is 40000 and corresponding no is 904.
But, this query is giving me different output.

-- no and salary of max salary
select no, max(salary)
from account ;

The output is:
no  max(salary)
901 40000

It is printing the first no and the max salary.
i.e. data of different rows are shown in a same row.
How to fix this???

Same type of problem for my next query.

-- no and salary of second highest salary.
select no, max(salary)
from account
where salary not in
(select max(salary) from account);

The output is:
no  max(salary)
901 30000

Whereas expected is 902,30000.

I searched through the stack overflow for issue where data of different rows are shown in one but didn't get any help.

Thanking you in advance.


问:
How to display Arraylist of type String in a dialogue
I have a Arraylist of String type. How can i display it on a dialogue to a user and him select the one.also the need is to highlight the earlier selection in the made by the user.
Some code example will be helpful.
thanks</p>

答:
Try this code in ur onCreate</p>

```<code>protected CharSequence[] Months = { "January", "February", "March", "April", "May","June", "July", "August", "September","October","November","December" };
Button selected_month = ( Button ) findViewById( R.id.button );
selected_month.setOnClickListener(new View.OnClickListener(){
                       new AlertDialog.Builder( <Classname>.this )
                  .setTitle( "Months" )
                      .setSingleChoiceItems( Months, 0, new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Toast.makeText(<Classname>.this, Months[which], Toast.LENGTH_SHORT).show();
            }

        })
        .setPositiveButton( "OK", new DialogButtonClickHandler() )
        .setNegativeButton("No", new DialogButtonClickHandler() )
        .create();
});
</code>```

Body:
Try this code in ur onCreate

protected CharSequence[] Months = { "January", "February", "March", "April", "May","June", "July", "August", "September","October","November","December" };
Button selected_month = ( Button ) findViewById( R.id.button );
selected_month.setOnClickListener(new View.OnClickListener(){
                       new AlertDialog.Builder( <Classname>.this )
                  .setTitle( "Months" )
                      .setSingleChoiceItems( Months, 0, new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Toast.makeText(<Classname>.this, Months[which], Toast.LENGTH_SHORT).show();
            }

        })
        .setPositiveButton( "OK", new DialogButtonClickHandler() )
        .setNegativeButton("No", new DialogButtonClickHandler() )
        .create();
});


问:
C# - ASP.NET MVC - Convert a List of object , to a List of string, to use in a Session
I have that typed List:

```<code>IEnumerable<Resource> ResourceAuthorizedForLoggedUser= resourceAuthorizer.FindAll();
</code>```

First a try this, but didn't work:

```<code>var authorizations= ResourceAuthorizedForLoggedUser.Select(x => x.Id).ToString();
</code>```

And I need to put inside that Session:

```<code>System.Web.HttpContext.Current.Session["Authorized_List"] = authorizations;
</code>```

To be able to access this data in the base controller

```<code>public class BaseController : Controller
{
   public static List<string> authorizations { get { return Getauthorizations(); } }

   private static List<string> Getauthorizations()
   {
      List<string> authorizationsList = (List<string>)System.Web.HttpContext.Current.Session["Authorized_List"];
      return authorizationsList != null && authorizationsList.Any() ? authorizationsList : new List<string>();
   }
}
</code>```

And in the end, I get the following error at Getauthorizations method:

It is not possible to convert an object of type 'System.String' to type 'System.Collections.Generic.List`1 [System.String]'

Any ideas how I can convert that list?

答:
I would write your code as follows:

First, you get your colletion of type Resource:

```<code> IEnumerable<Resource> ResourceAuthorizedForLoggedUser=
 resourceAuthorizer.FindAll();
</code>```

Then you save the list of Ids (I assume they are strings)

```<code> List<string> authorizations=
 ResourceAuthorizedForLoggedUser.Select(x=> x.Id).ToList();
</code>```

Save that in the session variable:

```<code> System.Web.HttpContext.Current.Session["Authorized_List"] =
 authorizations;
</code>```

Read it back from Session:

```<code>public class BaseController : Controller
     {
        public static List<string> authorizations { get { return Getauthorizations(); } }

   private static List<string> Getauthorizations()
   {
      List<string> authorizationsList = (List<string>)System.Web.HttpContext.Current.Session["Authorized_List"];
      return authorizationsList != null && authorizationsList.Any() ? authorizationsList : new List<string>();
   }
}`enter code here`
</code>```

Body:
I have that typed List:

IEnumerable<Resource> ResourceAuthorizedForLoggedUser= resourceAuthorizer.FindAll();

First a try this, but didn't work:

var authorizations= ResourceAuthorizedForLoggedUser.Select(x => x.Id).ToString();

And I need to put inside that Session:

System.Web.HttpContext.Current.Session["Authorized_List"] = authorizations;

To be able to access this data in the base controller

public class BaseController : Controller
{
   public static List<string> authorizations { get { return Getauthorizations(); } }

   private static List<string> Getauthorizations()
   {
      List<string> authorizationsList = (List<string>)System.Web.HttpContext.Current.Session["Authorized_List"];
      return authorizationsList != null && authorizationsList.Any() ? authorizationsList : new List<string>();
   }
}

And in the end, I get the following error at Getauthorizations method:

It is not possible to convert an object of type 'System.String' to type 'System.Collections.Generic.List`1 [System.String]'

Any ideas how I can convert that list?

Body:
I would write your code as follows:

First, you get your colletion of type Resource:

 IEnumerable<Resource> ResourceAuthorizedForLoggedUser=
 resourceAuthorizer.FindAll();

Then you save the list of Ids (I assume they are strings)

 List<string> authorizations=
 ResourceAuthorizedForLoggedUser.Select(x=> x.Id).ToList();

Save that in the session variable:

 System.Web.HttpContext.Current.Session["Authorized_List"] =
 authorizations;

Read it back from Session:

public class BaseController : Controller
     {
        public static List<string> authorizations { get { return Getauthorizations(); } }

   private static List<string> Getauthorizations()
   {
      List<string> authorizationsList = (List<string>)System.Web.HttpContext.Current.Session["Authorized_List"];
      return authorizationsList != null && authorizationsList.Any() ? authorizationsList : new List<string>();
   }
}`enter code here`


问:
ag-grid column search not working with object as cell value
I am using cell_renderer to define my cell, something like this:

```<code>        var cell_renderer = function(params) {
            var element = "";
            var values = params.value;
                angular.forEach(values, function(each_param){
                    element += '<a href="#/workunit/' + each_param.id + '" target="_blank">' + each_param.id +
                            '<span class="text-danger text-bold">'+
                            '<span class="" title="' + inactive_message +
                            '">' + inactive_flag + ' </span>' +
                            '<span class="" title="' + misconfigured_message +
                            '"> ' +misconfigured_flag + '</span>'+
                            '</span></a><br>';
                })
            return element;
        };
</code>```

My column definnition is this:

```<code>                var testObject = {};
                testObject.headerName = "my header";
                testObject.field = each_branch;
                testObject.width = 200;
                testObject.cellClassRules = cell_class_rules;
                testObject.cellRenderer = cell_renderer;
                columnDefs.push(testObject);
</code>```

Here testObject.field = each_branch , is a json object.

Hence the inbuild search functionality not working in ag-grid. Can anyone please help me here.

答:
When using a column that is an Object, you have at least 2 options:

Specify a valueGetter function on the column. If you do this, the table will no longer contain the object, but rather the value returned by the valueGetter.

valueGetter: this.getDateValueGetter("dateCol")

private getDateValueGetter(col: string): Function {
  return function (p: ValueGetterParams) {
    if (!p.data) {
       return null;
    }
    return this.ui.convertStringToDate(p.data[col], "YYYY-MM-DD");
  }
}

If you want your table to contain the object, specify both a keyCreator function and a valueFormatter function on the column.  If you do this, the column, filters, and grouping will work as expected.

{ keyCreator: (param) => {return param.value},
  valueFormatter: (param) => {return param.value}
}

Body:
I am using cell_renderer to define my cell, something like this:

        var cell_renderer = function(params) {
            var element = "";
            var values = params.value;
                angular.forEach(values, function(each_param){
                    element += '' + each_param.id +
                            ''+
                            '' + inactive_flag + ' ' +
                            ' ' +misconfigured_flag + ''+
                            '
';
                })
            return element;
        };

My column definnition is this:

                var testObject = {};
                testObject.headerName = "my header";
                testObject.field = each_branch;
                testObject.width = 200;
                testObject.cellClassRules = cell_class_rules;
                testObject.cellRenderer = cell_renderer;
                columnDefs.push(testObject);

Here testObject.field = each_branch , is a json object.

Hence the inbuild search functionality not working in ag-grid. Can anyone please help me here.


问:
Can Qt lrelease tool process XLIFF files instead of ts-files?
In the documentation of the Qt lrelease tool I read, that .ts files can be compiled to .qm binaries using following command:

```<code>lrelease.exe main_en.ts languages\main_fr.ts
</code>```

Is it possible to take .xliff files as well as input instead of the .ts files to compile .xliff files to .qm files? How is it done?

答:
To convert a xliff file to ts, you can use the lconvert utility with a command line like this:

```<code>lconvert -o converted.ts -i original.xlf
</code>```

Here is the output of lconvert -help:

Usage:
      lconvert [options]  [...]

lconvert is part of Qt's Linguist tool chain. It can be used as a
  stand-alone tool to convert and filter translation data files. The
  following file formats are supported:

```<code>qm    - Compiled Qt translations
pot   - GNU Gettext localization template files
ts11  - Qt translation sources (format 1.1)
ts20  - Qt translation sources (format 2.0)
qph   - Qt Linguist 'Phrase Book'
ts    - Qt translation sources (latest format)
po    - GNU Gettext localization files
xlf   - XLIFF localization files
</code>```

If multiple input files are specified, they are merged with
  translations from later files taking precedence.

Options:
      -h
      --help  Display this information and exit.

```<code>-i <infile>
--input-file <infile>
       Specify input file. Use if <infile> might start with a dash.
       This option can be used several times to merge inputs.
       May be '-' (standard input) for use in a pipe.

-o <outfile>
--output-file <outfile>
</code>```

More info  here about this Qt tool

Body:
In the documentation of the Qt lrelease tool I read, that .ts files can be compiled to .qm binaries using following command:

lrelease.exe main_en.ts languages\main_fr.ts

Is it possible to take .xliff files as well as input instead of the .ts files to compile .xliff files to .qm files? How is it done?

Body:
To convert a xliff file to ts, you can use the lconvert utility with a command line like this:

lconvert -o converted.ts -i original.xlf

Here is the output of lconvert -help:

Usage:
      lconvert [options]  [...]

lconvert is part of Qt's Linguist tool chain. It can be used as a
  stand-alone tool to convert and filter translation data files. The
  following file formats are supported:

qm    - Compiled Qt translations
pot   - GNU Gettext localization template files
ts11  - Qt translation sources (format 1.1)
ts20  - Qt translation sources (format 2.0)
qph   - Qt Linguist 'Phrase Book'
ts    - Qt translation sources (latest format)
po    - GNU Gettext localization files
xlf   - XLIFF localization files

If multiple input files are specified, they are merged with
  translations from later files taking precedence.

Options:
      -h
      --help  Display this information and exit.

-i <infile>
--input-file <infile>
       Specify input file. Use if <infile> might start with a dash.
       This option can be used several times to merge inputs.
       May be '-' (standard input) for use in a pipe.

-o <outfile>
--output-file <outfile>

More info  here about this Qt tool


问:
DateTime.TryParse works as different cultures even when set
So my string dateRangeStart goes in the format 2019-01-31 i.e. 31st Jan 2019

```<code>IFormatProvider culture = new CultureInfo("en-UK", true);
if (!string.IsNullOrEmpty(dateRangeStart))
{
    DateTime d = new DateTime();
    if(DateTime.TryParse(dateRangeStart, culture, DateTimeStyles.None, out d))
    {
        /// whatever
    }
}
</code>```

Using the same routine, if I put in 31-01-2019 - it fails to parse. Why? I've told it that it's a UK date? Can it not recognise dd-MM-yyyy formats?! but totally ok with MM-dd-yyyy?

Also happens if I swap culture for CultureInfo.InvariantCulture

答:
Instead of TryParse, use TryParseExact. This way, you have full control over the string representation format you're attempting to parse:

if (!string.IsNullOrEmpty(dateRangeStart))
{
    DateTime d;
    if(DateTime.TryParseExact(dateRangeStart, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out d))
    {
        /// whatever
    }
}
```

Body:
So my string dateRangeStart goes in the format 2019-01-31 i.e. 31st Jan 2019

IFormatProvider culture = new CultureInfo("en-UK", true);
if (!string.IsNullOrEmpty(dateRangeStart))
{
    DateTime d = new DateTime();
    if(DateTime.TryParse(dateRangeStart, culture, DateTimeStyles.None, out d))
    {
        /// whatever
    }
}

Using the same routine, if I put in 31-01-2019 - it fails to parse. Why? I've told it that it's a UK date? Can it not recognise dd-MM-yyyy formats?! but totally ok with MM-dd-yyyy?

Also happens if I swap culture for CultureInfo.InvariantCulture


问:
SQL - sum data for all time, 30 days and 90 days for multiple columns indiviually
BACKGROUND:

I have data that looks like this

```<code>date        src    subsrc   subsubsrc   param1  param2
2020-02-01  src1    ksjd    dfd8        47      31
2020-02-02  src1    djsk    zmnc        44      95
2020-02-03  src2    skdj    awes        92      100
2020-02-04  src2    mxsf    kajs        80      2
2020-02-05  src3    skdj    asio        46      53
2020-02-06  src3    dekl    jdqo        19      18
2020-02-07  src3    dskl    dqqq        69      18
2020-02-08  src4    sqip    riow        64      46
2020-02-09  src5    ss01    qwep        34      34
</code>```

I am trying to aggregate for all time, last 30 days and last 90 days (no rolling sum)

So my final data would look like this:

```<code>src     subsrc  subsubsrc   p1_all  p1_30   p1_90   p2_all  p2_30   p2_90
src1    ksjd    dfd8        7       1       7       98      7        98
src1    djsk    zmnc        0       0       0       0       0         0
src2    skdj    awes        12      12      12      4       4         4
src2    mxsf    kajs        6       6       6       31      31       31
src3    skdj    asio        0       0       0       0       0         0
src3    dekl    jdqo        20      20      20      17      17        17
src3    dskl    dqqq        3       3       3       4       4         4
src4    sqip    qwep        0       0       0       0       0         0
src5    ss01    qwes        15      15      15      2       2         2
</code>```

ABOUT DATA:

This is only dummy data and therefore incorrect.

There are tens of thousands of rows in my data.

There are a dozen of src columns that make up the key for the table.

There are a dozen of param columns that I have to sum for 30 and 90 and all time.

Also there are null values in param columns.

Also there are might be multiple rows for same day and src column.

New data is being added every day and the query is probably going to be run every day to get the latest 30, 90, all time data.

WHAT I HAVE TRIED:

This is what I have come up with:

```<code>SELECT src, subsubsrc, subsubsrc,
SUM(param1) as param1_all,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 30 THEN param1 END) as param1_30,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 90 THEN param1 END) as param1_90,
SUM(param2) as param2_all,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 30 THEN param2 END) as param2_30,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 90 THEN param2 END) as param2_90,
FROM `MY_TABLE`
GROUP BY src
ORDER BY src
</code>```

This actually works but I can anticipate how long this query is going to become for multiple sources and even more param columns.

I have been trying something called "Filtered aggregate functions (or manual pivot)" explained HERE. But I am unable to understand/implement it for my case.

Also  I have looked at dozens of answers and most of them are running sums for each day OR are complicated cases of this basic calculation. Maybe I am not searching it correctly.

As you can see I am newbie in SQL and would really appreciate any help.

答:
I'd recommend you use 3 different queries for that:

Sum for all time

Sum for 30 days

Sum for 90 days

Because when you're trying to do all-in-1 query then you end up with full table scan because of CASE-WHEN-END (BTW there is compact form IF() in MySQL). This is extremely non-optimal.

If you split it into 3 different queries and add an index to the date column then it won't do full-scan for the 2nd and 3rd query. Only for the 1st query, which can be optimised separately (for example by caching).

Also this approach: DATE_DIFF(CURRENT_DATE,date,day) <= 90

should be changed to: date >= 'date-90-days-ago' (where 'date-90-days-ago' is a fixed date)

Thus you won't have to compute difference of 2 dates for every row. You'll have just to compute 2 dates: 30 days ago and 90 days ago and compare all other dates to these two. This approach will benefit of the date column index.

Body:
BACKGROUND:

I have data that looks like this

date        src    subsrc   subsubsrc   param1  param2
2020-02-01  src1    ksjd    dfd8        47      31
2020-02-02  src1    djsk    zmnc        44      95
2020-02-03  src2    skdj    awes        92      100
2020-02-04  src2    mxsf    kajs        80      2
2020-02-05  src3    skdj    asio        46      53
2020-02-06  src3    dekl    jdqo        19      18
2020-02-07  src3    dskl    dqqq        69      18
2020-02-08  src4    sqip    riow        64      46
2020-02-09  src5    ss01    qwep        34      34

I am trying to aggregate for all time, last 30 days and last 90 days (no rolling sum)

So my final data would look like this:

src     subsrc  subsubsrc   p1_all  p1_30   p1_90   p2_all  p2_30   p2_90
src1    ksjd    dfd8        7       1       7       98      7        98
src1    djsk    zmnc        0       0       0       0       0         0
src2    skdj    awes        12      12      12      4       4         4
src2    mxsf    kajs        6       6       6       31      31       31
src3    skdj    asio        0       0       0       0       0         0
src3    dekl    jdqo        20      20      20      17      17        17
src3    dskl    dqqq        3       3       3       4       4         4
src4    sqip    qwep        0       0       0       0       0         0
src5    ss01    qwes        15      15      15      2       2         2

ABOUT DATA:

This is only dummy data and therefore incorrect.

There are tens of thousands of rows in my data.

There are a dozen of src columns that make up the key for the table.

There are a dozen of param columns that I have to sum for 30 and 90 and all time.

Also there are null values in param columns.

Also there are might be multiple rows for same day and src column.

New data is being added every day and the query is probably going to be run every day to get the latest 30, 90, all time data.

WHAT I HAVE TRIED:

This is what I have come up with:

SELECT src, subsubsrc, subsubsrc,
SUM(param1) as param1_all,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 30 THEN param1 END) as param1_30,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 90 THEN param1 END) as param1_90,
SUM(param2) as param2_all,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 30 THEN param2 END) as param2_30,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 90 THEN param2 END) as param2_90,
FROM `MY_TABLE`
GROUP BY src
ORDER BY src

This actually works but I can anticipate how long this query is going to become for multiple sources and even more param columns.

I have been trying something called "Filtered aggregate functions (or manual pivot)" explained HERE. But I am unable to understand/implement it for my case.

Also  I have looked at dozens of answers and most of them are running sums for each day OR are complicated cases of this basic calculation. Maybe I am not searching it correctly.

As you can see I am newbie in SQL and would really appreciate any help.


问:
Flutter GestureDetector: How to pinch in/out or zoom in/out Text using two fingers?
I'm creating a text field like Text or RichText. And after that, I want to zoom in/out the size of text using pinching. For now, I tried implementing GestureDetector but it zooms in/out with one finger too. And it is really hard to aim pinching detection. Sometimes is freezing. I added a video that shows when after pinching it freezes and suddenly get bigger. The second video is with the case that image zoom in only when I tap on the text with one finger and move to up left corner. The ideal implementation is to detect pinch and zoom in/out all text area. And disable zooming when I use only one finger. Could you send me some hints, link or code how to solve or where to find the solution?

body: GestureDetector(
  onScaleUpdate: (details) {
    setState(() {
      _textSize =
          _initTextSize + (_initTextSize * (details.scale * .35));
    });
  },
  onScaleEnd: (ScaleEndDetails details) {
    setState(() {
      _initTextSize = _textSize;
    });
  },
  child: Center(
      child: SizedBox(
    height: _textSize,
    child: FittedBox(
      child: Text("Test"),
    ),
  ))),
```

答:
In Stateful widget with these configuration

double _scaleFactor = 1.0;
double _baseScaleFactor = 1.0;
```
<p>And use <code>setState</code> only on update, using the <code>scaleFactor</code> on <code>textScaleFactor</code> property of <code>RichText</code>.</p>
<p><strong>Only one setState to rebuild widget and store the initial factor when scale starts</strong></p>
<pre class="lang-dart prettyprint-override"><code>GestureDetector(
  onScaleStart: (details) {
    _baseScaleFactor = _scaleFactor;
  },
  onScaleUpdate: (details) {
    setState(() {
      _scaleFactor = _baseScaleFactor * details.scale;
    });
  },
  child: Container(
    height: MediaQuery.of(context).size.height,
    width: MediaQuery.of(context).size.width,
    color: Colors.red,
    child: Center(
      child: Text(
        'Test',
        textScaleFactor: _scaleFactor,
      ),
    ),
  ),
);
</code>```

The height and width I put just to expand and simulate area of gesture detector.

Body:
In Stateful widget with these configuration

double _scaleFactor = 1.0;
double _baseScaleFactor = 1.0;

And use setState only on update, using the scaleFactor on textScaleFactor property of RichText.

Only one setState to rebuild widget and store the initial factor when scale starts

GestureDetector(
  onScaleStart: (details) {
    _baseScaleFactor = _scaleFactor;
  },
  onScaleUpdate: (details) {
    setState(() {
      _scaleFactor = _baseScaleFactor * details.scale;
    });
  },
  child: Container(
    height: MediaQuery.of(context).size.height,
    width: MediaQuery.of(context).size.width,
    color: Colors.red,
    child: Center(
      child: Text(
        'Test',
        textScaleFactor: _scaleFactor,
      ),
    ),
  ),
);

The height and width I put just to expand and simulate area of gesture detector.


问:
How do I make my Angular 8 application use the whole viewport?
I am developing a single-page application consisting of a navbar and a router-outlet which displays the component selected in the navbar. The primary component which loads by default is a Leaflet map which I would like to fill the entire page aside from the navbar. Currently I cannot even get the main component to fill the whole page, as it insists on including white space on the sides. I've set the container to have a high-res background image so I can see how much space it is actually filling.

The main page with all its unnecessary whitespace

The code:

app.component.html

```<code><body>
  <app-nav-menu></app-nav-menu>
  <div class="container" id="main-container">
    <router-outlet></router-outlet>
  </div>
</body>
</code>```

styles.css

```<code>body {
height: 98vh;
width: 98vw;
}

html, body, .container {
    height: 100%;
    overflow: hidden;
    width: 100%;
}

#main-container {
  background-image: url("src/assets/chicago-wallpaper.jpg");
  width: 98vw;
  height: 94vh;
}
</code>```

答: If you add float:left to all elements in the css that could help.

Body:
I am developing a single-page application consisting of a navbar and a router-outlet which displays the component selected in the navbar. The primary component which loads by default is a Leaflet map which I would like to fill the entire page aside from the navbar. Currently I cannot even get the main component to fill the whole page, as it insists on including white space on the sides. I've set the container to have a high-res background image so I can see how much space it is actually filling.

The main page with all its unnecessary whitespace

The code:

app.component.html

  <app-nav-menu></app-nav-menu>

    <router-outlet></router-outlet>

styles.css

body {
height: 98vh;
width: 98vw;
}

html, body, .container {
    height: 100%;
    overflow: hidden;
    width: 100%;
}

#main-container {
  background-image: url("src/assets/chicago-wallpaper.jpg");
  width: 98vw;
  height: 94vh;
}


问:
How to disable line wrapping in Jupyter notebook output cells?
By default longer lines of text in the output cells of a Jupyter notebook will be wrapped. How to stop this behaviour?</p>

答:
If you don't want to mess around with a config file, you can modify the behaviour of a notebook ad hoc by calling the IPython.core.display function. Then add the CSS suggested by @atevm:</p>

```<code>from IPython.core.display import display, HTML
display(HTML("<style>div.output_area pre {white-space: pre;}</style>"))

for line in range(5):
    for num in range(70):
        print(f" {num}", end="")
    print()
</code>```

Body:
If you don't want to mess around with a config file, you can modify the behaviour of a notebook ad hoc by calling the IPython.core.display function. Then add the CSS suggested by @atevm:

from IPython.core.display import display, HTML
display(HTML("<style>div.output_area pre {white-space: pre;}</style>"))

for line in range(5):
    for num in range(70):
        print(f" {num}", end="")
    print()


问:
What is a better way of handling this type of issue?
I'm sort of new to iOS development using Swift.  So, I might be missing a simple solution in Swift that I'm not aware of.
 I am working on a tvOS app where I display a list of video content that the user can select from.  The app also contains a settings tab that allows the user to configure 5 different types of settings.  Once they select a specific category, it displays a new table view with the corresponding options which are in the options array.  This is where the "issue" is that I need help.

I have this struct which I'm using as a singleton:

```<code>struct BMUserSettings
{
    internal static var shared = BMUserSettings()
    var categories = [String]()
    var options = [[String]]()
    var currOptionsSelected: [Int] = [0,0,0,0,0] // This array corresponds to the categories array.  It tells us what option within that group was selected.
    init()
    {
        self.categories = ["Brand", "Environment","UI Language", "Playback Language", "Geo Location Permission"]

        let brandOptionsGroup: [String] = ["CTV", "CTVHUB", "TSN", "Snackable", "RDS", "CP24", "BNN", "CTVNews", "Crave", "BRAVO", "E_BRAND", "SE", "VIDIQA"]
        let environmentOptionsGroup: [String] = ["Staging", "Prod"]
        let uiLanguageOptionsGroup: [String] = ["en", "fr"]
        let playbackLanguageOptionsGroup: [String] = ["en", "fr"]
        let geoLocationOptionsGroup: [String] = ["Allow", "Don't Allow"]

        options.append(brandOptionsGroup)
        options.append(environmentOptionsGroup)
        options.append(uiLanguageOptionsGroup)
        options.append(playbackLanguageOptionsGroup)
        options.append(geoLocationOptionsGroup)
    }

    // MARK: - Custom Methods
    func displayUserSettings() -> String
    {
        let displayText: String = "Brand=\(options[0][currOptionsSelected[0]])     Environment=\(options[1][currOptionsSelected[1]])     UI Language=\(options[2][currOptionsSelected[2]])     Playback Language=\(options[3][currOptionsSelected[3]])     Geo Location=\(options[4][currOptionsSelected[4]])"
        return displayText
    }

    // MARK: - User Defaults
    func saveToUserDefaults()
    {
        UserDefaults.standard.set(BMUserSettings.shared.currOptionsSelected, forKey: "currentoptions")
    }

    func loadFromUserDefaults(){
        if let currentOptionsSelected = UserDefaults.standard.object(forKey: "currentoptions") as? [Int]{
            BMUserSettings.shared.currOptionsSelected = currentOptionsSelected
        }
        else{
            BMUserSettings.shared.currOptionsSelected = [0,0,0,0,0]
        }
    }
}
</code>```

As you can see, the "currOptionsSelected" integer array is holding the option that the user selected for each of the categories.  For example, if the user chooses the brand "Snackable", then the first element of the currOptionsSelected array will hold a 3 as a value.

I'm saving and loading the currOptionsSelected to/from UserDefaults so that I know what the user's current settings are.

The problem with this approach is:
1) Even if I know the index of the specific option that the user chose, I will still need a set if if-else or switch conditions to make sure I can actually get the correct string value from the corresponding "options" array
2) If any other developer needs to add categories and corresponding options, then they need to make sure they keep everything in order
3) I just don't know if this is the best way of handling this type of issue

What is a better way of doing this?

Here's how I'm trying to use it in a table view:

```<code>import UIKit

final class BMSettingsViewController: UIViewController
{
    // MARK: - Instance Variables
    private static let reuseIdentifier = String(describing: BMContentCell.self)
    private let tableview = UITableView(backgroundColor: .white, autoResizingMask: false)
    private let tabBarBannerHeight: CGFloat = 150
    private var selectedCategoryIndex: Int = 0
    private var settingsDetailVC: BMDetailSettingsViewController?
    private var categoryNames: [String] = [String]()
    private var categoryOptions: [String] = [String]()

    // MARK: - View Lifecycle Methods
    override func viewWillAppear(_ animated: Bool)
    {
        super.viewWillAppear(animated)
        categoryNames = BMCategory.allValues
        categoryOptions = BMUserSettings.shared.currOptionsSelected.map { $0.value }
        self.tableview.reloadData()
    }

    override func viewWillDisappear(_ animated: Bool)
    {
        BMUserSettings.shared.saveToUserDefaults()
    }

    override func loadView()
    {
        super.loadView()
        self.tableview.dataSource = self
        self.tableview.delegate = self
        self.tableview.register(BMUserSettingsCell.self, forCellReuseIdentifier: BMSettingsViewController.reuseIdentifier)
        displayContent()
    }

    // MARK: - Custom Methods
    private func displayContent()
    {
        view.addSubview(tableview)
        tableview.anchor(
            top: self.view.topAnchor,
            leading: self.view.leadingAnchor,
            bottom: self.view.bottomAnchor,
            trailing: self.view.trailingAnchor,
            padding: UIEdgeInsets(top: tabBarBannerHeight, left: 0, bottom: 0, right: 0)
        )
    }
}

// MARK: - UITableView Datasource & Delegate Extension
extension BMSettingsViewController: UITableViewDataSource, UITableViewDelegate
{
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?
    {
        return "Select an option below to configure it's settings..."
    }

    func numberOfSections(in tableView: UITableView) -> Int
    {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return categoryNames.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: BMSettingsViewController.reuseIdentifier, for: indexPath) as! BMUserSettingsCell
        cell.configureCell(categoryName: categoryNames[indexPath.row], optionDetailDescription: categoryOptions[indexPath.row])
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        let selectedCategory = categoryNames[indexPath.row]
        settingsDetailVC = BMDetailSettingsViewController()
        guard let settingsVC = settingsDetailVC else {return}
        settingsVC.options = BMUserSettings.shared.options[BMCategory.init(rawValue: selectedCategory)!]!
        settingsVC.delegate = self
        settingsVC.selectedCategoryIndex = indexPath.row
        BMViewControllerManager.shared.getTopViewController()?.present(settingsVC, animated: true)
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
    {
        return 120
    }
}

// MARK: - Protocol Extension
extension BMSettingsViewController: OptionsSelector
{
    func didFinishSelectingOption(selectedCategoryIndex: Int, selectedOptionIndex: Int)
    {
        self.selectedCategoryIndex = selectedCategoryIndex
//      BMUserSettings.shared.currOptionsSelected[self.selectedCategoryIndex] = selectedOptionIndex
    }
}
</code>```

Here's the settings detail controller that lists just the options within that specific category:

```<code>import UIKit

// MARK: - Protocol (used to notify Settings view controller when an option was selected)
protocol OptionsSelector
{
    func didFinishSelectingOption(selectedCategoryIndex: Int, selectedOptionIndex: Int)
}

final class BMDetailSettingsViewController: UIViewController
{
    // MARK: - Instance Variables
    private let cellId = "cellId"
    private let tabBarBannerHeight: CGFloat = 150
    private var selectedOptionIndex: Int = 0
    private let tableview = UITableView(backgroundColor: .white, autoResizingMask: false)

    var options: [String] = [String]()
    var selectedCategoryIndex: Int = 0
    var delegate: OptionsSelector?

    // MARK: - View Life Cycle Methods
    override func loadView()
    {
        super.loadView()
        self.tableview.dataSource = self
        self.tableview.delegate = self
        self.tableview.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        displayContent()
    }

    // MARK: - Custom Methods
    private func displayContent()
    {
        view.addSubview(tableview)
        tableview.anchor(
            top: self.view.topAnchor,
            leading: self.view.leadingAnchor,
            bottom: self.view.bottomAnchor,
            trailing: self.view.trailingAnchor,
            padding: UIEdgeInsets(top: tabBarBannerHeight, left: 0, bottom: 0, right: 0)
        )
    }
}

// MARK: - UITableView Datasource & Delegate Extension
extension BMDetailSettingsViewController: UITableViewDataSource, UITableViewDelegate
{
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Select an option below..." }
    func numberOfSections(in tableView: UITableView) -> Int { return 1 }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return options.count }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = UITableViewCell(style:  .subtitle, reuseIdentifier: nil)
        cell.textLabel?.text = "\(options[indexPath.row])"
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        BMViewControllerManager.shared.getTopViewController()?.dismiss(animated: true)
        self.selectedOptionIndex = indexPath.row
        self.delegate?.didFinishSelectingOption(selectedCategoryIndex: self.selectedCategoryIndex, selectedOptionIndex: self.selectedOptionIndex)
    }
}
</code>```

Thank you!

答:
First of all create an enum Category,

```<code>enum Category: String {
    case brand = "Brand"
    case environment = "Environment"
    case uiLanguage = "UI Language"
    case playbackLanguage = "Playback Language"
    case geoLocationPermission = "Geo Location"
}
</code>```

Next,

Create options of type [Category:[String]], currOptionsSelected of type [Category:String] and defaultOptions of type [Category:String].

Also, instead of displayUserSettings, conform struct BMUserSettings to CustomStringConvertible and implement the description to return the relevant String value.

And, to create the Singleton, mark init() as private.

There is no need to create a separate array for categories.

So the whole struct BMUserSettings will be like,

```<code>struct BMUserSettings: CustomStringConvertible {
    static var shared = BMUserSettings()

    let options: [Category:[String]]
    let defaultOptions: [Category:String]
    var currOptionsSelected: [Category:String]
    let categories: [Category]

    private init() {
        options = [
            .brand : ["CTV", "CTVHUB", "TSN", "Snackable", "RDS", "CP24", "BNN", "CTVNews", "Crave", "BRAVO", "E_BRAND", "SE", "VIDIQA"],
            .environment : ["Staging", "Prod"],
            .uiLanguage : ["en", "fr"],
            .playbackLanguage : ["en", "fr"],
            .geoLocationPermission : ["Allow", "Don't Allow"]
        ]

        defaultOptions = self.options.mapValues{ $0.first! }
        currOptionsSelected = self.defaultOptions
        categories = [.brand, .environment, .uiLanguage, .playbackLanguage, .geoLocationPermission]
    }

    var description: String {
        return self.currOptionsSelected.reduce("") { (result, option) -> String in
            return "\(result) \(option.key.rawValue) = \(option.value)\n"
        }
    }

    // MARK: - User Defaults
    func saveToUserDefaults() {
        var dict = [String:String]()
        currOptionsSelected.forEach { dict[$0.key.rawValue] = $0.value }
        UserDefaults.standard.set(dict, forKey: "currentoptions")
    }

    mutating func loadFromUserDefaults() {
        if let currentOptionsSelected = UserDefaults.standard.object(forKey: "currentoptions") as? [String:String] {
            var dict = [Category:String]()
            currentOptionsSelected.forEach {
                if let category = Category(rawValue: $0.key) {
                    dict[category] = $0.value
                }
            }
            self.currOptionsSelected = dict
        }
        else {
            self.currOptionsSelected = self.defaultOptions
        }
    }
}
</code>```

Use it in the following way,

```<code>BMUserSettings.shared.currOptionsSelected[.brand] = "Snackable"
BMUserSettings.shared.saveToUserDefaults()
BMUserSettings.shared.loadFromUserDefaults()
print(BMUserSettings.shared)
BMUserSettings.shared.categories.forEach {
    print($0.rawValue, ":", BMUserSettings.shared.currOptionsSelected[$0]!)
}
</code>```

Body:
I'm sort of new to iOS development using Swift.  So, I might be missing a simple solution in Swift that I'm not aware of.
 I am working on a tvOS app where I display a list of video content that the user can select from.  The app also contains a settings tab that allows the user to configure 5 different types of settings.  Once they select a specific category, it displays a new table view with the corresponding options which are in the options array.  This is where the "issue" is that I need help.

I have this struct which I'm using as a singleton:

struct BMUserSettings
{
    internal static var shared = BMUserSettings()
    var categories = [String]()
    var options = [[String]]()
    var currOptionsSelected: [Int] = [0,0,0,0,0] // This array corresponds to the categories array.  It tells us what option within that group was selected.
    init()
    {
        self.categories = ["Brand", "Environment","UI Language", "Playback Language", "Geo Location Permission"]

        let brandOptionsGroup: [String] = ["CTV", "CTVHUB", "TSN", "Snackable", "RDS", "CP24", "BNN", "CTVNews", "Crave", "BRAVO", "E_BRAND", "SE", "VIDIQA"]
        let environmentOptionsGroup: [String] = ["Staging", "Prod"]
        let uiLanguageOptionsGroup: [String] = ["en", "fr"]
        let playbackLanguageOptionsGroup: [String] = ["en", "fr"]
        let geoLocationOptionsGroup: [String] = ["Allow", "Don't Allow"]

        options.append(brandOptionsGroup)
        options.append(environmentOptionsGroup)
        options.append(uiLanguageOptionsGroup)
        options.append(playbackLanguageOptionsGroup)
        options.append(geoLocationOptionsGroup)
    }

    // MARK: - Custom Methods
    func displayUserSettings() -> String
    {
        let displayText: String = "Brand=\(options[0][currOptionsSelected[0]])     Environment=\(options[1][currOptionsSelected[1]])     UI Language=\(options[2][currOptionsSelected[2]])     Playback Language=\(options[3][currOptionsSelected[3]])     Geo Location=\(options[4][currOptionsSelected[4]])"
        return displayText
    }

    // MARK: - User Defaults
    func saveToUserDefaults()
    {
        UserDefaults.standard.set(BMUserSettings.shared.currOptionsSelected, forKey: "currentoptions")
    }

    func loadFromUserDefaults(){
        if let currentOptionsSelected = UserDefaults.standard.object(forKey: "currentoptions") as? [Int]{
            BMUserSettings.shared.currOptionsSelected = currentOptionsSelected
        }
        else{
            BMUserSettings.shared.currOptionsSelected = [0,0,0,0,0]
        }
    }
}

As you can see, the "currOptionsSelected" integer array is holding the option that the user selected for each of the categories.  For example, if the user chooses the brand "Snackable", then the first element of the currOptionsSelected array will hold a 3 as a value.

I'm saving and loading the currOptionsSelected to/from UserDefaults so that I know what the user's current settings are.

The problem with this approach is:
1) Even if I know the index of the specific option that the user chose, I will still need a set if if-else or switch conditions to make sure I can actually get the correct string value from the corresponding "options" array
2) If any other developer needs to add categories and corresponding options, then they need to make sure they keep everything in order
3) I just don't know if this is the best way of handling this type of issue

What is a better way of doing this?

Here's how I'm trying to use it in a table view:

import UIKit

final class BMSettingsViewController: UIViewController
{
    // MARK: - Instance Variables
    private static let reuseIdentifier = String(describing: BMContentCell.self)
    private let tableview = UITableView(backgroundColor: .white, autoResizingMask: false)
    private let tabBarBannerHeight: CGFloat = 150
    private var selectedCategoryIndex: Int = 0
    private var settingsDetailVC: BMDetailSettingsViewController?
    private var categoryNames: [String] = [String]()
    private var categoryOptions: [String] = [String]()

    // MARK: - View Lifecycle Methods
    override func viewWillAppear(_ animated: Bool)
    {
        super.viewWillAppear(animated)
        categoryNames = BMCategory.allValues
        categoryOptions = BMUserSettings.shared.currOptionsSelected.map { $0.value }
        self.tableview.reloadData()
    }

    override func viewWillDisappear(_ animated: Bool)
    {
        BMUserSettings.shared.saveToUserDefaults()
    }

    override func loadView()
    {
        super.loadView()
        self.tableview.dataSource = self
        self.tableview.delegate = self
        self.tableview.register(BMUserSettingsCell.self, forCellReuseIdentifier: BMSettingsViewController.reuseIdentifier)
        displayContent()
    }

    // MARK: - Custom Methods
    private func displayContent()
    {
        view.addSubview(tableview)
        tableview.anchor(
            top: self.view.topAnchor,
            leading: self.view.leadingAnchor,
            bottom: self.view.bottomAnchor,
            trailing: self.view.trailingAnchor,
            padding: UIEdgeInsets(top: tabBarBannerHeight, left: 0, bottom: 0, right: 0)
        )
    }
}

// MARK: - UITableView Datasource & Delegate Extension
extension BMSettingsViewController: UITableViewDataSource, UITableViewDelegate
{
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?
    {
        return "Select an option below to configure it's settings..."
    }

    func numberOfSections(in tableView: UITableView) -> Int
    {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return categoryNames.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: BMSettingsViewController.reuseIdentifier, for: indexPath) as! BMUserSettingsCell
        cell.configureCell(categoryName: categoryNames[indexPath.row], optionDetailDescription: categoryOptions[indexPath.row])
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        let selectedCategory = categoryNames[indexPath.row]
        settingsDetailVC = BMDetailSettingsViewController()
        guard let settingsVC = settingsDetailVC else {return}
        settingsVC.options = BMUserSettings.shared.options[BMCategory.init(rawValue: selectedCategory)!]!
        settingsVC.delegate = self
        settingsVC.selectedCategoryIndex = indexPath.row
        BMViewControllerManager.shared.getTopViewController()?.present(settingsVC, animated: true)
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
    {
        return 120
    }
}

// MARK: - Protocol Extension
extension BMSettingsViewController: OptionsSelector
{
    func didFinishSelectingOption(selectedCategoryIndex: Int, selectedOptionIndex: Int)
    {
        self.selectedCategoryIndex = selectedCategoryIndex
//      BMUserSettings.shared.currOptionsSelected[self.selectedCategoryIndex] = selectedOptionIndex
    }
}

Here's the settings detail controller that lists just the options within that specific category:

import UIKit

// MARK: - Protocol (used to notify Settings view controller when an option was selected)
protocol OptionsSelector
{
    func didFinishSelectingOption(selectedCategoryIndex: Int, selectedOptionIndex: Int)
}

final class BMDetailSettingsViewController: UIViewController
{
    // MARK: - Instance Variables
    private let cellId = "cellId"
    private let tabBarBannerHeight: CGFloat = 150
    private var selectedOptionIndex: Int = 0
    private let tableview = UITableView(backgroundColor: .white, autoResizingMask: false)

    var options: [String] = [String]()
    var selectedCategoryIndex: Int = 0
    var delegate: OptionsSelector?

    // MARK: - View Life Cycle Methods
    override func loadView()
    {
        super.loadView()
        self.tableview.dataSource = self
        self.tableview.delegate = self
        self.tableview.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        displayContent()
    }

    // MARK: - Custom Methods
    private func displayContent()
    {
        view.addSubview(tableview)
        tableview.anchor(
            top: self.view.topAnchor,
            leading: self.view.leadingAnchor,
            bottom: self.view.bottomAnchor,
            trailing: self.view.trailingAnchor,
            padding: UIEdgeInsets(top: tabBarBannerHeight, left: 0, bottom: 0, right: 0)
        )
    }
}

// MARK: - UITableView Datasource & Delegate Extension
extension BMDetailSettingsViewController: UITableViewDataSource, UITableViewDelegate
{
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Select an option below..." }
    func numberOfSections(in tableView: UITableView) -> Int { return 1 }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return options.count }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = UITableViewCell(style:  .subtitle, reuseIdentifier: nil)
        cell.textLabel?.text = "\(options[indexPath.row])"
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        BMViewControllerManager.shared.getTopViewController()?.dismiss(animated: true)
        self.selectedOptionIndex = indexPath.row
        self.delegate?.didFinishSelectingOption(selectedCategoryIndex: self.selectedCategoryIndex, selectedOptionIndex: self.selectedOptionIndex)
    }
}

Thank you!

Body:
First of all create an enum Category,

enum Category: String {
    case brand = "Brand"
    case environment = "Environment"
    case uiLanguage = "UI Language"
    case playbackLanguage = "Playback Language"
    case geoLocationPermission = "Geo Location"
}

Next,

Create options of type [Category:[String]], currOptionsSelected of type [Category:String] and defaultOptions of type [Category:String].

Also, instead of displayUserSettings, conform struct BMUserSettings to CustomStringConvertible and implement the description to return the relevant String value.

And, to create the Singleton, mark init() as private.

There is no need to create a separate array for categories.

So the whole struct BMUserSettings will be like,

struct BMUserSettings: CustomStringConvertible {
    static var shared = BMUserSettings()

    let options: [Category:[String]]
    let defaultOptions: [Category:String]
    var currOptionsSelected: [Category:String]
    let categories: [Category]

    private init() {
        options = [
            .brand : ["CTV", "CTVHUB", "TSN", "Snackable", "RDS", "CP24", "BNN", "CTVNews", "Crave", "BRAVO", "E_BRAND", "SE", "VIDIQA"],
            .environment : ["Staging", "Prod"],
            .uiLanguage : ["en", "fr"],
            .playbackLanguage : ["en", "fr"],
            .geoLocationPermission : ["Allow", "Don't Allow"]
        ]

        defaultOptions = self.options.mapValues{ $0.first! }
        currOptionsSelected = self.defaultOptions
        categories = [.brand, .environment, .uiLanguage, .playbackLanguage, .geoLocationPermission]
    }

    var description: String {
        return self.currOptionsSelected.reduce("") { (result, option) -> String in
            return "\(result) \(option.key.rawValue) = \(option.value)\n"
        }
    }

    // MARK: - User Defaults
    func saveToUserDefaults() {
        var dict = [String:String]()
        currOptionsSelected.forEach { dict[$0.key.rawValue] = $0.value }
        UserDefaults.standard.set(dict, forKey: "currentoptions")
    }

    mutating func loadFromUserDefaults() {
        if let currentOptionsSelected = UserDefaults.standard.object(forKey: "currentoptions") as? [String:String] {
            var dict = [Category:String]()
            currentOptionsSelected.forEach {
                if let category = Category(rawValue: $0.key) {
                    dict[category] = $0.value
                }
            }
            self.currOptionsSelected = dict
        }
        else {
            self.currOptionsSelected = self.defaultOptions
        }
    }
}

Use it in the following way,

BMUserSettings.shared.currOptionsSelected[.brand] = "Snackable"
BMUserSettings.shared.saveToUserDefaults()
BMUserSettings.shared.loadFromUserDefaults()
print(BMUserSettings.shared)
BMUserSettings.shared.categories.forEach {
    print($0.rawValue, ":", BMUserSettings.shared.currOptionsSelected[$0]!)
}


问:
Question on threading in C#
I have a Windows Forms application at the moment, and I want to create a new thread and run a method on another class that accepts an input.

For example

```<code>public partial class Form1: Form {
    SerialPort serialInput;
    // I want to create a new thread that will pass the parameter serialInput into the method
    // SMSListener on another class and run the method contionously on the background.
}

class SMS
{
    public void SMSListener(SerialPort serial1)
    {
        serial1.DataReceived += port_DataRecieved;
    }

    private void port_DataRecieved(object sender, SerialDataReceivedEventArgs e)
    {
        // Other codes
    }
}
</code>```

How do I perform this in C#? I have seen numerous examples on the web, and most of them run the method on the same class with no parameters, but none that suits my requirements.

答:
I am not an expert on Multithreading but to the best of my knowledge you can only start threads on methods that accept an object parameter and return void. So in order to achieve that for your problem (don't shoot me down if there is a better approach!) I would do something like</p>

```<code>public partial class Form1: Form {
    SerialPort serialInput;
    // I want to create a new thread that will pass the parameter serialInput into the method
    // SMSListener on another class and run the method contionously on the background.
    SMS sms = new SMS();
    Thread t = new Thread(sms.SMSListenerUntyped);
    t.Start(serialInput);
}

class SMS
{
    public void SMSListenerUntyped(object serial1) {
        if (serial1 is SerialPort) //Check if the parameter is correctly typed.
             this.SMSListener(serial1 as SerialPort);
        else
           throw new ArgumentException();
    }

    public void SMSListener(SerialPort serial1)
    {
        serial1.DataReceived += port_DataRecieved;
    }

    private void port_DataRecieved(object sender, SerialDataReceivedEventArgs e)
    {
        // Other code.
    }
</code>```

Title: Question on threading in C#

Body:
I have a Windows Forms application at the moment, and I want to create a new thread and run a method on another class that accepts an input.

For example

public partial class Form1: Form {
    SerialPort serialInput;
    // I want to create a new thread that will pass the parameter serialInput into the method
    // SMSListener on another class and run the method contionously on the background.
}

class SMS
{
    public void SMSListener(SerialPort serial1)
    {
        serial1.DataReceived += port_DataRecieved;
    }

    private void port_DataRecieved(object sender, SerialDataReceivedEventArgs e)
    {
        // Other codes
    }
}

How do I perform this in C#? I have seen numerous examples on the web, and most of them run the method on the same class with no parameters, but none that suits my requirements.

Body:
I am not an expert on Multithreading but to the best of my knowledge you can only start threads on methods that accept an object parameter and return void. So in order to achieve that for your problem (don't shoot me down if there is a better approach!) I would do something like

public partial class Form1: Form {
    SerialPort serialInput;
    // I want to create a new thread that will pass the parameter serialInput into the method
    // SMSListener on another class and run the method contionously on the background.
    SMS sms = new SMS();
    Thread t = new Thread(sms.SMSListenerUntyped);
    t.Start(serialInput);
}

class SMS
{
    public void SMSListenerUntyped(object serial1) {
        if (serial1 is SerialPort) //Check if the parameter is correctly typed.
             this.SMSListener(serial1 as SerialPort);
        else
           throw new ArgumentException();
    }

    public void SMSListener(SerialPort serial1)
    {
        serial1.DataReceived += port_DataRecieved;
    }

    private void port_DataRecieved(object sender, SerialDataReceivedEventArgs e)
    {
        // Other code.
    }


问:
ConfigurationElement set null default value
I have a small problem with a custom configuration section in App.config.
The problem is: I have a CustomElement (let's call it 'a') whose properties CustomElement another (let's call it 'b').

I would like to have b as a value not null only if specified as a secondary element.

Eg

In this case, I have a b as not null, and that's ok.

```<code><a prop_a1="" prop_a2="">
    <B prop_b1 = "" />
</ A>
</code>```

But, in the following case, b should be null, but it is not.

```<code><a prop_a1="" prop_a2="" />
</code>```

Is it possible to have a null value in case 2?

Thanks to all those who want to help me.

```<code>public class Cfg : ConfigurationElement
{
        [ConfigurationProperty("prop", IsRequired = true)]
        public ErrorCfg Prop
        {
            get { return (string)this["prop"]; }
            set { this["prop"] = value; }
        }
}

public class ErrorCfg : ConfigurationElement
{
    [ConfigurationProperty("prop1", IsRequired = true)]
    public string Prop1
    {
        get { return (string)this["prop1"]; }
        set { this["prop1"] = value; }
    }

    [ConfigurationProperty("prop2", IsRequired = true)]
    public string Prop2
    {
        get { return (string)this["prop2"]; }
        set { this["prop2"] = value; }
    }
}

if (_cfgItem.ErrorCfg != null)
{....}
</code>```

In this case ErrorCfg is not null, but Prop1 and Pro2 are empty string

答:
I think this is not possible. But you can find out if the ConfigurationElement is present in the configuration file:

```<code>if (_cfgItem.ErrorCfg.ElementInformation.IsPresent)
{....}
</code>```

Body:
I have a small problem with a custom configuration section in App.config.
The problem is: I have a CustomElement (let's call it 'a') whose properties CustomElement another (let's call it 'b').

I would like to have b as a value not null only if specified as a secondary element.

Eg

In this case, I have a b as not null, and that's ok.

But, in the following case, b should be null, but it is not.

Is it possible to have a null value in case 2?

Thanks to all those who want to help me.

public class Cfg : ConfigurationElement
{
        [ConfigurationProperty("prop", IsRequired = true)]
        public ErrorCfg Prop
        {
            get { return (string)this["prop"]; }
            set { this["prop"] = value; }
        }
}

public class ErrorCfg : ConfigurationElement
{
    [ConfigurationProperty("prop1", IsRequired = true)]
    public string Prop1
    {
        get { return (string)this["prop1"]; }
        set { this["prop1"] = value; }
    }

    [ConfigurationProperty("prop2", IsRequired = true)]
    public string Prop2
    {
        get { return (string)this["prop2"]; }
        set { this["prop2"] = value; }
    }
}

if (_cfgItem.ErrorCfg != null)
{....}

In this case ErrorCfg is not null, but Prop1 and Pro2 are empty string

Body:
I think this is not possible. But you can find out if the ConfigurationElement is present in the configuration file:

if (_cfgItem.ErrorCfg.ElementInformation.IsPresent)
{....}


问:
Select range if - depending on a value of each cell of a range (VBA)
I want to select whole rows of a range (C14:M34) if value = 1 in a column(F14:F34). Otherwise I want to select the same rows except a specific column(G).
I can do this if I have only a single row but how can I apply this for a range (multiple rows)?

Hereby my code (which is not working):

```<code>ActiveSheet.Range("$C$13:$M$34").AutoFilter Field:=6, Criteria1:="<>"
    Dim d As Range
    For Each d In Range("F14:F34")
        If d.Value = 1 Then
            ActiveSheet.Range("C14:M34").Select
        Else
        Application.Union(Range("C14:F34"), Range("H14:M34")).Select
        End If
        Selection.Copy
    Next d
</code>```

答:
Try this code, please:

```<code>Sub testSelecting()
  Dim sh As Worksheet, rngSel As Range, i As Long
  Set sh = ActiveSheet
    For i = 14 To 34
        If sh.Range("F" & i).Value = 1 Then
           If rngSel Is Nothing Then
              Set rngSel = sh.Range("C" & i & ":M" & i)
           Else
              Set rngSel = Union(rngSel, sh.Range("C" & i & ":M" & i))
           End If
        Else
            If rngSel Is Nothing Then
                Set rngSel = Union(sh.Range("C" & i & ":F" & i), sh.Range("H" & i & ":M" & i))
            Else
                Set rngSel = Union(rngSel, sh.Range("C" & i & ":F" & i), sh.Range("H" & i & ":M" & i))
            End If
        End If
    Next i
    If rngSel.Cells.count > 1 Then rngSel.Select: Stop
    rngSel.Copy
End Sub
</code>```

The code is not tested, because I do not have your file to do that. It is based only on logic. It stops after selection, in order to let you appreciate that the selected range is the one you need.

Please confirm that it works as you need, or what problem does it create, if any...

Body:
I want to select whole rows of a range (C14:M34) if value = 1 in a column(F14:F34). Otherwise I want to select the same rows except a specific column(G).
I can do this if I have only a single row but how can I apply this for a range (multiple rows)?

Hereby my code (which is not working):

ActiveSheet.Range("$C$13:$M$34").AutoFilter Field:=6, Criteria1:="<>"
    Dim d As Range
    For Each d In Range("F14:F34")
        If d.Value = 1 Then
            ActiveSheet.Range("C14:M34").Select
        Else
        Application.Union(Range("C14:F34"), Range("H14:M34")).Select
        End If
        Selection.Copy
    Next d

Body:
Try this code, please:

Sub testSelecting()
  Dim sh As Worksheet, rngSel As Range, i As Long
  Set sh = ActiveSheet
    For i = 14 To 34
        If sh.Range("F" & i).Value = 1 Then
           If rngSel Is Nothing Then
              Set rngSel = sh.Range("C" & i & ":M" & i)
           Else
              Set rngSel = Union(rngSel, sh.Range("C" & i & ":M" & i))
           End If
        Else
            If rngSel Is Nothing Then
                Set rngSel = Union(sh.Range("C" & i & ":F" & i), sh.Range("H" & i & ":M" & i))
            Else
                Set rngSel = Union(rngSel, sh.Range("C" & i & ":F" & i), sh.Range("H" & i & ":M" & i))
            End If
        End If
    Next i
    If rngSel.Cells.count > 1 Then rngSel.Select: Stop
    rngSel.Copy
End Sub

The code is not tested, because I do not have your file to do that. It is based only on logic. It stops after selection, in order to let you appreciate that the selected range is the one you need.

Please confirm that it works as you need, or what problem does it create, if any...


答:
You can use the str.split method to split the string into "words".

```<code>df['list_of_words'] = dftopdata['Date'].str.split()
</code>```

If there is a pattern to split the Professional and Description parts from this list_of_words - you can use it. For instance, if the first 2 words of list_of_words make up the name of the professional then you can do -

```<code>df['Professional'] = df.apply(lambda x: ' '.join(x['list_of_words'][:2]), axis=1)
df['Description'] = df.apply(lambda x: ' '.join(x['list_of_words'][2:]), axis=1)
</code>```

Title: How to split data from a merged cell into other cells in its same row of a Python data frame?

Body:
I have a sample of a data frame which looks like this:

+---+--------------------------------------------------------------------------------------+---------------+--------------------------------------------+
|   | Date                                                                                | Professional  | Description                                |
+---+--------------------------------------------------------------------------------------+---------------+--------------------------------------------+
| 0 | 2019-12-19 00:00:00                                                                  | Katie Cool    | Travel to Space ...                        |
+---+--------------------------------------------------------------------------------------+---------------+--------------------------------------------+
| 1 | 2019-12-20 00:00:00                                                                  | Jenn Blossoms | Review stuff; prepare cancellations of ... |
+---+--------------------------------------------------------------------------------------+---------------+--------------------------------------------+
| 2 | 2019-12-27 00:00:00                                                                  | Jenn Blossoms | Review lots of stuff/o...                  |
+---+--------------------------------------------------------------------------------------+---------------+--------------------------------------------+
| 3 | 2019-12-27 00:00:00                                                                  | Jenn Blossoms | Draft email to world leader...             |
+---+--------------------------------------------------------------------------------------+---------------+--------------------------------------------+
| 4 | 2019-12-30 00:00:00                                                                  | Jenn Blossoms | Review this thing.                         |
+---+--------------------------------------------------------------------------------------+---------------+--------------------------------------------+
| 5 | 12-30-2019 Jenn Blossoms Telephone   Call   to   A.   Bell   return   her   multiple | NaN           | NaN                                        |
|   | voicemails.                                                                          |               |                                            |
+---+--------------------------------------------------------------------------------------+---------------+--------------------------------------------+

Much of the row's data is in the date cell.

I would like for the sample to look like this:

+---+---------------------+---------------+-------------------------------------------------------------+
|   | Date                | Professional  | Description                                                 |
+---+---------------------+---------------+-------------------------------------------------------------+
| 0 | 2019-12-19 00:00:00 | Katie Cool    | Travel to Space ...                                         |
+---+---------------------+---------------+-------------------------------------------------------------+
| 1 | 2019-12-20 00:00:00 | Jenn Blossoms | Review stuff; prepare cancellations of ...                  |
+---+---------------------+---------------+-------------------------------------------------------------+
| 2 | 2019-12-27 00:00:00 | Jenn Blossoms | Review lots of stuff/o...                                   |
+---+---------------------+---------------+-------------------------------------------------------------+
| 3 | 2019-12-27 00:00:00 | Jenn Blossoms | Draft email to world leader...                              |
+---+---------------------+---------------+-------------------------------------------------------------+
| 4 | 2019-12-30 00:00:00 | Jenn Blossoms | Review this thing.                                          |
+---+---------------------+---------------+-------------------------------------------------------------+
| 5 | 12-30-2019          | Jenn Blossoms | Telephone   Call   to   A.   Bell   return   her   multiple |
|   |                     |               | voicemails.                                                 |
+---+---------------------+---------------+-------------------------------------------------------------+

I have tried this code:

date = dftopdata['Date'].str.extract('(\d{2}-\d{2}-\d{4})(\s\w+\s\w+)\s(\w+.*)')[0]
name = dftopdata['Date'].str.extract('(\d{2}-\d{2}-\d{4})(\s\w+\s\w+)\s(\w+.*)')[1]
description = dftopdata['Date'].str.extract('(\d{2}-\d{2}-\d{4})(\s\w+\s\w+)\s(\w+.*)')[2]

dftopdata.loc[pd.to_datetime(dftopdata['Date'],errors='coerce').isnull(),'Professional'] = name
dftopdata.loc[pd.to_datetime(dftopdata['Date'],errors='coerce').isnull(),'Description'] = description
dftopdata.loc[pd.to_datetime(dftopdata['Date'],errors='coerce').isnull(),'Date'] = date

But when I run the above code, the data frame sample looks like this:

+---+------------+---------------+--------------------------------------------+
|   | Date       | Professional  | Description                                |
+---+------------+---------------+--------------------------------------------+
| 0 | 12/19/2019 | Katie Cool    | Travel to space ...                        |
+---+------------+---------------+--------------------------------------------+
| 1 | 12/20/2019 | Jenn Blossoms | Review stuff; prepare cancellations of ... |
+---+------------+---------------+--------------------------------------------+
| 2 | 12/27/2019 | Jenn Blossoms | Review lots of stuff/o…                    |
+---+------------+---------------+--------------------------------------------+
| 3 | 12/27/2019 | Jenn Blossoms | Draft email to world leader...             |
+---+------------+---------------+--------------------------------------------+
| 4 | 12/30/2019 | Jenn Blossoms | Review this thing.                         |
+---+------------+---------------+--------------------------------------------+
| 5 | NaN        | NaN           | NaN                                        |
+---+------------+---------------+--------------------------------------------+

Body:
You can use the str.split method to split the string into "words".

df['list_of_words'] = dftopdata['Date'].str.split()

If there is a pattern to split the Professional and Description parts from this list_of_words - you can use it. For instance, if the first 2 words of list_of_words make up the name of the professional then you can do -

df['Professional'] = df.apply(lambda x: ' '.join(x['list_of_words'][:2]), axis=1)
df['Description'] = df.apply(lambda x: ' '.join(x['list_of_words'][2:]), axis=1)


问:
How can I update my Database using AJAX after the user has entered text?
I have created a table which has a column for notes, the notes are from a MySQL table and displayed. When the user clicks on the notes it'll convert to an input box and allow them to edit the text. How would I then update my table with the new data that's been entered, so when the user clicks off of the input box they've just entered text in, it'll update the notes column using the correct row ID

Here is my code at the moment...

Javascript

```<code>    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
    <script>
    $( document ).ready(function() {
    $(function(){
      $("#loading").hide();
      //acknowledgement message
      var message_status = $("#status");
      $("td[contenteditable=true]").blur(function(){
          var field_id = $(this).attr("id") ;
          var value = $(this).text() ;
          $.post('scripts/update-jobdiary-notes.php' , field_id + "=" + value, function(data){ //change this to your liveupdatingpage.php
              if(data != '')
              {
                  message_status.show();
                  message_status.text(data);
                  //hide the message
                  setTimeout(function(){message_status.hide()},1000);
              }
          });
      });
    });
    });
    </script>
</code>```

HTML

```<code><td data-editable contenteditable="true" id="note_text_db_column:<?php $note['notes_id']; ?>"><?= $note['notes_text']; ?></td>
</code>```

PHP

```<code>//DATABASE CONNECTION
if(!empty($_POST))
{
    //database settings

    foreach($_POST as $field_name => $val)
    {
        //clean post values
        $field_id = strip_tags(trim($field_name));

        //from the fieldname:user_id we need to get user_id
        $split_data = explode(':', $field_id);
        $data_id = $split_data[1];
        $field_name = $split_data[0];
        if(!empty($data_id) && !empty($field_name) && !empty($val))
        {
            $stmt = $pdo->prepare("UPDATE ser_diarynotes SET notes_text = ? WHERE notes_id = ?"); //here just change name of your table and name of your unique_column
            $stmt->bind_param("si", $val, $data_id);
            $stmt->execute();
            $stmt->close();

            echo "Updated";
        } else {
            echo "Invalid Requests";
        }
    }
}
?>
</code>```

答:
Lets me modify your code further with an alternative js and updated html in order to capture:

unique ID of your content. assuming each record has to have a unique id column for easy update

the content being edited

Here is a sample HTML

```<code><style>
#status { padding:10px; position:fixed; top:10px; border-radius:5px; z-index:10000000; background:#88C4FF; color:#000; font-weight:bold; font-size:12px; margin-bottom:10px; display:none; width:100%; }
#loading { padding:10px; position:absolute; top:10px; border-radius:5px; z-index:10000000; background:#F99; color:#000; font-weight:bold; font-size:12px; margin-bottom:10px; display:none; width:100%; }
</style>

 <div id="status"> </div>
 <div id="loading"></div>

<table id="tableID">
<tbody>
  <tr>
    <!--Edit below by specifying notes_text column and notes_unique_id-->
    <td data-editable contenteditable="true" id="note_text_db_column:<?php echo $note['notes_unique_id']; ?>"><?php echo $note['notes_text']; ?></td>
    </tr>
 </tbody>
</table>
</code>```

Here is the JavaScript that will pass the two variables to your PHP page to update on db

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
 <script>
$( document ).ready(function() {
$(function(){
    $("#loading").hide();
    //acknowledgement message
    var message_status = $("#status");
    $("td[contenteditable=true]").blur(function(){
        var field_id = $(this).attr("id") ;
        var value = $(this).text() ;
        $.post('liveupdatingpage.php' , field_id + "=" + value, function(data){ //change this to your liveupdatingpage.php
            if(data != '')
            {
                message_status.show();
                message_status.text(data);
                //hide the message
                setTimeout(function(){message_status.hide()},1000);
            }
        });
    });
});
});
</script>
</code>```

and now Your PHP sample page to update your data

```<code><?php
//Your connection
$conn = new mysqli( 'localhost', 'db_user', 'user_password', 'your_db');

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $con->connect_error);
}

if(!empty($_POST))
{
    //database settings

    foreach($_POST as $field_name => $val)
    {
        //clean post values
        $field_id = strip_tags(trim($field_name));

        //from the fieldname:user_id we need to get user_id
        $split_data = explode(':', $field_id);
        $data_id = $split_data[1];
        $field_name = $split_data[0];
        if(!empty($data_id) && !empty($field_name) && !empty($val))
        {
            $stmt = $conn->prepare("UPDATE your_table SET $field_name = ? WHERE column_id = ?"); //here just change name of your table and name of your unique_column
            $stmt->bind_param("si", $val, $data_id);
            $stmt->execute();
            $stmt->close();

            echo "Updated";
        } else {
            echo "Invalid Requests";
        }
    }
}

else {
    echo "Invalid Requests";
}
?>
</code>```

Body:
I have created a table which has a column for notes, the notes are from a MySQL table and displayed. When the user clicks on the notes it'll convert to an input box and allow them to edit the text. How would I then update my table with the new data that's been entered, so when the user clicks off of the input box they've just entered text in, it'll update the notes column using the correct row ID

Here is my code at the moment...

Javascript

HTML

<td data-editable contenteditable="true" id="note_text_db_column:<?php $note['notes_id']; ?>"><?= $note['notes_text']; ?>

PHP

//DATABASE CONNECTION
if(!empty($_POST))
{
    //database settings

    foreach($_POST as $field_name => $val)
    {
        //clean post values
        $field_id = strip_tags(trim($field_name));

        //from the fieldname:user_id we need to get user_id
        $split_data = explode(':', $field_id);
        $data_id = $split_data[1];
        $field_name = $split_data[0];
        if(!empty($data_id) && !empty($field_name) && !empty($val))
        {
            $stmt = $pdo->prepare("UPDATE ser_diarynotes SET notes_text = ? WHERE notes_id = ?"); //here just change name of your table and name of your unique_column
            $stmt->bind_param("si", $val, $data_id);
            $stmt->execute();
            $stmt->close();

            echo "Updated";
        } else {
            echo "Invalid Requests";
        }
    }
}
?>

Body:
Lets me modify your code further with an alternative js and updated html in order to capture:

unique ID of your content. assuming each record has to have a unique id column for easy update

the content being edited

Here is a sample HTML

<style>
#status { padding:10px; position:fixed; top:10px; border-radius:5px; z-index:10000000; background:#88C4FF; color:#000; font-weight:bold; font-size:12px; margin-bottom:10px; display:none; width:100%; }
#loading { padding:10px; position:absolute; top:10px; border-radius:5px; z-index:10000000; background:#F99; color:#000; font-weight:bold; font-size:12px; margin-bottom:10px; display:none; width:100%; }
</style>

 <div id="status"> </div>
 <div id="loading"></div>

<table id="tableID">
<tbody>
  <tr>
    <!--Edit below by specifying notes_text column and notes_unique_id-->
    <td data-editable contenteditable="true" id="note_text_db_column:<?php echo $note['notes_unique_id']; ?>"><?php echo $note['notes_text']; ?></td>
    </tr>
 </tbody>
</table>

Here is the JavaScript that will pass the two variables to your PHP page to update on db

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
 <script>
$( document ).ready(function() {
$(function(){
    $("#loading").hide();
    //acknowledgement message
    var message_status = $("#status");
    $("td[contenteditable=true]").blur(function(){
        var field_id = $(this).attr("id") ;
        var value = $(this).text() ;
        $.post('liveupdatingpage.php' , field_id + "=" + value, function(data){ //change this to your liveupdatingpage.php
            if(data != '')
            {
                message_status.show();
                message_status.text(data);
                //hide the message
                setTimeout(function(){message_status.hide()},1000);
            }
        });
    });
});
});
</script>

and now Your PHP sample page to update your data

<?php
//Your connection
$conn = new mysqli( 'localhost', 'db_user', 'user_password', 'your_db');

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $con->connect_error);
}

if(!empty($_POST))
{
    //database settings

    foreach($_POST as $field_name => $val)
    {
        //clean post values
        $field_id = strip_tags(trim($field_name));

        //from the fieldname:user_id we need to get user_id
        $split_data = explode(':', $field_id);
        $data_id = $split_data[1];
        $field_name = $split_data[0];
        if(!empty($data_id) && !empty($field_name) && !empty($val))
        {
            $stmt = $conn->prepare("UPDATE your_table SET $field_name = ? WHERE column_id = ?"); //here just change name of your table and name of your unique_column
            $stmt->bind_param("si", $val, $data_id);
            $stmt->execute();
            $stmt->close();

            echo "Updated";
        } else {
            echo "Invalid Requests";
        }
    }
}

else {
    echo "Invalid Requests";
}
?>


问:
ERROR TypeError: Cannot read property '__source' of undefined
Since I upgrade to the new spartacus version (1.5) I've seen this bug in the console. It's came from SiteContextComponentService.getInjectedService.

I have not implemented nor used yet this service. How I can fix this bug? Cause I strongly believe is the origin of other little problems in my develop environment.

答: So the origin of the error was that in the GET /pages request I was not receiving the context attribute neither in the LanguageComponent nor the CurrencyComponent.


问:
How to show <Select > in sorted order
How can I sort the <option> elements of a <select> tag using JavaScript?

Here is the HTML I have:

```<code><form action="example.asp">
<div>
<select size="3">
<option value="op2" >Option 2</option>
<option value="op1">Option 1</option>
<option value="op4">Option 4</option>
<option value="op3">Option 3</option>

</select>
</div>
</form>
</code>```

答:
This function works as in the last answer, but also keeps the selection of  item</p>

```<code>// Sorts all entries of a select item (= dropdown) by their visible name, keeping the internal values and the selection
function sortSelectEntries(selItem) {
    let formerSel = selItem.value;
    let count = selItem.length;
    let options = new Array();
    for (var i = 0; i < count; i++)
        options[i] = selItem.options[i];
    options.sort((e1, e2) => e1.text > e2.text ? 1 : (e1.text < e2.text ? -1 : 0));
    for (i = 0; i < count; i++)
        selItem.options[i] = options[i];
    selItem.value = formerSel; // restore selection
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to show <Select > in sorted order

Body:
How can I sort the <option> elements of a <select> tag using JavaScript?

Here is the HTML I have:

<form action="example.asp">

<select size="3">
<option value="op2" >Option 2</option>
<option value="op1">Option 1</option>
<option value="op4">Option 4</option>
<option value="op3">Option 3</option>

</select>

</form>

Body:
This function works as in the last answer, but also keeps the selection of  item

// Sorts all entries of a select item (= dropdown) by their visible name, keeping the internal values and the selection
function sortSelectEntries(selItem) {
    let formerSel = selItem.value;
    let count = selItem.length;
    let options = new Array();
    for (var i = 0; i < count; i++)
        options[i] = selItem.options[i];
    options.sort((e1, e2) => e1.text > e2.text ? 1 : (e1.text < e2.text ? -1 : 0));
    for (i = 0; i < count; i++)
        selItem.options[i] = options[i];
    selItem.value = formerSel; // restore selection
}


问:
A simple "javac" style command-line C/C++ compiler for Windows 7
Over the last couple of months I practiced console programming with Java just with the help of JDK and a text editor of my choice (Notepad++). And I loved the simplicity as a program can be compiled from the command line plainly using javac and run using java.

Now, I'm looking for similar compiler for C/C++, such that I create a .c or .cpp file and compile it in the command prompt, and all it does is create a "native" executable that can be run directly from the command prompt. Thus, without any need of bloated IDE. The reason I'm looking for such simple compiler is because it is going to be used by high-school students so I'm advised to avoid any IDE as far as possible, so students can practice all the concepts of C/C++ languages without having to go for IDE. Which compiler can I use that does this job? also, I must work across all the versions Windows starting from Windows XP.

答: Visual Studio includes the ability to compile from the command line. Like others just said you can look at cygwin/MinGW. I would recommended using Code::Blocks or Dev-C++. I know you stated you do not want an IDE, but I would highly suggest a minimalist IDE like the ones I just suggested, or at least SciTE or Notepad++ to get some basic syntax highlighting with the ability to configure build tools if you want as well.</p>


问:
How to render dynamic symfony form?
I have symfony 5.

class FoodType has list of sauce checkboxes

```<code>->add('sauces', EntityType::class, [
                'class' => Sauce::class,
                'expanded' => true,
                'multiple' => true,
 ])
</code>```

Sauce entity has the desired method.

```<code>public function getAvailability(): bool
{
    return $this->availability;
}
</code>```

controller create form and pass it to twig.

```<code>$form = $this->createForm(FoodType::class, $food);
</code>```

Twig file

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

How can I implement something like this?

pseudo code

```<code>foreach($sauces as $sauce)
{
   if($sauce->getAvailability())
   {
     //show the sauce checkbox
   }
   else
   {
     //skip (hide) the checkbox
   }
}

</code>```

That is, I would like to display only those sauce checkboxes that are available.

Any ideas ?

答:
The solution is very simple.

class FoodType

```<code>->add('sauces', EntityType::class, [
                'class' => Sauce::class,
                'expanded' => true,
                'multiple' => true,

                'query_builder' => function (SauceRepository $sauceRepository) {
                    return $sauceRepository->createQueryBuilder('s')
                        ->andWhere('s.availability = 1');
                }

            ])
</code>```

Title: How to render dynamic symfony form?

Body:
I have symfony 5.

class FoodType has list of sauce checkboxes

->add('sauces', EntityType::class, [
                'class' => Sauce::class,
                'expanded' => true,
                'multiple' => true,
 ])

Sauce entity has the desired method.

public function getAvailability(): bool
{
    return $this->availability;
}

controller create form and pass it to twig.

$form = $this->createForm(FoodType::class, $food);

Twig file

{{ form(form) }}

How can I implement something like this?

pseudo code

foreach($sauces as $sauce)
{
   if($sauce->getAvailability())
   {
     //show the sauce checkbox
   }
   else
   {
     //skip (hide) the checkbox
   }
}

That is, I would like to display only those sauce checkboxes that are available.

Any ideas ?

Body:
The solution is very simple.

class FoodType

->add('sauces', EntityType::class, [
                'class' => Sauce::class,
                'expanded' => true,
                'multiple' => true,

                'query_builder' => function (SauceRepository $sauceRepository) {
                    return $sauceRepository->createQueryBuilder('s')
                        ->andWhere('s.availability = 1');
                }

            ])