问:
Class attributes not getting called outside the class in ROS
I was doing in a project where i have to take values from two subscribers then fulfill some conditions and then publish data. Im using classes to values for the two subscribers. However, whenever In the attribute move_bot i call self.ranges and self.linear_pose which should work as they have been set when the code subscribed to them. However, i have to call the move_bot attribute within the laser_callback to make it work but now it only recognizes the self.ranges and not the self.linear_pose. If i do place the move_bot in the odom_callback the same thing happens but with self.linear_pose. Why are the callbacks not working?

```<code>import rospy
import math
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry

class Move(object):
  def __init__(self):
      rospy.init_node('robot_maze')
      rospy.Subscriber('/kobuki/laser/scan',LaserScan,self.laser_callback)
      rospy.Subscriber('/odom',Odometry,self.odom_callback)
      self.pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)
      self.twist_angle = Twist()

  def laser_callback(self,msg):
      self.ranges = msg.ranges

  def odom_callback(self,msg):
      self.linear_pose = msg

  def move_bot(self):
      pi = math.pi
      kp = -0.027

      val =[]

      if self.linear_pose.twist.twist.linear.x < 0.001:
         self.twist_angle.linear.x = -0.2
         for i in self.ranges:
             if i <= 0.6:
                  if self.ranges.index(i) > 360:
                      self.twist_angle.angular.z = 1
             else:
                  self.twist_angle.angular.z = -1
             break
      elif self.ranges[360] > 1.2:
         self.twist_angle.angular.z = 0
         self.twist_angle.linear.x = 0.5
      else:
         for i in self.ranges:
            if i > 1.2:
               val.append(i)
         angle = self.ranges.index(max(val))
         print(max(val))

         if self.ranges[angle] > self.ranges[360]:
            self.twist_angle.angular.z = kp * (360 - angle)

      self.pub.publish(self.twist_angle)

if  __name__== '__main__':

  try:
      move = Move()
      move.move_bot()
      rate = rospy.Rate(10)
  except rospy.ROSInterruptException:  pass

  while not rospy.is_shutdown():
     rate.sleep()
</code>```

I get the following error message

```<code>  Traceback (most recent call last):
    File "/home/user/catkin_ws/src/robot_maze/src/robot_maze.py", line 100, in <module>
      move.move_bot()
    File "/home/user/catkin_ws/src/robot_maze/src/robot_maze.py", line 45, in move_bot
      if self.ranges[360] > 1.2:
  AttributeError: 'Move' object has no attribute 'ranges'
  [robot_maze-1] process has died [pid 16344, exit code 1, cmd
  /home/user/catkin_ws/src/robot_maze/src/robot_maze.py
  __name:=robot_maze __log:=/home/user/.ros/log/e4216cee-9f0e-11ea-9fd8-06b6df32753c/robot_maze-
  1.log].
  log file: /home/user/.ros/log/e4216cee-9f0e-11ea-9fd8-06b6df32753c/robot_maze-1*.log
</code>```

答:
To point out what @a_guest said in the comments:

```<code>class Move(object):
  def __init__(self):
      ...
      self.ranges = None
      self.linear_pose = None
  ...
  def move_bot(self):
      if self.ranges is not None and self.linear_pose is not None:
          if self.linear_pose.twist.twist.linear.x < 0.001:
              ...
          elif self.ranges[360] > 1.2:
              ...
          else:
              ...
          self.pub.publish(self.twist_angle) # Don't publish until received initial values
</code>```

Body:
I was doing in a project where i have to take values from two subscribers then fulfill some conditions and then publish data. Im using classes to values for the two subscribers. However, whenever In the attribute move_bot i call self.ranges and self.linear_pose which should work as they have been set when the code subscribed to them. However, i have to call the move_bot attribute within the laser_callback to make it work but now it only recognizes the self.ranges and not the self.linear_pose. If i do place the move_bot in the odom_callback the same thing happens but with self.linear_pose. Why are the callbacks not working?

import rospy
import math
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry

class Move(object):
  def __init__(self):
      rospy.init_node('robot_maze')
      rospy.Subscriber('/kobuki/laser/scan',LaserScan,self.laser_callback)
      rospy.Subscriber('/odom',Odometry,self.odom_callback)
      self.pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)
      self.twist_angle = Twist()

  def laser_callback(self,msg):
      self.ranges = msg.ranges

  def odom_callback(self,msg):
      self.linear_pose = msg

  def move_bot(self):
      pi = math.pi
      kp = -0.027

      val =[]

      if self.linear_pose.twist.twist.linear.x < 0.001:
         self.twist_angle.linear.x = -0.2
         for i in self.ranges:
             if i <= 0.6:
                  if self.ranges.index(i) > 360:
                      self.twist_angle.angular.z = 1
             else:
                  self.twist_angle.angular.z = -1
             break
      elif self.ranges[360] > 1.2:
         self.twist_angle.angular.z = 0
         self.twist_angle.linear.x = 0.5
      else:
         for i in self.ranges:
            if i > 1.2:
               val.append(i)
         angle = self.ranges.index(max(val))
         print(max(val))

         if self.ranges[angle] > self.ranges[360]:
            self.twist_angle.angular.z = kp * (360 - angle)

      self.pub.publish(self.twist_angle)

if  __name__== '__main__':

  try:
      move = Move()
      move.move_bot()
      rate = rospy.Rate(10)
  except rospy.ROSInterruptException:  pass

  while not rospy.is_shutdown():
     rate.sleep()

I get the following error message

  Traceback (most recent call last):
    File "/home/user/catkin_ws/src/robot_maze/src/robot_maze.py", line 100, in <module>
      move.move_bot()
    File "/home/user/catkin_ws/src/robot_maze/src/robot_maze.py", line 45, in move_bot
      if self.ranges[360] > 1.2:
  AttributeError: 'Move' object has no attribute 'ranges'
  [robot_maze-1] process has died [pid 16344, exit code 1, cmd
  /home/user/catkin_ws/src/robot_maze/src/robot_maze.py
  __name:=robot_maze __log:=/home/user/.ros/log/e4216cee-9f0e-11ea-9fd8-06b6df32753c/robot_maze-
  1.log].
  log file: /home/user/.ros/log/e4216cee-9f0e-11ea-9fd8-06b6df32753c/robot_maze-1*.log

Body:
To point out what @a_guest said in the comments:

class Move(object):
  def __init__(self):
      ...
      self.ranges = None
      self.linear_pose = None
  ...
  def move_bot(self):
      if self.ranges is not None and self.linear_pose is not None:
          if self.linear_pose.twist.twist.linear.x < 0.001:
              ...
          elif self.ranges[360] > 1.2:
              ...
          else:
              ...
          self.pub.publish(self.twist_angle) # Don't publish until received initial values


来源: stackexchange

问:
How to import and read large binary file data in c#?
i have a large binary file that contains different data types, i can access single records in the file but i am not sure how to loop over the binary values and load it in the memory stream byte by byte

i have been using binary reader

```<code>BinaryReader binReader = new BinaryReader(File.Open(fileName, FileMode.Open));
            Encoding ascii = Encoding.ASCII;
            string authorName = binReader.ReadString();
            Console.WriteLine(authorName);
            Console.ReadLine();
</code>```

but this won't work since i have a large file with different data types
simply, i need to convert the file to read byte by byte and then read these data either if it's a string or whatsoever.

would appreciate any thought that can help

答:
Here's a simple bit of code that shows the most basic way of doing it.

using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace binary_read
{
    class Program
    {
        private static readonly int bufferSize = 1024;

        static async Task Main(string[] args)
        {
            var bytesRead = 0;
            var totalBytes = 0;

            using (var stream = File.OpenRead(args.First()))
            {
                do
                {
                    var buffer = new byte[bufferSize];
                    bytesRead = await stream.ReadAsync(buffer, 0, bufferSize);
                    totalBytes += bytesRead;

                    // Process buffer

                } while (bytesRead > 0);

                Console.WriteLine($"Processed {totalBytes} bytes.");
            }
        }
    }
}

```

The main bit to take note of is within the using block.

Firstly, when working with files/streams/sockets it's best to use using if possible to deterministically clean up after yourself.

Then it's really just a matter of calling Read/ReadAsync on the stream if you're just after the raw data. However there are various 'readers' that provide an abstraction to make working with certain formats easier.

So if you know that you're going to be reading ints and doubles and strings, then you can use the BinaryReader  and it's ReadIntxx/ReadDouble/ReadString methods.

If you're reading into a struct, then you can read the properties in a loop as suggested by @JonasH above. Or use the method in this answer.

ContentLicense: CC BY-SA 4.0

Body:
i have a large binary file that contains different data types, i can access single records in the file but i am not sure how to loop over the binary values and load it in the memory stream byte by byte

i have been using binary reader

BinaryReader binReader = new BinaryReader(File.Open(fileName, FileMode.Open));
            Encoding ascii = Encoding.ASCII;
            string authorName = binReader.ReadString();
            Console.WriteLine(authorName);
            Console.ReadLine();

but this won't work since i have a large file with different data types
simply, i need to convert the file to read byte by byte and then read these data either if it's a string or whatsoever.

would appreciate any thought that can help

Body:
Here's a simple bit of code that shows the most basic way of doing it.

using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace binary_read
{
    class Program
    {
        private static readonly int bufferSize = 1024;

        static async Task Main(string[] args)
        {
            var bytesRead = 0;
            var totalBytes = 0;

            using (var stream = File.OpenRead(args.First()))
            {
                do
                {
                    var buffer = new byte[bufferSize];
                    bytesRead = await stream.ReadAsync(buffer, 0, bufferSize);
                    totalBytes += bytesRead;

                    // Process buffer

                } while (bytesRead > 0);

                Console.WriteLine($"Processed {totalBytes} bytes.");
            }
        }
    }
}

The main bit to take note of is within the using block.

Firstly, when working with files/streams/sockets it's best to use using if possible to deterministically clean up after yourself.

Then it's really just a matter of calling Read/ReadAsync on the stream if you're just after the raw data. However there are various 'readers' that provide an abstraction to make working with certain formats easier.

So if you know that you're going to be reading ints and doubles and strings, then you can use the BinaryReader  and it's ReadIntxx/ReadDouble/ReadString methods.

If you're reading into a struct, then you can read the properties in a loop as suggested by @JonasH above. Or use the method in this answer.


问:
jQuery Validate and disabled input field
I'm using below bootstrap as a dropdown picker, which then with an associated jQuery function displays the choosen field in the input type="text". But users can still write their own in the input field, which I would like to avoid. I tried using the disabled attribute on the input field, but if I do that the jQuery Validate plugin will just ignore it and grant permission even if it's empty.

Is it possible to "deactivate" an input field with type="text", without using the disabled attribute so that I may still use jQuery Validate.

```<code><div class="form-group">
    <div class="input-group">
         <div class="input-group-btn">
              <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Choose<span class="caret"></span></button>
              <ul class="dropdown-menu">
                  <li><a href="#" id="a">1</a></li>
                  <li><a href="#" id="b">2</a></li>
                  <li><a href="#" id="c">3</a></li>
                  <li><a href="#" id="d">4</a></li>
                  <li role="separator" class="divider"></li>
                  <li><a href="#" id="e">5</a></li>
              </ul>
         </div>
         <input type="text" id="abc" autocomplete="off" name="abc" placeholder="Select *" class="form-control" aria-label="...">
    </div>
</div>
</code>```

答:
Your best bet would be to rely on validator.showErrors() method and manually validate this disabled input.

I had a similar situation when I needed to validate terms checkbox, but it was designed to be disabled until user scrolls through the terms text.
That's what I come up with in the end:

```<code>        var message = "You must accept the Terms and Conditions in order to proceed with registration";
        var termsValidator = $('#step-5 form').validate({
            rules: {
                acceptTnC: "required"
            },
            messages: {
                acceptTnC: message
            },
            submitHandler : function (form) {
                // Need to manually validate, cause checkbox is disabled by default and validation
                // skips disabled fields
                if(!form.acceptTnC.checked) {
                    termsValidator.showErrors({
                        acceptTnC: message
                    })
                }
                else {
                    submitForm();
                }
            }
        });
        $('[name="acceptTnC"]').on('change', function (e) {
            termsValidator.element(e.target);
        })
</code>```

Bottom part is important to toggle error message once the checkbox is enabled and user can click it on or off

ContentLicense: CC BY-SA 3.0

Body:
I'm using below bootstrap as a dropdown picker, which then with an associated jQuery function displays the choosen field in the input type="text". But users can still write their own in the input field, which I would like to avoid. I tried using the disabled attribute on the input field, but if I do that the jQuery Validate plugin will just ignore it and grant permission even if it's empty.

Is it possible to "deactivate" an input field with type="text", without using the disabled attribute so that I may still use jQuery Validate.

              <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Choose</button>

1

2

3

4

5

         <input type="text" id="abc" autocomplete="off" name="abc" placeholder="Select *" class="form-control" aria-label="...">

Body:
Your best bet would be to rely on validator.showErrors() method and manually validate this disabled input.

I had a similar situation when I needed to validate terms checkbox, but it was designed to be disabled until user scrolls through the terms text.
That's what I come up with in the end:

        var message = "You must accept the Terms and Conditions in order to proceed with registration";
        var termsValidator = $('#step-5 form').validate({
            rules: {
                acceptTnC: "required"
            },
            messages: {
                acceptTnC: message
            },
            submitHandler : function (form) {
                // Need to manually validate, cause checkbox is disabled by default and validation
                // skips disabled fields
                if(!form.acceptTnC.checked) {
                    termsValidator.showErrors({
                        acceptTnC: message
                    })
                }
                else {
                    submitForm();
                }
            }
        });
        $('[name="acceptTnC"]').on('change', function (e) {
            termsValidator.element(e.target);
        })

Bottom part is important to toggle error message once the checkbox is enabled and user can click it on or off


问:
How to redirect a page and disguise its url?
I need to do the following on my apache webserver :

Redirect any URL starting with :

```<code> http://mydomain1.com/archive
 to
 http://mydomain2.com/archive
</code>```

Is there a way using mod-rewrite or RewriteEngine to disguise that URL, so that the URL that appears in the browser is mydomain1.com ?   I don't want to give away the fact that we are switching servers.

答:
Try adding this in the .htaccess from domain1.com/archive

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule (.*) http://mydomain2.com/archive [P]
</IfModule>
</code>```

Edit: Tell me if you've tried this and if it worked or not.

Body:
I need to do the following on my apache webserver :

Redirect any URL starting with :

 http://mydomain1.com/archive
 to
 http://mydomain2.com/archive

Is there a way using mod-rewrite or RewriteEngine to disguise that URL, so that the URL that appears in the browser is mydomain1.com ?   I don't want to give away the fact that we are switching servers.

Body:
Try adding this in the .htaccess from domain1.com/archive

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule (.*) http://mydomain2.com/archive [P]
</IfModule>

Edit: Tell me if you've tried this and if it worked or not.


问:
call() is not working with getter and setter in javascript

let Name = {
   get fullname() {
        return this.fname + this.last
    }
}

function pension() {
    return this.age > 60
}
let firstclass_employee = [{
    fname: "sangeth",
    last: "AV",
    age: 21,
    address: {
        housename: "good house",
        place: "goodplace",
        city: "goodtwon",
        postcode: 121212
    },
    hobbies: ["driving", "travelling", "sports"]
}, {
    fname: "ramu",
    last: "kv",
    age: 29,
    address: {
        housename: "etho veedu",
        place: "vayadi",
        city: "kalur",
        postcode: 11111
    },
    hobbies: ["travelling", "sports"]
}]
console.log(" objects::\t", Name, "\n", firstclass_employee)
    //calling a out side function for an object(out side function may be inside an object oe not)
console.log("Fullname of first employee::", Name.fullname.call(firstclass_employee[0]))
console.log("Pension status of of first emlpoyee::", pension.call(firstclass_employee[0]))
console.log("Fullname of 2nd employee::", Name.fullname.call(firstclass_employee[1]))
console.log("Pension status of of 2nd emlpoyee::", pension.call(firstclass_employee[1]))```

AND getting error--->
console.log("Fullname of first employee::", Name.fullname.call(firstclass_employee[0]))
                                                          ^

TypeError: Name.fullname.call is not a function

答:
If you want regular function remove the get and it will work fine. Sorry, I was mistakenly said you have errors in the console.log() part.

let Name = {
  fullname() {
       return this.fname + this.last
   }
}

function pension() {
   return this.age > 60
}
let firstclass_employee = [{
   fname: "sangeth",
   last: "AV",
   age: 21,
   address: {
       housename: "good house",
       place: "goodplace",
       city: "goodtwon",
       postcode: 121212
   },
   hobbies: ["driving", "travelling", "sports"]
}, {
   fname: "ramu",
   last: "kv",
   age: 29,
   address: {
       housename: "etho veedu",
       place: "vayadi",
       city: "kalur",
       postcode: 11111
   },
   hobbies: ["travelling", "sports"]
}]
console.log(" objects::\t", Name, "\n", firstclass_employee)
//calling a out side function for an object(out side function may be inside an object oe not)
console.log("Fullname of first employee::", Name.fullname.call(firstclass_employee[0]))
console.log("Pension status of of first emlpoyee::", pension.call(firstclass_employee[0]))
console.log("Fullname of 2nd employee::", Name.fullname.call(firstclass_employee[1]))
console.log("Pension status of of 2nd emlpoyee::", pension.call(firstclass_employee[1]))```

Body:
let Name = {
   get fullname() {
        return this.fname + this.last
    }
}

function pension() {
    return this.age > 60
}
let firstclass_employee = [{
    fname: "sangeth",
    last: "AV",
    age: 21,
    address: {
        housename: "good house",
        place: "goodplace",
        city: "goodtwon",
        postcode: 121212
    },
    hobbies: ["driving", "travelling", "sports"]
}, {
    fname: "ramu",
    last: "kv",
    age: 29,
    address: {
        housename: "etho veedu",
        place: "vayadi",
        city: "kalur",
        postcode: 11111
    },
    hobbies: ["travelling", "sports"]
}]
console.log(" objects::\t", Name, "\n", firstclass_employee)
    //calling a out side function for an object(out side function may be inside an object oe not)
console.log("Fullname of first employee::", Name.fullname.call(firstclass_employee[0]))
console.log("Pension status of of first emlpoyee::", pension.call(firstclass_employee[0]))
console.log("Fullname of 2nd employee::", Name.fullname.call(firstclass_employee[1]))
console.log("Pension status of of 2nd emlpoyee::", pension.call(firstclass_employee[1]))

AND getting error--->
console.log("Fullname of first employee::", Name.fullname.call(firstclass_employee[0]))
                                                          ^

TypeError: Name.fullname.call is not a function


问:
Merging several vcf files using snakemake
I am trying to merge several vcf files by chromosome using snakemake. My files are like this, and as you can see has various coordinates. What is the best way to merge all chr1A and all chr1B?

```<code>chr1A:0-2096.filtered.vcf
chr1A:2096-7896.filtered.vcf
chr1B:0-3456.filtered.vcf
chr1B:3456-8796.filtered.vcf
</code>```

My pseudocode:

```<code>chromosomes=["chr1A","chr1B"]

rule all:
    input:
        expand("{sample}.vcf", sample=chromosomes)

rule merge:
    input:
        I1="path/to/file/{sample}.xxx.filtered.vcf",
        I2="path/to/file/{sample}.xxx.filtered.vcf",
    output:
        outf ="{sample}.vcf"
    shell:
        """
        java -jar picard.jar GatherVcfs I={input.I1} I={input.I2} O={output.outf}
        """
</code>```

EDIT:

```<code>workdir: "/media/prova/Maxtor2/vcf2/merged/"

import subprocess

d = {"chr1A": ["chr1A:0-2096.flanking.view.filtered.vcf", "chr1A:2096-7896.flanking.view.filtered.vcf"],
     "chr1B": ["chr1B:0-3456.flanking.view.filtered.vcf", "chr1B:3456-8796.flanking.view.filtered.vcf"]}

rule all:
    input:
        expand("{sample}.vcf", sample=d)

def f(w):
    return d.get(w.chromosome, "")

rule merge:
    input:
        f
    output:
        outf ="{chromosome}.vcf"
    params:
        lambda w: "I=" + " I=".join(d[w.chromosome])
    shell:
        "java -jar /home/Documents/Tools/picard.jar GatherVcfs {params[0]} O={output.outf}"
</code>```

答:
I was able to reproduce your bug. When constraining the wildcards, it works:

```<code>d = {"chr1A": ["chr1A:0-2096.flanking.view.filtered.vcf", "chr1A:2096-7896.flanking.view.filtered.vcf"],
     "chr1B": ["chr1B:0-3456.flanking.view.filtered.vcf", "chr1B:3456-8796.flanking.view.filtered.vcf"]}

chromosomes = list(d)

rule all:
    input:
        expand("{sample}.vcf", sample=chromosomes)

# these tell Snakemake exactly what values the wildcards may take
# we use "|" to create the regex chr1A|chr1B
wildcard_constraints:
    chromosome = "|".join(chromosomes)

rule merge:
    input:
        # a lambda is an unnamed function
        # the first argument is the wildcards
        # we merely use it to look up the appropriate files in the dict d
        lambda w: d[w.chromosome]
    output:
        outf = "{chromosome}.vcf"
    params:
        # here we create the string
        # "I=chr1A:0-2096.flanking.view.filtered.vcf I=chr1A:2096-7896.flanking.view.filtered.vcf"
        # for use in our command
        lambda w: "I=" + " I=".join(d[w.chromosome])
    shell:
        "java -jar /home/Documents/Tools/picard.jar GatherVcfs {params[0]} O={output.outf}"
</code>```

It should have worked without the constraints too; this seems like a bug in Snakemake.

Body:
I am trying to merge several vcf files by chromosome using snakemake. My files are like this, and as you can see has various coordinates. What is the best way to merge all chr1A and all chr1B?

chr1A:0-2096.filtered.vcf
chr1A:2096-7896.filtered.vcf
chr1B:0-3456.filtered.vcf
chr1B:3456-8796.filtered.vcf

My pseudocode:

chromosomes=["chr1A","chr1B"]

rule all:
    input:
        expand("{sample}.vcf", sample=chromosomes)

rule merge:
    input:
        I1="path/to/file/{sample}.xxx.filtered.vcf",
        I2="path/to/file/{sample}.xxx.filtered.vcf",
    output:
        outf ="{sample}.vcf"
    shell:
        """
        java -jar picard.jar GatherVcfs I={input.I1} I={input.I2} O={output.outf}
        """

EDIT:

workdir: "/media/prova/Maxtor2/vcf2/merged/"

import subprocess

d = {"chr1A": ["chr1A:0-2096.flanking.view.filtered.vcf", "chr1A:2096-7896.flanking.view.filtered.vcf"],
     "chr1B": ["chr1B:0-3456.flanking.view.filtered.vcf", "chr1B:3456-8796.flanking.view.filtered.vcf"]}

rule all:
    input:
        expand("{sample}.vcf", sample=d)

def f(w):
    return d.get(w.chromosome, "")

rule merge:
    input:
        f
    output:
        outf ="{chromosome}.vcf"
    params:
        lambda w: "I=" + " I=".join(d[w.chromosome])
    shell:
        "java -jar /home/Documents/Tools/picard.jar GatherVcfs {params[0]} O={output.outf}"

Body:
I was able to reproduce your bug. When constraining the wildcards, it works:

d = {"chr1A": ["chr1A:0-2096.flanking.view.filtered.vcf", "chr1A:2096-7896.flanking.view.filtered.vcf"],
     "chr1B": ["chr1B:0-3456.flanking.view.filtered.vcf", "chr1B:3456-8796.flanking.view.filtered.vcf"]}

chromosomes = list(d)

rule all:
    input:
        expand("{sample}.vcf", sample=chromosomes)

# these tell Snakemake exactly what values the wildcards may take
# we use "|" to create the regex chr1A|chr1B
wildcard_constraints:
    chromosome = "|".join(chromosomes)

rule merge:
    input:
        # a lambda is an unnamed function
        # the first argument is the wildcards
        # we merely use it to look up the appropriate files in the dict d
        lambda w: d[w.chromosome]
    output:
        outf = "{chromosome}.vcf"
    params:
        # here we create the string
        # "I=chr1A:0-2096.flanking.view.filtered.vcf I=chr1A:2096-7896.flanking.view.filtered.vcf"
        # for use in our command
        lambda w: "I=" + " I=".join(d[w.chromosome])
    shell:
        "java -jar /home/Documents/Tools/picard.jar GatherVcfs {params[0]} O={output.outf}"

It should have worked without the constraints too; this seems like a bug in Snakemake.


问:
Load pdf file from url
I have this url from server
https://xxxx.pdf20200529". How can I load it as pdf in my flutter app?

I use this plugin, but nothing happened.

Code

```<code>OpenFile.open(value);  // value is https://xxxx.pdf20200529
</code>```

Edit

```<code> generatePDF(dynamic value) async {
    final filename = value.substring(value.lastIndexOf("/") + 1);
    var request = await HttpClient().getUrl(Uri.parse(value));
    var response = await request.close();
    var bytes = await consolidateHttpClientResponseBytes(response);
    String dir = (await getApplicationDocumentsDirectory()).path;
    File file = new File('$dir/$filename');
    await file.writeAsBytes(bytes);
    OpenFile.open(file.path);
  }
</code>```

答:
Opening PDF's in Flutter is pretty fiddly. So I suggest you use a package. flutter_full_pdf_viewer works pretty well and is easy to use, but there are others out there.

https://pub.dev/packages/flutter_full_pdf_viewer

This will be your PDF Screen:

```<code>class PDFScreen extends StatelessWidget {
  String pathPDF = "";
  PDFScreen(this.pathPDF);

  @override
  Widget build(BuildContext context) {
    return PDFViewerScaffold(
        appBar: AppBar(
          title: Text("Document"),
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.share),
              onPressed: () {},
            ),
          ],
        ),
        path: pathPDF);
  }
}
</code>```

Navigate to it like this. Make sure to pass the local path to the screen.:

```<code>Navigator.push(context, MaterialPageRoute(builder: (context) => PDFScreen(pathPDF)),
</code>```

Title: Load pdf file from url

Body:
I have this url from server
https://xxxx.pdf20200529". How can I load it as pdf in my flutter app?

I use this plugin, but nothing happened.

Code

OpenFile.open(value);  // value is https://xxxx.pdf20200529

Edit

 generatePDF(dynamic value) async {
    final filename = value.substring(value.lastIndexOf("/") + 1);
    var request = await HttpClient().getUrl(Uri.parse(value));
    var response = await request.close();
    var bytes = await consolidateHttpClientResponseBytes(response);
    String dir = (await getApplicationDocumentsDirectory()).path;
    File file = new File('$dir/$filename');
    await file.writeAsBytes(bytes);
    OpenFile.open(file.path);
  }

Body:
Opening PDF's in Flutter is pretty fiddly. So I suggest you use a package. flutter_full_pdf_viewer works pretty well and is easy to use, but there are others out there.

https://pub.dev/packages/flutter_full_pdf_viewer

This will be your PDF Screen:

class PDFScreen extends StatelessWidget {
  String pathPDF = "";
  PDFScreen(this.pathPDF);

  @override
  Widget build(BuildContext context) {
    return PDFViewerScaffold(
        appBar: AppBar(
          title: Text("Document"),
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.share),
              onPressed: () {},
            ),
          ],
        ),
        path: pathPDF);
  }
}

Navigate to it like this. Make sure to pass the local path to the screen.:

Navigator.push(context, MaterialPageRoute(builder: (context) => PDFScreen(pathPDF)),


问:
Count on multiple fields in Django querysets
I have a model representing a transaction between two users, like this:

```<code>class Transaction(models.Model):
    buyer = models.ForeignKey(
        Person, on_delete=models.SET_NULL, null=True, related_name="bought"
    )
    seller = models.ForeignKey(
        Person, on_delete=models.SET_NULL, null=True, related_name="sold"
    )
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
</code>```

I would like to get the number of transactions for each user (either as a buyer or a seller). If a I want to count on only one field, I can just do :

```<code>Transaction.objects.values('seller').annotate(Count('seller'))
</code>```

but I can't manage to do it on two fields at the same time in 1 query.
Is there a way to do that ?

Thanks

答:
I just came across this question from myself, so I'll post an answer, in case someone ever need it:
The obvious idea is to use two Count in a single annotate, but as the django doc says, using multiple aggregations in annotate will yield the wrong result. It does work with Count, using distinct keyword, for Django 2.2 or 3:

```<code>from django.db.models import Count
result = Person.objects.annotate(
    transaction_count=Count("bought", distinct=True) + Count("sold", distinct=True)
).values("id", "transaction_count")
</code>```

For Django < 2.2, you can use subqueries:

```<code>from django.db.models import Count, OuterRef, F

buyer_subquery = (
    Transaction.objects.filter(buyer_id=OuterRef("id"))
    .values("buyer_id")
    .annotate(subcount=Count("id"))
    .values("subcount")
)
seller_subquery = (
    Transaction.objects.filter(seller_id=OuterRef("id"))
    .values("seller_id")
    .annotate(subcount=Count("id"))
    .values("subcount")
)
Person.objects.annotate(
    buyer_count=buyer_subquery,
    seller_count=seller_subquery,
    transaction_count=F("buyer_count") + F("seller_count"),
).values("id", "transaction_count")
</code>```

Body:
I have a model representing a transaction between two users, like this:

class Transaction(models.Model):
    buyer = models.ForeignKey(
        Person, on_delete=models.SET_NULL, null=True, related_name="bought"
    )
    seller = models.ForeignKey(
        Person, on_delete=models.SET_NULL, null=True, related_name="sold"
    )
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)

I would like to get the number of transactions for each user (either as a buyer or a seller). If a I want to count on only one field, I can just do :

Transaction.objects.values('seller').annotate(Count('seller'))

but I can't manage to do it on two fields at the same time in 1 query.
Is there a way to do that ?

Thanks

Body:
I just came across this question from myself, so I'll post an answer, in case someone ever need it:
The obvious idea is to use two Count in a single annotate, but as the django doc says, using multiple aggregations in annotate will yield the wrong result. It does work with Count, using distinct keyword, for Django 2.2 or 3:

from django.db.models import Count
result = Person.objects.annotate(
    transaction_count=Count("bought", distinct=True) + Count("sold", distinct=True)
).values("id", "transaction_count")

For Django < 2.2, you can use subqueries:

from django.db.models import Count, OuterRef, F

buyer_subquery = (
    Transaction.objects.filter(buyer_id=OuterRef("id"))
    .values("buyer_id")
    .annotate(subcount=Count("id"))
    .values("subcount")
)
seller_subquery = (
    Transaction.objects.filter(seller_id=OuterRef("id"))
    .values("seller_id")
    .annotate(subcount=Count("id"))
    .values("subcount")
)
Person.objects.annotate(
    buyer_count=buyer_subquery,
    seller_count=seller_subquery,
    transaction_count=F("buyer_count") + F("seller_count"),
).values("id", "transaction_count")


问:
how compilers detect overflow in numbers while compiling?
Compiler deal with source code as strings so in C++ for example when it encourage statement like unsigned char x = 150; it knows from type limits that unsigned char must be in range between 0 and 255.

My question is while the number 150 remain string what algorithm compiler use to compare digit sequence - 150 in this case - against type limits?

I made a simple algorithm to do that for type 'int' for decimal, octal, hexadecimal and little endian binary but i don't think compiler do such thing like that to detect overflow in numbers.

the algorithm i made are coded in C++:

```<code>typedef signed char int8;
typedef signed int  int32;

#define DEC  0
#define HEX  1
#define OCT  2
#define BIN  3

bool isOverflow(const char* value, int32 base)
{
    // left-most digit for maximum and minimum number
    static const char* max_numbers[4][2] =
    {
        //                 INT_MAX                           INT_MIN
        {                       "2147483647",                       "2147483648" }, // decimal
        {                         "7fffffff",                         "80000000" }, // hexadecimal
        {                      "17777777777",                      "20000000000" }, // octal
        { "01111111111111111111111111111111", "10000000000000000000000000000000" }  // binary
    };

    // size of strings in max_numbers array
    static const int32 number_sizes[] = { 10, 8, 11, 32 };

    // input string size
    int32 str_len = strlen(value);

    // is sign mark exist in input string
    int32 signExist = ((base == DEC || base == OCT) && *value == '-');

    // first non zero digit in input number
    int32 non_zero_index = signExist;

    // locate first non zero index
    while(non_zero_index < str_len && value[non_zero_index] == 0) non_zero_index++;

    // if non_zero_index equal length then all digits are zero
    if (non_zero_index == str_len) return false;

    // get number of digits that actually represent the number
    int32 diff = str_len - non_zero_index;

    // if difference less than 10 digits then no overflow will happened
    if (diff < number_sizes[base]) return false;
    // if difference greater than 10 digits then overflow will happened
    if (diff > number_sizes[base]) return true;

    // left digit in input and search strings
    int8 left1 = 0, left2 = 0;

    // if digits equal to 10 then loop over digits from left to right and compare
    for (int32 i = 0; non_zero_index < str_len; non_zero_index++, i++)
    {
        // get input digit
        left1 = value[non_zero_index];
        // get match digit
        left2 = max_numbers[signExist][i];

        // if digits not equal then if left1 is greater overflow will occurred, false otherwise
        if (left1 != left2) return left1 > left2;
    }

    // overflow won't happened
    return false;
}
</code>```

This algorithm can be optimized to work with all integers types but with float-point i have to make new one to work with IEEE float-point representation.

i think compilers use efficient algorithm to detect overflow other than mine, don't you?

答:
In most compiler theory, the text of a program (translation unit) is converted into tokens and values.  For example, the text "150" would be converted into a token of constant integer with a value of 150.  This is of course, after the preprocessor has run.

The compiler then begins the process of syntax and semantic checking.  So an assignment statement is evaluated for syntax (correct spelling and format), then checked for semantics.

The compiler can either complain about a value that is out of range (such as -150 for unsigned char) or apply some transformations.  In the case of -150, this would be transformed into an 8-bit value (the Most Significant Bit that indicated negativity is now the value 128).  I am not a language lawyer, so I don't exactly know the freedom the compiler has in this respect, nor whether a warning is required or not.

In summary, the compiler has some freedoms when evaluating statements and checking the semantics.  All text is converted into an internal representation for tokens and values (a more compact data structure).  Checking for whether a constant integer literal is within range for an assignment statement takes place during the semantics stage of the compilation process.  Semantics are decided from the language standard or company policy.  Some semantics are turned into compiler options and left for the programmer.

Body:
Compiler deal with source code as strings so in C++ for example when it encourage statement like unsigned char x = 150; it knows from type limits that unsigned char must be in range between 0 and 255.

My question is while the number 150 remain string what algorithm compiler use to compare digit sequence - 150 in this case - against type limits?

I made a simple algorithm to do that for type 'int' for decimal, octal, hexadecimal and little endian binary but i don't think compiler do such thing like that to detect overflow in numbers.

the algorithm i made are coded in C++:

typedef signed char int8;
typedef signed int  int32;

#define DEC  0
#define HEX  1
#define OCT  2
#define BIN  3

bool isOverflow(const char* value, int32 base)
{
    // left-most digit for maximum and minimum number
    static const char* max_numbers[4][2] =
    {
        //                 INT_MAX                           INT_MIN
        {                       "2147483647",                       "2147483648" }, // decimal
        {                         "7fffffff",                         "80000000" }, // hexadecimal
        {                      "17777777777",                      "20000000000" }, // octal
        { "01111111111111111111111111111111", "10000000000000000000000000000000" }  // binary
    };

    // size of strings in max_numbers array
    static const int32 number_sizes[] = { 10, 8, 11, 32 };

    // input string size
    int32 str_len = strlen(value);

    // is sign mark exist in input string
    int32 signExist = ((base == DEC || base == OCT) && *value == '-');

    // first non zero digit in input number
    int32 non_zero_index = signExist;

    // locate first non zero index
    while(non_zero_index < str_len && value[non_zero_index] == 0) non_zero_index++;

    // if non_zero_index equal length then all digits are zero
    if (non_zero_index == str_len) return false;

    // get number of digits that actually represent the number
    int32 diff = str_len - non_zero_index;

    // if difference less than 10 digits then no overflow will happened
    if (diff < number_sizes[base]) return false;
    // if difference greater than 10 digits then overflow will happened
    if (diff > number_sizes[base]) return true;

    // left digit in input and search strings
    int8 left1 = 0, left2 = 0;

    // if digits equal to 10 then loop over digits from left to right and compare
    for (int32 i = 0; non_zero_index < str_len; non_zero_index++, i++)
    {
        // get input digit
        left1 = value[non_zero_index];
        // get match digit
        left2 = max_numbers[signExist][i];

        // if digits not equal then if left1 is greater overflow will occurred, false otherwise
        if (left1 != left2) return left1 > left2;
    }

    // overflow won't happened
    return false;
}

This algorithm can be optimized to work with all integers types but with float-point i have to make new one to work with IEEE float-point representation.

i think compilers use efficient algorithm to detect overflow other than mine, don't you?


问:
Send an executable python file to someone
I've done a project and i want to send it to my friends to see and try

The problem is that once I make it an executable file i can t send it anywhere

They don t have python install so i can't  just send the files and i was
wondering what are the possibilities to send the executable

I've tried to rename the file extension, send it, but he could not run it

I want to know if there is a chance that windows can't compile or open the executable if python is not install

here s the code in any case

```<code>from tkinter import *

tura=0

def golire(parent):
    for elemente in parent.winfo_children():
        elemente.grid_forget()

def terminare(parent,castigator,joc_nou):
    global tura
    tura=0
    golire(parent)
    afis=Label(parent,text=castigator+' a castigat!',font=('Arial',30),width=20,height=3)
    buton1=Button(parent,text='Din nou?',font=('Courier',10),width=5,height=5,command=joc_nou)
    buton2=Button(parent,text='Neah',font=('Courier',10),width=5,height=5,command=root.quit)

    afis.grid(columnspan=2,sticky=NSEW)
    buton1.grid(row=1,column=0,sticky=NSEW)
    buton2.grid(row=1,column=1,sticky=NSEW)

class joc:
    def __init__(self,parent):
        global tura

        tura=0

        self.parent=parent

        b0=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b0.grid(row=0,column=0,sticky=NSEW)

        b1=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b1.grid(row=0,column=1,sticky=NSEW)

        b2=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b2.grid(row=0,column=2,sticky=NSEW)

        b3=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b3.grid(row=1,column=0,sticky=NSEW)

        b4=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b4.grid(row=1,column=1,sticky=NSEW)

        b5=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b5.grid(row=1,column=2,sticky=NSEW)

        b6=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b6.grid(row=2,column=0,sticky=NSEW)

        b7=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b7.grid(row=2,column=1,sticky=NSEW)

        b8=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b8.grid(row=2,column=2,sticky=NSEW)

        def enter(event):
            event.widget.config(bg='black')
        def left(event):
            event.widget.config(bg='white')

        def adaugare(event):
            global tura
            if event.widget['state']!='disabled':
                if tura%2==0:
                    event.widget.config(text='X')
                else:
                    event.widget.config(text='O')
                event.widget.config(state='disabled')
                tura+=1
        def verificare(event):
            def joc_nou():
                golire(self.parent)
                joc(self.parent)

            if b0['text']==b1['text']==b2['text'] and b0['state']==b1['state']==b2['state']=='disabled':
                terminare(self.parent,b0['text'],joc_nou)
            elif b3['text']==b4['text']==b5['text'] and b3['state']==b4['state']==b5['state']=='disabled':
                terminare(self.parent,b3['text'],joc_nou)
            elif b6['text']==b7['text']==b8['text'] and b6['state']==b7['state']==b8['state']=='disabled':
                terminare(self.parent,b6['text'],joc_nou)
            elif b0['text']==b3['text']==b6['text'] and b0['state']==b3['state']==b6['state']=='disabled':
                terminare(self.parent,b0['text'],joc_nou)
            elif b1['text']==b4['text']==b7['text'] and b1['state']==b4['state']==b7['state']=='disabled':
                terminare(self.parent,b1['text'],joc_nou)
            elif b2['text']==b5['text']==b8['text'] and b2['state']==b5['state']==b8['state']=='disabled':
                terminare(self.parent,b0['text'],joc_nou)
            elif b0['text']==b4['text']==b8['text'] and b0['state']==b4['state']==b8['state']=='disabled':
                terminare(self.parent,b0['text'],joc_nou)
            elif b2['text']==b4['text']==b6['text'] and b2['state']==b4['state']==b6['state']=='disabled':
                terminare(self.parent,b0['text'],joc_nou)
            elif b0['state']==b1['state']==b2['state']==b3['state']==b4['state']==b5['state']==b6['state']==b7['state']==b8['state']=='disabled':
                terminare(self.parent,'Nimeni',joc_nou)

        b0.bind("<Enter>",enter)
        b0.bind("<Leave>",left)

        b1.bind("<Enter>",enter)
        b1.bind("<Leave>",left)

        b2.bind("<Enter>",enter)
        b2.bind("<Leave>",left)

        b3.bind("<Enter>",enter)
        b3.bind("<Leave>",left)

        b4.bind("<Enter>",enter)
        b4.bind("<Leave>",left)

        b5.bind("<Enter>",enter)
        b5.bind("<Leave>",left)

        b6.bind("<Enter>",enter)
        b6.bind("<Leave>",left)

        b7.bind("<Enter>",enter)
        b7.bind("<Leave>",left)

        b8.bind("<Enter>",enter)
        b8.bind("<Leave>",left)

        b0.bind("<Button-1>",adaugare,add="+")

        b1.bind("<Button-1>",adaugare,add="+")

        b2.bind("<Button-1>",adaugare,add="+")

        b3.bind("<Button-1>",adaugare,add="+")

        b4.bind("<Button-1>",adaugare,add="+")

        b5.bind("<Button-1>",adaugare,add="+")

        b6.bind("<Button-1>",adaugare,add="+")

        b7.bind("<Button-1>",adaugare,add="+")

        b8.bind("<Button-1>",adaugare,add="+")

        #verificare
        b0.bind("<Button-1>",verificare,add="+")

        b1.bind("<Button-1>",verificare,add="+")

        b2.bind("<Button-1>",verificare,add="+")

        b3.bind("<Button-1>",verificare,add="+")

        b4.bind("<Button-1>",verificare,add="+")

        b5.bind("<Button-1>",verificare,add="+")

        b6.bind("<Button-1>",verificare,add="+")

        b7.bind("<Button-1>",verificare,add="+")

        b8.bind("<Button-1>",verificare,add="+")

if __name__=='__main__':
    root=Tk()
    joc(root)
    root.mainloop()
</code>```

答: I always use PyInstaller for this, easy to install, easy to use</p>

Body:
I've done a project and i want to send it to my friends to see and try

The problem is that once I make it an executable file i can t send it anywhere

They don t have python install so i can't  just send the files and i was
wondering what are the possibilities to send the executable

I've tried to rename the file extension, send it, but he could not run it

I want to know if there is a chance that windows can't compile or open the executable if python is not install

here s the code in any case

from tkinter import *

tura=0

def golire(parent):
    for elemente in parent.winfo_children():
        elemente.grid_forget()

def terminare(parent,castigator,joc_nou):
    global tura
    tura=0
    golire(parent)
    afis=Label(parent,text=castigator+' a castigat!',font=('Arial',30),width=20,height=3)
    buton1=Button(parent,text='Din nou?',font=('Courier',10),width=5,height=5,command=joc_nou)
    buton2=Button(parent,text='Neah',font=('Courier',10),width=5,height=5,command=root.quit)

    afis.grid(columnspan=2,sticky=NSEW)
    buton1.grid(row=1,column=0,sticky=NSEW)
    buton2.grid(row=1,column=1,sticky=NSEW)

class joc:
    def __init__(self,parent):
        global tura

        tura=0

        self.parent=parent

        b0=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b0.grid(row=0,column=0,sticky=NSEW)

        b1=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b1.grid(row=0,column=1,sticky=NSEW)

        b2=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b2.grid(row=0,column=2,sticky=NSEW)

        b3=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b3.grid(row=1,column=0,sticky=NSEW)

        b4=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b4.grid(row=1,column=1,sticky=NSEW)

        b5=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b5.grid(row=1,column=2,sticky=NSEW)

        b6=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b6.grid(row=2,column=0,sticky=NSEW)

        b7=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b7.grid(row=2,column=1,sticky=NSEW)

        b8=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b8.grid(row=2,column=2,sticky=NSEW)

        def enter(event):
            event.widget.config(bg='black')
        def left(event):
            event.widget.config(bg='white')

        def adaugare(event):
            global tura
            if event.widget['state']!='disabled':
                if tura%2==0:
                    event.widget.config(text='X')
                else:
                    event.widget.config(text='O')
                event.widget.config(state='disabled')
                tura+=1
        def verificare(event):
            def joc_nou():
                golire(self.parent)
                joc(self.parent)

            if b0['text']==b1['text']==b2['text'] and b0['state']==b1['state']==b2['state']=='disabled':
                terminare(self.parent,b0['text'],joc_nou)
            elif b3['text']==b4['text']==b5['text'] and b3['state']==b4['state']==b5['state']=='disabled':
                terminare(self.parent,b3['text'],joc_nou)
            elif b6['text']==b7['text']==b8['text'] and b6['state']==b7['state']==b8['state']=='disabled':
                terminare(self.parent,b6['text'],joc_nou)
            elif b0['text']==b3['text']==b6['text'] and b0['state']==b3['state']==b6['state']=='disabled':
                terminare(self.parent,b0['text'],joc_nou)
            elif b1['text']==b4['text']==b7['text'] and b1['state']==b4['state']==b7['state']=='disabled':
                terminare(self.parent,b1['text'],joc_nou)
            elif b2['text']==b5['text']==b8['text'] and b2['state']==b5['state']==b8['state']=='disabled':
                terminare(self.parent,b0['text'],joc_nou)
            elif b0['text']==b4['text']==b8['text'] and b0['state']==b4['state']==b8['state']=='disabled':
                terminare(self.parent,b0['text'],joc_nou)
            elif b2['text']==b4['text']==b6['text'] and b2['state']==b4['state']==b6['state']=='disabled':
                terminare(self.parent,b0['text'],joc_nou)
            elif b0['state']==b1['state']==b2['state']==b3['state']==b4['state']==b5['state']==b6['state']==b7['state']==b8['state']=='disabled':
                terminare(self.parent,'Nimeni',joc_nou)

        b0.bind("<Enter>",enter)
        b0.bind("<Leave>",left)

        b1.bind("<Enter>",enter)
        b1.bind("<Leave>",left)

        b2.bind("<Enter>",enter)
        b2.bind("<Leave>",left)

        b3.bind("<Enter>",enter)
        b3.bind("<Leave>",left)

        b4.bind("<Enter>",enter)
        b4.bind("<Leave>",left)

        b5.bind("<Enter>",enter)
        b5.bind("<Leave>",left)

        b6.bind("<Enter>",enter)
        b6.bind("<Leave>",left)

        b7.bind("<Enter>",enter)
        b7.bind("<Leave>",left)

        b8.bind("<Enter>",enter)
        b8.bind("<Leave>",left)

        b0.bind("<Button-1>",adaugare,add="+")

        b1.bind("<Button-1>",adaugare,add="+")

        b2.bind("<Button-1>",adaugare,add="+")

        b3.bind("<Button-1>",adaugare,add="+")

        b4.bind("<Button-1>",adaugare,add="+")

        b5.bind("<Button-1>",adaugare,add="+")

        b6.bind("<Button-1>",adaugare,add="+")

        b7.bind("<Button-1>",adaugare,add="+")

        b8.bind("<Button-1>",adaugare,add="+")

        #verificare
        b0.bind("<Button-1>",verificare,add="+")

        b1.bind("<Button-1>",verificare,add="+")

        b2.bind("<Button-1>",verificare,add="+")

        b3.bind("<Button-1>",verificare,add="+")

        b4.bind("<Button-1>",verificare,add="+")

        b5.bind("<Button-1>",verificare,add="+")

        b6.bind("<Button-1>",verificare,add="+")

        b7.bind("<Button-1>",verificare,add="+")

        b8.bind("<Button-1>",verificare,add="+")

if __name__=='__main__':
    root=Tk()
    joc(root)
    root.mainloop()


问:
Print the count of element in a column in table format
Given this dataframe:

```<code>import pandas as pd
df=pd.DataFrame({"Name":["A","A","B"]})
</code>```

I want to print the count of element in Name column in table format as follows:

This is what I am doing right now:

```<code>df['Name'].value_counts().reset_index().rename(columns={'index':'Name','Name':'Count'})
</code>```

Though it works, is there a simpler (shorter way) to achieve the same result?

答:
```<code>pd.DataFrame({"Count": df.groupby("Name").size()})

     Count
Name
A     2
B     1
</code>```

Body:
Given this dataframe:

import pandas as pd
df=pd.DataFrame({"Name":["A","A","B"]})

I want to print the count of element in Name column in table format as follows:

This is what I am doing right now:

df['Name'].value_counts().reset_index().rename(columns={'index':'Name','Name':'Count'})

Though it works, is there a simpler (shorter way) to achieve the same result?


问:
How to save cache in device Flutter
I am new in Flutter, this is my first project in Flutter. I want to do a project that once data are loaded from API, they're cached in the device. Next time it can be loaded very fast even if my device is offline. I here that can using Dio package with dio cache manager package for caching server's json response. And then using cache image package to cache images. Anyone can give me some example how to write the code? Thanks in advance

答:
Another best way for caching in flutter is the use of the hive. And it  retrieves data faster than Sqflite and Shared preferences

For example, you can check this GitHub repo:https://github.com/shashiben/Anime-details

This will show how to cache the rest API data into the hive and for the next time it will show data from the hive.

I think this answer helped you

Title: How to save cache in device Flutter


问:
How to call function from other local file Node.js?
I tried like this from main.js

```<code>// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
const parser = require('./parser.js');
parser.parseHash(url)
</code>```

But got error that: parser.parseHash is not function

```<code>// parser.js file
function parseHash(url) {
    ...
}
</code>```

答:
```<code>// parser.js
exports.parseHash = function (url) {
    ...
};

//main.js
const parseHash = require('./parser').parseHash;
parseHash(url)
</code>```

Body:
I tried like this from main.js

// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
const parser = require('./parser.js');
parser.parseHash(url)

But got error that: parser.parseHash is not function

// parser.js file
function parseHash(url) {
    ...
}


问:
Drupal menu edit/delete permissions module
I created a website, I have a content manager role, and I want him to be able to rearange the menu, but I don't want him to see the edit/delete buttons in the view.

Is there anyy module for this ?

@Edit, I am talking about drupal 6

I solved the problem by overwriting the template, checking on the role and removing the operation links in the view for certain roles

答: I think you're talking about something like Menu Access. When you say "see edit/delete buttons" I assume you mean you don't want him to have permissions to edit views. Also, I assume you're talking about Drupal 6.</p>


问:
How to use TimeDsitributed layer for neural network ensmeble (specifically CNN+LSTM)?
So this is the first of 2 ways that I tried:

```<code>inputs=Input(shape=(frames, 103*4, 1))

z=TimeDistributed(Conv2D(32, (5,25), padding='same', activation='relu'), input_shape=(frames, 103*4, 1))(inputs)
z=TimeDistributed(BatchNormalization())(z)
z=TimeDistributed(ReLU())(z)
z=TimeDistributed(Dropout(0.2))(z)
z=TimeDistributed(MaxPooling2D(pool_size=(1,2)))(z)

z=TimeDistributed(Conv2D(32, (3,5), padding='same', activation='relu'))(z)
z=TimeDistributed(BatchNormalization())(z)
z=TimeDistributed(ReLU())(z)
z=TimeDistributed(Dropout(0.2))(z)
z=TimeDistributed(MaxPooling2D(pool_size=(1,2)))(z)

z=TimeDistributed(Flatten())(z)

z=LSTM(1000, dropout=0.1, recurrent_dropout=0.2, return_sequences=True)(z)
z=LSTM(1000, dropout=0.1, recurrent_dropout=0.2, return_sequences=True)(z)
z=LSTM(1000, dropout=0.1, recurrent_dropout=0.2, return_sequences=True)(z)

z=Flatten()(z)

z=Dense(1000, activation='relu')(z)
z=Dropout(0.5)(z)

z=Dense(500, activation='relu')(z)
z=Dropout(0.5)(z)

z=Dense(200, activation='relu')(z)
z=Dropout(0.5)(z)

outputs=Dense(88, activation='sigmoid')(z)
</code>```

I'm getting this error (although I don't have strides size of 2 anywhere in my code):

```<code>ValueError: strides should be of length 1, 1 or 3 but was 2
</code>```

I've already looked at this question and it seems that I've implemented the advice given in my code. But what's the problem? I can't get a grasp of it.

Finally I managed to combine CNN and LSTM via FunctionalAPI of Keras:

```<code>inputs=Input(shape=(frames, 103*4, 1))

z=Conv2D(32, (5,25), padding='same', activation='relu')(inputs)
z=BatchNormalization()(z)
z=ReLU()(z)
z=Dropout(0.2)(z)
z=MaxPooling2D(pool_size=(1,2))(z)

z=Conv2D(32, (3,5), padding='same', activation='relu')(z)
z=BatchNormalization()(z)
z=ReLU()(z)
z=Dropout(0.2)(z)
z=MaxPooling2D(pool_size=(1,2))(z)

z=TimeDistributed(Flatten())(z)

z=LSTM(1000, dropout=0.1, recurrent_dropout=0.2, return_sequences=True)(z)
z=LSTM(1000, dropout=0.1, recurrent_dropout=0.2, return_sequences=True)(z)
z=LSTM(1000, dropout=0.1, recurrent_dropout=0.2, return_sequences=True)(z)

z=Flatten()(z)

z=Dense(1000, activation='relu')(z)
z=Dropout(0.5)(z)

z=Dense(500, activation='relu')(z)
z=Dropout(0.5)(z)

z=Dense(200, activation='relu')(z)
z=Dropout(0.5)(z)

outputs=Dense(88, activation='sigmoid')(z)

model=Model(inputs=inputs, outputs=outputs)
</code>```

It works, but I'm still at a loss if that's the right way. I can see via model.summary() that my TimeDstributed wrapper has output shape (None, 7, 3296) and all LSTM layers have output shapes (None, 7, 1000). What should I change to give it center frame instead of 7 frames?

Speaking of my dataset, I give 7 frames of amplitudes of frequencies values to predict values in the center frame.

答:
@priyach You're right, but as I can see I gave a somewhat poor explanation of my dataset. I have 2d arrays with time on x axis and frequency on y axis (trying to predict notes being played given information about frequencies)

So if I'd fed columns of my 2d array (each representing all frequencies at a given time) into my network, then Conv1D and MaxPooling1D would be the right choice

But instead of columns as inputs I feed each column surrounded by 3 cols to the left of it and 3 cols to the right of it (or using zero-padding then I can't get columns). So my input is essentially 2d and I treat it as images.

I managed to create another network (CNN+DNN+LSTM+DNN) and used a Reshape layer before 1st LSTM layer (instead of TimeDistributed).

Still the question remains (out of curiosity and for future programming). What's wrong with that my usage of the TimeDistributed layer?

Body:
So this is the first of 2 ways that I tried:

inputs=Input(shape=(frames, 103*4, 1))

z=TimeDistributed(Conv2D(32, (5,25), padding='same', activation='relu'), input_shape=(frames, 103*4, 1))(inputs)
z=TimeDistributed(BatchNormalization())(z)
z=TimeDistributed(ReLU())(z)
z=TimeDistributed(Dropout(0.2))(z)
z=TimeDistributed(MaxPooling2D(pool_size=(1,2)))(z)

z=TimeDistributed(Conv2D(32, (3,5), padding='same', activation='relu'))(z)
z=TimeDistributed(BatchNormalization())(z)
z=TimeDistributed(ReLU())(z)
z=TimeDistributed(Dropout(0.2))(z)
z=TimeDistributed(MaxPooling2D(pool_size=(1,2)))(z)

z=TimeDistributed(Flatten())(z)

z=LSTM(1000, dropout=0.1, recurrent_dropout=0.2, return_sequences=True)(z)
z=LSTM(1000, dropout=0.1, recurrent_dropout=0.2, return_sequences=True)(z)
z=LSTM(1000, dropout=0.1, recurrent_dropout=0.2, return_sequences=True)(z)

z=Flatten()(z)

z=Dense(1000, activation='relu')(z)
z=Dropout(0.5)(z)

z=Dense(500, activation='relu')(z)
z=Dropout(0.5)(z)

z=Dense(200, activation='relu')(z)
z=Dropout(0.5)(z)

outputs=Dense(88, activation='sigmoid')(z)

I'm getting this error (although I don't have strides size of 2 anywhere in my code):

ValueError: strides should be of length 1, 1 or 3 but was 2

I've already looked at this question and it seems that I've implemented the advice given in my code. But what's the problem? I can't get a grasp of it.

Finally I managed to combine CNN and LSTM via FunctionalAPI of Keras:

inputs=Input(shape=(frames, 103*4, 1))

z=Conv2D(32, (5,25), padding='same', activation='relu')(inputs)
z=BatchNormalization()(z)
z=ReLU()(z)
z=Dropout(0.2)(z)
z=MaxPooling2D(pool_size=(1,2))(z)

z=Conv2D(32, (3,5), padding='same', activation='relu')(z)
z=BatchNormalization()(z)
z=ReLU()(z)
z=Dropout(0.2)(z)
z=MaxPooling2D(pool_size=(1,2))(z)

z=TimeDistributed(Flatten())(z)

z=LSTM(1000, dropout=0.1, recurrent_dropout=0.2, return_sequences=True)(z)
z=LSTM(1000, dropout=0.1, recurrent_dropout=0.2, return_sequences=True)(z)
z=LSTM(1000, dropout=0.1, recurrent_dropout=0.2, return_sequences=True)(z)

z=Flatten()(z)

z=Dense(1000, activation='relu')(z)
z=Dropout(0.5)(z)

z=Dense(500, activation='relu')(z)
z=Dropout(0.5)(z)

z=Dense(200, activation='relu')(z)
z=Dropout(0.5)(z)

outputs=Dense(88, activation='sigmoid')(z)

model=Model(inputs=inputs, outputs=outputs)

It works, but I'm still at a loss if that's the right way. I can see via model.summary() that my TimeDstributed wrapper has output shape (None, 7, 3296) and all LSTM layers have output shapes (None, 7, 1000). What should I change to give it center frame instead of 7 frames?

Speaking of my dataset, I give 7 frames of amplitudes of frequencies values to predict values in the center frame.


问:
How to delete print
Here's the problem. In the following code, I wish to produce a 'moving cursor' effect. Here's the code:

```<code>sys.stdout.write('\033[2K\033[1G')
time.sleep(2)
print ('virus_prevention.fix.virus.|attempt_enter')
time.sleep(2)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.virus|.attempt_enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.viru|s.attempt.enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print('virus_prevention.fix.vir|us.attempt.enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.vi|rus.attempt.enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.v|irus.attempt.enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.|virus.attempt.enter')
time.sleep(2)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix|virus.attempt.enter')
</code>```

And this is the output:

```<code>[2K[1Gvirus_prevention.fix.virus.|attempt_enter
[2K[1Gvirus_prevention.fix.virus|.attempt_enter
[2K[1Gvirus_prevention.fix.viru|s.attempt.enter
[2K[1Gvirus_prevention.fix.vir|us.attempt.enter
[2K[1Gvirus_prevention.fix.vi|rus.attempt.enter
[2K[1Gvirus_prevention.fix.v|irus.attempt.enter
[2K[1Gvirus_prevention.fix.|virus.attempt.enter
</code>```

And the sys.stdout.write doesn't really help. It just ends up with added text on the front of the current text. So if there are solutions anyone is willing to share (Python 3) please do. (I did have a solution which used repeatedly clearing the screen via os.system('clear'), which I don't really want to use.)

答:
sys.stdout.write is a good start, but you also need to pass a "carriage return" '\r' to jump to the beginning of the line. This will overwrite the old characters with the next call:

```<code>for i in range(10):
    sys.stdout.write(str(i)+'\r')
    time.sleep(1)
</code>```

If the new line is shorter than the previous line, you will still see the additional characters of the previous line. As a fix you can add some additional spaces to overwrite them.

The main difference between sys.stdout.write and print is, that print will automatically append a linebreak (\n). This is why you see the sys.stdout.write infront of the next printed line.

Running this in an interactive Python session has some weird side effects, but it is fine if you use it in a Python script. Also, make sure not to have any other print() commands inbetween. This only works on the current line, and any '\n' creates a new line.

```<code>sys.stdout.write('virus_prevention.fix.virus.|attempt_enter\r')
time.sleep(2)
sys.stdout.write('virus_prevention.fix.virus|.attempt_enter\r')
print()  # create a linebreak at the end
</code>```

Title: How to delete print

Body:
Here's the problem. In the following code, I wish to produce a 'moving cursor' effect. Here's the code:

sys.stdout.write('\033[2K\033[1G')
time.sleep(2)
print ('virus_prevention.fix.virus.|attempt_enter')
time.sleep(2)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.virus|.attempt_enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.viru|s.attempt.enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print('virus_prevention.fix.vir|us.attempt.enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.vi|rus.attempt.enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.v|irus.attempt.enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.|virus.attempt.enter')
time.sleep(2)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix|virus.attempt.enter')

And this is the output:

[2K[1Gvirus_prevention.fix.virus.|attempt_enter
[2K[1Gvirus_prevention.fix.virus|.attempt_enter
[2K[1Gvirus_prevention.fix.viru|s.attempt.enter
[2K[1Gvirus_prevention.fix.vir|us.attempt.enter
[2K[1Gvirus_prevention.fix.vi|rus.attempt.enter
[2K[1Gvirus_prevention.fix.v|irus.attempt.enter
[2K[1Gvirus_prevention.fix.|virus.attempt.enter

And the sys.stdout.write doesn't really help. It just ends up with added text on the front of the current text. So if there are solutions anyone is willing to share (Python 3) please do. (I did have a solution which used repeatedly clearing the screen via os.system('clear'), which I don't really want to use.)

Body:
sys.stdout.write is a good start, but you also need to pass a "carriage return" '\r' to jump to the beginning of the line. This will overwrite the old characters with the next call:

for i in range(10):
    sys.stdout.write(str(i)+'\r')
    time.sleep(1)

If the new line is shorter than the previous line, you will still see the additional characters of the previous line. As a fix you can add some additional spaces to overwrite them.

The main difference between sys.stdout.write and print is, that print will automatically append a linebreak (\n). This is why you see the sys.stdout.write infront of the next printed line.

Running this in an interactive Python session has some weird side effects, but it is fine if you use it in a Python script. Also, make sure not to have any other print() commands inbetween. This only works on the current line, and any '\n' creates a new line.

sys.stdout.write('virus_prevention.fix.virus.|attempt_enter\r')
time.sleep(2)
sys.stdout.write('virus_prevention.fix.virus|.attempt_enter\r')
print()  # create a linebreak at the end


问:
Android 10 Xamarin.Forms MainActivity as FullScreen Intent for Alarm
I'm trying to patch an existing Xamarin.Android Forms based application to work with Android 10 devices.

We have one only one activity in the app, and we use the Forms Navigation system to push and pop alert pages.

We have a background service that may request the main activity to push a new page and interrupt the user on pre 10 devices.

Because we can no more interrupt the user running Android 10, we've decided to take the Google recommended route. I have found this previous answer for an implementation example.

Basically the pre Android 10 code is this:

```<code>    // post on ui thread
    Android.App.Application.SynchronizationContext.Post(
   _ =>
   {
       Intent intent = new Intent(this.applicationContext, typeof(MainActivity));
       // intent.AddFlags(ActivityFlags.NoHistory);
       intent.AddFlags(ActivityFlags.FromBackground);
       intent.AddFlags(ActivityFlags.NewTask);
       this.applicationContext.StartActivity(intent);
   },
   null);
</code>```

The new code becomes:

```<code>var builder = new NotificationCompat.Builder(context: this.applicationContext, channelId: channelId);
builder.SetContentTitle(title: notification.Title);
builder.SetContentText(text: notification.Text);
builder.SetSmallIcon(icon: this.resourceManager.GetImage(resourceName: notification.Icon));
builder.SetPriority(pri: notification.Priority);
builder.SetAutoCancel(autoCancel: true);

Intent nextScreen = new Intent(this.applicationContext, typeof(MainActivity));

PendingIntent intent = PendingIntent.GetActivity(
context: this.applicationContext,
requestCode: 0,
intent: nextScreen,
flags: PendingIntentFlags.OneShot);

builder.SetFullScreenIntent(intent: intent, highPriority: true);
this.notificationManager.Notify(id: notification.Id, notification: builder.Build());
</code>```

But the new code does not work.

What happens is that the notification is displayed in the notification Area and not full screen.

I'm under the impression that I need to use a new Activity.

Can't I use the app root activity?

答:
Update 1 : this code works on pre android 10 device wether the device is locked or not, the app in the foreground or not.

This works partially (not on the lock screen) with this new code:

```<code>var manager = (Android.App.AlarmManager)this.applicationContext.GetSystemService(Context.AlarmService);
using (var calendar = Calendar.Instance)
{
    calendar.Add(CalendarField.Second, 1);

    Intent fullScreenIntent = new Intent(this.applicationContext, typeof(MainActivity));
    PendingIntent fullScreenPendingIntent = PendingIntent.GetActivity(
         this.applicationContext,
         0,
         fullScreenIntent,
         PendingIntentFlags.OneShot);

         manager.SetExact(AlarmType.RtcWakeup, calendar.TimeInMillis, fullScreenPendingIntent);
}
</code>```

Update 2: A working solution was simply to request OverlayPermission for the application and stick with the old code (first block of the question).

At startup we call the following new method:

```<code>private async Task ManageOverlayPermissionAsync()
{
    IPopupService popupService = Locator.GetSharedInstance<IPopupService>();
    if (BusinessHelper.AndroidMajorVersion >= 10 && !Android.Provider.Settings.CanDrawOverlays(Forms.Context))
    {
        if (await popupService.DisplayAlertAsync(
                BusinessResources.GoToOverlayPermissionTitle,
                BusinessResources.GoToOverlayPermissionMessage,
                BusinessResources.Ok,
                BusinessResources.Cancel))
        {
            var intent = new Intent(Android.Provider.Settings.ActionManageOverlayPermission,
                Android.Net.Uri.Parse("package:" + Forms.Context.PackageName));
            Forms.Context.StartActivity(intent);
        }
    }
}
</code>```

The user is then directed to the settings to enable the feature.

Body:
I'm trying to patch an existing Xamarin.Android Forms based application to work with Android 10 devices.

We have one only one activity in the app, and we use the Forms Navigation system to push and pop alert pages.

We have a background service that may request the main activity to push a new page and interrupt the user on pre 10 devices.

Because we can no more interrupt the user running Android 10, we've decided to take the Google recommended route. I have found this previous answer for an implementation example.

Basically the pre Android 10 code is this:

    // post on ui thread
    Android.App.Application.SynchronizationContext.Post(
   _ =>
   {
       Intent intent = new Intent(this.applicationContext, typeof(MainActivity));
       // intent.AddFlags(ActivityFlags.NoHistory);
       intent.AddFlags(ActivityFlags.FromBackground);
       intent.AddFlags(ActivityFlags.NewTask);
       this.applicationContext.StartActivity(intent);
   },
   null);

The new code becomes:

var builder = new NotificationCompat.Builder(context: this.applicationContext, channelId: channelId);
builder.SetContentTitle(title: notification.Title);
builder.SetContentText(text: notification.Text);
builder.SetSmallIcon(icon: this.resourceManager.GetImage(resourceName: notification.Icon));
builder.SetPriority(pri: notification.Priority);
builder.SetAutoCancel(autoCancel: true);

Intent nextScreen = new Intent(this.applicationContext, typeof(MainActivity));

PendingIntent intent = PendingIntent.GetActivity(
context: this.applicationContext,
requestCode: 0,
intent: nextScreen,
flags: PendingIntentFlags.OneShot);

builder.SetFullScreenIntent(intent: intent, highPriority: true);
this.notificationManager.Notify(id: notification.Id, notification: builder.Build());

But the new code does not work.

What happens is that the notification is displayed in the notification Area and not full screen.

I'm under the impression that I need to use a new Activity.

Can't I use the app root activity?

Body:
Update 1 : this code works on pre android 10 device wether the device is locked or not, the app in the foreground or not.

This works partially (not on the lock screen) with this new code:

var manager = (Android.App.AlarmManager)this.applicationContext.GetSystemService(Context.AlarmService);
using (var calendar = Calendar.Instance)
{
    calendar.Add(CalendarField.Second, 1);

    Intent fullScreenIntent = new Intent(this.applicationContext, typeof(MainActivity));
    PendingIntent fullScreenPendingIntent = PendingIntent.GetActivity(
         this.applicationContext,
         0,
         fullScreenIntent,
         PendingIntentFlags.OneShot);

         manager.SetExact(AlarmType.RtcWakeup, calendar.TimeInMillis, fullScreenPendingIntent);
}

Update 2: A working solution was simply to request OverlayPermission for the application and stick with the old code (first block of the question).

At startup we call the following new method:

private async Task ManageOverlayPermissionAsync()
{
    IPopupService popupService = Locator.GetSharedInstance<IPopupService>();
    if (BusinessHelper.AndroidMajorVersion >= 10 && !Android.Provider.Settings.CanDrawOverlays(Forms.Context))
    {
        if (await popupService.DisplayAlertAsync(
                BusinessResources.GoToOverlayPermissionTitle,
                BusinessResources.GoToOverlayPermissionMessage,
                BusinessResources.Ok,
                BusinessResources.Cancel))
        {
            var intent = new Intent(Android.Provider.Settings.ActionManageOverlayPermission,
                Android.Net.Uri.Parse("package:" + Forms.Context.PackageName));
            Forms.Context.StartActivity(intent);
        }
    }
}

The user is then directed to the settings to enable the feature.


问:
Using BulkUpdateAsync or UpdateRange
Until now, I got used async methods everywhere was possible, when the subject was the dbContext. But, for updating entities, I doesn't know an async method and used UpdateRange (for entities list).

Now, I found BulkUpdateAsync(entities) and I don't see a big difference between these two methods, this accept a IEnumerable list, while UpdateRange which accept a IEnumerable.

Because using await context.SaveChangesAsync after each used version, it is necesary to use BulkUpdateAsync?

Its about .Net Core 3 and EF Core 3

答:
Only methods that actually interact with the database need to be asynchronous.

UpdateRange simply tells EF to start tracking the entities; this is done completely synchronously, in memory, and does not commit to the database.

Once you call await context.SaveChangesAsync the updates are committed to the database asynchronously.

Title: Using BulkUpdateAsync or UpdateRange


问:
Deviation to weekday and weekend mean on daily data in dataframe
I have some daily data and I wish to compute the deviation of each data point to its monthly mean but I want to distinct the monthly average between weekday and weekend.

some sample data:

```<code>import pandas as pd
import numpy as np
from datetime import datetime, timedelta
date_today = datetime.now()
days = pd.date_range(date_today, date_today + timedelta(100), freq='D')
np.random.seed(seed=1111)
data = 66*np.random.randint(1, high=100, size=len(days))/100
df = pd.DataFrame({'Date': days, 'vals': data})
df = df.set_index('Date')
print(df)
</code>```

Now if I treated all days equal I can do this:

```<code>df['valdifftoavg']= df['vals'].sub(df.resample("M")['vals'].transform('mean'))
</code>```

But I want to distinguish, so if the daily data is a weekday substract the weekday average of that month and if its a weekend, substract the weekend average of that month.

答:
I would do:</p>

```<code>is_weekend = df.index.weekday >= 5

# groupby month and is_weekend
means = (df.groupby([df.index.to_period('M'),is_weekend])
           ['vals'].transform('mean')
        )

df['deviation'] = df['vals'] - means
</code>```

Body:
I have some daily data and I wish to compute the deviation of each data point to its monthly mean but I want to distinct the monthly average between weekday and weekend.

some sample data:

import pandas as pd
import numpy as np
from datetime import datetime, timedelta
date_today = datetime.now()
days = pd.date_range(date_today, date_today + timedelta(100), freq='D')
np.random.seed(seed=1111)
data = 66*np.random.randint(1, high=100, size=len(days))/100
df = pd.DataFrame({'Date': days, 'vals': data})
df = df.set_index('Date')
print(df)

Now if I treated all days equal I can do this:

df['valdifftoavg']= df['vals'].sub(df.resample("M")['vals'].transform('mean'))

But I want to distinguish, so if the daily data is a weekday substract the weekday average of that month and if its a weekend, substract the weekend average of that month.

Body:
I would do:

is_weekend = df.index.weekday >= 5

# groupby month and is_weekend
means = (df.groupby([df.index.to_period('M'),is_weekend])
           ['vals'].transform('mean')
        )

df['deviation'] = df['vals'] - means


问:
Keras: Error when checking input of cnn model
I'm trying to create a CNN model for image classification, however, I'm getting an error with the input shape and I don´t understand why. Please, see below the code:

```<code>import pandas as pd
from keras_preprocessing.image import ImageDataGenerator
import numpy as np

#CREATING 3 DATAFRAMES FROM 3 .TXT FILES
trainingfile = pd.read_table('data/training.txt', delim_whitespace=True, names=('class', 'image'))
testingfile = pd.read_table('data/testing.txt', delim_whitespace=True, names=('class', 'image'))
validationfile = pd.read_table('data/validation.txt', delim_whitespace=True, names=('class', 'image'))
# CHANGING TYPE OF TARGET ATTRIBUTE
trainingfile = trainingfile.replace([0, 1, 2], ['class0', 'class1', 'class2'])
testingfile = testingfile.replace([0, 1, 2], ['class0', 'class1', 'class2'])
validationfile = validationfile.replace([0, 1, 2], ['class0', 'class1', 'class2'])

#DATA AUGMENTATION
datagen=ImageDataGenerator()
train_datagen = ImageDataGenerator(
    rotation_range=5,
    zoom_range=0.1)

#Generating train, test and validation datasets with RGB, Batch = 32.
train=train_datagen.flow_from_dataframe(dataframe=trainingfile, directory="data/", x_col="image", y_col="class", class_mode="categorical", target_size=(256,256),color_mode='rgb',batch_size=32)
test=datagen.flow_from_dataframe(dataframe=testingfile, directory="data/", x_col="image", y_col="class", class_mode="categorical", target_size=(256,256),color_mode='rgb',batch_size=32)
#No data augmentation to the validation set
validation=datagen.flow_from_dataframe(dataframe=validationfile, directory="data/", x_col="image", y_col="class", class_mode="categorical", target_size=(256,256),color_mode='rgb', batch_size=32)
</code>```

And now is when I start designing the CNN model:

```<code>from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten, Activation, Dropout, MaxPooling2D, BatchNormalization
from keras.constraints import maxnorm

#CNN model
model = Sequential()
model.add(Conv2D(32, kernel_size = (3, 3), activation='relu', input_shape=(32, 250, 250, 3)))
</code>```

As you can see the input_shape is 32 (batch), 250 x 250 image size and 3 channels because of RGB. However, I get the following error:

```<code>ValueError: Input 0 is incompatible with layer conv2d_1: expected ndim=4, found ndim=5
</code>```

答:
The input_shape in the convolutional layer should not include the batch dimension. Here's an excerpt from the Keras documentation:

When using [Conv2D] as the first layer in a model, provide the keyword argument input_shape (tuple of integers, does not include the sample axis), e.g. input_shape=(128, 128, 3) for 128x128 RGB pictures in data_format="channels_last".

So the solution would be to change your model definition, as below. You had another error in the input_shape -- it should be 256x256x3, not 250x250x3.

```<code>model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(256, 256, 3)))
</code>```

You do not need to specify the batch size explicitly in the model definition because it can vary.

Body:
I'm trying to create a CNN model for image classification, however, I'm getting an error with the input shape and I don´t understand why. Please, see below the code:

import pandas as pd
from keras_preprocessing.image import ImageDataGenerator
import numpy as np

#CREATING 3 DATAFRAMES FROM 3 .TXT FILES
trainingfile = pd.read_table('data/training.txt', delim_whitespace=True, names=('class', 'image'))
testingfile = pd.read_table('data/testing.txt', delim_whitespace=True, names=('class', 'image'))
validationfile = pd.read_table('data/validation.txt', delim_whitespace=True, names=('class', 'image'))
# CHANGING TYPE OF TARGET ATTRIBUTE
trainingfile = trainingfile.replace([0, 1, 2], ['class0', 'class1', 'class2'])
testingfile = testingfile.replace([0, 1, 2], ['class0', 'class1', 'class2'])
validationfile = validationfile.replace([0, 1, 2], ['class0', 'class1', 'class2'])

#DATA AUGMENTATION
datagen=ImageDataGenerator()
train_datagen = ImageDataGenerator(
    rotation_range=5,
    zoom_range=0.1)

#Generating train, test and validation datasets with RGB, Batch = 32.
train=train_datagen.flow_from_dataframe(dataframe=trainingfile, directory="data/", x_col="image", y_col="class", class_mode="categorical", target_size=(256,256),color_mode='rgb',batch_size=32)
test=datagen.flow_from_dataframe(dataframe=testingfile, directory="data/", x_col="image", y_col="class", class_mode="categorical", target_size=(256,256),color_mode='rgb',batch_size=32)
#No data augmentation to the validation set
validation=datagen.flow_from_dataframe(dataframe=validationfile, directory="data/", x_col="image", y_col="class", class_mode="categorical", target_size=(256,256),color_mode='rgb', batch_size=32)

And now is when I start designing the CNN model:

from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten, Activation, Dropout, MaxPooling2D, BatchNormalization
from keras.constraints import maxnorm

#CNN model
model = Sequential()
model.add(Conv2D(32, kernel_size = (3, 3), activation='relu', input_shape=(32, 250, 250, 3)))

As you can see the input_shape is 32 (batch), 250 x 250 image size and 3 channels because of RGB. However, I get the following error:

ValueError: Input 0 is incompatible with layer conv2d_1: expected ndim=4, found ndim=5

Body:
The input_shape in the convolutional layer should not include the batch dimension. Here's an excerpt from the Keras documentation:

When using [Conv2D] as the first layer in a model, provide the keyword argument input_shape (tuple of integers, does not include the sample axis), e.g. input_shape=(128, 128, 3) for 128x128 RGB pictures in data_format="channels_last".

So the solution would be to change your model definition, as below. You had another error in the input_shape -- it should be 256x256x3, not 250x250x3.

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(256, 256, 3)))

You do not need to specify the batch size explicitly in the model definition because it can vary.


问:
Expression Changed after it has been checked Angular
I have this input for uploading a document, and i'm trying to check if it's empty to show an alert.

This is my code:

```<code><div class="form-group">
    <input type="file" name="file" accept="application/pdf, application/msword, application/vnd.ms-powerpoint"
    (change)="onUpload($event)">
    <input type="text" #documentLink class="form-control" name="urlDocument" [value]="urlDocument | async">
</div>
<div *ngIf="!documentLink.value" class="alert alert-danger">
   Imaginea de coperta este necesara!
</div>

</code>```

I have this error:

```<code>ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.
Previous value: 'ngIf: true'. Current value: 'ngIf: false'.
</code>```

I use this viewchild to take the value

```<code>@ViewChild('documentLink', {static: false}) inputDocumentLink : ElementRef;
</code>```

and that's in my method for adding it in the database:

```<code>const link = this.inputDocumentLink.nativeElement.value;
...
</code>```

Can you help me? Thank you very much!

答:
The problem is use of async pipe and refering that value below in the template.

Remove async pipe from template

In Ts have it like

```<code>public inputValue;
ngOnInit() {
    this.getData();
}

public getData() {
   this.urlDocument.subscribe((res) => {
          this.inputValue = res;
   });
 }
</code>```

HTML :-

```<code><div class="form-group">
    <input type="file" name="file" accept="application/pdf, application/msword, application/vnd.ms-powerpoint"
    (change)="onUpload($event)">
    <input type="text" #documentLink class="form-control" name="urlDocument" [value]="inputValue">
</div>
<div *ngIf="!inputValue" class="alert alert-danger">
   Imaginea de coperta este necesara!
</div>
</code>```

Reason :- while navigating through template your url document was undefined, when it angular's another life cycle hook rechecked the template it got changed because observable emitted value. Because in normal ng serve angular does every change detection twice to let you know irregularities in your code. try running ng serve --prod and you won't get this error. But you should go with approach i gave as this error is given to avoid such irregularities.

Body:
I have this input for uploading a document, and i'm trying to check if it's empty to show an alert.

This is my code:

    <input type="file" name="file" accept="application/pdf, application/msword, application/vnd.ms-powerpoint"
    (change)="onUpload($event)">
    <input type="text" #documentLink class="form-control" name="urlDocument" [value]="urlDocument | async">

   Imaginea de coperta este necesara!

I have this error:

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.
Previous value: 'ngIf: true'. Current value: 'ngIf: false'.

I use this viewchild to take the value

@ViewChild('documentLink', {static: false}) inputDocumentLink : ElementRef;

and that's in my method for adding it in the database:

const link = this.inputDocumentLink.nativeElement.value;
...

Can you help me? Thank you very much!

Body:
The problem is use of async pipe and refering that value below in the template.

Remove async pipe from template

In Ts have it like

public inputValue;
ngOnInit() {
    this.getData();
}

public getData() {
   this.urlDocument.subscribe((res) => {
          this.inputValue = res;
   });
 }

HTML :-

<div class="form-group">
    <input type="file" name="file" accept="application/pdf, application/msword, application/vnd.ms-powerpoint"
    (change)="onUpload($event)">
    <input type="text" #documentLink class="form-control" name="urlDocument" [value]="inputValue">
</div>
<div *ngIf="!inputValue" class="alert alert-danger">
   Imaginea de coperta este necesara!
</div>

Reason :- while navigating through template your url document was undefined, when it angular's another life cycle hook rechecked the template it got changed because observable emitted value. Because in normal ng serve angular does every change detection twice to let you know irregularities in your code. try running ng serve --prod and you won't get this error. But you should go with approach i gave as this error is given to avoid such irregularities.


问:
Empty Square Brackets in Javascript?
I came across this code in https://upmostly.com/tutorials/setinterval-in-react-components-using-hooks:

```<code>useEffect(() => {
  const interval = setInterval(() => {
    console.log('This will run every second!');
  }, 1000);
  return () => clearInterval(interval);
}, []);
</code>```

I am curious what the square brackets [] at the end do? According to this site https://reactjs.org/docs/hooks-effect.html, we can use useEffect() without them.

答:
See the documentation:

We don’t need to create a new subscription on every update, only if the source prop has changed.

...

pass a second argument to useEffect that is the array of values that the effect depends on.

...

If you pass an empty array ([]), the props and state inside the effect will always have their initial values. While passing [] as the second argument is closer to the familiar componentDidMount and componentWillUnmount mental model, there are usually better solutions to avoid re-running effects too often.

Title: Empty Square Brackets in Javascript?

Body:
I came across this code in https://upmostly.com/tutorials/setinterval-in-react-components-using-hooks:

useEffect(() => {
  const interval = setInterval(() => {
    console.log('This will run every second!');
  }, 1000);
  return () => clearInterval(interval);
}, []);

I am curious what the square brackets [] at the end do? According to this site https://reactjs.org/docs/hooks-effect.html, we can use useEffect() without them.


问:
Date time format in PowerShell returning incorrect date in powershell
I want to change text 11.30 to time format 11:30 using [datetime] in powershell

```<code>$Stime = "11.30"
$time = "{00:hh:mm}" -f [datetime]$Stime
Write-Host $time
</code>```

This code returns value 12:00

I tried this too -

```<code>$fromtime = "11.30"
[datetime]$fromtime12hrFormat = ([datetime]$fromtime)
$fromtime12hrFormat.ToString("hh:mm:ss")
</code>```

This code returns value 12:00

答:
"11.30" cast to [datetime] with en-US locale will be interpreted as "November 30" at midnight.

Use DateTime.ParseExact() instead:

```<code>'{0:HH:mm}' -f [datetime]::ParseExact($Stime, 'HH.mm', $null)
</code>```

Body:
I want to change text 11.30 to time format 11:30 using [datetime] in powershell

$Stime = "11.30"
$time = "{00:hh:mm}" -f [datetime]$Stime
Write-Host $time

This code returns value 12:00

I tried this too -

$fromtime = "11.30"
[datetime]$fromtime12hrFormat = ([datetime]$fromtime)
$fromtime12hrFormat.ToString("hh:mm:ss")

This code returns value 12:00

Body:
"11.30" cast to [datetime] with en-US locale will be interpreted as "November 30" at midnight.

Use DateTime.ParseExact() instead:

'{0:HH:mm}' -f [datetime]::ParseExact($Stime, 'HH.mm', $null)


问:
How to print a word from list upon executing a bot command
So I have this list of some cars below, and when I type in !car, the bot should be able to send only one word from the list but in an embedded message.
So every time I type in this command, the bot sends a single word, until it reaches the end of the list (ascending order).

Example:

List of cars: BMW, Mercedes, Porsche, Honda, Pontiac

User: !car

Bot: BMW

User: !car

Bot: Mercedes

Etc...

Here's my code: How can I modify it to fulfill my request?

```<code>import discord

client = discord.Client()

@client.event
async def on_message(message):

    cars = ['BMW', 'Mercedes', 'Porsche', 'Honda', 'Pontiac']

    if message.content == '!car'
        embed = discord.Embed(title=cars, description=None, color=0xfffb00)
        # It prints the whole list, I would like only one word from the list.
        await message.channel.send(content=None, embed=embed)

client.run('token')
</code>```

Any help would be appreciated

答:
I have no knowledge about how discord works, but if you want to randomly select an element from the list you can use random.choice()

```<code>import random
cars = ['BMW', 'Mercedes', 'Porsche', 'Honda', 'Pontiac']

print(random.choice(cars))
</code>```

This will give you a random car name from the list each time.

Body:
So I have this list of some cars below, and when I type in !car, the bot should be able to send only one word from the list but in an embedded message.
So every time I type in this command, the bot sends a single word, until it reaches the end of the list (ascending order).

Example:

List of cars: BMW, Mercedes, Porsche, Honda, Pontiac

User: !car

Bot: BMW

User: !car

Bot: Mercedes

Etc...

Here's my code: How can I modify it to fulfill my request?

import discord

client = discord.Client()

@client.event
async def on_message(message):

    cars = ['BMW', 'Mercedes', 'Porsche', 'Honda', 'Pontiac']

    if message.content == '!car'
        embed = discord.Embed(title=cars, description=None, color=0xfffb00)
        # It prints the whole list, I would like only one word from the list.
        await message.channel.send(content=None, embed=embed)

client.run('token')

Any help would be appreciated

Body:
I have no knowledge about how discord works, but if you want to randomly select an element from the list you can use random.choice()

import random
cars = ['BMW', 'Mercedes', 'Porsche', 'Honda', 'Pontiac']

print(random.choice(cars))

This will give you a random car name from the list each time.


问:
npm ERR! Unexpected end of JSON input while parsing near '...ersion: OpenPGP.js v3' getting this error while installing create-react-app and aborting
npm ERR! Unexpected end of JSON input while parsing near '...ersion: OpenPGP.js v3' getting this error while installing create-react-app and aborting

答:
I had the same issue, and the answers in this question helped me.

source issue: Error installing reactjs: Error unexpected end of JSON input while parsing near

I just needed to run the following command

npm cache clean --force