问:
Validate Regex groups with OR when both groups are present in Java code
Need to validate a format where either of transport and protocol can be present or both can be. I have applied this regex to validate both the group. But when any one validation succeeds, it does not validate other group, like in the code.
Note: transport can accepts either tcp, sctp or udp and protocol can either accept radius, diameter and tacacs+.

Like example, if both transport and protocol are part of URL, and if format of transport is correct and it validates with the value provided in Regex, then it returns true even if the value of protocol is invalid.

Java Code:

```<code>String pattern = "((?=.*;transport=(tcp|sctp|udp)\\b)|(?=.*;protocol=(diameter|radius|tacacs+)\\b))";
String url = "transport=tcp;protocol=aradius";
    Pattern regExPattern = Pattern.compile(pattern);
    if(regExPattern.matcher(url).find()) {
        return true;
    } else {
        return false;
    }
</code>```

This returns true, since it validates transport successfully but unable to validate protocol values.

答:
I am not 100% sure what strings shall be detected as valid, but let me try to give an example:

```<code>import java.util.regex.Pattern;

public class Main
{

    private static void check(String s,Pattern regExPattern)
    {
        boolean matches=regExPattern.matcher(s).matches();
        System.out.println(s);
        System.out.println("matches:"+regExPattern.matcher(s).matches()+", find:"+regExPattern.matcher(s).find());
        System.out.println();
    }

    public static void main(String[] args) throws Exception
    {
        String pattern = "((.+=.+;transport=(tcp|sctp|udp))||(.+=.+;protocol=(diameter|radius|tacacs\\+)))";
        Pattern regExPattern = Pattern.compile(pattern);

        check("transport=tcp;protocol=diameter", regExPattern);
        check("transport=udp", regExPattern);
        check("protocol=radius", regExPattern);
        check("other=other;protocol=radius", regExPattern);
        check("other=other;transport=sctp", regExPattern);
        check("wrong;protocol=tacacs+", regExPattern);
        check("wrong;transport=tcp", regExPattern);
        check("wrong;wrong", regExPattern);
        check("something else;transport=tcp;protocol=diameter;something else", regExPattern);
    }
}
</code>```

Outputs:

```<code>transport=tcp;protocol=diameter
matches:true, find:true

transport=udp
matches:false, find:true

protocol=radius
matches:false, find:true

other=other;protocol=radius
matches:true, find:true

other=other;transport=sctp
matches:true, find:true

wrong;protocol=tacacs+
matches:false, find:true

wrong;transport=tcps
matches:false, find:true

wrong;wrong
matches:false, find:true

something else;transport=tcp;protocol=diameter;something else
matches:false, find:true
</code>```

I replaced ? by .+ because ? matches only a single character, .+ matches more than one characters. Then you can use match() instead of find().

match() requires that the whole string matches the pattern. find() requires that only part of the string matches a part of the pattern. I think you wanted to match (not find).

I replaced .* by .+ because .* matches any number of characters (including zero) but I assume that you only want to match at least one character here.

I removed the \\b because that matches the character b literally which seems to be not what you want.

I replaced tacacs+ by tacacs\\+ because you wanted to match the + literally not matching all all words that start with tacacs and any number of s like tacacsssssss.

The website https://regex101.com/ is very helpful to test regular expression because it marks parts of the pattern with colors and explains what the parts mean.

Instead of using complex expressions that you do not understand you might check the two parts individually and then write an if (matches || matches2)... statement that checks if at least one of both match:

```<code>import java.util.regex.Pattern;

public class Main
{

    private static void check(String s, String pattern1, String pattern2)
    {
        System.out.println(s);
        boolean matches1 = s.matches(pattern1);
        boolean matches2 = s.matches(pattern2);
        if (matches1 || matches2)
        {
            System.out.println("matches");
        }
        else
        {
            System.out.println("does not match");
        }
    }

    public static void main(String[] args) throws Exception
    {
        String pattern1 = ".*;transport=(tcp|sctp|udp).*";
        String pattern2 = ".*;protocol=(diameter|radius|tacacs\\+).*";

        check("transport=tcp;protocol=diameter", pattern1, pattern2);
        check("transport=udp", pattern1, pattern2);
        check("protocol=radius", pattern1, pattern2);
        check("other=other;protocol=radius", pattern1, pattern2);
        check("other=other;transport=sctp", pattern1, pattern2);
        check("wrong;protocol=tacacs+", pattern1, pattern2);
        check("wrong;transport=tcp", pattern1, pattern2);
        check("wrong;wrong", pattern1, pattern2);
        check("something else;transport=tcp;protocol=diameter;something else", pattern1, pattern2);
    }
}
</code>```

Outputs:

```<code>transport=tcp;protocol=diameter
matches
transport=udp
does not match
protocol=radius
does not match
other=other;protocol=radius
matches
other=other;transport=sctp
matches
wrong;protocol=tacacs+
matches
wrong;transport=tcp
matches
wrong;wrong
does not match
something else;transport=tcp;protocol=diameter;something else
matches
</code>```

Body:
Need to validate a format where either of transport and protocol can be present or both can be. I have applied this regex to validate both the group. But when any one validation succeeds, it does not validate other group, like in the code.
Note: transport can accepts either tcp, sctp or udp and protocol can either accept radius, diameter and tacacs+.

Like example, if both transport and protocol are part of URL, and if format of transport is correct and it validates with the value provided in Regex, then it returns true even if the value of protocol is invalid.

Java Code:

String pattern = "((?=.*;transport=(tcp|sctp|udp)\\b)|(?=.*;protocol=(diameter|radius|tacacs+)\\b))";
String url = "transport=tcp;protocol=aradius";
    Pattern regExPattern = Pattern.compile(pattern);
    if(regExPattern.matcher(url).find()) {
        return true;
    } else {
        return false;
    }

This returns true, since it validates transport successfully but unable to validate protocol values.

Body:
I am not 100% sure what strings shall be detected as valid, but let me try to give an example:

import java.util.regex.Pattern;

public class Main
{

    private static void check(String s,Pattern regExPattern)
    {
        boolean matches=regExPattern.matcher(s).matches();
        System.out.println(s);
        System.out.println("matches:"+regExPattern.matcher(s).matches()+", find:"+regExPattern.matcher(s).find());
        System.out.println();
    }

    public static void main(String[] args) throws Exception
    {
        String pattern = "((.+=.+;transport=(tcp|sctp|udp))||(.+=.+;protocol=(diameter|radius|tacacs\\+)))";
        Pattern regExPattern = Pattern.compile(pattern);

        check("transport=tcp;protocol=diameter", regExPattern);
        check("transport=udp", regExPattern);
        check("protocol=radius", regExPattern);
        check("other=other;protocol=radius", regExPattern);
        check("other=other;transport=sctp", regExPattern);
        check("wrong;protocol=tacacs+", regExPattern);
        check("wrong;transport=tcp", regExPattern);
        check("wrong;wrong", regExPattern);
        check("something else;transport=tcp;protocol=diameter;something else", regExPattern);
    }
}

Outputs:

transport=tcp;protocol=diameter
matches:true, find:true

transport=udp
matches:false, find:true

protocol=radius
matches:false, find:true

other=other;protocol=radius
matches:true, find:true

other=other;transport=sctp
matches:true, find:true

wrong;protocol=tacacs+
matches:false, find:true

wrong;transport=tcps
matches:false, find:true

wrong;wrong
matches:false, find:true

something else;transport=tcp;protocol=diameter;something else
matches:false, find:true

I replaced ? by .+ because ? matches only a single character, .+ matches more than one characters. Then you can use match() instead of find().

match() requires that the whole string matches the pattern. find() requires that only part of the string matches a part of the pattern. I think you wanted to match (not find).

I replaced .* by .+ because .* matches any number of characters (including zero) but I assume that you only want to match at least one character here.

I removed the \\b because that matches the character b literally which seems to be not what you want.

I replaced tacacs+ by tacacs\\+ because you wanted to match the + literally not matching all all words that start with tacacs and any number of s like tacacsssssss.

The website https://regex101.com/ is very helpful to test regular expression because it marks parts of the pattern with colors and explains what the parts mean.

Instead of using complex expressions that you do not understand you might check the two parts individually and then write an if (matches || matches2)... statement that checks if at least one of both match:

import java.util.regex.Pattern;

public class Main
{

    private static void check(String s, String pattern1, String pattern2)
    {
        System.out.println(s);
        boolean matches1 = s.matches(pattern1);
        boolean matches2 = s.matches(pattern2);
        if (matches1 || matches2)
        {
            System.out.println("matches");
        }
        else
        {
            System.out.println("does not match");
        }
    }

    public static void main(String[] args) throws Exception
    {
        String pattern1 = ".*;transport=(tcp|sctp|udp).*";
        String pattern2 = ".*;protocol=(diameter|radius|tacacs\\+).*";

        check("transport=tcp;protocol=diameter", pattern1, pattern2);
        check("transport=udp", pattern1, pattern2);
        check("protocol=radius", pattern1, pattern2);
        check("other=other;protocol=radius", pattern1, pattern2);
        check("other=other;transport=sctp", pattern1, pattern2);
        check("wrong;protocol=tacacs+", pattern1, pattern2);
        check("wrong;transport=tcp", pattern1, pattern2);
        check("wrong;wrong", pattern1, pattern2);
        check("something else;transport=tcp;protocol=diameter;something else", pattern1, pattern2);
    }
}

Outputs:

transport=tcp;protocol=diameter
matches
transport=udp
does not match
protocol=radius
does not match
other=other;protocol=radius
matches
other=other;transport=sctp
matches
wrong;protocol=tacacs+
matches
wrong;transport=tcp
matches
wrong;wrong
does not match
something else;transport=tcp;protocol=diameter;something else
matches


来源: stackexchange

问:
Can't get out this while loop
I want this loop to break when user enters anything but y or Y. But, instead the Enter the new location prompt is returning again and again.

```<code>    def add_locations(self):
        while True:
            new = str(input("Enter the new loation: "))
            self.locations.append(new)
            ask = str(input("add new location? (y/n):  "))
            if ask == 'y' or 'Y':
                continue
            else:
                break
</code>```

答: Your if-clause is evaluated like this: (ask == 'y') or 'Y' and 'Y' is always true. You need to ask if ask == 'y' or ask == 'Y': instead

ContentLicense: CC BY-SA 4.0

Title: Can't get out this while loop

Body:
I want this loop to break when user enters anything but y or Y. But, instead the Enter the new location prompt is returning again and again.

    def add_locations(self):
        while True:
            new = str(input("Enter the new loation: "))
            self.locations.append(new)
            ask = str(input("add new location? (y/n):  "))
            if ask == 'y' or 'Y':
                continue
            else:
                break


问:
LINQ Get full list of objects, include only the properties that match certain condition
I have these two models:

    public class Seat
    {
        public int Id { get; set; }
        public ICollection<Reservation> Reservations { get; set; }
    //..
    }

    public class Reservation
    {
        public int Id { get; set; }
        public int SeatId { get; set; }
        public Seat Seat { get; set; }
        public DateTime DateTime { get; set; }
        //..
    }
```

<p>Say a seat has a reservations for every day of the week. I want to make a query that takes the seats and filters the reservations for the seats for a requested day. I want to display the seats and show which ones are free/reserved for the day X.
The ways I tried to achieve it:</p>

<pre class="lang-cs prettyprint-override"><code>        var seats = _dbContext.Seats
             .Include(s => s.Reservations.Where(r => r.DateTime.Date == dateParam.Date));
        // InvalidOperationException: 'Lambda expression used
        // inside Include is not valid.'
</code>```

Sample

       var seats = _dbContext.Seats
             .Include(s => s.Reservations)
             .Where(r => r.Reservations.Any(r => r.DateTime.Date == dateParam.Date));
        // Gets the seats which meet the condition. I want these, but also I want the free seats
```

<p>Sample</p>

<pre class="lang-cs prettyprint-override"><code>        var seatsFiltered = _dbContext.Seats
             .Include(t => t.Reservations)
             .Where(r => r.Reservations.Any(r => r.DateTime.Date == dateParam.Date))
             .ToList();

        var seats = _dbContext.Seats
             .ToList()
             .Select(x => { x.Reservations = new List<Reservation>(); return x; })
             .Concat(seatsFiltered);
        // Not optimal since I obviously ToList twice
        // In the end I get an empty list

        return (ICollection<Seat>)seats;
</code>```

EDIT: Add sample data as requested:

Seats

```<code>Id|AreaId|
--|------|
 1|3     |
 2|3     |
 3|3     |
 4|3     |
 5|3     |
 6|3     |
 7|3     |
 8|3     |
</code>```

Reservations

```<code>Id|SeatId|Name|Phone|DateTime           |
--|------|----|-----|-------------------|
 7|     1|    |     |2020-02-15 20:30:00|
 8|     1|    |     |2020-02-21 12:00:00|
 9|     1|    |     |2020-02-23 09:00:00|
10|     2|    |     |2020-02-15 20:30:00|
11|     2|    |     |2020-02-21 12:00:00|
12|     2|    |     |2020-02-23 09:00:00|
13|     4|    |     |2020-02-21 12:00:00|
15|     7|    |     |2020-02-15 20:30:00|
16|     7|    |     |2020-02-21 12:00:00|
17|     8|    |     |2020-02-21 12:00:00|
14|     8|    |     |2020-02-23 09:00:00|
18|     3|    |     |2020-02-15 20:30:00|
19|     3|    |     |2020-02-21 12:00:00|
20|     3|    |     |2020-02-23 09:00:00|
</code>```

When I tried the code by Phong, I got the following error:

System.InvalidOperationException: 'The LINQ expression '(GroupByShaperExpression:
  KeySelector: (r.SeatId),
  ElementSelector:(EntityShaperExpression:
      EntityType: Reservation
      ValueBufferExpression:
          (ProjectionBindingExpression: EmptyProjectionMember)
      IsNullable: False
  )
  )
      .ToList()' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.'

答:
You should GroupBy() like below.

```<code>var seatsFiltered = _dbContext.Reservations
                          .Where(r => r.DateTime.Date == dateParam.Date))
                          .GroupBy(r => r.SeatId)
                          .Select(g => new
{
  SeatId = g.Key,
  ListOfReservations = g // No need to .ToList() here
}) .ToList();
</code>```

Body:
I have these two models:

    public class Seat
    {
        public int Id { get; set; }
        public ICollection<Reservation> Reservations { get; set; }
    //..
    }

    public class Reservation
    {
        public int Id { get; set; }
        public int SeatId { get; set; }
        public Seat Seat { get; set; }
        public DateTime DateTime { get; set; }
        //..
    }

Say a seat has a reservations for every day of the week. I want to make a query that takes the seats and filters the reservations for the seats for a requested day. I want to display the seats and show which ones are free/reserved for the day X.
The ways I tried to achieve it:

        var seats = _dbContext.Seats
             .Include(s => s.Reservations.Where(r => r.DateTime.Date == dateParam.Date));
        // InvalidOperationException: 'Lambda expression used
        // inside Include is not valid.'

Sample

       var seats = _dbContext.Seats
             .Include(s => s.Reservations)
             .Where(r => r.Reservations.Any(r => r.DateTime.Date == dateParam.Date));
        // Gets the seats which meet the condition. I want these, but also I want the free seats

Sample

        var seatsFiltered = _dbContext.Seats
             .Include(t => t.Reservations)
             .Where(r => r.Reservations.Any(r => r.DateTime.Date == dateParam.Date))
             .ToList();

        var seats = _dbContext.Seats
             .ToList()
             .Select(x => { x.Reservations = new List<Reservation>(); return x; })
             .Concat(seatsFiltered);
        // Not optimal since I obviously ToList twice
        // In the end I get an empty list

        return (ICollection<Seat>)seats;

EDIT: Add sample data as requested:

Seats

Id|AreaId|
--|------|
 1|3     |
 2|3     |
 3|3     |
 4|3     |
 5|3     |
 6|3     |
 7|3     |
 8|3     |

Reservations

Id|SeatId|Name|Phone|DateTime           |
--|------|----|-----|-------------------|
 7|     1|    |     |2020-02-15 20:30:00|
 8|     1|    |     |2020-02-21 12:00:00|
 9|     1|    |     |2020-02-23 09:00:00|
10|     2|    |     |2020-02-15 20:30:00|
11|     2|    |     |2020-02-21 12:00:00|
12|     2|    |     |2020-02-23 09:00:00|
13|     4|    |     |2020-02-21 12:00:00|
15|     7|    |     |2020-02-15 20:30:00|
16|     7|    |     |2020-02-21 12:00:00|
17|     8|    |     |2020-02-21 12:00:00|
14|     8|    |     |2020-02-23 09:00:00|
18|     3|    |     |2020-02-15 20:30:00|
19|     3|    |     |2020-02-21 12:00:00|
20|     3|    |     |2020-02-23 09:00:00|

When I tried the code by Phong, I got the following error:

System.InvalidOperationException: 'The LINQ expression '(GroupByShaperExpression:
  KeySelector: (r.SeatId),
  ElementSelector:(EntityShaperExpression:
      EntityType: Reservation
      ValueBufferExpression:
          (ProjectionBindingExpression: EmptyProjectionMember)
      IsNullable: False
  )
  )
      .ToList()' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.'

Body:
You should GroupBy() like below.

var seatsFiltered = _dbContext.Reservations
                          .Where(r => r.DateTime.Date == dateParam.Date))
                          .GroupBy(r => r.SeatId)
                          .Select(g => new
{
  SeatId = g.Key,
  ListOfReservations = g // No need to .ToList() here
}) .ToList();


问:
How to use OR Condition in Paginate function in Cakephp?
I am facing a problem while fetching values using paginate function in cakephp. In the "to" field of message I have CSV fields of userid. To search messages for a single user. I am using the code below...

```<code>$this->set('message', $this->paginate('Message', array(
    'or'=> array(
        "Message.to LIKE" => "".$this->Session->read('Auth.User.id').",",
        "Message.to LIKE" => ",".$this->Session->read('Auth.User.id').","
    )
)));
</code>```

But the query is formed in this manner which is not what I want.. I want to two conditions with OR condition.

```<code>SELECT `Message`.`id`, `Message`.`timestamp`, `Message`.`to`, `Message`.`from`,
       `Message`.`message`, `Message`.`subject`, `Message`.`urgent`, `Message`.`read`,
       `Message`.`tag`, `Message`.`open`, `Message`.`reply_id`, `User`.`id`,
       `User`.`fname`, `User`.`lname`, `User`.`user`, `User`.`password`,
       `User`.`photo`, `User`.`created`, `User`.`access`, `User`.`login`,
       `User`.`status`, `User`.`role`
FROM `messages` AS `Message`
LEFT JOIN `users` AS `User` ON (`Message`.`to` = `User`.`id`)
WHERE `Message`.`to` LIKE ',1,'
ORDER BY `Message`.`timestamp` desc
LIMIT 5
</code>```

答:
Just make the condition into an array</p>

```<code>$this->set('message', $this->paginate('Message', array(
        "Message.to LIKE" => array("".$this->Session->read('Auth.User.id').",",",".$this->Session->read('Auth.User.id').",")
)));
</code>```

OwnerDisplayName: delete me

ContentLicense: CC BY-SA 2.5

Body:
I am facing a problem while fetching values using paginate function in cakephp. In the "to" field of message I have CSV fields of userid. To search messages for a single user. I am using the code below...

$this->set('message', $this->paginate('Message', array(
    'or'=> array(
        "Message.to LIKE" => "".$this->Session->read('Auth.User.id').",",
        "Message.to LIKE" => ",".$this->Session->read('Auth.User.id').","
    )
)));

But the query is formed in this manner which is not what I want.. I want to two conditions with OR condition.

SELECT `Message`.`id`, `Message`.`timestamp`, `Message`.`to`, `Message`.`from`,
       `Message`.`message`, `Message`.`subject`, `Message`.`urgent`, `Message`.`read`,
       `Message`.`tag`, `Message`.`open`, `Message`.`reply_id`, `User`.`id`,
       `User`.`fname`, `User`.`lname`, `User`.`user`, `User`.`password`,
       `User`.`photo`, `User`.`created`, `User`.`access`, `User`.`login`,
       `User`.`status`, `User`.`role`
FROM `messages` AS `Message`
LEFT JOIN `users` AS `User` ON (`Message`.`to` = `User`.`id`)
WHERE `Message`.`to` LIKE ',1,'
ORDER BY `Message`.`timestamp` desc
LIMIT 5

Body:
Just make the condition into an array

$this->set('message', $this->paginate('Message', array(
        "Message.to LIKE" => array("".$this->Session->read('Auth.User.id').",",",".$this->Session->read('Auth.User.id').",")
)));

ContentLicense: CC BY-SA 3.0


问:
How can I select Python 3.7 or Python 3.8 in iPython?
My OS is Windows 7

I need to use TensorFlow with Keras in Python, but it doesn't work yet in Python 3.8. So I've installed again Python 3.7 and his packages.

Inside the IDE PyCharm was easy. It just add another interpreter in settings and it works. So when I create a project I need to select the right interpreter.

I also use iPython to make small tests. I've searched in all Stackoverflow and I don't find any answer that works in 2020.  I use iPython and not the Jupyter environment.

First, I've created the kernels, as iPython instructions said in its site.

```<code>python -m ipykernel install --user
</code>```

It creates a json file in  c:\Users\myname\AppData\Roaming\jupyter\kernels

After I use iPython -h and he told me to use kernel subcommand:

```<code>Subcommands are launched as `ipython cmd [args]`. For information on using
subcommand 'cmd', do: `ipython cmd -h`.
</code>```

Feeling more motivated, I've tried the command iPython kernel -h. But I've got a very confusing text.

So I've tried to use the kernel option,

```<code>C:> iPython kernel
</code>```

It gave me the following message:

```<code>To connect another client to this kernel, use:
    --existing kernel-3404.json
</code>```

However, I'm not getting select the right kernel.

I try to use use my kernel file, but with no success.

```<code>Invalid argument: '--kernel.json'
</code>```

So I'm lost, because in no place I've found a detailed instructions for kernel subcommand in line command options for iPython.

答:
I've found a solution that solves my problem in  Windows 7. I don't even need ipyKernet package.

I've started locating iPython.exe files in Python 3.7 and Python 3.8

```<code>c:\Users\myname\AppData\Local\Programs\Python\Python37\Scripts\ipython.exe
c:\Users\myname\AppData\Local\Programs\Python\Python38\Scripts\ipython.exe
</code>```

So I've made the following script py.BAT and stored it in a folder inside the PATH environment variable (One can edit the PATH variable using Control Panel, Systems,  Advanced system settings, environment variables):

```<code>@echo off
cd\dropbox\python
if "%1"=="37" goto ip37
if "%1"=="38" goto ip38
if not "%1"== "" goto erro
:ip38
  c:\Users\myname\AppData\Local\Programs\Python\Python38\Scripts\ipython
  goto fim
:ip37
  c:\Users\myname\AppData\Local\Programs\Python\Python37\Scripts\ipython
  goto fim
:erro
  echo Syntax: py 37   - iPython 3.7
  echo         py 38   - iPython 3.8
  echo         py      - iPython 3.8
:fim
</code>```

Now it's a piece of cake:

If I want to run iPython over Python 3.7

```<code>py 37
</code>```

If I what to run iPython over Python 3.8

```<code>py
</code>```

or

```<code>py 38
</code>```

Of course I've checked  Python version in each iPython session:

```<code>import sys
print(sys.version)
</code>```

The messages was

```<code>3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)]
</code>```

or

```<code>3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30)[MSC v.1916 64 bit (AMD64)]
</code>```

Any other param

```<code>py 40 # e.g.
</code>```

results in

```<code>Syntax: py 37   - iPython 3.7
        py 38   - iPython 3.8
        py      - iPython 3.8
</code>```

Internal references in Python don't use PATH environment variables in general, but when one uses an utility in the shell as pip, has a problem because if you write pip in the shell, it searchs the first executable in the order of the string content in the PATH variable, generally the last Python version.

So one has to make a copy in the old  Python version that utility in the same folder (please not rename the original file) with another name (Eg: pip.exe to pi.exe)

Other solution would be temporarily change the path environment variable inside PY.BAT and any other, if necessary. I haven't done it yet because everything is fine so far.

Body:
My OS is Windows 7

I need to use TensorFlow with Keras in Python, but it doesn't work yet in Python 3.8. So I've installed again Python 3.7 and his packages.

Inside the IDE PyCharm was easy. It just add another interpreter in settings and it works. So when I create a project I need to select the right interpreter.

I also use iPython to make small tests. I've searched in all Stackoverflow and I don't find any answer that works in 2020.  I use iPython and not the Jupyter environment.

First, I've created the kernels, as iPython instructions said in its site.

python -m ipykernel install --user

It creates a json file in  c:\Users\myname\AppData\Roaming\jupyter\kernels

After I use iPython -h and he told me to use kernel subcommand:

Subcommands are launched as `ipython cmd [args]`. For information on using
subcommand 'cmd', do: `ipython cmd -h`.

Feeling more motivated, I've tried the command iPython kernel -h. But I've got a very confusing text.

So I've tried to use the kernel option,

C:> iPython kernel

It gave me the following message:

To connect another client to this kernel, use:
    --existing kernel-3404.json

However, I'm not getting select the right kernel.

I try to use use my kernel file, but with no success.

Invalid argument: '--kernel.json'

So I'm lost, because in no place I've found a detailed instructions for kernel subcommand in line command options for iPython.

Body:
I've found a solution that solves my problem in  Windows 7. I don't even need ipyKernet package.

I've started locating iPython.exe files in Python 3.7 and Python 3.8

c:\Users\myname\AppData\Local\Programs\Python\Python37\Scripts\ipython.exe
c:\Users\myname\AppData\Local\Programs\Python\Python38\Scripts\ipython.exe

So I've made the following script py.BAT and stored it in a folder inside the PATH environment variable (One can edit the PATH variable using Control Panel, Systems,  Advanced system settings, environment variables):

@echo off
cd\dropbox\python
if "%1"=="37" goto ip37
if "%1"=="38" goto ip38
if not "%1"== "" goto erro
:ip38
  c:\Users\myname\AppData\Local\Programs\Python\Python38\Scripts\ipython
  goto fim
:ip37
  c:\Users\myname\AppData\Local\Programs\Python\Python37\Scripts\ipython
  goto fim
:erro
  echo Syntax: py 37   - iPython 3.7
  echo         py 38   - iPython 3.8
  echo         py      - iPython 3.8
:fim

Now it's a piece of cake:

If I want to run iPython over Python 3.7

py 37

If I what to run iPython over Python 3.8

py

or

py 38

Of course I've checked  Python version in each iPython session:

import sys
print(sys.version)

The messages was

3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)]

or

3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30)[MSC v.1916 64 bit (AMD64)]

Any other param

py 40 # e.g.

results in

Syntax: py 37   - iPython 3.7
        py 38   - iPython 3.8
        py      - iPython 3.8

Internal references in Python don't use PATH environment variables in general, but when one uses an utility in the shell as pip, has a problem because if you write pip in the shell, it searchs the first executable in the order of the string content in the PATH variable, generally the last Python version.

So one has to make a copy in the old  Python version that utility in the same folder (please not rename the original file) with another name (Eg: pip.exe to pi.exe)

Other solution would be temporarily change the path environment variable inside PY.BAT and any other, if necessary. I haven't done it yet because everything is fine so far.


问:
Segmentation fault while using shared memory
This code performs the following:
Reads the contents of the "read" text file and writes it into the shared memory space.The code was working until yesterday but the same code shows segmentation fault today. Can you help me figure out where I'd made a mistake?</p>

```<code>#include<sys/ipc.h>
#define NULL 0
#include<sys/shm.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/wait.h>
#include<ctype.h>
#include<fcntl.h>
#include<stdio_ext.h>

int main()
{

char *a;
char name[20];
int id,n;
char buf[50];
int fd;
fd=open("read",O_RDONLY);
int s1=read(fd,&buf,50);

id=shmget(200,50,IPC_CREAT);

    a=shmat(id,NULL,0);
    strcpy(a,buf);
    wait(NULL);
    shmdt(a);

shmctl(id,IPC_RMID,NULL);
return 0;

 }
</code>```

答:
You have to check the return value of every function you used in your code. The segmentation fault occurred when you call strcpy(a,buf);. If you check the value of a it does not have a valid memory address, that is because you never checked the value returned from shmat() call and you need to carefully check the parameters that this function is taking(man page).

Below, I commented where the seg fault occurs:

```<code>int main()
{
  //char name[20]; // never used
  int id;

  char *a;
  char buf[50];
  int fd;
  fd=open("read",O_RDONLY); // check return value
  //make sure you provide the correct path for your "read" text file
  int restlt = read(fd,&buf,50); // check return value

  key_t mem_key = ftok(".", 'a');
  id = shmget(mem_key, 50, IPC_CREAT | 0666);
  //id = shmget(200,50,IPC_CREAT); //check the return value
  if (id < 0) {
      printf("Error occured during shmget() call\n");
      exit(1);
  }
  a = shmat(id,NULL,0); //check the return value
  if ((int) a == -1) {
       printf("Error occured during shmat() call\n");
       exit(1);
  }
  printf("Value of pointer a = %p \n", a);
  strcpy(a,buf); // better to use strncpy(a, buf, n);

  printf("Value of a[0]  = %c \n", *a);

  wait(NULL);
  shmdt(a);
  shmctl(id,IPC_RMID,NULL);

  return 0;

 }
</code>```

Check out this link: http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/shm/shmat.html

Body:
This code performs the following:
Reads the contents of the "read" text file and writes it into the shared memory space.The code was working until yesterday but the same code shows segmentation fault today. Can you help me figure out where I'd made a mistake?

#include<sys/ipc.h>
#define NULL 0
#include<sys/shm.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/wait.h>
#include<ctype.h>
#include<fcntl.h>
#include<stdio_ext.h>

int main()
{

char *a;
char name[20];
int id,n;
char buf[50];
int fd;
fd=open("read",O_RDONLY);
int s1=read(fd,&buf,50);

id=shmget(200,50,IPC_CREAT);

    a=shmat(id,NULL,0);
    strcpy(a,buf);
    wait(NULL);
    shmdt(a);

shmctl(id,IPC_RMID,NULL);
return 0;

 }

Body:
You have to check the return value of every function you used in your code. The segmentation fault occurred when you call strcpy(a,buf);. If you check the value of a it does not have a valid memory address, that is because you never checked the value returned from shmat() call and you need to carefully check the parameters that this function is taking(man page).

Below, I commented where the seg fault occurs:

int main()
{
  //char name[20]; // never used
  int id;

  char *a;
  char buf[50];
  int fd;
  fd=open("read",O_RDONLY); // check return value
  //make sure you provide the correct path for your "read" text file
  int restlt = read(fd,&buf,50); // check return value

  key_t mem_key = ftok(".", 'a');
  id = shmget(mem_key, 50, IPC_CREAT | 0666);
  //id = shmget(200,50,IPC_CREAT); //check the return value
  if (id < 0) {
      printf("Error occured during shmget() call\n");
      exit(1);
  }
  a = shmat(id,NULL,0); //check the return value
  if ((int) a == -1) {
       printf("Error occured during shmat() call\n");
       exit(1);
  }
  printf("Value of pointer a = %p \n", a);
  strcpy(a,buf); // better to use strncpy(a, buf, n);

  printf("Value of a[0]  = %c \n", *a);

  wait(NULL);
  shmdt(a);
  shmctl(id,IPC_RMID,NULL);

  return 0;

 }

Check out this link: http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/shm/shmat.html


问:
Python and Seaborn how to plot two categorical features using barplot
I am trying to solve kaggle's titanic competition.

I need to generate a plot where X is representing Sex having male and female as values. And Y as two variables 0 and 1.

From this, I need to see how many males/females survived.

I am trying the following:

```<code>sns.barplot(x='Sex', y='Survived', data=train)
</code>```

But I am getting a plot representing percentage of each male and female:

Any idea how to create stacked bar using seaborn?

I need to plot 2 features, each of them having 2 values.

答:
I would probably try with "Grouped barplots". Interestingly, the seaborn's gallery page has a nice example about it... with titanic data as an example:

import seaborn as sns
sns.set(style="whitegrid")

# Load the example Titanic dataset
titanic = sns.load_dataset("titanic")

# Draw a nested barplot to show survival for class and sex
g = sns.catplot(x="class", y="survived", hue="sex", data=titanic,
                height=6, kind="bar", palette="muted")
g.despine(left=True)
g.set_ylabels("survival probability")
```

Body:
I am trying to solve kaggle's titanic competition.

I need to generate a plot where X is representing Sex having male and female as values. And Y as two variables 0 and 1.

From this, I need to see how many males/females survived.

I am trying the following:

sns.barplot(x='Sex', y='Survived', data=train)

But I am getting a plot representing percentage of each male and female:

Any idea how to create stacked bar using seaborn?

I need to plot 2 features, each of them having 2 values.


问:
Transform rows to multiple rows in Spark Scala
I have a problem where I need to transform one row to multiple rows. This is based on a different mapping that I have. I have tried to provide an example below.

Suppose I have a parquet file with the below schema

```<code>ColA, ColB, ColC, Size, User
</code>```

I need to aggregate the above data into multiple rows based on a lookup map. Suppose I have a static map

```<code>ColA, ColB, Sum(Size)
ColB, ColC, Distinct (User)
ColA, ColC, Sum(Size)
</code>```

This means that one row in the input RDD needs to be transformed to 3 aggregate. I believe RDD is the way to go with FlatMapPair, but I am not sure how to go about this.

I am also OK to concat the columns into one key, something like ColA_ColB etc.

For creating multiple aggregates from the same data, I have started with something like this

```<code>
val keyData: PairFunction[Row, String, Long] = new PairFunction[Row, String, Long]() {
    override def call(x: Row) = {
      (x.getString(1),x.getLong(5))
    }
  }

val ip15M = spark.read.parquet("a.parquet").toJavaRDD

val pairs = ip15M.mapToPair(keyData)

java.util.List[(String, Long)] = [(ios,22), (ios,23), (ios,10), (ios,37), (ios,26), (web,52), (web,1)]

</code>```

I believe I need to do flatmaptopair instead of mapToPair. On similar lines, I tried

```<code>  val FlatMapData: PairFlatMapFunction[Row, String, Long] = new PairFlatMapFunction[Row, String, Long]() {
    override def call(x: Row) = {
      (x.getString(1),x.getLong(5))
    }
  }

</code>```

but it is giving Error

```<code>Expression of type (String, Long) doesn't conform to expected type util.Iterator[(String, Long)]
</code>```

Any help is appreciated. Please let me know if I need to add any more details.

答:
the outcome should only have 3 columns? I mean col1, col2, col3 (the agg outcome).
The second aggregate is a distinct count of users? (I assume yes).

If so you can basically create 3 data frames and then union them.
Something in the way of:

val df1 = spark.sql("select colA as col1, colB as col2 ,sum(Size) as colAgg group by colA,colB")

val df2 = spark.sql("select colB as col1, colC as col2 ,Distinct(User) as colAgg group by colB,colC")

val df3 = spark.sql("select colA as col1, colC as col2 ,sum(Size) as colAgg group by colA,colC")

df1.union(df2).union(df3)

Body:
I have a problem where I need to transform one row to multiple rows. This is based on a different mapping that I have. I have tried to provide an example below.

Suppose I have a parquet file with the below schema

ColA, ColB, ColC, Size, User

I need to aggregate the above data into multiple rows based on a lookup map. Suppose I have a static map

ColA, ColB, Sum(Size)
ColB, ColC, Distinct (User)
ColA, ColC, Sum(Size)

This means that one row in the input RDD needs to be transformed to 3 aggregate. I believe RDD is the way to go with FlatMapPair, but I am not sure how to go about this.

I am also OK to concat the columns into one key, something like ColA_ColB etc.

For creating multiple aggregates from the same data, I have started with something like this

val keyData: PairFunction[Row, String, Long] = new PairFunction[Row, String, Long]() {
    override def call(x: Row) = {
      (x.getString(1),x.getLong(5))
    }
  }

val ip15M = spark.read.parquet("a.parquet").toJavaRDD

val pairs = ip15M.mapToPair(keyData)

java.util.List[(String, Long)] = [(ios,22), (ios,23), (ios,10), (ios,37), (ios,26), (web,52), (web,1)]

I believe I need to do flatmaptopair instead of mapToPair. On similar lines, I tried

  val FlatMapData: PairFlatMapFunction[Row, String, Long] = new PairFlatMapFunction[Row, String, Long]() {
    override def call(x: Row) = {
      (x.getString(1),x.getLong(5))
    }
  }

but it is giving Error

Expression of type (String, Long) doesn't conform to expected type util.Iterator[(String, Long)]

Any help is appreciated. Please let me know if I need to add any more details.


问:
How to add ViewHolder for a GrideView list?
I'm trying to write a ViewHolder for this GridView list but I'm getting an error every time.
Can you tell me how to make a right ViewHolder for this gridView list?

my code:

```<code>  public static String[] stringArray = {"IRAN","Uganda",
"Ukraine","United Arab Emirates","United Kingdom","United States Minor Outlying Islands",};

public int[] imageArray = {R.drawable.iran,R.drawable.united_states,R.drawable.iran,R.drawable.russia,
R.drawable.iran,R.drawable.united_states,R.drawable.iran,R.drawable.uk,
R.drawable.iran,R.drawable.united_states  };

public CountryImageAdapter(Context mContext) {this.mContext = mContext;}

@Override
public int getCount() {return imageArray.length;}

@Override
public Object getItem(int position) {return imageArray[position];}

@Override
public long getItemId(int position) {return 0;}

@Override
public View getView(int position, View view, ViewGroup viewGroup) {View v;

LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

v = inflater.inflate(R.layout.sample_gridlayout, null);
v.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

TextView textView = (TextView) v.findViewById(R.id.country_text);
ImageView imageView = (ImageView) v.findViewById(R.id.ivGallery);

textView.setText(stringArray[position]);
imageView.setImageResource(imageArray[position]);

return v;}
</code>```

答:
you should create a customViewHolder class which extends RecyclerView.ViewHolder and you should find your views there:

```<code>TextView textView = (TextView) v.findViewById(R.id.country_text);
ImageView imageView = (ImageView) v.findViewById(R.id.ivGallery);
</code>```

and you should put these lines:

```<code>textView.setText(stringArray[position]);
imageView.setImageResource(imageArray[position]);
</code>```

in onBindViewHolder function.

Body:
I'm trying to write a ViewHolder for this GridView list but I'm getting an error every time.
Can you tell me how to make a right ViewHolder for this gridView list?

my code:

  public static String[] stringArray = {"IRAN","Uganda",
"Ukraine","United Arab Emirates","United Kingdom","United States Minor Outlying Islands",};

public int[] imageArray = {R.drawable.iran,R.drawable.united_states,R.drawable.iran,R.drawable.russia,
R.drawable.iran,R.drawable.united_states,R.drawable.iran,R.drawable.uk,
R.drawable.iran,R.drawable.united_states  };

public CountryImageAdapter(Context mContext) {this.mContext = mContext;}

@Override
public int getCount() {return imageArray.length;}

@Override
public Object getItem(int position) {return imageArray[position];}

@Override
public long getItemId(int position) {return 0;}

@Override
public View getView(int position, View view, ViewGroup viewGroup) {View v;

LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

v = inflater.inflate(R.layout.sample_gridlayout, null);
v.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

TextView textView = (TextView) v.findViewById(R.id.country_text);
ImageView imageView = (ImageView) v.findViewById(R.id.ivGallery);

textView.setText(stringArray[position]);
imageView.setImageResource(imageArray[position]);

return v;}

Body:
you should create a customViewHolder class which extends RecyclerView.ViewHolder and you should find your views there:

TextView textView = (TextView) v.findViewById(R.id.country_text);
ImageView imageView = (ImageView) v.findViewById(R.id.ivGallery);

and you should put these lines:

textView.setText(stringArray[position]);
imageView.setImageResource(imageArray[position]);

in onBindViewHolder function.


问:
Invalid data from data frame in R
I am new in R and i am trying to analyze some data. I occured an error in extracting data from data frame. This is my code:

```<code>library('BCA')
eggs<-read.csv2("http://jolej.linuxpl.info/Eggs.csv", header=TRUE, stringsAsFactors = T, sep = ',')
weeks<-eggs$Week
eggs_prices = as.numeric(eggs$Egg.Pr)
matplot(weeks, eggs$Egg.Pr, pch = ".", type = "o", col = "blue", xlab = "Tydzień", ylab = "Cena
jajek")
title(main = "Cena jajek w poszczególnych tygodniach")
mean(eggs_prices)
eggs_prices
</code>```

As you can see i am trying to get eggs prices from data. Then i am creating graph and to this point everything went fine. Problem is in mean value: i am getting value: 51.61905, which is totally wrong.
What am i doing wrong?

答:
NVM, it was tottaly my mistake:

```<code>eggs<-read.csv2("http://jolej.linuxpl.info/Eggs.csv", header=TRUE, stringsAsFactors =
T, sep = ',')
</code>```

This line cause a problem, argument stringsAsFactor should have been FALSE.

Title: Invalid data from data frame in R

Body:
I am new in R and i am trying to analyze some data. I occured an error in extracting data from data frame. This is my code:

library('BCA')
eggs<-read.csv2("http://jolej.linuxpl.info/Eggs.csv", header=TRUE, stringsAsFactors = T, sep = ',')
weeks<-eggs$Week
eggs_prices = as.numeric(eggs$Egg.Pr)
matplot(weeks, eggs$Egg.Pr, pch = ".", type = "o", col = "blue", xlab = "Tydzień", ylab = "Cena
jajek")
title(main = "Cena jajek w poszczególnych tygodniach")
mean(eggs_prices)
eggs_prices

As you can see i am trying to get eggs prices from data. Then i am creating graph and to this point everything went fine. Problem is in mean value: i am getting value: 51.61905, which is totally wrong.
What am i doing wrong?

Body:
NVM, it was tottaly my mistake:

eggs<-read.csv2("http://jolej.linuxpl.info/Eggs.csv", header=TRUE, stringsAsFactors =
T, sep = ',')

This line cause a problem, argument stringsAsFactor should have been FALSE.


问:
Is there any reason not to use fixed width integer types (e.g. uint8_t)?
Assuming you're using a compiler that supports C99 (or even just stdint.h), is there any reason not to use fixed-width integer types such as uint8_t?

One reason that I'm aware of is that it makes much more sense to use chars when dealing with characters instead of using (u)int8_ts, as mentioned in this question.

But if you are planning on storing a number, when would you want to use a type that you don't know how big it is? I.e. In what situation would you want to store a number in an unsigned short without knowing if it is 8, 16, or even 32 bits, instead of using a uint16t?

Following on from this, is it considered better practice to use fixed-width integers, or to use the normal integer types and just never assume anything and use sizeof wherever you need to know how many bytes they are using?

答:
There are many reasons why one would want to use the, let's call them semantic types like int or char over the fixed-width types like uint8_t:

Matching existing API

The Standard C lib uses char* everywhere. Why confuse users (and introduce possible bugs?) by using a different type when talking to that API?

Similarly, printf() format strings are defined in terms of these semantic types. If you want to print a fixed-size type, you need macros like PRIu64 etc. in stdint.h to let you get the right format string for printing a fixed-size type with the old printf format strings.

Speed

The semantic types are usually chosen so that they work best for the current CPU's performance characteristics. They may be bumped to slightly larger sizes than what you would have picked because that's the register size on your CPU and will save you unnecessary conversion etc.

Now these days this is a bit of a contested answer ... that was the original intent, but due to stdint not being available in early C/C++, many platforms (like 32-bit Windows or macOS X) just guaranteed the size of int and long. So during the 64-bit move, some of those sizes stayed the same (leading to fun new types like long long, among other things). That's why we got the least and fast types.

Code Portability

The semantic types may be larger on a 64-bit platform than on a 32-bit platform (e.g. to permit array indexes to fill all of the memory). So if you're running on different platforms, using a semantic type (which by my definition would include size_t where available) instead of a fixed one means you're taking advantage of the better hardware and not adding arbitrary limits.

Of course, this makes only your algorithm portable. If you need to serialize data to bytes and exchange it between different platforms, this may make your code portable, but not your network packets or output files. So for that case, you would actually want to stick to the fixed types so data stays portable, at the cost of your code running unbearably slow or not compiling on certain platforms.

Comment: Don't ask me why they didn't introduce format strings for int64_t, int32_t etc. Maybe they were out of letters? Maybe too many code-bases defined their own format strings and would have broken?


问:
Android kotlin coroutines return object from lifecycle scopes
I have a function getNewProduct that it should be return an object of type ProductCats. Inside this function I call a Async method and cause of it I should call it by coroutine scopes. this is codes:

```<code>    private fun addProductCatAsync(pc: ProductCats) = viewModelScope.async {
        withContext(Dispatchers.Default){
            productService.addProductCatToServer(pc)
        }
    }

    fun getNewProduct(pc: ProductCats) = viewModelScope.launch{

        if (_newProduct.value == null) {
            val res = addProductCatAsync(pc).await()
            _newProduct.value = res
            println("NEW PRODUCT INSIDE COROUTINE: ${_newProduct.value}")
            return@launch res
        }
        return@launch _newProduct.value
    }
</code>```

but i got this error on compile time, from lines of return: required: Unit, found: ProductCats?. How can I convert getNewProduct function and make it return my desired object instead ob job?

答:
Try with this</p>

```<code>fun getNewProduct(pc: ProductCats): ProductCats{
    label@GlobalScope.launch{
        if (_newProduct.value == null) {
        val res = addProductCatAsync(pc).await()
        _newProduct.value = res
        println("NEW PRODUCT INSIDE COROUTINE: ${_newProduct.value}")
        return@label res
    }
    return _newProduct.value
}

GlobalScope.launch will return job object.
</code>```

Body:
I have a function getNewProduct that it should be return an object of type ProductCats. Inside this function I call a Async method and cause of it I should call it by coroutine scopes. this is codes:

    private fun addProductCatAsync(pc: ProductCats) = viewModelScope.async {
        withContext(Dispatchers.Default){
            productService.addProductCatToServer(pc)
        }
    }

    fun getNewProduct(pc: ProductCats) = viewModelScope.launch{

        if (_newProduct.value == null) {
            val res = addProductCatAsync(pc).await()
            _newProduct.value = res
            println("NEW PRODUCT INSIDE COROUTINE: ${_newProduct.value}")
            return@launch res
        }
        return@launch _newProduct.value
    }

but i got this error on compile time, from lines of return: required: Unit, found: ProductCats?. How can I convert getNewProduct function and make it return my desired object instead ob job?

Body:
Try with this

fun getNewProduct(pc: ProductCats): ProductCats{
    label@GlobalScope.launch{
        if (_newProduct.value == null) {
        val res = addProductCatAsync(pc).await()
        _newProduct.value = res
        println("NEW PRODUCT INSIDE COROUTINE: ${_newProduct.value}")
        return@label res
    }
    return _newProduct.value
}

GlobalScope.launch will return job object.


问:
How to return upto date serializer data django rest framework
I am trying to vote up comments in my serializer.
All seems to work well with the voting part of it.

However, the serializer returns old values rather than the updated values.

I know I am doing something wrong, just not sure how to put it all together to return the recent value through $ajax after the comment vote is recorded.

Note: When I refresh the page, I get the right vote count.

Here is my view.py that records the votes:

```<code>class CommentUpdateAPIView(DestroyModelMixin, generics.RetrieveUpdateAPIView):
    queryset = Comment.objects.all()
    serializer_class = CommentUpdateSerializer
    permission_classes = [IsOwnerOrReadOnly]

    def perform_update(self, serializer):
        if self.request.user.is_authenticated:
            serializer.save(user=self.request.user)

    # For Comments Voting
    def partial_update(self, request, *args, **kwargs):
        if request.method == 'PATCH':
            if self.request.user.is_authenticated:
                comment = get_object_or_404(Comment, pk=kwargs['pk'])
                posttype = self.request.data['type']
                try:
                    if posttype == 'down':
                        if comment.votes.exists(request.user.id, 1):
                            comment.votes.delete(request.user.id)
                        else:
                            comment.votes.down(request.user.id)
                    elif posttype == 'up':
                        if comment.votes.exists(request.user.id, 0):
                            comment.votes.delete(request.user.id)
                        else:
                            comment.votes.up(request.user.id)

                    # Should return the latest, values in the database
                    # Unfortunately Only old value keep coming back...
                    return Response(CommentUpdateSerializer(comment).data)
                except:
                    raise serializers.ValidationError({'detail': _('Something isn\'t right! Try again later')})
</code>```

And my serializer:

```<code>class UserPublicSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = [
            'username',
            'first_name',
            'last_name',
            'is_superuser',
            'is_staff'
        ]

class CommentSerializer(serializers.ModelSerializer):
    user = UserPublicSerializer(read_only=True)
    image = serializers.SerializerMethodField(read_only=True)
    class Meta:
        model = Comment
        fields = ('id', 'url', 'user', 'content', 'timestamp', 'updated_at', 'image', 'num_vote_down', 'num_vote_up')

    def get_image(self, obj):
        img_  = static("img/avatar.png")
        if obj.user.photo_url:
            img_ = obj.user.photo_url
        return img_

class CommentUpdateSerializer(serializers.ModelSerializer):
    user = UserPublicSerializer(read_only=True)
    image = serializers.SerializerMethodField(read_only=True)
    class Meta:
        model = Comment
        fields = ('id', 'url', 'user', 'content', 'timestamp', 'updated_at', 'image', 'num_vote_down', 'num_vote_up')
        read_only_fields = ('url', 'user')
</code>```

Updated: Model:

```<code>class Comment(VoteModel, models.Model):
    user        = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=True, blank=True, on_delete=models.SET_NULL)
    url         = models.URLField()
    content     = models.TextField()
    num_vote    = models.IntegerField(default=0)
    #image       = models.ImageField()
    allow_annon    = models.BooleanField(default=True)
    created_at     =  models.DateTimeField(auto_now=False, auto_now_add=True)
    updated_at     = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.url

    class Meta:
        ordering = ['-created_at']

    @property
    def owner(self):
        return self.user
</code>```

What do I need to change to get the recent values after a vote is recorded?

答:
you can use refresh_from_db() to update the values of an object.
So it would be:

```<code>comment.refresh_from_db()
return Response(CommentUpdateSerializer(comment).data)
</code>```

Based on this comment

Body:
I am trying to vote up comments in my serializer.
All seems to work well with the voting part of it.

However, the serializer returns old values rather than the updated values.

I know I am doing something wrong, just not sure how to put it all together to return the recent value through $ajax after the comment vote is recorded.

Note: When I refresh the page, I get the right vote count.

Here is my view.py that records the votes:

class CommentUpdateAPIView(DestroyModelMixin, generics.RetrieveUpdateAPIView):
    queryset = Comment.objects.all()
    serializer_class = CommentUpdateSerializer
    permission_classes = [IsOwnerOrReadOnly]

    def perform_update(self, serializer):
        if self.request.user.is_authenticated:
            serializer.save(user=self.request.user)

    # For Comments Voting
    def partial_update(self, request, *args, **kwargs):
        if request.method == 'PATCH':
            if self.request.user.is_authenticated:
                comment = get_object_or_404(Comment, pk=kwargs['pk'])
                posttype = self.request.data['type']
                try:
                    if posttype == 'down':
                        if comment.votes.exists(request.user.id, 1):
                            comment.votes.delete(request.user.id)
                        else:
                            comment.votes.down(request.user.id)
                    elif posttype == 'up':
                        if comment.votes.exists(request.user.id, 0):
                            comment.votes.delete(request.user.id)
                        else:
                            comment.votes.up(request.user.id)

                    # Should return the latest, values in the database
                    # Unfortunately Only old value keep coming back...
                    return Response(CommentUpdateSerializer(comment).data)
                except:
                    raise serializers.ValidationError({'detail': _('Something isn\'t right! Try again later')})

And my serializer:

class UserPublicSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = [
            'username',
            'first_name',
            'last_name',
            'is_superuser',
            'is_staff'
        ]

class CommentSerializer(serializers.ModelSerializer):
    user = UserPublicSerializer(read_only=True)
    image = serializers.SerializerMethodField(read_only=True)
    class Meta:
        model = Comment
        fields = ('id', 'url', 'user', 'content', 'timestamp', 'updated_at', 'image', 'num_vote_down', 'num_vote_up')

    def get_image(self, obj):
        img_  = static("img/avatar.png")
        if obj.user.photo_url:
            img_ = obj.user.photo_url
        return img_

class CommentUpdateSerializer(serializers.ModelSerializer):
    user = UserPublicSerializer(read_only=True)
    image = serializers.SerializerMethodField(read_only=True)
    class Meta:
        model = Comment
        fields = ('id', 'url', 'user', 'content', 'timestamp', 'updated_at', 'image', 'num_vote_down', 'num_vote_up')
        read_only_fields = ('url', 'user')

Updated: Model:

class Comment(VoteModel, models.Model):
    user        = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=True, blank=True, on_delete=models.SET_NULL)
    url         = models.URLField()
    content     = models.TextField()
    num_vote    = models.IntegerField(default=0)
    #image       = models.ImageField()
    allow_annon    = models.BooleanField(default=True)
    created_at     =  models.DateTimeField(auto_now=False, auto_now_add=True)
    updated_at     = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.url

    class Meta:
        ordering = ['-created_at']

    @property
    def owner(self):
        return self.user

What do I need to change to get the recent values after a vote is recorded?

Body:
you can use refresh_from_db() to update the values of an object.
So it would be:

comment.refresh_from_db()
return Response(CommentUpdateSerializer(comment).data)

Based on this comment


问:
I am trying to install prophet library , But getting error .How i fix this error?
```<code> ERROR: Command errored out with exit status 1:
   command: 'C:\Anaconda\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\hp\\AppData\\Local\\Temp\\pip-install-o3yl73zr\\fbprophet\\setup.py'"'"'; __file__='"'"'C:\\Users\\hp\\AppData\\Local\\Temp\\pip-install-o3yl73zr\\fbprophet\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\hp\AppData\Local\Temp\pip-wheel-3503otpz' --python-tag cp37
       cwd: C:\Users\hp\AppData\Local\Temp\pip-install-o3yl73zr\fbprophet\
  Complete output (12 lines):
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib
  creating build\lib\fbprophet
  creating build\lib\fbprophet\stan_model
  INFO:pystan:COMPILING THE C++ CODE FOR MODEL anon_model_db8febf10f23d7fa27a62fbcfd7f17b2 NOW.
  WARNING:pystan:MSVC compiler is not supported
  stanfit4anon_model_db8febf10f23d7fa27a62fbcfd7f17b2_3952845139843312099.cpp
  C:\Anaconda\include\pyconfig.h(59): fatal error C1083: Cannot open include file: 'io.h': No such file or directory
  error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Tools\\MSVC\\14.23.28105\\bin\\HostX86\\x64\\cl.exe' failed with exit status 2
</code>```

```<code>  ERROR: Failed building wheel for fbprophet
    ERROR: Command errored out with exit status 1:
     command: 'C:\Anaconda\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\hp\\AppData\\Local\\Temp\\pip-install-o3yl73zr\\fbprophet\\setup.py'"'"'; __file__='"'"'C:\\Users\\hp\\AppData\\Local\\Temp\\pip-install-o3yl73zr\\fbprophet\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\hp\AppData\Local\Temp\pip-record-_iv7s74v\install-record.txt' --single-version-externally-managed --compile
         cwd: C:\Users\hp\AppData\Local\Temp\pip-install-o3yl73zr\fbprophet\
    Complete output (12 lines):
    running install
    running build
    running build_py
    creating build
    creating build\lib
    creating build\lib\fbprophet
    creating build\lib\fbprophet\stan_model
    INFO:pystan:COMPILING THE C++ CODE FOR MODEL anon_model_db8febf10f23d7fa27a62fbcfd7f17b2 NOW.
    WARNING:pystan:MSVC compiler is not supported
    stanfit4anon_model_db8febf10f23d7fa27a62fbcfd7f17b2_8412490456183199120.cpp
    C:\Anaconda\include\pyconfig.h(59): fatal error C1083: Cannot open include file: 'io.h': No such file or directory
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Tools\\MSVC\\14.23.28105\\bin\\HostX86\\x64\\cl.exe' failed with exit status 2
</code>```

```<code>ERROR: Command errored out with exit status 1: 'C:\Anaconda\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\hp\\AppData\\Local\\Temp\\pip-install-o3yl73zr\\fbprophet\\setup.py'"'"'; __file__='"'"'C:\\Users\\hp\\AppData\\Local\\Temp\\pip-install-o3yl73zr\\fbprophet\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\hp\AppData\Local\Temp\pip-record-_iv7s74v\install-record.txt' --single-version-externally-managed --compile Check the logs for full command output.
</code>```

答:
maybe you need to look here: https://pystan.readthedocs.io/en/latest/windows.html

and install the python windows compiler as shown on the website

Body:
 ERROR: Command errored out with exit status 1:
   command: 'C:\Anaconda\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\hp\\AppData\\Local\\Temp\\pip-install-o3yl73zr\\fbprophet\\setup.py'"'"'; __file__='"'"'C:\\Users\\hp\\AppData\\Local\\Temp\\pip-install-o3yl73zr\\fbprophet\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\hp\AppData\Local\Temp\pip-wheel-3503otpz' --python-tag cp37
       cwd: C:\Users\hp\AppData\Local\Temp\pip-install-o3yl73zr\fbprophet\
  Complete output (12 lines):
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib
  creating build\lib\fbprophet
  creating build\lib\fbprophet\stan_model
  INFO:pystan:COMPILING THE C++ CODE FOR MODEL anon_model_db8febf10f23d7fa27a62fbcfd7f17b2 NOW.
  WARNING:pystan:MSVC compiler is not supported
  stanfit4anon_model_db8febf10f23d7fa27a62fbcfd7f17b2_3952845139843312099.cpp
  C:\Anaconda\include\pyconfig.h(59): fatal error C1083: Cannot open include file: 'io.h': No such file or directory
  error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Tools\\MSVC\\14.23.28105\\bin\\HostX86\\x64\\cl.exe' failed with exit status 2

  ERROR: Failed building wheel for fbprophet
    ERROR: Command errored out with exit status 1:
     command: 'C:\Anaconda\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\hp\\AppData\\Local\\Temp\\pip-install-o3yl73zr\\fbprophet\\setup.py'"'"'; __file__='"'"'C:\\Users\\hp\\AppData\\Local\\Temp\\pip-install-o3yl73zr\\fbprophet\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\hp\AppData\Local\Temp\pip-record-_iv7s74v\install-record.txt' --single-version-externally-managed --compile
         cwd: C:\Users\hp\AppData\Local\Temp\pip-install-o3yl73zr\fbprophet\
    Complete output (12 lines):
    running install
    running build
    running build_py
    creating build
    creating build\lib
    creating build\lib\fbprophet
    creating build\lib\fbprophet\stan_model
    INFO:pystan:COMPILING THE C++ CODE FOR MODEL anon_model_db8febf10f23d7fa27a62fbcfd7f17b2 NOW.
    WARNING:pystan:MSVC compiler is not supported
    stanfit4anon_model_db8febf10f23d7fa27a62fbcfd7f17b2_8412490456183199120.cpp
    C:\Anaconda\include\pyconfig.h(59): fatal error C1083: Cannot open include file: 'io.h': No such file or directory
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Tools\\MSVC\\14.23.28105\\bin\\HostX86\\x64\\cl.exe' failed with exit status 2

ERROR: Command errored out with exit status 1: 'C:\Anaconda\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\hp\\AppData\\Local\\Temp\\pip-install-o3yl73zr\\fbprophet\\setup.py'"'"'; __file__='"'"'C:\\Users\\hp\\AppData\\Local\\Temp\\pip-install-o3yl73zr\\fbprophet\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\hp\AppData\Local\Temp\pip-record-_iv7s74v\install-record.txt' --single-version-externally-managed --compile Check the logs for full command output.


问:
How to fix issue with msg about blocked webdriver.dll when it is not blocked
I'm trying to run Selenium (using WebDriver 3.1.4)  with ChromeDriver79 and it throws this error:

Could not load webdriver.dll and webdriver.support.dll from {path} ─
  they may be blocked (Properties>General>Unblock)

That msg is wrong, however, because...

those files aren't blocked! (I ran Powershell's Unlock-File on them - but that did not change anything. Ok, is there a difference between "unlock" and "unblock"?)

ChromeDriver.exe instead was blocked - but even after
unblocking it, I got the same error

I also tested with GeckoDriver and it ran w/o problems. However, after that session I noticed that
geckodriver.eve was locked, indeed! (Makes me doubt about the validity
of the whole mechanism.) Anyway, I unlocked geckodriver and it still runs ;)

How can this problem be solved?

Update: I thought this was over when suddenly the message did not show up any more, I even closed the question. Unfortunately I rejoiced too early - it's back again now. And again: I am not aware that I changed anything in the environment. This is really painful - I will start a bounty and hope to get it resolved. This time geckodriver AND chromedriver are affected.

答:
Looked at it again: actually these files are not locked.

I had thought the msg came straight out of Selenium, but in fact it was the error-handler of an old subroutine which did that (I inherited that code). So, the real problem is this exception when instantiating ChromeDriver:

Could not load file or assembly 'System.Security.Permissions,
  Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'.

That issue has been discussed here before. I'm still a bit puzzled why it would work one day and fail on the next...(will update if I find out more...)


问:
View within a view Layout issue
I want to display a view within a view. This works as I want but I'm having an issue with the layout of a table.

I want to move the table left so it is under the address button. I'm not quite sure why it is placed where it is. Here is my Reports View.

```<code><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>    @{
        ViewBag.Title = "Reports";
        Layout = "~/Views/Shared/_layout.cshtml";
    }

    <h2>Reports</h2>
    <br />
    <button id="address">Addresses</button>
<button id="Qualifications"> Qualifications</button>
    <style>
        #addrRpt { color: red;
                   background-color:blue;
                   margin-left:10px;
                   /*height: 250px;*/

        }

    </style>

    <script>
        document.getElementById("address").onclick = function () { myFunction() };
        function myFunction() {

            $("#addrRpt").load("@Html.Raw(Url.Action("index", "Addresses")) ")
        }
    </script>

    @*<div class="row" >
        <div class="col" style="background-color:red">

            <div id="addrRpt">
                </div>
            </div>
        </div>*@
    <div id="addrRpt"></div></code>```

```

答:
Setting the layout for the view to null resolved my issue.

Layout = null;

Title: View within a view Layout issue

Body:
I want to display a view within a view. This works as I want but I'm having an issue with the layout of a table.

I want to move the table left so it is under the address button. I'm not quite sure why it is placed where it is. Here is my Reports View.

    @{
        ViewBag.Title = "Reports";
        Layout = "~/Views/Shared/_layout.cshtml";
    }

Reports

    <button id="address">Addresses</button>
<button id="Qualifications"> Qualifications</button>

    @*

*@


问:
How do i access state of one reducer in other in react redux. State flow between reducers and store
I'm an absolute beginner in react-redux and I watched many videos and articles,docs and couldn't understand how the state flows between reducers and between store to reducer.

I am having state for each reducer like this

const initState = {todos:[]}

cont reducer = (state=initState,action) ....

Reducer 2 similarly with different state

initState2 = {todo:" "}

reducer2 = (state=initState2,action) ...

And then I import and combine the reducers. Here I am using two different reducers which have different states and is it the right way of doing things ?  If so, How can redux be called single state if each reducer have its own individual state.

Don't we have a single state in the store which is accessed by all the reducers and dispatch actions to change state of store directly instead of changing the reducer's store. Any help is appreciated and it may seems like a silly question but filling the gaps is really important and many beginners have same doubt as mine and please do help. Thank you

答:
You only need 1 reducer to store your todos.

How can redux be called single state if each reducer have its own
  individual state.

The application effectively has only 1 global store where all the application state is stored. What the reducer returns is what effectively gets stored in the store.

The configuration of what is stored is a map (key-value) where the key is defined in the root reducer, and the value is what is returned from the reducer function.

The way you have to look at it is that the view is "dumb", in that the only thing it does is tell the app what it wants by dispatching an action. This action is  just an event that is marked with some string you give it to identify clearly what it is the view wants. The reducer intercepts this action and updates the state in the store accordingly. This state in turn is accessible to all the components in your app. So it clearly is global.

In your example, the view would just tell the application for example: "Add a todo". The reducer will intercept this message and return an array with the added todo. This returned array is what will be saved in the store.

If you want a seperate "todo", this will probably refer to the currently "active" to do. Marking it as such will make the purpose more expressive.

This is single state because your root reducer will end up with something like:

```<code>{
    "activeTodo": activeTodoReducer
    "todos": todosReducer
}
</code>```

And you can access these key / values in your components throughout the entire application.

Body:
You only need 1 reducer to store your todos.

How can redux be called single state if each reducer have its own
  individual state.

The application effectively has only 1 global store where all the application state is stored. What the reducer returns is what effectively gets stored in the store.

The configuration of what is stored is a map (key-value) where the key is defined in the root reducer, and the value is what is returned from the reducer function.

The way you have to look at it is that the view is "dumb", in that the only thing it does is tell the app what it wants by dispatching an action. This action is  just an event that is marked with some string you give it to identify clearly what it is the view wants. The reducer intercepts this action and updates the state in the store accordingly. This state in turn is accessible to all the components in your app. So it clearly is global.

In your example, the view would just tell the application for example: "Add a todo". The reducer will intercept this message and return an array with the added todo. This returned array is what will be saved in the store.

If you want a seperate "todo", this will probably refer to the currently "active" to do. Marking it as such will make the purpose more expressive.

This is single state because your root reducer will end up with something like:

{
    "activeTodo": activeTodoReducer
    "todos": todosReducer
}

And you can access these key / values in your components throughout the entire application.


问:
Doctype Problems
I have problems, to set the correct Doc Type. Please have a look at my code above. it returns an error in the w3org validator.
Where is the error?

```<code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://ogp.me/ns#" xmlns:fb="http://www.facebook.com/2008/fbml">
<html dir="ltr" lang="de-DE" xmlns:og="http://opengraphprotocol.org/schema/">
<head>
</code>```

I found the solution:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de" xmlns:og="http://opengraphprotocol.org/schema/" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
</code>```

答:
As suggested by @David Dorward, posting comment as an answer.

The  element is the root-element of the html document, and as such can only appear once in a valid html document. For the purposes of validity you could either just remove one of the  opening tags (and, if you have two  closing tags remove one of those too), or combine all the attributes into one and then remove the empty html tag (which isn't much of a difference to the previous option, really).

Also, but as an addenda, I'm unsure as to the use of the xml namespaces within an html document; given that it passed without comment, except for my own, in the comments to your question it's probably alright; but it...feels wrong. Which is about the worst explanation for anything I've ever put on this site. And I feel ashamed for it.

Title: Doctype Problems

Body:
I have problems, to set the correct Doc Type. Please have a look at my code above. it returns an error in the w3org validator.
Where is the error?

<!DOCTYPE html>

I found the solution:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">

Body:
As suggested by @David Dorward, posting comment as an answer.

The <html> element is the root-element of the html document, and as such can only appear once in a valid html document. For the purposes of validity you could either just remove one of the <html> opening tags (and, if you have two </html> closing tags remove one of those too), or combine all the attributes into one and then remove the empty html tag (which isn't much of a difference to the previous option, really).

Also, but as an addenda, I'm unsure as to the use of the xml namespaces within an html document; given that it passed without comment, except for my own, in the comments to your question it's probably alright; but it...feels wrong. Which is about the worst explanation for anything I've ever put on this site. And I feel ashamed for it.


问:
Set icon and back button on action bar at same time in Android
getSupportActionBar().setIcon(R.drawable.icon); is not working in Android. </p>

```<code>    getSupportActionBar().setTitle("Dictionary");
    getSupportActionBar().setDisplayUseLogoEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setIcon(R.drawable.ic_dictionary);
</code>```

答:
in your case you should have a line of code before these lines...if you dont have this line that is the problem

```<code>setSupportActionBar(toolbar);
</code>```

however i myself use material toolbar and add icon and text to toolbar in xml and got rid of these methods! see one of my xml files for sample

```<code><com.google.android.material.appbar.AppBarLayout
    android:background="@color/colorPrimary"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <com.google.android.material.appbar.MaterialToolbar
        android:layout_width="match_parent"
        android:layout_height="?actionBarSize">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/iv_back"
                android:onClick="onClick"
                android:layout_width="wrap_content"
                android:padding="16dp"
                android:background="@drawable/ripple_on_primary"
                android:layout_centerVertical="true"
                android:layout_alignParentEnd="true"
                android:src="@drawable/ic_back"
                android:layout_height="wrap_content"/>

            <TextView
                android:layout_centerVertical="true"
                android:layout_toStartOf="@id/iv_back"
                android:id="@+id/tv_toolbar"
                style="@style/tvTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/previous_transactions" />

            <TextView
                style="@style/tvContent"
                android:text="@string/help"
                android:id="@+id/tv_help"
                android:onClick="onClick"
                android:layout_centerVertical="true"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>

        </RelativeLayout>

    </com.google.android.material.appbar.MaterialToolbar>

</com.google.android.material.appbar.AppBarLayout>
</code>```

Body:
getSupportActionBar().setIcon(R.drawable.icon); is not working in Android.

    getSupportActionBar().setTitle("Dictionary");
    getSupportActionBar().setDisplayUseLogoEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setIcon(R.drawable.ic_dictionary);

Body:
in your case you should have a line of code before these lines...if you dont have this line that is the problem

setSupportActionBar(toolbar);

however i myself use material toolbar and add icon and text to toolbar in xml and got rid of these methods! see one of my xml files for sample

<com.google.android.material.appbar.AppBarLayout
    android:background="@color/colorPrimary"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <com.google.android.material.appbar.MaterialToolbar
        android:layout_width="match_parent"
        android:layout_height="?actionBarSize">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/iv_back"
                android:onClick="onClick"
                android:layout_width="wrap_content"
                android:padding="16dp"
                android:background="@drawable/ripple_on_primary"
                android:layout_centerVertical="true"
                android:layout_alignParentEnd="true"
                android:src="@drawable/ic_back"
                android:layout_height="wrap_content"/>

            <TextView
                android:layout_centerVertical="true"
                android:layout_toStartOf="@id/iv_back"
                android:id="@+id/tv_toolbar"
                style="@style/tvTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/previous_transactions" />

            <TextView
                style="@style/tvContent"
                android:text="@string/help"
                android:id="@+id/tv_help"
                android:onClick="onClick"
                android:layout_centerVertical="true"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>

        </RelativeLayout>

    </com.google.android.material.appbar.MaterialToolbar>

</com.google.android.material.appbar.AppBarLayout>


问:
Boolean and of three columns in pandas
I have a dataframe as shown below

```<code>ID     F1       F2         F3
1      True     False      False
2      True     True       True
3      False    False      False
4      True     False      False
5      True     True       True
</code>```

From the above, I want to create new column which will be True if F1, F2 and F3 are True

```<code>ID     F1       F2         F3        CONSIDER
1      True     False      False     False
2      True     True       True      True
3      False    False      False     False
4      True     False      False     False
5      True     True       True      True
</code>```

答:
Use DataFrame.all with filtered columns in list:

```<code>df['CONSIDER'] = df[['F1','F2','F3']].all(axis=1)
print (df)
   ID     F1     F2     F3  CONSIDER
0   1   True  False  False     False
1   2   True   True   True      True
2   3  False  False  False     False
3   4   True  False  False     False
4   5   True   True   True      True
</code>```

Title: Boolean and of three columns in pandas

Body:
I have a dataframe as shown below

ID     F1       F2         F3
1      True     False      False
2      True     True       True
3      False    False      False
4      True     False      False
5      True     True       True

From the above, I want to create new column which will be True if F1, F2 and F3 are True

ID     F1       F2         F3        CONSIDER
1      True     False      False     False
2      True     True       True      True
3      False    False      False     False
4      True     False      False     False
5      True     True       True      True

Body:
Use DataFrame.all with filtered columns in list:

df['CONSIDER'] = df[['F1','F2','F3']].all(axis=1)
print (df)
   ID     F1     F2     F3  CONSIDER
0   1   True  False  False     False
1   2   True   True   True      True
2   3  False  False  False     False
3   4   True  False  False     False
4   5   True   True   True      True


问:
How to check if EFS is mounted on a docker container?
I have created a task definition and mounted EFS but i'm not sure if it works..

So i wanted to verify if my EFS file system is mounted to the running container ?

How can i verify ?

答:
One way is to add a file to the folder inside your container:

ssh into the underlying ECS EC2 instance with ssh -i "somekey.pem" ec2-user@ec2-xxxxxxxxx.eu-west-1.compute.amazonaws.com

Run docker ps to get the id of your container.

docker exec -it CONTAINERID /bin/bash to move inside the container. Inside the container create or copy a file to the EFS-folder.

Now go to the EFS console and verify that the Metered size is greater than 0 meaning your file is in EFS.


问:
How to solve Android MultiDex Apllication Instance Null Pointer Exception?
I want to do a core api service integration in my Android project.
My core service class is as follows:

```<code>public class TestApplication extends MultiDexApplication {
    private static final String LOG_TAG_NETWORK = "GNetwork";
    public static JacksonConverterFactory factory;
    private static TestApplication instance;
    private OkHttpClient.Builder okHttpBuilder;
    private TestService testtService;
    private Location lastKnownLocation;

public static TestApplication getInstance() {
    return instance;
}

@Override
public void onCreate() {
    super.onCreate();
    instance = this;

    Pref.init(this);

    okHttpBuilder = new OkHttpClient.Builder();
    okHttpBuilder.connectTimeout(UrlConstants.CONNECT_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
            .readTimeout(UrlConstants.READ_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
            .writeTimeout(UrlConstants.WRITE_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS);
    if (BuildConfig.LOG_ENABLED) {
        HttpLoggingInterceptor httpLoggingInterceptor =
                new HttpLoggingInterceptor(message -> Log.d(LOG_TAG_NETWORK, message));
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        okHttpBuilder.addInterceptor(httpLoggingInterceptor);
    }
    factory = getJacksonConverterFactory();
}

@NonNull
private JacksonConverterFactory getJacksonConverterFactory() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return JacksonConverterFactory.create(objectMapper);
}

public void setupRetrofit() {

    String BASE_URL = "http://xxxxx";

    Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).client(okHttpBuilder.build())
            .addConverterFactory(factory).build();

    testService = retrofit.create(TestService.class);
}

public TestService getTestService() {
    return testService;
    }
}
</code>```

Then I create an instance from this core class. But here my constant getIntance value returns null.

```<code>TestApplication.getInstance().setupRetrofit();
</code>```

I can't understand that. GetInstance method always return null;

In my app build.gradle file is multiDexEnabled true.

How to solve this situation?

答:
never use instance of application like this. for get application instance you need activity and in your activity you can use

    static TestApplication getInstance(Activity activity) {
        if (instance == null)
            instance = ((TestApplication) activity.getApplication());
        return instance;
    }
```

this will solve your issues but the way you implement retrofit and using it is not best practices. You can find better way that doesn't need activity.

Body:
I want to do a core api service integration in my Android project.
My core service class is as follows:

public class TestApplication extends MultiDexApplication {
    private static final String LOG_TAG_NETWORK = "GNetwork";
    public static JacksonConverterFactory factory;
    private static TestApplication instance;
    private OkHttpClient.Builder okHttpBuilder;
    private TestService testtService;
    private Location lastKnownLocation;

public static TestApplication getInstance() {
    return instance;
}

@Override
public void onCreate() {
    super.onCreate();
    instance = this;

    Pref.init(this);

    okHttpBuilder = new OkHttpClient.Builder();
    okHttpBuilder.connectTimeout(UrlConstants.CONNECT_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
            .readTimeout(UrlConstants.READ_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
            .writeTimeout(UrlConstants.WRITE_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS);
    if (BuildConfig.LOG_ENABLED) {
        HttpLoggingInterceptor httpLoggingInterceptor =
                new HttpLoggingInterceptor(message -> Log.d(LOG_TAG_NETWORK, message));
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        okHttpBuilder.addInterceptor(httpLoggingInterceptor);
    }
    factory = getJacksonConverterFactory();
}

@NonNull
private JacksonConverterFactory getJacksonConverterFactory() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return JacksonConverterFactory.create(objectMapper);
}

public void setupRetrofit() {

    String BASE_URL = "http://xxxxx";

    Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).client(okHttpBuilder.build())
            .addConverterFactory(factory).build();

    testService = retrofit.create(TestService.class);
}

public TestService getTestService() {
    return testService;
    }
}

Then I create an instance from this core class. But here my constant getIntance value returns null.

TestApplication.getInstance().setupRetrofit();

I can't understand that. GetInstance method always return null;

In my app build.gradle file is multiDexEnabled true.

How to solve this situation?

Body:
never use instance of application like this. for get application instance you need activity and in your activity you can use

    static TestApplication getInstance(Activity activity) {
        if (instance == null)
            instance = ((TestApplication) activity.getApplication());
        return instance;
    }

this will solve your issues but the way you implement retrofit and using it is not best practices. You can find better way that doesn't need activity.


问:
Entity Framework. Code First. Relationship with a table in between
I have a Database similar to the one in this example. Not the Student-courses scenario, but 2 tables that have a common third related to both of them.

My case is, Items, PerformanceGraphItems and PerformanceGraphSeries.

Each item can have several GraphItems and a GraphItem belongs to a GraphSeries row. How could I model it in the Entity Framework in order to be able to access the GraphSeries that belong to an Item?

Something like this.

```<code>public class Item
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual ICollection<PerformanceGraphItem> PerformanceGraphItems { get; set; }

        public virtual ICollection<PerformanceGraphSeries> PerformanceGraphSeries { get; set; }
    }

public class PerformanceGraphItem
    {
        [Key]
        public int Id { get; set; }
        [ForeignKey("Item")]
        public int ItemId { get; set; }
        public int SeriesId { get; set; }
        public short Year { get; set; }
        public double RateOfReturn { get; set; }
        public virtual Item Item { get; set; }
        [ForeignKey("SeriesId")]
        public virtual PerformanceGraphSeries PerformanceGraphSeries { get; set; }

    }

public class PerformanceGraphSeries
    {
        public int id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }

        public virtual ICollection<PerformanceGraphItem> PerformanceGraphItems { get; set; }

    }
</code>```

答:
It seems to me that what you have is pretty close to what you want, though I would change your

```<code>public virtual ICollection<PerformanceGraphSeries> PerformanceGraphSeries { get; set; }
</code>```

line to instead be

```<code>public virtual IEnumerable<PerformanceGraphSeries> PerformanceGraphSeries
{
    get
    {
        return PerformanceGraphItems.Select(pgi => pgi.PerformanceGraphSeries);
    }
}
</code>```

or

```<code>public virtual IEnumerable<PerformanceGraphSeries> PerformanceGraphSeries
{
    get
    {
        return PerformanceGraphItems.Select(pgi => pgi.PerformanceGraphSeries)
                                    .Distinct();
    }
}
</code>```

depending on your scenario.

Thius is because you're not really modeling a database that has a direct connect between Item and PerformanceGraphSeries - so you don't want your database to be generated that way. But this still allows you to access it in one property (instead of having to do that query everywhere).

Also, since you're using virtual in most places, I assume you're trying to go for proxy objects - make sure you're setting all of your properties to be virtual, otherwise it won't happen.

Body:
I have a Database similar to the one in this example. Not the Student-courses scenario, but 2 tables that have a common third related to both of them.

My case is, Items, PerformanceGraphItems and PerformanceGraphSeries.

Each item can have several GraphItems and a GraphItem belongs to a GraphSeries row. How could I model it in the Entity Framework in order to be able to access the GraphSeries that belong to an Item?

Something like this.

public class Item
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual ICollection<PerformanceGraphItem> PerformanceGraphItems { get; set; }

        public virtual ICollection<PerformanceGraphSeries> PerformanceGraphSeries { get; set; }
    }

public class PerformanceGraphItem
    {
        [Key]
        public int Id { get; set; }
        [ForeignKey("Item")]
        public int ItemId { get; set; }
        public int SeriesId { get; set; }
        public short Year { get; set; }
        public double RateOfReturn { get; set; }
        public virtual Item Item { get; set; }
        [ForeignKey("SeriesId")]
        public virtual PerformanceGraphSeries PerformanceGraphSeries { get; set; }

    }

public class PerformanceGraphSeries
    {
        public int id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }

        public virtual ICollection<PerformanceGraphItem> PerformanceGraphItems { get; set; }

    }

Body:
It seems to me that what you have is pretty close to what you want, though I would change your

public virtual ICollection<PerformanceGraphSeries> PerformanceGraphSeries { get; set; }

line to instead be

public virtual IEnumerable<PerformanceGraphSeries> PerformanceGraphSeries
{
    get
    {
        return PerformanceGraphItems.Select(pgi => pgi.PerformanceGraphSeries);
    }
}

or

public virtual IEnumerable<PerformanceGraphSeries> PerformanceGraphSeries
{
    get
    {
        return PerformanceGraphItems.Select(pgi => pgi.PerformanceGraphSeries)
                                    .Distinct();
    }
}

depending on your scenario.

Thius is because you're not really modeling a database that has a direct connect between Item and PerformanceGraphSeries - so you don't want your database to be generated that way. But this still allows you to access it in one property (instead of having to do that query everywhere).

Also, since you're using virtual in most places, I assume you're trying to go for proxy objects - make sure you're setting all of your properties to be virtual, otherwise it won't happen.