text:
Q: How can I check if an ip is in a network in Python? Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?
Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.

A: I'm not a fan of using modules when they are not needed.  This job only requires simple math, so here is my simple function to do the job:
def ipToInt(ip):
    o = map(int, ip.split('.'))
    res = (16777216 * o[0]) + (65536 * o[1]) + (256 * o[2]) + o[3]
    return res

def isIpInSubnet(ip, ipNetwork, maskLength):
    ipInt = ipToInt(ip)#my test ip, in int form

    maskLengthFromRight = 32 - maskLength

    ipNetworkInt = ipToInt(ipNetwork) #convert the ip network into integer form
    binString = "{0:b}".format(ipNetworkInt) #convert that into into binary (string format)

    chopAmount = 0 #find out how much of that int I need to cut off
    for i in range(maskLengthFromRight):
        if i < len(binString):
            chopAmount += int(binString[len(binString)-1-i]) * 2**i

    minVal = ipNetworkInt-chopAmount
    maxVal = minVal+2**maskLengthFromRight -1

    return minVal <= ipInt and ipInt <= maxVal

Then to use it:
>>> print isIpInSubnet('66.151.97.0', '66.151.97.192',24)
True
>>> print isIpInSubnet('66.151.97.193', '66.151.97.192',29)
True
>>> print isIpInSubnet('66.151.96.0', '66.151.97.192',24)
False
>>> print isIpInSubnet('66.151.97.0', '66.151.97.192',29)

That's it, this is much faster than the solutions above with the included modules.

A: I tried Dave Webb's solution but hit some problems:
Most fundamentally - a match should be checked by ANDing the IP address with the mask, then checking the result matched the Network address exactly. Not ANDing the IP address with the Network address as was done.
I also noticed that just ignoring the Endian behaviour assuming that consistency will save you will only work for masks on octet boundaries (/24, /16). In order to get other masks (/23, /21) working correctly I added a "greater than" to the struct commands and changed the code for creating the binary mask to start with all "1" and shift left by (32-mask).
Finally, I added a simple check that the network address is valid for the mask and just print a warning if it is not.
Here's the result:
def addressInNetwork(ip,net):
    "Is an address in a network"
    ipaddr = struct.unpack('>L',socket.inet_aton(ip))[0]
    netaddr,bits = net.split('/')
    netmask = struct.unpack('>L',socket.inet_aton(netaddr))[0]
    ipaddr_masked = ipaddr & (4294967295<<(32-int(bits)))   # Logical AND of IP address and mask will equal the network address if it matches
    if netmask == netmask & (4294967295<<(32-int(bits))):   # Validate network address is valid for mask
            return ipaddr_masked == netmask
    else:
            print "***WARNING*** Network",netaddr,"not valid with mask /"+bits
            return ipaddr_masked == netmask

A: Not in the Standard library for 2.5, but ipaddr makes this very easy. I believe it is in 3.3 under the name ipaddress.
import ipaddr

a = ipaddr.IPAddress('192.168.0.1')
n = ipaddr.IPNetwork('192.168.0.0/24')

#This will return True
n.Contains(a)

A: For python3
import ipaddress
ipaddress.IPv4Address('192.168.1.1') in ipaddress.IPv4Network('192.168.0.0/24')
ipaddress.IPv4Address('192.168.1.1') in ipaddress.IPv4Network('192.168.0.0/16')

Output :
False
True

A: Marc's code is nearly correct. A complete version of the code is -
def addressInNetwork3(ip,net):
    '''This function allows you to check if on IP belogs to a Network'''
    ipaddr = struct.unpack('=L',socket.inet_aton(ip))[0]
    netaddr,bits = net.split('/')
    netmask = struct.unpack('=L',socket.inet_aton(calcDottedNetmask(int(bits))))[0]
    network = struct.unpack('=L',socket.inet_aton(netaddr))[0] & netmask
    return (ipaddr & netmask) == (network & netmask)

def calcDottedNetmask(mask):
    bits = 0
    for i in xrange(32-mask,32):
        bits |= (1 << i)
    return "%d.%d.%d.%d" % ((bits & 0xff000000) >> 24, (bits & 0xff0000) >> 16, (bits & 0xff00) >> 8 , (bits & 0xff))

Obviously from the same sources as above...
A very Important note is that the first code has a small glitch - The IP address 255.255.255.255 also shows up as a Valid IP for any subnet. I had a heck of time getting this code to work and thanks to Marc for the correct answer.

A: Relying on the "struct" module can cause problems with endian-ness and type sizes, and just isn't needed. Nor is socket.inet_aton(). Python works very well with dotted-quad IP addresses:
def ip_to_u32(ip):
  return int(''.join('%02x' % int(d) for d in ip.split('.')), 16)

I need to do IP matching on each socket accept() call, against a whole set of allowable source networks, so I precompute masks and networks, as integers:
SNS_SOURCES = [
  # US-EAST-1
  '207.171.167.101',
  '207.171.167.25',
  '207.171.167.26',
  '207.171.172.6',
  '54.239.98.0/24',
  '54.240.217.16/29',
  '54.240.217.8/29',
  '54.240.217.64/28',
  '54.240.217.80/29',
  '72.21.196.64/29',
  '72.21.198.64/29',
  '72.21.198.72',
  '72.21.217.0/24',
  ]

def build_masks():
  masks = [ ]
  for cidr in SNS_SOURCES:
    if '/' in cidr:
      netstr, bits = cidr.split('/')
      mask = (0xffffffff << (32 - int(bits))) & 0xffffffff
      net = ip_to_u32(netstr) & mask
    else:
      mask = 0xffffffff
      net = ip_to_u32(cidr)
    masks.append((mask, net))
  return masks

Then I can quickly see if a given IP is within one of those networks:
ip = ip_to_u32(ipstr)
for mask, net in cached_masks:
  if ip & mask == net:
    # matched!
    break
else:
  raise BadClientIP(ipstr)

No module imports needed, and the code is very fast at matching.

A: As of Python 3.7, you can use subnet_of and supernet_of helper methods, which are part of the standard library:
To just test against a single IP, you can just use the subnet mask /32 which means "only this IP address" as a subnet, or you can pass the IP address to IPv4Nework or IPv6Nework constructors and they will return a subnet value for you.
So for your example:
from ipaddress import IPv4Network, IPv4Address

# Store IP Address as variable
>>> myip = IPv4Address('192.168.0.1')
>>> myip
IPv4Address('192.168.0.1')

# This treats the IP as a subnet
>>> myip_subnet = IPv4Network(myip)
>>> myip_subnet
IPv4Network('192.168.0.1/32')

# The other subnet to test membership against
>>> other_subnet = IPv4Network('192.168.0.0/24')
>>> other_subnet
IPv4Network('192.168.0.0/24')

# Now we can test
>>> myip_subnet.subnet_of(other_subnet)
True

Are there general tools in Python for ip address manipulation? Stuff
like host lookups, ip adddress to int, network address with netmask to
int and so on? Hopefully in the standard Python library for 2.5.

In Python 3, there's the ipaddress module which has tools for IPv4 and IPv6 manipulation. You can convert them to an int, by casting, i.e. int(IPv4Address('192.168.0.1')).  Lots of other useful functions in the ipaddress module for hosts, etc.

A: The choosen answer has a bug.
Following is the correct code:
def addressInNetwork(ip, net_n_bits):
   ipaddr = struct.unpack('<L', socket.inet_aton(ip))[0]
   net, bits = net_n_bits.split('/')
   netaddr = struct.unpack('<L', socket.inet_aton(net))[0]
   netmask = ((1L << int(bits)) - 1)
   return ipaddr & netmask == netaddr & netmask

Note: ipaddr & netmask == netaddr & netmask instead of ipaddr & netmask == netmask.
I also replace ((2L<<int(bits)-1) - 1) with ((1L << int(bits)) - 1), as the latter seems more understandable.

A: This article shows you can do it with socket and struct modules without too much extra effort.  I added a little to the article as follows:
import socket,struct

def makeMask(n):
    "return a mask of n bits as a long integer"
    return (2L<<n-1) - 1

def dottedQuadToNum(ip):
    "convert decimal dotted quad string to long integer"
    return struct.unpack('L',socket.inet_aton(ip))[0]

def networkMask(ip,bits):
    "Convert a network address to a long integer"
    return dottedQuadToNum(ip) & makeMask(bits)

def addressInNetwork(ip,net):
   "Is an address in a network"
   return ip & net == net

address = dottedQuadToNum("192.168.1.1")
networka = networkMask("10.0.0.0",24)
networkb = networkMask("192.168.0.0",24)
print (address,networka,networkb)
print addressInNetwork(address,networka)
print addressInNetwork(address,networkb)

This outputs:
False
True

If you just want a single function that takes strings it would look like this:
import socket,struct

def addressInNetwork(ip,net):
   "Is an address in a network"
   ipaddr = struct.unpack('L',socket.inet_aton(ip))[0]
   netaddr,bits = net.split('/')
   netmask = struct.unpack('L',socket.inet_aton(netaddr))[0] & ((2L<<int(bits)-1) - 1)
   return ipaddr & netmask == netmask

A: Using Python >= 3.7 ipaddress:
import ipaddress

address = ipaddress.ip_address("192.168.0.1")
network = ipaddress.ip_network("192.168.0.0/16")

print(network.supernet_of(ipaddress.ip_network(f"{address}/{address.max_prefixlen}")))

Explanation
You can think of an IP Address as a Network with the largest possible netmask (/32 for IPv4, /128 for IPv6)
Checking whether 192.168.0.1 is in 192.168.0.0/16 is essentially the same as checking whether 192.168.0.1/32 is a subnet of 192.168.0.0/16

A: from netaddr import all_matching_cidrs
>>> from netaddr import all_matching_cidrs
>>> all_matching_cidrs("212.11.70.34", ["192.168.0.0/24","212.11.64.0/19"] )
[IPNetwork('212.11.64.0/19')]

Here is the usage for this method:
>>> help(all_matching_cidrs)

Help on function all_matching_cidrs in module netaddr.ip:

all_matching_cidrs(ip, cidrs)
    Matches an IP address or subnet against a given sequence of IP addresses and subnets.

    @param ip: a single IP address or subnet.

    @param cidrs: a sequence of IP addresses and/or subnets.

    @return: all matching IPAddress and/or IPNetwork objects from the provided
    sequence, an empty list if there was no match.

Basically you provide an ip address as the first argument and a list of cidrs as the second argument.  A list of hits are returned.

A:
#This works properly without the weird byte by byte handling
def addressInNetwork(ip,net):
    '''Is an address in a network'''
    # Convert addresses to host order, so shifts actually make sense
    ip = struct.unpack('>L',socket.inet_aton(ip))[0]
    netaddr,bits = net.split('/')
    netaddr = struct.unpack('>L',socket.inet_aton(netaddr))[0]
    # Must shift left an all ones value, /32 = zero shift, /0 = 32 shift left
    netmask = (0xffffffff &lt&lt (32-int(bits))) & 0xffffffff
    # There's no need to mask the network address, as long as its a proper network address
    return (ip & netmask) == netaddr

A: Here is a class I wrote for longest prefix matching:
#!/usr/bin/env python

class Node:
def __init__(self):
    self.left_child = None
    self.right_child = None
    self.data = "-"

def setData(self, data): self.data = data
def setLeft(self, pointer): self.left_child = pointer
def setRight(self, pointer): self.right_child = pointer
def getData(self): return self.data
def getLeft(self): return self.left_child
def getRight(self): return self.right_child

def __str__(self):
        return "LC: %s RC: %s data: %s" % (self.left_child, self.right_child, self.data)

class LPMTrie:

def __init__(self):
    self.nodes = [Node()]
    self.curr_node_ind = 0

def addPrefix(self, prefix):
    self.curr_node_ind = 0
    prefix_bits = ''.join([bin(int(x)+256)[3:] for x in prefix.split('/')[0].split('.')])
    prefix_length = int(prefix.split('/')[1])
    for i in xrange(0, prefix_length):
        if (prefix_bits[i] == '1'):
            if (self.nodes[self.curr_node_ind].getRight()):
                self.curr_node_ind = self.nodes[self.curr_node_ind].getRight()
            else:
                tmp = Node()
                self.nodes[self.curr_node_ind].setRight(len(self.nodes))
                tmp.setData(self.nodes[self.curr_node_ind].getData());
                self.curr_node_ind = len(self.nodes)
                self.nodes.append(tmp)
        else:
            if (self.nodes[self.curr_node_ind].getLeft()):
                self.curr_node_ind = self.nodes[self.curr_node_ind].getLeft()
            else:
                tmp = Node()
                self.nodes[self.curr_node_ind].setLeft(len(self.nodes))
                tmp.setData(self.nodes[self.curr_node_ind].getData());
                self.curr_node_ind = len(self.nodes)
                self.nodes.append(tmp)

        if i == prefix_length - 1 :
            self.nodes[self.curr_node_ind].setData(prefix)

def searchPrefix(self, ip):
    self.curr_node_ind = 0
    ip_bits = ''.join([bin(int(x)+256)[3:] for x in ip.split('.')])
    for i in xrange(0, 32):
        if (ip_bits[i] == '1'):
            if (self.nodes[self.curr_node_ind].getRight()):
                self.curr_node_ind = self.nodes[self.curr_node_ind].getRight()
            else:
                return self.nodes[self.curr_node_ind].getData()
        else:
            if (self.nodes[self.curr_node_ind].getLeft()):
                self.curr_node_ind = self.nodes[self.curr_node_ind].getLeft()
            else:
                return self.nodes[self.curr_node_ind].getData()

    return None

def triePrint(self):
    n = 1
    for i in self.nodes:
        print n, ':'
        print i
        n += 1

And here is a test program:
n=LPMTrie()
n.addPrefix('10.25.63.0/24')
n.addPrefix('10.25.63.0/16')
n.addPrefix('100.25.63.2/8')
n.addPrefix('100.25.0.3/16')
print n.searchPrefix('10.25.63.152')
print n.searchPrefix('100.25.63.200')
#10.25.63.0/24
#100.25.0.3/16

A: previous solution have a bug in ip & net == net. Correct ip lookup is ip & netmask = net
bugfixed code:
import socket
import struct

def makeMask(n):
    "return a mask of n bits as a long integer"
    return (2L<<n-1) - 1

def dottedQuadToNum(ip):
    "convert decimal dotted quad string to long integer"
    return struct.unpack('L',socket.inet_aton(ip))[0]

def addressInNetwork(ip,net,netmask):
   "Is an address in a network"
   print "IP "+str(ip) + " NET "+str(net) + " MASK "+str(netmask)+" AND "+str(ip & netmask)
   return ip & netmask == net

def humannetcheck(ip,net):
        address=dottedQuadToNum(ip)
        netaddr=dottedQuadToNum(net.split("/")[0])
        netmask=makeMask(long(net.split("/")[1]))
        return addressInNetwork(address,netaddr,netmask)

print humannetcheck("192.168.0.1","192.168.0.0/24");
print humannetcheck("192.169.0.1","192.168.0.0/24");

A: Using ipaddress (in the stdlib since 3.3, at PyPi for 2.6/2.7):
>>> import ipaddress
>>> ipaddress.ip_address('192.168.0.1') in ipaddress.ip_network('192.168.0.0/24')
True

If you want to evaluate a lot of IP addresses this way, you'll probably want to calculate the netmask upfront, like
n = ipaddress.ip_network('192.0.0.0/16')
netw = int(n.network_address)
mask = int(n.netmask)

Then, for each address, calculate the binary representation with one of
a = int(ipaddress.ip_address('192.0.43.10'))
a = struct.unpack('!I', socket.inet_pton(socket.AF_INET, '192.0.43.10'))[0]
a = struct.unpack('!I', socket.inet_aton('192.0.43.10'))[0]  # IPv4 only

Finally, you can simply check:
in_network = (a & mask) == netw

A: I like to use netaddr for that:
from netaddr import CIDR, IP

if IP("192.168.0.1") in CIDR("192.168.0.0/24"):
    print "Yay!"

As arno_v pointed out in the comments, new version of netaddr does it like this:
from netaddr import IPNetwork, IPAddress
if IPAddress("192.168.0.1") in IPNetwork("192.168.0.0/24"):
    print "Yay!"

A: This code is working for me on Linux x86.  I haven't really given any thought to endianess issues, but I have tested it against the "ipaddr" module using over 200K IP addresses tested against 8 different network strings, and the results of ipaddr are the same as this code.
def addressInNetwork(ip, net):
   import socket,struct
   ipaddr = int(''.join([ '%02x' % int(x) for x in ip.split('.') ]), 16)
   netstr, bits = net.split('/')
   netaddr = int(''.join([ '%02x' % int(x) for x in netstr.split('.') ]), 16)
   mask = (0xffffffff << (32 - int(bits))) & 0xffffffff
   return (ipaddr & mask) == (netaddr & mask)

Example:
>>> print addressInNetwork('10.9.8.7', '10.9.1.0/16')
True
>>> print addressInNetwork('10.9.8.7', '10.9.1.0/24')
False

A: Wherever possible I'd recommend the built in ipaddress module. It's only available in Python 3 though, but it is super easy to use, and supports IPv6. And why aren't you using Python 3 yet anyway, right?

The accepted answer doesn't work ... which is making me angry. Mask is backwards and doesn't work with any bits that are not a simple 8 bit block (eg /24). I adapted the answer, and it works nicely.
    import socket,struct

    def addressInNetwork(ip, net_n_bits):
      ipaddr = struct.unpack('!L', socket.inet_aton(ip))[0]
      net, bits = net_n_bits.split('/')
      netaddr = struct.unpack('!L', socket.inet_aton(net))[0]
      netmask = (0xFFFFFFFF >> int(bits)) ^ 0xFFFFFFFF
      return ipaddr & netmask == netaddr

here is a function that returns a dotted binary string to help visualize the masking.. kind of like ipcalc output.
    def bb(i):
     def s = '{:032b}'.format(i)
     def return s[0:8]+"."+s[8:16]+"."+s[16:24]+"."+s[24:32]

eg:

A: I don't know of anything in the standard library, but PySubnetTree is a Python library that will do subnet matching.

A: Thank you for your script!
I have work quite a long on it to make everything working... So I'm sharing it here

*

*Using netaddr Class is 10 times slower than using binary conversion, so if you'd like to use it on a big list of IP, you should consider not using netaddr class

*makeMask function is not working! Only working for /8,/16,/24 Ex:

bits = "21" ; socket.inet_ntoa(struct.pack('=L',(2L << int(bits)-1) - 1))
  '255.255.31.0' whereas it should be 255.255.248.0

So I have used another function calcDottedNetmask(mask) from  http://code.activestate.com/recipes/576483-convert-subnetmask-from-cidr-notation-to-dotdecima/
Ex:

#!/usr/bin/python
>>> calcDottedNetmask(21)
>>> '255.255.248.0'

*

*Another problem is the process of matching if an IP belongs to a network! Basic Operation should be to compare (ipaddr & netmask) and (network & netmask).Ex: for the time being, the function is wrong

#!/usr/bin/python
>>> addressInNetwork('188.104.8.64','172.16.0.0/12')
>>>True which is completely WRONG!!

So my new addressInNetwork function looks-like:

#!/usr/bin/python
import socket,struct
def addressInNetwork(ip,net):
    '''This function allows you to check if on IP belogs to a Network'''
    ipaddr = struct.unpack('=L',socket.inet_aton(ip))[0]
    netaddr,bits = net.split('/')
    netmask = struct.unpack('=L',socket.inet_aton(calcDottedNetmask(bits)))[0]
    network = struct.unpack('=L',socket.inet_aton(netaddr))[0] & netmask
    return (ipaddr & netmask) == (network & netmask)

def calcDottedNetmask(mask):
    bits = 0
    for i in xrange(32-int(mask),32):
        bits |= (1 > 24, (bits & 0xff0000) >> 16, (bits & 0xff00) >> 8 , (bits & 0xff))

And now, answer is right!!

#!/usr/bin/python
>>> addressInNetwork('188.104.8.64','172.16.0.0/12')
False

I hope that it will help other people, saving time for them!

A: Relating to all of the above, I think socket.inet_aton() returns bytes in network order, so the correct way to unpack them is probably
struct.unpack('!L', ... )

A: import socket,struct
def addressInNetwork(ip,net):
    "Is an address in a network"
    ipaddr = struct.unpack('!L',socket.inet_aton(ip))[0]
    netaddr,bits = net.split('/')
    netaddr = struct.unpack('!L',socket.inet_aton(netaddr))[0]
    netmask = ((1<<(32-int(bits))) - 1)^0xffffffff
    return ipaddr & netmask == netaddr & netmask
print addressInNetwork('10.10.10.110','10.10.10.128/25')
print addressInNetwork('10.10.10.110','10.10.10.0/25')
print addressInNetwork('10.10.10.110','10.20.10.128/25')

$ python check-subnet.py
False
True
False

A: From various sources above, and from my own research, this is how I got subnet and address calculation working.  These pieces are enough to solve the question and other related questions.
class iptools:
    @staticmethod
    def dottedQuadToNum(ip):
        "convert decimal dotted quad string to long integer"
        return struct.unpack('>L', socket.inet_aton(ip))[0]

    @staticmethod
    def numToDottedQuad(n):
        "convert long int to dotted quad string"
        return socket.inet_ntoa(struct.pack('>L', n))

    @staticmethod
    def makeNetmask(mask):
        bits = 0
        for i in xrange(32-int(mask), 32):
            bits |= (1 << i)
        return bits

    @staticmethod
    def ipToNetAndHost(ip, maskbits):
        "returns tuple (network, host) dotted-quad addresses given"
        " IP and mask size"
        # (by Greg Jorgensen)
        n = iptools.dottedQuadToNum(ip)
        m = iptools.makeMask(maskbits)
        net = n & m
        host = n - mask
        return iptools.numToDottedQuad(net), iptools.numToDottedQuad(host)

A: There is an API that's called SubnetTree available in python that do this job very well.
This is a simple example :
import SubnetTree
t = SubnetTree.SubnetTree()
t.insert("10.0.1.3/32")
print("10.0.1.3" in t)

This is the link

A: Here is my code
# -*- coding: utf-8 -*-
import socket

class SubnetTest(object):
    def __init__(self, network):
        self.network, self.netmask = network.split('/')
        self._network_int = int(socket.inet_aton(self.network).encode('hex'), 16)
        self._mask = ((1L << int(self.netmask)) - 1) << (32 - int(self.netmask))
        self._net_prefix = self._network_int & self._mask

    def match(self, ip):
        '''
        判断传入的 IP 是不是本 Network 内的 IP
        '''
        ip_int = int(socket.inet_aton(ip).encode('hex'), 16)
        return (ip_int & self._mask) == self._net_prefix

st = SubnetTest('100.98.21.0/24')
print st.match('100.98.23.32')

A: If you do not want to import other modules you could go with:
def ip_matches_network(self, network, ip):
    """
    '{:08b}'.format(254): Converts 254 in a string of its binary representation

    ip_bits[:net_mask] == net_ip_bits[:net_mask]: compare the ip bit streams

    :param network: string like '192.168.33.0/24'
    :param ip: string like '192.168.33.1'
    :return: if ip matches network
    """
    net_ip, net_mask = network.split('/')
    net_mask = int(net_mask)
    ip_bits = ''.join('{:08b}'.format(int(x)) for x in ip.split('.'))
    net_ip_bits = ''.join('{:08b}'.format(int(x)) for x in net_ip.split('.'))
    # example: net_mask=24 -> compare strings at position 0 to 23
    return ip_bits[:net_mask] == net_ip_bits[:net_mask]

A: I tried one subset of proposed solutions in these answers.. with no success, I finally adapted and fixed the proposed code and wrote my fixed function.
I tested it and works at least on little endian architectures--e.g.x86-- if anyone likes to try on a big endian architecture, please give me feedback.
IP2Int code comes from this post, the other method is a fully (for my test cases) working fix of previous proposals in this question.
The code:
def IP2Int(ip):
    o = map(int, ip.split('.'))
    res = (16777216 * o[0]) + (65536 * o[1]) + (256 * o[2]) + o[3]
    return res

def addressInNetwork(ip, net_n_bits):
    ipaddr = IP2Int(ip)
    net, bits = net_n_bits.split('/')
    netaddr = IP2Int(net)
    bits_num = int(bits)
    netmask = ((1L << bits_num) - 1) << (32 - bits_num)
    return ipaddr & netmask == netaddr & netmask

Hope useful,

A: Here is the solution using netaddr package
from netaddr import IPNetwork, IPAddress

def network_has_ip(network, ip):

    if not isinstance(network, IPNetwork):
        raise Exception("network parameter must be {0} instance".format(IPNetwork.__name__))

    if not isinstance(ip, IPAddress):
        raise Exception("ip parameter must be {0} instance".format(IPAddress.__name__))

    return (network.cidr.ip.value & network.netmask.value) == (ip.value & network.netmask.value)

A: To avoid having builtin or third party modules change their syntax over time, I created my own that does this. I'm using this as an importable module. I hope this helps someone:

def subnet_lookup(subnet: str, netmask: str, ip_address: str):
    """
    :param subnet: subnet to test against (as string)
    :param netmask: mask of subnet
    :param ip_address: ip to test against subnet and mask

    :return True if a match; False if not a match

    Steps:

    1) convert entire subnet into one binary word
    2) convert entire mask into one binary word
    3) determine bcast from comparing subnet and mask
    4) convert entire ip_address into one binary word
    5) convert entire subnet into decimal
    6) convert entire bcast into decimal
    7) convert entire ip_address into decimal
    8) determine if ip_address falls between subnet and bcast using range(); returns True if yes, False if no
    """

    def convert_whole_to_bin(whole):
        ip_dec_list = whole.split(".")
        ip_bin_str = ""

        for ip in ip_dec_list:
            binary = dec_to_bin(int(ip))
            ip_bin_str += binary

        return ip_bin_str

    def dec_to_bin(decimal_octet: int):
        binary = bin(decimal_octet).replace("0b", "")

        return binary.rjust(8, '0')

    def split_binary_into_list(binary_octet: str):
        bin_list = []
        for s in binary_octet:
            bin_list.append(s)

        return bin_list

    def determine_bcast(subnet, netmask):
        subnet_split = split_binary_into_list(subnet)
        netmask_split = split_binary_into_list(netmask)
        bcast_list = []

        for subnet, mask in zip(subnet_split, netmask_split):
            if mask != '0':
                bcast_list.append(subnet)

            else:
                bcast_list.append('1')

        bcast_bin = "".join(bcast_list)

        return bcast_bin

    def bin_to_dec(binary_single_word: str):
        decimal = int(binary_single_word, 2)

        return decimal

    def subnet_lookup(ip_address, subnet, bcast):

        return ip_address in range(subnet, bcast + 1)

    # 1) convert entire subnet into one binary word
    subnet_single_bin = convert_whole_to_bin(whole=subnet)

    # 2) convert entire mask into one binary word
    mask_single_bin = convert_whole_to_bin(whole=netmask)

    # 3) determine bcast from comparing subnet and mask
    bcast_single_bin = determine_bcast(subnet=subnet_single_bin, netmask=mask_single_bin)

    # 4) convert entire ip_address into one binary word
    ip_address_single_bin = convert_whole_to_bin(whole=ip_address)

    # 5) convert entire subnet into decimal
    subnet_single_dec = bin_to_dec(binary_single_word=subnet_single_bin)

    # 6) convert entire bcast into decimal
    bcast_single_dec = bin_to_dec(binary_single_word=bcast_single_bin)

    # 7) convert entire ip_address into decimal
    ip_address_single_dec = bin_to_dec(binary_single_word=ip_address_single_bin)

    # 8) determine if ip_address falls between subnet and bcast; returns True if yes, False if no
    lookup_result = subnet_lookup(ip_address=ip_address_single_dec, subnet=subnet_single_dec, bcast=bcast_single_dec)

    return lookup_result

# Testing:

subnet = "172.16.0.0"
netmask = "255.255.0.0"
ip_address = "172.16.255.255"

result = subnet_lookup(subnet=subnet, netmask=netmask, ip_address=ip_address)

print(result)


text:
Q: How do you change the date format when modifying an event in Calendar? I would to change the date format when modifying an event in Calendar. Currently, Calendar shows the date as 12/10/2020 when I go to modify the date/time. This is the same as is displayed above the calendar preview in System Preferences → Date & Time.
My formats in System Preferences → Language & Region → Advanced... → Dates are the following:
Short  : 2020-06-01
Medium : 01 Jun 2020
Long   : 01 June 2020
Full   : Monday, 1 June 2020

Calendar seems to be using the Medium format when creating a new Event. In Calendar, if I right click → New Event, the date is displayed as 10 Dec 2020 13:00 to 14:00.

However, when I click on that line to modify the date/time, the window changes to
starts  : 12/10/2020 13:00
ends    : 12/10/2020 14:00

Where is Calendar getting the format of month/day/year from? In Calendar → Preferences, I could not find a way to change this, as the only preferences there are things like the Days per week, Start week on, and how many hours to display at once.
I am on macOS Catalina 10.15.7.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to check if a two dimensional Array contains only digits I got a two dimensional String array with only numbers in it;
System.out.println(Arrays.deepToString(temp));
[[1, 3, 1, 2], [2, 3, 2, 2], [5, 6, 7, 1], [3, 3, 1, 1]]

I need to check if the array contains only numbers, otherwise I will throw an exception.
System.out.println(Arrays.deepToString(temp[0]).matches("[0-9]*")); - return false
System.out.println(Arrays.deepToString(temp[0]).matches("[0-9]+")); - return false

As far as I get, The code says that the array does not contains only numbers, because when converted to char the array is like :
[[, [, 1, ,,  , 3, ,,  , 1, ,,  , 2, ], ,,  , [, 2, ,,  , 3, ,,  , 2, ,,  , 2, ], ,,  , [, 5, ,,  , 6, ,,  , 7, ,,  , 1, ], ,,  , [, 3, ,,  , 3, ,,  , 1, ,,  , 1, ], ]]

How can I check if it contains only numbers?

A: You should first loop through your array. Since each element will be an array, loop through it. Then for each element (that should be a String) check if it's what you want.
To loop through your Array of arrays :
boolean arrayIsCorrect = true; //flag to know if array is correct
for(int i=0; i<array.length; i++) { //loop through the array of arrays
    for(int j=0; j<array[i].length; j++) { //loop through the sub-array array[i]
        if(!isCorrect(array[i][j])) {
            arrayIsCorrect = false;
            break; //optimization not required
        }
    }
    if(!arrayIsCorrect) { //optimization not required
        break;
    }
}
System.out.println("Is the array correct ? " + arrayIsCorrect ); //print the result

In your question it's not clear if you want elements to be digit or numbers. In case of digit the function isCorrect() should look like :
public boolean isCorrect(String s) {
    return s.matches("[0-9]");
}

In case of number, check this answer

A: I would make a function that checks if it is numeric.
Something like this:
for(int i = 0; i < array.size();i++){
    for(int j = 0; j < array.size();j++){
        if(temp.isNumeric(temp[i][j] == false)
        break;
    }
}

public static boolean isNumeric(String value) {
    boolean result;
    try {
        Integer.parseInt(value);
        result = true;
    } catch (NumberFormatException excepcion) {
        result = false;
    }
    return result;
}


text:
Q: Rails incorrect action call I have some simple actions which I want to call via js but got strange error, here is my code:
Controller:
class Admin::CEventsController < Admin::BaseController
  def add_speaker
    # speakers = session[:speakers] ? [] : session[:speakers]
    # speakers << Partner.find(params[:id])
    # session[:speakers] << speakers.uniq
    # @speakers = Partner.find(session[:speakers])
    # puts @speakers.inspect
  end

  def remove_speaker
    # speakers = session[:speakers]
    # speakers.destroy(params[:id])
    # session[:speakers] = speakers
    # @speakers = Partner.find(session[:speakers])
  end
end

Routes:
resources :c_events,         :except => [:show] do
      member do
        post :add_speaker
        post :remove_speaker
      end
    end

View:

    <% speakers.each do |p| %>

<%= link_to p.name remove_speaker_admin_c_event_path(p), :method => :post, :remote => true %>

    <% end %>

    <% Partner.all.each do |p| %>

<%= link_to p.name, add_speaker_admin_c_event_path(p), :method => :post, :remote => true %>

    <% end %>

I commented some of actions code just to try to find the problem.
The error I got is:

Started POST "/admin/c_events/2/add_speaker" for 127.0.0.1 at
  2014-01-06 21:38:25 +0200 Processing by
  Admin::CEventsController#add_speaker as JS   Parameters: {"id"=>"2"}
  CEvent Load (0.1ms)  SELECT "c_events".* FROM "c_events" WHERE
  "c_events"."id" = ? LIMIT 1  [["id", "2"]] Completed 404 Not Found in
  12ms
ActiveRecord::RecordNotFound (Couldn't find CEvent with id=2):

Seems like another actions is called, another actions in this controller is standard CRUD rails acctions

A: This is a partial answer because I don't know precisely how to solve your problem, but I can at least tell you where it is and hopefully give you an idea so you can figure out the rest.
Based on the stacktrace, it looks like you're using the CanCan gem. Apparently, it is intercepting the request before it gets to your action, as evidenced by this portion of the stacktrace:
...
activerecord (3.2.14) lib/active_record/querying.rb:5:in `find'
cancan (1.6.10) lib/cancan/model_adapters/abstract_adapter.rb:20:in `find'<- here
cancan (1.6.10) lib/cancan/controller_resource.rb:116:in `find_resource'
...

Unfortunately, I am not familiar with this library. However, after browsing their wiki page, I was able to find this information regarding conditionally checking authorization.
According to that page, you might be able to get away with something like this:
skip_authorization_check :only => [:add_speaker, :remove_speaker]

I assume doing this will suppress CanCan's authorization check, thus preventing your error.


text:
Q: DataTable Iteration And Fill Up I need to iterate through a 5 row 8 column DataTable (excluding the table headers etc). I need to go on filling each cell with string data and after the 8th cell has been reached, I will go to next row. Diagrammatically exactly like this:

How can this be achieved?
The problem that I am facing is that I am unable to write the nested loops which will iterate through the cells row wise and fill a string data similar to this:
Artificial Intelligence
Faculty: John Doe
Room: LS110

This string above is the content of one cell of the data table. Other cells would be filled with similar strings. The output would be similar:

This I need to do to convert to a HTML table later on.
Thanks.

A: I'm not sure where you got stuck, but if you don't know how to create the table and fill it with data:
string input = "Artificial Intelligence Faculty: John Doe Room: LS110";
var dt = new DataTable();
for (int i = 1; i <= 8; i++)
    dt.Columns.Add("Per-" + i);

DataRow tue = dt.Rows.Add();
for (int i = 1; i <= 8; i++)
    tue.SetField("Per-" + i, input);
DataRow wed = dt.Rows.Add();
for (int i = 1; i <= 8; i++)
    wed.SetField("Per-" + i, input);
DataRow thu = dt.Rows.Add();
for (int i = 1; i <= 8; i++)
    thu.SetField("Per-" + i, input);
DataRow fri = dt.Rows.Add();
for (int i = 1; i <= 8; i++)
    fri.SetField("Per-" + i, input);
DataRow sat = dt.Rows.Add();
for (int i = 1; i <= 8; i++)
    sat.SetField("Per-" + i, input);

Update: If you want the first column to contain the week-day:
var dt = new DataTable();
dt.Columns.Add(" "); // for the day
for (int i = 1; i <= 8; i++)
    dt.Columns.Add("Per-" + i);

DataRow tue = dt.Rows.Add();
tue.SetField(0, "Tue");
for (int i = 1; i <= 8; i++)
    tue.SetField("Per-" + i, input);
DataRow wed = dt.Rows.Add();
wed.SetField(0, "Wed");
for (int i = 1; i <= 8; i++)
    wed.SetField("Per-" + i, input);
DataRow thu = dt.Rows.Add();
thu.SetField(0, "Thu");
for (int i = 1; i <= 8; i++)
    thu.SetField("Per-" + i, input);
DataRow fri = dt.Rows.Add();
fri.SetField(0, "Fri");
for (int i = 1; i <= 8; i++)
    fri.SetField("Per-" + i, input);
DataRow sat = dt.Rows.Add();
sat.SetField(0, "Sat");
for (int i = 1; i <= 8; i++)
    sat.SetField("Per-" + i, input);


text:
Q: Regex.Split not keeping newline I am trying to split a string based on either \n \r \r\n but i do not want to remove them from the string
I know Regex.Split can keep delimiter but some how it is removing them
String Content
string contentString = @"幘䄍ਫ਼䱌㈰ぞ䙓ഊ幃噎ഊ幃䤱㝞䙏㈵ⰳ㕞䅁丬ㄲⰷ幆ㄶ幆䐀吀栀椀猀 昀漀爀洀愀琀 琀攀猀琀猀㨀幆匠ഊ幃䤱㝞䙏㈵ⰵ㕞䅁丬ㄲⰷ幆ㄶ幆䐀倀䐀䘀㐀㄀㜀 ⠀䈀㜀⤀Ⰰ 䴀漀搀攀㨀  Ⰰ 䌀䤀㈀㤀 眀椀琀栀 瘀愀氀椀搀 挀栀愀爀愀挀琀攀爀猀 幆匍ਫ਼䍉ㄷ幆伲㔬㤵幂㝎ⰵⰬⰬⱞ䘱㙞䙄01234>A>B>CABC<A<B<C^䙓ഊ幈䌍ਫ਼塚
^FX CRC Block No 1 ^FS
਍ਫ਼塁ഊ幌䰲〰幆匍ਫ਼䍖不ਫ਼䍉ㄷ幆伲㔬㌵幁䅎ⰱ㈬㝞䘱㙞䙄This format tests:^䙓ഊ幃䤱㝞䙏㈵ⰵ㕞䅁丬ㄲⰷ幆ㄶ幆䐀倀䐀䘀㐀㄀㜀 ⠀䈀㜀⤀Ⰰ 䴀漀搀攀㨀  Ⰰ 䌀䤀㈀㤀 眀椀琀栀 椀渀瘀愀氀椀搀 挀栀愀爀愀挀琀攀爀猀 幆匍ਫ਼䍉ㄷ幆伲㔬㤵幂㝎ⰵⰬⰬⱞ䘱㙞䙄01234þ>A>B>CABC<A<B<C^䙓ഊ幈䌍ਫ਼塚
^FX CRC Block No 2 ^FS
਍ਫ਼塁ഊ幌䰲〰幆匍ਫ਼䍖复ਫ਼䍉ㄷ幆伲㔬㌵幁䅎ⰱ㈬㝞䘱㙞䙄This format tests:^䙓ഊ幃䤱㝞䙏㈵ⰵ㕞䅁丬ㄲⰷ幆ㄶ幆䐀倀䐀䘀㐀㄀㜀 ⠀䈀㜀⤀Ⰰ 䴀漀搀攀㨀  Ⰰ 䌀䤀㈀㤀 眀椀琀栀 瘀愀氀椀搀 挀栀愀爀愀挀琀攀爀猀Ⰰ 愀渀搀 挀漀搀攀 瘀愀氀椀搀愀琀椀漀渀 ⠀䌀嘀⤀ 幆匍ਫ਼䍉ㄷ幆伲㔬㤵幂㝎ⰵⰬⰬⱞ䘱㙞䙄01234>A>B>CABC<A<B<C^䙓ഊ幈䌍ਫ਼塚
^FX CRC Block No 3 ^FS
਍ਫ਼塁ഊ幌䰲〰幆匍ਫ਼䍖复ਫ਼䍉ㄷ幆伲㔬㌵幁䅎ⰱ㈬㝞䘱㙞䙄This format tests:^䙓ഊ幃䤱㝞䙏㈵ⰵ㕞䅁丬ㄲⰷ幆ㄶ幆䐀倀䐀䘀㐀㄀㜀 ⠀䈀㜀⤀Ⰰ 䴀漀搀攀㨀  Ⰰ 䌀䤀㈀㤀 眀椀琀栀 椀渀瘀愀氀椀搀 挀栀愀爀愀挀琀攀爀猀Ⰰ 愀渀搀 挀漀搀攀 瘀愀氀椀搀愀琀椀漀渀⠀䌀嘀⤀ 幆匍ਫ਼䍉ㄷ幆伲㔬㤵幂㝎ⰵⰬⰬⱞ䘱㙞䙄01234þ>A>B>CABC<A<B<C^䙓ഊ幈䌍ਫ਼塚
^FX CRC Block No 4 ^FS
ਫ਼䙘⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⩞䙓"

Expression using
  Regex.Split(contentString, "\n|\r\n|\r");

Please help me to do it
Thanks in advance
Monika

A: You should add capturing parentheses into the pattern:
https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.split?redirectedfrom=MSDN&view=netframework-4.7.2#System_Text_RegularExpressions_Regex_Split_System_String_System_String_

If capturing parentheses are used in a Regex.Split expression, any
  captured text is included in the resulting string array. For example,
  if you split the string "plum-pear" on a hyphen placed within
  capturing parentheses, the returned array includes a string element
  that contains the hyphen.

(bold is mine)
In your case, to split
string contentString = @"幘䄍ਫ਼䱌㈰ぞ䙓ഊ幃噎ഊ幃䤱㝞䙏㈵ⰳ㕞䅁丬ㄲⰷ幆ㄶ幆䐀吀栀椀猀 昀漀爀洀愀琀 琀攀猀琀猀㨀幆匠ഊ幃䤱㝞䙏㈵ⰵ㕞䅁丬ㄲⰷ幆ㄶ幆䐀倀䐀䘀㐀㄀㜀 ⠀䈀㜀⤀Ⰰ 䴀漀搀攀㨀  Ⰰ 䌀䤀㈀㤀 眀椀琀栀 瘀愀氀椀搀 挀栀愀爀愀挀琀攀爀猀 幆匍ਫ਼䍉ㄷ幆伲㔬㤵幂㝎ⰵⰬⰬⱞ䘱㙞䙄01234>A>B>CABC<A<B<C^䙓ഊ幈䌍ਫ਼塚
^FX CRC Block No 1 ^FS
਍ਫ਼塁ഊ幌䰲〰幆匍ਫ਼䍖不ਫ਼䍉ㄷ幆伲㔬㌵幁䅎ⰱ㈬㝞䘱㙞䙄This format tests:^䙓ഊ幃䤱㝞䙏㈵ⰵ㕞䅁丬ㄲⰷ幆ㄶ幆䐀倀䐀䘀㐀㄀㜀 ⠀䈀㜀⤀Ⰰ 䴀漀搀攀㨀  Ⰰ 䌀䤀㈀㤀 眀椀琀栀 椀渀瘀愀氀椀搀 挀栀愀爀愀挀琀攀爀猀 幆匍ਫ਼䍉ㄷ幆伲㔬㤵幂㝎ⰵⰬⰬⱞ䘱㙞䙄01234þ>A>B>CABC<A<B<C^䙓ഊ幈䌍ਫ਼塚
^FX CRC Block No 2 ^FS
਍ਫ਼塁ഊ幌䰲〰幆匍ਫ਼䍖复ਫ਼䍉ㄷ幆伲㔬㌵幁䅎ⰱ㈬㝞䘱㙞䙄This format tests:^䙓ഊ幃䤱㝞䙏㈵ⰵ㕞䅁丬ㄲⰷ幆ㄶ幆䐀倀䐀䘀㐀㄀㜀 ⠀䈀㜀⤀Ⰰ 䴀漀搀攀㨀  Ⰰ 䌀䤀㈀㤀 眀椀琀栀 瘀愀氀椀搀 挀栀愀爀愀挀琀攀爀猀Ⰰ 愀渀搀 挀漀搀攀 瘀愀氀椀搀愀琀椀漀渀 ⠀䌀嘀⤀ 幆匍ਫ਼䍉ㄷ幆伲㔬㤵幂㝎ⰵⰬⰬⱞ䘱㙞䙄01234>A>B>CABC<A<B<C^䙓ഊ幈䌍ਫ਼塚
^FX CRC Block No 3 ^FS
਍ਫ਼塁ഊ幌䰲〰幆匍ਫ਼䍖复ਫ਼䍉ㄷ幆伲㔬㌵幁䅎ⰱ㈬㝞䘱㙞䙄This format tests:^䙓ഊ幃䤱㝞䙏㈵ⰵ㕞䅁丬ㄲⰷ幆ㄶ幆䐀倀䐀䘀㐀㄀㜀 ⠀䈀㜀⤀Ⰰ 䴀漀搀攀㨀  Ⰰ 䌀䤀㈀㤀 眀椀琀栀 椀渀瘀愀氀椀搀 挀栀愀爀愀挀琀攀爀猀Ⰰ 愀渀搀 挀漀搀攀 瘀愀氀椀搀愀琀椀漀渀⠀䌀嘀⤀ 幆匍ਫ਼䍉ㄷ幆伲㔬㤵幂㝎ⰵⰬⰬⱞ䘱㙞䙄01234þ>A>B>CABC<A<B<C^䙓ഊ幈䌍ਫ਼塚
^FX CRC Block No 4 ^FS
ਫ਼䙘⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⩞䙓";

Instead of the original "\n|\r\n|\r" pattern you can put the same one but with capturing parentheses: "(\n|\r\n|\r)" i.e.
  string[] parts = Regex.Split(contentString, "(\n|\r\n|\r)");


text:
Q: ¿Cómo puedo coger un elemento aleatorio de un array? Deseo hacer un programa que reproduzca un audio aleatoriamente a partir de unos links que asigné como variables...
Aquí mi código:
RANGE=3

echo

number=$RANDOM
let "number %= $RANGE"

ARRAY=(https://www.youtube.com/watch?v=iPKJUzkTt6Y https://www.youtube.com/watch?v=-jix8bSotZ4 https://www.youtube.com/watch?v=YnmEePUXLRs)
mpv ${ARRAY[$number]}

Por cierto, utilizo MPV como reproductor.
El problema es que quiero que alguno de los links se reproduzcan por medio de MPV, pero me toma la variable como comando y el "mpv" como otro..
Code1.sh: line 9: https://www.youtube.com/watch?v=-jix8bSotZ4: No such file or directory

¿Alguien sabe cómo puedo corregir el error?

A: $RANDOM es una función interna de Bash, que retorna un "pseudorandom" entero en el rango de 0 a 32767. En tu caso, lo que te interesa es generar un número aleatorio de 0 a la longitud del array - 1. Para esto puedes aprovechar la función módulo para obtener el resto de la división por la cantidad de ítems del array. Por ejemplo:
#!/bin/bash

items=("Juan" "Pedro" "Luis" "Laura" "Marcela" "Natalia")

# Obtener un valor random del array
size=${#items[@]}
randomindex=$(($RANDOM % $size))

echo ${items[$randomindex]}


text:
Q: Microsoft Playwright for .NET NUnit, cant launch tests in headed mode Im starting to use Playwright to automate my tests for a Blazor WebAssembly application, i created a new NUnit Test project and following the docs on playwright.dev i installed:

dotnet add package Microsoft.Playwright.NUnit

doing so i can inherit the PageTest class and directly use a Page object already configured for me without needing to instantiate the browser and the context
now i need to see what happens during my tests so i wanted to enable headed mode, normally i would launch the browser with this options like this:
await playwright.Firefox.LaunchAsync(new BrowserTypeLaunchOptions
{
    Headless = false,
    SlowMo = 50,
});

but i cant do that here, the official docs suggest to use this commands on the console

set HEADED=1

dotnet test

but nothing happens, the tests are run headless mode regardless.

A: For the headless mode I first set the following in the terminal "$env:HEADED=1", so that it will open a browser. Keep in mind you have to set it to "0" if you want to run it in headless mode again.
From what I understood, after inheriting from PageTest, due to lack of config file, such things (headless/slowMo) should be set runtime from the terminal.

A: Use this
await using var browser = await playwright.Firefox.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false, SlowMo = 50 });
var context = await browser.NewContextAsync();
var page = await context.NewPageAsync();
await page.GotoAsync("The site you want to go");

It should work

A: If you set the environment variable PWDEBUG before your tests run, they will run in headed mode.
e.g. by doing something like this in a one time set up.
Environment.SetEnvironmentVariable("PWDEBUG", "console");

More information about Run in Debug Mode

A: The playwright libary also provided test Runners frameworks like: mstest, NUnit, and Xunit.
With the testing runner framework - NUnit, you can use customizing Browser/launch options by using the run settings file - .runsettings.
See the docs: https://playwright.dev/dotnet/docs/test-runners
See it under - "customizing Browser/launch options under Nunit/mstest"
Also about .runsettings file
https://learn.microsoft.com/en-us/visualstudio/test/configure-unit-tests-by-using-a-dot-runsettings-file?view=vs-2022
for that to work with Nunit you need NUnit3TestAdapter. So your .csproj file contains:
<ItemGroup>
  <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.3.2" />
  <PackageReference Include="Microsoft.Playwright.NUnit" Version="1.28.0" />
  <PackageReference Include="Microsoft.Playwright.TestAdapter" Version="1.28.0" />
  <PackageReference Include="NUnit3TestAdapter" Version="4.3.1" />
</ItemGroup>


text:
Q: Get table options from query Is there a way to query the options (specifically the autovacuum_vacuum_scale_factor) set for a specific table?
Right now I'm doing \d+ <table_name> in the CLI to get them, but I'd like to do it from a query.
Thanks :)

A: CREATE TABLE a_a (
    a int
)
WITH (
    autovacuum_vacuum_scale_factor = 20
);

SELECT
    relname,
    relnamespace,
    reloptions
FROM
    pg_class
WHERE
    relname = 'a_a';

you will get:
+---------+--------------+-------------------------------------+
| relname | relnamespace |             reloptions              |
+---------+--------------+-------------------------------------+
| a_a     |        16466 | {autovacuum_vacuum_scale_factor=20} |
+---------+--------------+-------------------------------------+


text:
Q: In playframework, where is the source code for `inputText` html helper? I want to use the inputText method in html.helper for forms.
Online Document for inputText
When I want to see how it generated the HTML code, I can't find its source code because the link to the source code embeded in their website is invalid: https://github.com/playframework/playframework/tree/2.3.x/framework/src/play/target/scala-2.10/twirl/main/views/html/helper/inputText.template.scala
Does anyone have ideas about where its source codes locate?

A: In the "src"-directory, not the "target":
https://github.com/playframework/playframework/blob/master/framework/src/play/src/main/scala/views/helper/inputText.scala.html


text:
Q: How can I hide the table cells contents dynamically using plain javascript? I am creating a table in plain JavaScript, and filling it up using onClick listener event in two ways - either clicking on a external button, or clicking on one of the cells itself.I am not able to hide the contents of my table cells dynamically i.e.I want to hide them when rendering values in them, which I want to unhide/display later-on on some other event.
I have already tried conventional methods available viz.
td {display: none;},  and  td {visibilty: hidden}
I have also tried inline CSS style method to hide the cell contents, but all these methods blank the table itself i.e. oblivate the cell borders themselves.

                 ...  ....  ...

All the techniques available blank the table itself i.e. oblivate the cell borders themselves.

A: There are a number of ways to do this, and some other ways might be better depending on the content of your table cells. But assuming it's just text, one way you could hide the cell contents would be to make the fontSize of the cell equal to 0. See this example:

hide.addEventListener("click", function(event) {
  document.getElementById("table").rows[1].cells[1].style.fontSize = 0;
});

show.addEventListener("click", function(event) {
  document.getElementById("table").rows[1].cells[1].style.fontSize = null;
});
table, td, th {
  border: 1px solid black;
}

    Firstname
    Lastname
    Age

    Jill
    Smith
    50

    Eve
    Jackson
    94

<button id="hide">Hide Cell "Smith"</button>
<button id="show">Show Cell "Smith"</button>


text:
Q: How to use log4j2 FileAppender with SLF4J API I've been trying to follow the recipes on this site and others for how to add a log4j2 FileAppender instance to a class that's using the SLF4J API for its overall logging, and I'm not having much luck. Can somebody tell me what I'm doing wrong with the following code?
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.FileAppender;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileAppenderTest {

    private static final Logger log = LoggerFactory.getLogger(FileAppenderTest.class);

    private final Layout<?> taskLogLayout = PatternLayout.newBuilder()
        .withPattern("%d %-5p [%t:%C{1}.%M] %m%n")
        .build();

    @Test
    public void testFileAppender() throws IOException {

        File appenderFile = new File("build/test", "file-appender.log");

        FileAppender taskLog = FileAppender.newBuilder()
            .withFileName(appenderFile.getAbsolutePath())
            .setName("file-appender.log")
            .setLayout(taskLogLayout)
            .build();
        taskLog.start();

        LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        Configuration c = ctx.getConfiguration();
        LoggerConfig lc = c.getLoggerConfig("");
        lc.addAppender(taskLog, Level.ALL, null);

        log.info("Here is a test message with INFO level");
        log.warn("Here is a test message with WARN level");

        lc.removeAppender("file-appender.log");

        assertTrue(appenderFile.exists());

        List<String> logLines = FileUtils.readLines(appenderFile, (Charset) null);
        assertEquals(2, logLines.size());

    }

}

The assertTrue statement passes, so the file is created by the FileAppender, but the assertEquals fails because the length of logLines is zero (i.e., the log file has no content).
Any ideas?

A: Found the problem:
In the code above, note that the Logger is obtained from the LoggerFactory prior to application of any logging configuration settings. This causes the logger to have a default level of ERROR. Thus, even though the APPENDER has a level of INFO, the LOGGER has a level of ERROR and that rejects the INFO and WARN messages before they even get to the appender!
The following code will pass all its tests. Note that the Logger is no longer a static member and that the configuration is set to have a level of ANY before the Logger is obtained.
package gov.nasa.ziggy.worker;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.FileAppender;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileAppenderTest {

    private final Layout<?> taskLogLayout = PatternLayout.newBuilder()
        .withPattern("%d %-5p [%t:%C{1}.%M] %m%n")
        .build();

    @Test
    public void testFileAppender() throws IOException {

        LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        Configuration c = ctx.getConfiguration();
        LoggerConfig lc = c.getLoggerConfig("");
        lc.setLevel(Level.ALL);

        Logger log = LoggerFactory.getLogger(FileAppenderTest.class);
        File appenderFile = new File("build/test", "file-appender.log");

        FileAppender taskLog = FileAppender.newBuilder()
            .withFileName(appenderFile.getAbsolutePath())
            .setName("file-appender.log")
            .setLayout(taskLogLayout)
            .build();
        taskLog.start();

        lc.addAppender(taskLog, Level.ALL, null);

        log.info("Here is a test message with INFO level");
        log.warn("Here is a test message with WARN level");

        lc.removeAppender("file-appender.log");

        assertTrue(appenderFile.exists());

        List<String> logLines = FileUtils.readLines(appenderFile, (Charset) null);
        assertEquals(2, logLines.size());

    }

}


text: Q: Help determining if the following are legitimate files I have installed wordfence and did a scan and I have the following warnings.  I am not sure if they are left over from a hacking attack last year that sitelock have not removed or if they are required.  Appreciate help on how to determine if these are required files or suspicious.


text:
Q: Python average input not working I am trying to get average times of the speed skaters with Python and my code will not work. I have searched all over trying to find an answer and I am completely stumped.
print("Enter the skater times in seconds. Input -1 to finish and calculate.")

count = 0
sum = 0.0
number = 1

while number != -1:
    number = input("Enter skater time in seconds: ")
    if number != 0:
        count = count + 1
        sum = sum + number

print ("The number of skaters was: ", count)
print ("The average skater time was:", sum / count)

A: The if clause must be:
if number > 0:

Otherwise you are considering the last one, whose value is -1
Edit
I think it has nothing to do with integer division. It is only the if clause.

A: You can add from __future__ import division and it will make all divisions be floats.


text:
Q: How to set a custom icon to an IOS push notification? I'm currently adding notifications to my Flutter app for IOS, I wanted to add something similar to a largeIcon on Android, so far I didn't find a way to do that, only adding an image which is not a solution since I only want an icon at the right even if the user expands the notification (the image will expand too in this case which is undesirable for my use case).
As an alternative, I was wondering if I could change the notification app icon. As far as I looked around, this is not possible either, but at the same time I saw this image of notifications (the first one and the last one) that have a custom image and the app icon is smaller.
How can I do this in my app? I couldn't find any way in the documentation on how to do it.

A: You can do this with communication notifications. From HIG:

The system automatically displays a large version of your app icon at
the leading edge of each notification; in a communication
notification, the system displays the sender's contact image — or
avatar — badged with a small version of your icon.

Here is the documentation on how to implement communication notifications in your app.


text:
Q: reducing oracle table entity I have a table like this:

I want a query that make my table like this:

A: You can use aggregation:
select max(id1) as id1, max(id2) as id2, max(id3) as id3
from . . .

A: I would prefer to use SUM() here, because you might have negative numbers in a given column:
select sum(id1) as id1, sum(id2) as id2, sum(id3) as id3
from yourTable

If we use MAX(), then it would fail, if for example there were a -2 in one of the columns.  In that case, the max would return zero.

A: I'm not sure that solution is optimal for executing, but:
select (select id1 from table where id1 <> 0) id1,
       (select id2 from table where id2 <> 0) id2,
       (select id3 from table where id3 <> 0) id3
from dual;


text:
Q: What is the difference between the Interaction picture (Dirac Picture) and a rotating reference frame? In David McIntyre's Quantum Mechanics, we examine an electron within a magnetic field
$$\vec{B}=B_o \hat{z}+B_1[\cos(\omega t)\hat{x}+\sin(\omega t)\hat{y}]$$
The Hamiltonian is then time-dependent and in matrix form it is as follows
$$H=\frac{\hbar}{2}\begin{bmatrix}\omega_0& \omega_1e^{-i\omega t}\\\omega_1e^{i\omega t}&-\omega_0\end{bmatrix}=H_0+H_t(t)$$
where $\omega_0=\frac{eB_0}{m}$ and $\omega_1=\frac{eB_1}{m}$. McIntyre then says that the solution to the Schrödinger equation can be written using the energy basis of the time-independent part of the Hamiltonian (this is the usual basis: $|\uparrow\rangle_z=(1,0)$and $ |\downarrow\rangle_z=(0,1)$) as
$$|\psi(t)\rangle=c_+(t)|\uparrow\rangle_z +c_-(t)|\downarrow\rangle_z=(\,c_+(t)\,,\,c_-(t)\,) \tag{1}$$
Now as far as I am aware, the above solution is in the Schrödinger picture where $|\psi(t)\rangle_s=e^{-iHt/\hbar}|\psi(t=0)\rangle$. Now I have learnt in class that the state in the interaction picture is defined as
$$
|\psi(t)\rangle_I=e^{iH_0t/\hbar}|\psi(t)\rangle \tag{2}
$$
where the exponent only includes the time-independent part of the Hamiltonian. My issue is that McIntyre then says that we can simplify the problem by transforming the state in equation (1) to the rotating frame which he says (without justification) yields
$$
|\psi(t)_*\rangle=c_+(t)e^{i\omega t/2}|\uparrow\rangle_z +c_-(t)e^{-i\omega t/2}|\downarrow\rangle_z=(\,c_+(t)e^{i\omega t/2}\,,\,c_-(t)e^{-i\omega t/2}\,) \tag{3}
$$
Now I have read that the rotating frame is related to (if not entirely equivalent to) the interaction picture. This leads me to think that equation (3) is the state vector in the interaction picture for this problem. However, how can this be if the interaction picture is defined as in equation (2)? If we are to believe equation (2), then should we not get something like
$$
|\psi(t)_*\rangle=(\,c_+(t)e^{i\omega_1 t/2}\,,\,c_-(t)e^{-i\omega_1 t/2}\,)
$$
where we've used $\omega_1$ instead of $\omega$. In fact, why should we not use $\omega_0$ considering in equation (3), it is the unperturbed time-independent Hamiltonian that is present while $\omega$ is associated with the energy due to the time-dependent part?

A: Yes, the interaction picture is a rotating frame, but not every rotating frame is "the" interaction picture. Therefore we do not use equation (2) to find (3) but rather some [yet-to-be-proven-to-be] useful transformation
$$
\begin{pmatrix}c_+^R(t)\\c_-^R(t)\end{pmatrix}=\exp\left(i \begin{pmatrix}1&0\\0&-1\end{pmatrix}\omega t\right)
\begin{pmatrix}c_+^S(t)\\c_-^S(t)\end{pmatrix}.
$$ Note that we have not said anything about what functional form the coefficients $\begin{pmatrix}c_+^S(t)\\c_-^S(t)\end{pmatrix}$ actually take - we have only specified how they related to the "rotated" coordinates $\begin{pmatrix}c_+^R(t)\\c_-^R(t)\end{pmatrix}$. You have tried to guess the answer for what the coefficients should look like, but that is exactly what is hard to do because we are solving a problem with a time-dependent Hamiltonian!
Another way of looking at this is by considering the transformation to act on the basis states:
$$
|\uparrow\rangle_z\to |\uparrow(t)\rangle_z\equiv e^{i\omega t/2}|\uparrow\rangle_z ,\quad |\downarrow\rangle_z\to |\downarrow(t)\rangle_z\equiv e^{-i\omega t/2}|\downarrow\rangle_z.
$$ If we write the Hamiltonian in bra-ket notation, dropping the $z$ subscript, it looks like
\begin{align}
\frac{2H}{\hbar}=\omega_0|{\uparrow}\rangle\langle{\uparrow}|-\omega_0|{\downarrow}\rangle\langle{\downarrow}|
+\omega_1e^{-i\omega t}|{\uparrow}\rangle\langle{\downarrow}|
+\omega_1e^{i\omega t}|{\downarrow}\rangle\langle{\downarrow}|.
\end{align}  We can substitute in our new definitions of the states to see that (remembering to take all of the complex conjugates)
\begin{align}
\frac{2H}{\hbar}=\omega_0|{\uparrow(t)}\rangle\langle{\uparrow(t)}|-\omega_0|{\downarrow(t)}\rangle\langle{\downarrow(t)}|
+|{\uparrow(t)}\rangle\langle{\downarrow(t)}|
+|{\downarrow(t)}\rangle\langle{\downarrow(t)}|.
\end{align} Do you see the trick? Using this redefinition, we have made the Hamiltonian appear to be time-independent! It is only time-independent in this funky basis in which the states depend on time, but that time dependence is easy to sort out at the end of any calculation. This final form of the Hamiltonian justifies the choice of rotating frame. In other contexts, such as "the" interaction picture, another final form of the Hamiltonian justifies a different choice of rotating frame  like the one you suggested using $\exp(i H_0 t)$.


text:
Q: Google Calendar API show all events from public calendar I'm having trouble following tutorials to get a list of all events in a public calendar. I've tried following along this post: Retrieve Google Calendar events using API v3 in javascript, and the official docs, but I always get a 404 error.
This is the code I have (following the linked post). I am using localhost, and I have a public calendar, and I made an API key with no restrictions, and a client ID with http://localhost as authorized JS origin and Authorized redirect URIs

LOADING . . . .

updating . . . . .

[enter image description here][1]


text:
Q: Stylus on Mac: I get error trying to install it About 2 months ago I installed Node, I remember I had problem to do this, but I got it.
Now I am trying to install Stylus in Terminal and I can't, and I get this message:

MacBook-Pro-de-Antony:~ antony$ node -v
  v8.9.1
  MacBook-Pro-de-Antony:~ antony$ sudo npm install -g stylus
  /usr/local/bin/stylus -> /usr/local/lib/node_modules/stylus/bin/stylus
  + stylus@0.54.5
  updated 1 package in 2.07s
  MacBook-Pro-de-Antony:~ antony$ stylus -v
  /usr/local/lib/node_modules/stylus/bin/stylus:641
      if (err) throw err;
          ^
  Error: ENOENT: no such file or directory, stat '-v'
  MacBook-Pro-de-Antony:~ antony$

My question is :
Do I have to "active" Node before to do this?
or what I am doing wrong?
I am using MacOS Sierra.

A: No, you don't have to run it within Node. It is ok to do it where you were doing it (in the command line).
The problem: -v is not a valid parameter. To see its version you should do: stylus --version or stylus -V (with an uppercase V).
stylus --help will show you all the options available.


text:
Q: "Ionic Cordova run android" got launch success message, but the app isn't launching on the phone Some days ago I've updated my phone from Android 7.1.1 to Android 8.1 Oreo. After that update, when I try to run the command "ionic cordova run android" or "ionic cordova run android -l", the cmd console shows the message:
BUILD SUCCESSFUL in 15s 47 actionable tasks: 2 executed, 45 up-to-date Built the following apk(s):
        D:\Plural Systems\Painel do Gestor\siematecapp\platforms\android\app\build\outputs\apk\debug\app-debug.apk

ANDROID_HOME=C:\Users\Jer\AppData\Local\Android\sdk

JAVA_HOME=C:\Program Files\Java\jdk1.8.0_65 No target specified, deploying to device '0044699831'.

none

Skipping build... Built the following apk(s):
        D:\Plural Systems\Painel do Gestor\siematecapp\platforms\android\app\build\outputs\apk\debug\app-debug.apk

Using apk: D:\Plural Systems\Painel do Gestor\siematecapp\platforms\android\app\build\outputs\apk\debug\app-debug.apk

Package name: br.doctorvet.app

LAUNCH SUCCESS

But after this message, the app didn't open on Android.
I've already tried removing the android platform and add the platform again; update the cordova-plugin-webview from 1.2 to 2.0, remove and then add the android platform; disable USB debugging, revoke USB debugging authorizations, enable/disable "Verify apps over USB; I've created a new ionic blank project and run the command, it worked,  but only for the first time; I tried to clone the project from git and install the project, add android platform but the same problem occurs.
I don't know why it is happening. It started after I've updated my Android version to 8.1 and before that, everything was working fine.
What could be causing this?
My IONIC INFO
cli packages: (C:\Users\Jer\AppData\Roaming\npm\node_modules)
@ionic/cli-utils  : 1.19.2
ionic (Ionic CLI) : 3.20.0

global packages:
cordova (Cordova CLI) : 8.0.0

local packages:
@ionic/app-scripts : 3.1.9
Cordova Platforms  : android 7.1.1
Ionic Framework    : ionic-angular 3.9.2

System:
Node : v8.11.2
npm  : 5.6.0
OS   : Windows 10

Environment Variables:
ANDROID_HOME : not set

Misc:
backend : pro

My IONIC REQUIREMENTS
Android Studio project detected

Requirements check results for android:

Java JDK: installed 1.8.0
Android SDK: installed true
Android target: installed android-27,android-26,android-25
Gradle: installed C:\Program Files\Android\Android Studio\gradle\gradle-4.4\bin\gradle

A: the run command would be:
ionic cordova run android -lc

while you need to add one of these:
--device    Deploy Cordova build to a device
--target    Deploy Cordova build to a device (use --list to see all)

because it complains ...

no target specified

A: The problem was the guest user. I had a guest user enabled and everything that I installed under ionic commands in the main user was installed in the guest user, but when I run the command for the second time, the application on guest was updated. So every time I run some ionic command, I need to uninstall the application on guest user before run ionic cordova run-build android.


text:
Q: count the number of occurrences of a certain value in a dictionary in python? If I have got something like this:
D = {'a': 97, 'c': 0 , 'b':0,'e': 94, 'r': 97 , 'g':0}

If I want for example to count the number of occurrences for the "0" as a value without having to iterate the whole list, is that even possible and how?

A: As mentioned in THIS ANSWER using operator.countOf() is the way to go but you can also use a generator within sum() function as following:
sum(value == 0 for value in D.values())
# Or the following which is more optimized
sum(1 for v in D.values() if v == 0)

Or as a slightly more optimized and functional approach you can use map function  by passing the __eq__ method of the integer as the constructor function.
sum(map((0).__eq__, D.values()))

Benchmark:
In [15]: D = dict(zip(range(1000), range(1000)))

In [16]: %timeit sum(map((0).__eq__, D.values()))
49.6 µs ± 770 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [17]: %timeit sum(v==0 for v in D.values())
60.9 µs ± 669 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [18]: %timeit sum(1 for v in D.values() if v == 0)
30.2 µs ± 515 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [19]: %timeit countOf(D.values(), 0)
16.8 µs ± 74.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Note that although using map function in this case may be more optimized, but in order to have a more comprehensive and general idea about the two approaches you should run the benchmark for relatively large datasets as well. Then, you can use the most proper approach based on the structure and amount of data you have.

A: That's a job for operator.countOf.
countOf(D.values(), 0)

Benchmark with your example dictionary:
1537 ns  1540 ns  1542 ns  Counter(D.values())[0]
 791 ns   800 ns   802 ns  sum(value == 0 for value in D.values())
 694 ns   697 ns   717 ns  sum(map((0).__eq__, D.values()))
 680 ns   682 ns   689 ns  sum(1 for value in D.values() if value == 0)
 599 ns   599 ns   600 ns  sum([1 for i in D.values() if i == 0])
 368 ns   369 ns   375 ns  list(D.values()).count(0)
 229 ns   231 ns   231 ns  countOf(D.values(), 0)

Code (Try it online!):
from timeit import repeat

setup = '''
from collections import Counter
from operator import countOf
D = {'a': 97, 'c': 0 , 'b':0,'e': 94, 'r': 97 , 'g':0}
'''

E = [
    'Counter(D.values())[0]',
    'sum(value == 0 for value in D.values())',
    'sum(map((0).__eq__, D.values()))',
    'sum(1 for value in D.values() if value == 0)',
    'sum([1 for i in D.values() if i == 0])',
    'list(D.values()).count(0)',
    'countOf(D.values(), 0)',
]

for _ in range(3):
    for e in E:
        number = 10 ** 5
        ts = sorted(repeat(e, setup, number=number))[:3]
        print(*('%4d ns ' % (t / number * 1e9) for t in ts), e)
    print()

A: Alternatively, using collections.Counter:
from collections import Counter
D = {'a': 97, 'c': 0 , 'b':0,'e': 94, 'r': 97 , 'g':0}

Counter(D.values())[0]
# 3

A: You can count it converting it to a list as follows:
D = {'a': 97, 'c': 0 , 'b':0,'e': 94, 'r': 97 , 'g':0}
print(list(D.values()).count(0))
>>3

Or iterating over the values:
print(sum([1 for i in D.values() if i == 0]))
>>3

A: for i in hashmap:
  print(Counter(hashmap.values())[hashmap[i]])

# In this way we can traverse & check the count with the help of Counter


text:
Q: how do you create a dynamic tabs using jquery? i'm new to jquery and I like to know how to do the following:
1) Dynamically create tabs with iFrame inside
2) ability to remove tabs on the fly without postback
3) tabs are unlimited and can shrink depending on the length of the browser
Sorry if this may be too much to ask, but i'd like to learn how to do this. A perfect example of what I'm trying to achieve is the tabs present in the new Yahoo mail UI. When the user selects a mail entry, a new tab will be generated on the fly.
Thank you

A: Try this example..  This creates tabs dynamically the way you probably wanted.
Dynamically adding jQuery Tabs
Here's a quick working demo..
Dynamic TAB Demo

A: You can use jQuery Tabs 3 Plugin.

A: You can use the jQuery Tabs element at http://docs.jquery.com/UI/Tabs

A: The jQuery tabs plugin can be used. You will not lose the state on the other tabs, because they aren't removed, but simply hidden (display: none).


text:
Q: Convert brightness numbers to ASCII characters in python I am doing programming project ASCII art in python . So far I managed to convert RGB tuples to into single brightness numbers. Next step is to convert the numbers to to ASCII characters. I am stuck because I do not know what I should do next. I have to select ASCII character to each numbers, range of the numbers are in 0,255. I would like to get some hints how can I done this.
This is my code so far.
from PIL import Image

im = Image.open("IMG_3021.jpg")

#print(im.size)

#im.show()

def load_pixel():

    im = Image.open("IMG_3021.jpg")

    x = list(im.getdata())
    pixel = [int(sum(i)/3) for i in x]
    for i in iter(pixel):
        print(i)

   # return pixel

#    for pixel in iter(x):
#        x = sum(pixel)//3
#        x = (x * len(pixel_ascii_map)) // 255
#        ascii_val = pixel_ascii_map[x]
#        print(ascii_val)

print(load_pixel())

A: from PIL import Image

pixel_ascii_map = "`^\",:;Il!i~+_-?][}{1)(|\\/tfjrxnuvczXYUJCLQ0OZmwqpdbkhao*#MW&8%B@$"

def load_pixel():
  im = Image.open("IMG_3021.jpg")
  x = list(im.getdata())
  for pixel in iter(x):
    x = sum(pixel) // 3 # integer division
    ascii_val = pixel_ascii_map[x]
    print(ascii_val)

Beware that your ascii map has not enough length (pixels are in range 0-255). So in order to prevent it, you could rescale the x value in order to stay in the map range:
from PIL import Image

pixel_ascii_map = "`^\",:;Il!i~+_-?][}{1)(|\\/tfjrxnuvczXYUJCLQ0OZmwqpdbkhao*#MW&8%B@$"

def load_pixel():
  im = Image.open("IMG_3021.jpg")
  x = list(im.getdata())
  for pixel in iter(x):
    x = sum(pixel) // 3 # integer division
    x = (x * len(pixel_ascii_map)) // 255 # rescaling
    ascii_val = pixel_ascii_map[x]
    print(ascii_val)

Beware that by doing sum(pixel) // 3 you are actually grayscaling your image, so you will loose any color information.


text:
Q: sort vector of struct element i am trying to  sort vector  of struct's elements,but i can't construct  vector itself here is code
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

struct student_t{
      string name;
  int age,score;
}   ;

bool compare(student_t const &lhs,student_t const &rhs){
    if (lhs.name<rhs.name)
         return true;
    else if (rhs.name<lhs.name)
        return false;

    else
        if (lhs.age<rhs.age)
            return true;
        else if (rhs.age<lhs.age)
             return false;
    return lhs.score<rhs.score;

}
int main(){

               struct student_t st[10];

 return 0;
}

when i declared  vector<student_t>st  i can't  access  element of struct,please give me hint how to do it

A: std::vector<student_t> st;
for(unsigned i = 0; i < 10; ++i) st.push_back(student_t());
std::sort(st.begin(), st.end(), &compare);

You could also use this vector constructor instead of lines 1-2:
std::vector<student_t> st (10 /*, student_t() */);

Edit:
If you want to enter 10 students with the keyboard you can write a function that constructs a student:
struct student_t &enter_student()
{
     student_t s;
     std::cout << "Enter name" << std::endl;
     std::cin >> s.name;
     std::cout << "Enter age" << std::endl;
     std::cin >> s.age;
     std::cout << "Enter score" << std::endl;
     std::cin >> s.score;
     return s;
}
std::vector<student_t> st;
for(unsigned i = 0; i < 10; ++i) st.push_back(enter_student());

A: to sort the vector:
sort(st.begin(), st.end(), compare);

and to read input to your vector you should first resize the vector or input to a temporary
variable and push it to your vector:
www.cplusplus.com/reference/stl/vector/vector/


text:
Q: How to test all children from a Selector except the first child in Jest I want to test all children of a Selector except the first Child, if anyone can help I would appreciate it and thank you in advance.
I've tried this but none of those lines worked:
expect(wrapper.find('.icons .icon:nth-child(n+2)').hasClass('arrow-right')).toEqual(true);

//////////////////////////////

expect(wrapper.find('.icons .icon:not(:first-child)').hasClass('arrow-right')).toEqual(true);

A: It seems that enzyme does not fully support pseudo-classes/selectors. Furthermore, the hasClass method can only be used in a single node.
Taking that into account, you could do something like:
wrapper.find('.icons .icon').forEach(function(icon, index) {
    expect(icon.hasClass('arrow-right')).toEqual(index !== 0);
});


text:
Q: Problem with import in Python [Closing NOTE]
Thank you everyone that trying to help me.
I've found the problem and it have nothing to do with python understanding of mine (which is little). :p
The problem is that I edit the wrong branch of the same project, Main.py in one branch and XWinInfos.py in another branch.
Thanks anyway.
[Original Question]
I am a Java/PHP/Delphi programmer and only use Python when hack someone else program -- never to write a complex Python myself. Since I have a short free time this week, I determine to write something non-trivia with Python and here is my problem
First I have python files like this:
src/
    main.py
    SomeUtils.py

In "SomeUtils.py, I have a few functions and one class:
...
def funct1 ...

def funct2 ...

class MyClass1:
    __init__(self):
        self. ....
...

Then in "main.py", I use the function and class:
from SomeUtils import *;

def main():
    funct1();               # Use funct1   without problem;
    aMyObj1 = MyClass1();   # Use MyClass1 with error

if (__name__ == "__main__"):
    main();

The problem is that the functions are used without any problem what so ever but I cannot use the class.
The error is:
NameError: global name 'MyClass1' is not defined

What is the problem here? and What can I do?
EDIT: Thanks for answers for I still have problem. :(
When I change the import statements to:
from SomeUtils import funct1
from SomeUtils import MyClass1

I have this error
ImportError: cannot import name MyClass1
EDIT 2:----------------------------------------------------------
Thanks you guys.
I think, it may be better to post the actual code, so here it is:
NOTE: I am aware about ";" and "(...)" but I like it this way.
Here is the dir structure.
DIRS http://dl.getdropbox.com/u/1961549/images/Python_import_prolem_dir_.png
as you see, I just add an empty init.py but it seems to make no different.
Here is main.py:

from XWinInfos import GetCurrentWindowTitle;
from XWinInfos import XWinInfo;

def main():
    print GetCurrentWindowTitle();
    aXWinInfo = XWinInfo();

if (__name__ == "__main__"):
    main();

Here is XWinInfos.py:
from subprocess import Popen;
from subprocess import PIPE;
from RegExUtils import GetTail_ofLine_withPrefix;

def GetCurrentWindowID():
    aXProp = Popen(["xprop", "-root"], stdout=PIPE).communicate()[0];
    aLine  = GetTail_ofLine_withPrefix("_NET_ACTIVE_WINDOW\(WINDOW\): window id # 0x", aXProp);
    return aLine;

def GetCurrentWindowTitle():
    aWinID    = GetCurrentWindowID();
    aWinTitle = GetWindowTitle(aWinID);
    return aWinTitle;

def GetWindowTitle(pWinID):
    if (aWinID == None): return None

    aWMCtrlList = Popen(["wmctrl", "-l"], stdout=PIPE).communicate()[0];
    aWinTitle   = GetTail_ofLine_withPrefix("0x[0-9a-fA-F]*" + aWinID + "[ ]+[\-]?[0-9]+[ ]+[^\ ]+[ ]+", aWMCtrlList);
    return aWinTitle;

class XWinInfo:
    def __init__(self):
        aWinID = GetCurrentWindowID();
        self.WinID = pWinID;
        self.Title = GetWindowTitle(pWinID);

The file RegExUtils.py holds a function "GetTail_ofLine_withPrefix" which work fine so.
If I use "from XWinInfos import *;", the error goes "NameError: global name 'XWinInfo' is not defined".
If I use "from XWinInfos import XWinInfo;", the error goes "ImportError: cannot import name XWinInfo".
Please helps.
Thanks in advance.

A: Hmm... there's several typos in your example, so I wonder if your actual code has some typos as well.  Here's the complete source from a quick test that does work fine without import errors.
SomeUtils.py:
def funct1():
    print('Function 1')

def funct2():
    print('Function 2')

class MyClass1(object):
    def __init__(self):
        print('MyClass')

main.py:
from SomeUtils import *

def main():
    funct1()
    aObj = MyClass1()

if (__name__ == "__main__"):
    main()

[EDIT Based on OP additional info]
I still can't recreate the same error, but the code you posted won't initially work for at least a couple of errors in the XWinInfox.py init method:
self.WinID = pWinID #change to 'aWinID' since pWinID is not defined
self.Title = GetWindowTitle(pWinID)  #change to 'aWinID'since pWinID is not defined

so a corrected version would read:
self.WinID = aWinID
self.Title = GetWindowTitle(aWinID)

Also, you have a typo in your init file name, there should be two underscores before AND after the 'init' word.  Right now you have '__init_.py' and it should be '__init__.py', however this shouldn't keep your code from working.
Because I don't have the RegExUtils.py code, I just stubbed out the methods that rely on that file.  With the stubbed methods and correcting the aforementioned typos, the code you post now works.

A: why are you importing from XWinInfos? you should be importing from SomeUtils. Not to mention that *-style imports are discouraged.
Edit: your error

ImportError: cannot import name MyClass1

basically tells you that there is no MyClass1 defined in the SomeUtils. It could be because you have another SomeUtils.py file somewhere on the system path and it being imported instead. If that file doesn't have MyClass1, you'd get this error.
Again: it's irrelevant whether you class MyClass1 exist. What might be the case is that you have another XWinInfos.p(y|o|w) somewhere on your system and it's being imported. Otherwise: norepro.

A: You may want to rewrite main.py as follows:
import SomeUtils as util

def main():
    util.funct1()               # Use funct1   without problem;
    aMyObj1 = util.MyClass1()   # Use MyClass1 with error

if __name__ == "__main__":
    main()

A few quick notes:

*

*There is no need for semicolons in
Python unless you have more than one
statement on a line

*There is no need
to wrap conditional tests in
parentheses except for grouping

*from
module import * is discouraged as it
pollutes the global namespace

A: I suppose you mean
from SomeUtils import *

however, that does not trigger the error for me. This works fine for me:
SomeUtils.py
def funct1():
    print 4

class MyClass1:
    def __init__(self):
        print 8

main.py
from SomeUtils import *

def main():
    funct1()               # Use funct1   without problem;
    aMyObj1 = MyClass1()   # Use MyClass1 without error

if (__name__ == "__main__"):
    main()

A: Your question is naturally linked to a lot of SO older one.
See, just for reference, SO1342128 and SO1057843


text:
Q: JSON Nested data creation failing in Java import net.sf.json.*;

public class JSONDemo {

/**
 * @param args
 */
public static void main(String[] args) {
    JSONObject mainObj = new JSONObject();

    JSONObject jObj1 = new JSONObject();
    JSONObject jObj2 = new JSONObject();

    JSONArray jA1 = new JSONArray();
    JSONArray jA2 = new JSONArray();

    JSONArray mainArray= new JSONArray();

    jObj1.accumulate("id", 17);
    jObj1.accumulate("name", "Alex");
    jObj1.accumulate("children", jA1);

    mainArray.add(jObj1);

    jObj2.accumulate("id", 94);
    jObj2.accumulate("name", "Steve");
    jObj2.accumulate("children", jA2);

    //Adding the new object to jObj1 via jA1

    jA1.add(jObj2);

    mainObj.accumulate("ccgs", mainArray);
    System.out.println(mainObj.toString());
}

}

The output I got is
{"ccgs":[{"id":17,"name":"Alex","children":[]}]}

I wanted the jObj2 within the children key of jObj1.

A: Apparently the node creation order has an impact on the generated string. If you change the object creation order, beginning with the children, the Json is correct.
See that code :
    public static void main(String[] args) {
        // first create the child node
        JSONObject jObj2 = new JSONObject();
        jObj2.accumulate("id", 94);
        jObj2.accumulate("name", "Steve");
        jObj2.accumulate("children", new JSONArray());

        // then create the parent's children array
        JSONArray jA1 = new JSONArray();
        jA1.add(jObj2);

        // then create the parent
        JSONObject jObj1 = new JSONObject();
        jObj1.accumulate("id", 17);
        jObj1.accumulate("name", "Alex");
        jObj1.accumulate("children", jA1);

        // then create the main array
        JSONArray mainArray = new JSONArray();
        mainArray.add(jObj1);

        // then create the main object
        JSONObject mainObj = new JSONObject();
        mainObj.accumulate("ccgs", mainArray);

        System.out.println(mainObj);
    }

The output is :
{"ccgs":[{"id":17,"name":"Alex","children":[{"id":94,"name":"Steve","children":[]}]}]}

A: If you wanted something like this {"ccgs":[{"id":17,"name":"Alex","children":{"id":94,"name":"Steve","children":[]}}]}
Then you can do like this.
    JSONObject mainObj = new JSONObject();

    JSONObject jObj1 = new JSONObject();
    JSONObject jObj2 = new JSONObject();

    JSONArray jA1 = new JSONArray();
    JSONArray jA2 = new JSONArray();

    JSONArray mainArray= new JSONArray();

    jObj2.accumulate("id", 94);
    jObj2.accumulate("name", "Steve");
    jObj2.accumulate("children", jA2);

    jObj1.accumulate("id", 17);
    jObj1.accumulate("name", "Alex");
    jObj1.accumulate("children", jObj2);

    mainArray.add(jObj1);

    //Adding the new object to jObj1 via jA1

    jA1.add(jObj2);

    mainObj.accumulate("ccgs", mainArray);
    System.out.println(mainObj.toString());


text:
Q: Asymmetric Swaps - minimising max/min difference in list through swaps Was doing some exercises in CodeChef and came across the Asymmetric Swaps problem:

Problem
Chef has two arrays  and  of the same size .
In one operation, Chef can:

*

*Choose two integers  and  (1 ≤ , ≤ ) and swap the elements  and .

Chef came up with a task to find the minimum possible value of ( − ) after performing the swap operation any (possibly zero) number of times.
Since Chef is busy, can you help him solve this task?
Note that  and  denote the maximum and minimum elements of the array  respectively.

I have tried the below logic for the solution. But the logic fails for some test cases and I have no access to the failed test cases and where exactly the below code failed to meet the required output.
T = int(input())
for _ in range(T):
    arraySize = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    sortedList = sorted(A+B)
    minLower = sortedList[arraySize-1] - sortedList[0]                # First half of the sortedList
    minUpper = sortedList[(arraySize*2)-1] - sortedList[arraySize]    # Second half of the sortedList
    print(min(minLower,minUpper))

I saw some submitted answers and didn't get the reason or logic why they are doing so. Can someone guide where am I missing?

A: The approach to sort the input into one list is the right one. But it is not enough to look at the left and the right half of that sorted list.
It could well be that there is another sublist of length  that has its extreme values closer to each other.
Take for instance this input:
A = [1,4,5]
B = [6,11,12]

Then the sorted list is [1,4,5,6,11,12] and [4,5,6] is actually the sublist which minimises the difference between its maximum and minimum value.
So implement a loop where you select the minimum among A[i+N-1] - A[i].


text:
Q: How to convert percent encoded string to UTF-8 encoded and create directory using the UTF-8 string I have a percent encoded string: %DB%81%DB%8C%D9%84%D9%88/
I convert it to an UTF-8 encoded string by copying hexadecimal bytes (%hh -> 0xhh).
UTF-8 encoded string: str = U+00DB U+0081 U+00DB U+008C U+00D9 U+0084 U+00D9 U+0088
And in Octal: \333\201\333\214\331\204\331\201
But the name of created directory is Û ÛŒÙ"Ùˆ (something garbled) rather than یلو/. I know that in Linux we can create directory with name in any language (Urdu, Chinese, etc. if the name is encoded in UTF-8)
Also, locale of machine is set to en_US.UTF-8.
Any idea ?
Thanks @kmkamplan, I also used almost same logic to do byte by byte copy and still directory name is garbled. If on your system directory name is یلو/ then I think some issue with charset settings. My charset/encoding is set to en_US.UTF-8. Please help me with this strange behavior. Thanks.
I am getting:
0000cd0 3034 3639 4a20 6e61 3120 2038 3631 333a
0000ce0 2034 81db 8cdb 84d9 88d9 000a
0000ceb
Please refer to comment below. Thanks

A: There is confusion between UTF-8 and Unicode. Decoding %DB%81%DB%8C%D9%84%D9%88 will give you the bytes 0xDB 0x81 0xDB 0x8C 0xD9 0x84 0xD9 0x88. Apparently this is an UTF-8 encoded string consisting of arabic characters. If you read this as UTF-8 and decode it into Unicode code points you get:

*

*0xDB 0x81 → U+06C1 Arabic letter heh goal (ہ),

*0xDB 0x8C → U+06CC Arabic letter farsi yeh (ہی),

*0xD9 0x84 → U+0644 Arabic letter lam (ل),

*0xD9 0x88 → U+0648 Arabic letter waw (و).

This is not to be confused with what you are actually decoding into:

*

*U+00DB Latin capital letter U with circumflex (Û),

*U+0081

*U+0084

*U+0088

*U+008C

*U+00D9 Latin capital letter U with grave (Ù),

Furthemore, Unix filenames are actually composed of bytes, not characters. So this is up to you to choose how to display them.
So the easiest way for this case is probably to do the percent decoding into bytes, and create your directory using those bytes as filename, without translating them into actual Unicode characters.
Here is an example that works:
#include <sys/stat.h>
#include <string>

const int hex_value[256] = {
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0,
  0,10,11,12,13,14,15
};

int main(int argc, char **argv)
{
  std::string str("%DB%81%DB%8C%D9%84%D9%88");

  size_t t = 0;
  for (size_t s = 0; s < str.size(); s++) {
    if (str[s] == '%' && s + 2 < str.size()) {
      str[t] = hex_value[str[s+1]] * 16 + hex_value[str[s+2]];
      s += 2;
    }
    else
      str[t] = str[s];
    t++;
  }
  str.resize(t);

  mkdir(str.c_str(), 0755);
}

If you still see other stuff than ہیلو on your terminal, it could be your terminal that is confused as to the character set it should use. To clear up this possible confusion, pipe the output of ls through hexdump and make sure that you see the bytes you are expecting:
$ ls | hexdump
0000000 61 2e 6f 75 74 0a 63 6c 65 61 6e 2e 70 68 70 0a
…
00000c0 32 32 2e 63 6f 6d 3a 32 32 0a db 81 db 8c d9 84
00000d0 d9 88 0a
00000d3

Here you can clearly see the correct filename db 81 db 8c d9 84 d9 88 0a at the end.


text:
Q: Gitolite 3 - Setting repo description (not authorized) I'm using Gitolite 3.6
$ ssh git@host info
hello you, this is got@Git running gitolite3 v3.6.1-6-gdc8b590 on git 1.7.10.4
[...]
R W   my_project
[...]

Following the documentation on setting the repo description
$ ssh git@host desc my_project "Machin chouette"
FATAL: you are not authorized

How can this be explained ?

git@host $ cat ~/.gitolite.rc
[...]
    ENABLE => [
        [...]
        'desc',
        'cgit',
    ]
[...]

A: I found what was missing by reading the code of the desc command (didn't see it in the doc)
git@host $ nano ~/.gitolite.rc
%RC = (
    [...]
    WRITER_CAN_UPDATE_DESC          => 1,
    [...]
)


text:
Q: How to dualize norm-constrained optimization problem? Consider the following optimization problem:
\begin{equation*}
\begin{aligned}
& \underset{x\in\mathbb{R}^{+}}{\text{min}}
& & c^{T}x \\
& \text{s.t.}
& & ||x-\hat{x}||_{q} \leq \delta,\\
\end{aligned}
\end{equation*}
where $q$ could be 1, 2 or "inf".
Could anybody give some suggestions on how to dualize the norm-constrained problem like this?
Thanks!


text:
Q: Proof with binomial coefficient and kronecker delta I want to prove that
$$ \sum_{k=i}^n \binom{n}{k}\binom{k}{i}(-1)^{n-k}=\delta_{n,i} $$
Where $\delta_{n,i}$ is the Kronecker Delta, i.e. $\delta_{n,i}=0$ if $n \neq i$ and $\delta_{n,i}=1$ if $i=n$.
I have an intuitive proof with matrices representing the linear transformation $F(x)=(1+x)^n$ and $G(x)=(1-x)^n$ and their product.
But I'd prefer an accurate proof, if it exists.
Thanks.

A: By the binomial theorem we have
$$\begin{align}
x^n &= \bigl((x+1)-1\bigr)^n\\
&= \sum_{k=0}^n (-1)^{n-k}\binom{n}{k}(x+1)^k\\
&= \sum_{k=0}^n (-1)^{n-k}\binom{n}{k}\left(\sum_{i=0}^k \binom{k}{i}x^i\right)\\
&= \sum_{k=0}^n\sum_{i=0}^k (-1)^{n-k}\binom{n}{k}\binom{k}{i}x^i\\
&= \sum_{i=0}^n \left(\sum_{k=i}^n (-1)^{n-k}\binom{n}{k}\binom{k}{i}\right)x^i
\end{align}$$
and of course
$$x^n = \sum_{i=0}^n \delta_{n,i}x^i.$$

A: The sum is $$(-1)^n \sum_{k=i}^n (-1)^k \binom{n}{k,i,n-k-i}$$ which is equivalent to summing over all $i$-subsets $S$ of $[n]:=\{1,2,\ldots,n\}$ and $T \supseteq S$, so the formula is also given by $$(-1)^n \sum_{S \subseteq [n]:|S|=i} \underbrace{\sum_{T \subseteq [n]:S \subseteq T} (-1)^{|T|}}_{\text{call this } f(T)}.$$  This is illustrated below:

We observe that $f(T)$ is equal to the number of even-sized subsets of $T$ containing $S$ minus the number of odd-sized subsets of $T$ containing $S$.  Hence $f(T)=0$, and consequently the whole sum $=0$, unless $i=n$, in which case $S=[n]$, and the sum simplifies to $$(-1)^{n} (-1)^{n}=1.$$

A: Observe that when we multiply two exponential generating functions of the sequences $\{a_n\}$ and $\{b_n\}$ we get that
$$ A(z) B(z) = \sum_{n\ge 0} a_n \frac{z^n}{n!} \sum_{n\ge 0} b_n \frac{z^n}{n!}
= \sum_{n\ge 0} \sum_{k=0}^n \frac{1}{k!}\frac{1}{(n-k)!} a_k b_{n-k} z^n\\
= \sum_{n\ge 0} \sum_{k=0}^n \frac{n!}{k!(n-k)!} a_k b_{n-k} \frac{z^n}{n!}
= \sum_{n\ge 0} \left(\sum_{k=0}^n {n\choose k} a_k b_{n-k}\right)\frac{z^n}{n!}$$
i.e. the product of the two generating functions is the generating function of
$$\sum_{k=0}^n {n\choose k} a_k b_{n-k}.$$
In the present case we have
$$ A(z) = \sum_{k\ge 0} {k\choose j} \frac{z^k}{k!} =
\sum_{k\ge j} \frac{1}{j!} \frac{z^k}{(k-j)!} =
\frac{z^j}{j!} \sum_{k\ge j} \frac{z^{k-j}}{(k-j)!}
= \frac{z^j}{j!} \exp(z)$$
and
$$ B(z) = \sum_{k\ge 0} (-1)^k \frac{z^k}{k!} = \exp(-z).$$
The product $Q(z)$ of these two is
$$Q(z) = \frac{z^j}{j!} \exp(z) \exp(-z) = \frac{z^j}{j!}.$$
Extracting coefficients of the EGF with the coefficient extraction operator we clearly have
$$n! [z^n] Q(z) \quad = \quad
\begin{cases}
0 & n\ne j \\
n!  \frac{1}{j!} = 1 & n = j.
\end{cases}$$
This is precisely the definition of $\delta_{n,j}.$
We use $j$ instead of $i$ to avoid confusion with complex variables. A similar computation may be found here.


text:
Q: Send an email when adding a new user on Sakai I want an email to be sent to a new user when they login to Sakai. I searched and found a property that I can add on sakai.properties called notifyNewUserEmail. I set it to true, but upon adding a new user using admin account from the Users tool, the email is still not sent to new user's email.
Is there another config I need to do? How do I enable this?


text:
Q: blank space at the bottom of everything on my page I have a menu with a footer but when the height is greater than 1180px a blank space stands out that I tried in every way but I can't remove it and it's very annoying.
if I inspect that part it tells me that the white space is the body, I tried limiting the body and html but it still appears.

Youtube

Malvinas 1715, Libertad, Merlo (0220) 497-5100 Bs. As. Copyright © 2021

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    height: auto;
}

html {
    height: auto;
    scroll-behavior: smooth;
}

.footer-mobile {
        width: 100%;
        height: auto;
        background-color: #202020;
        display: flex;
        flex-direction: column;
    }

    .footer-list-mobile {
        width: 100%;
        height: 5rem;
        border-bottom: 1px solid #cccccc20;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        list-style: none;
        padding-left: 2rem;
    }

    .footer-list-mobile li {
        display: flex;
        justify-content: center;
        align-items: center;

    }
    .footer-list-mobile li a {
        display: flex;
        text-align: inherit;
        color: #fff;
        font-weight: 700;
        text-decoration: none;
    }
    .footer-list-mobile li a p {
        font-size: 1.1rem;
        margin-left: 0.5rem;
    }

    .footer-mobile .content-footer {
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        height: 15rem;
    }

    .footer-mobile .content-footer img {
        max-width: 60px;
        cursor: pointer;
    }

    .footer-mobile .content-footer p {
        margin-top: 1rem;
        color: #fff;
        width: 80%;
        text-align: center;
    }

Youtube

Malvinas 1715, Libertad, Merlo (0220) 497-5100 Bs. As. Copyright © 2021

This blank space only happens to me when I open the menu and the screen is larger than 1180px, but when the menu is closed I have no problem.
I already tried giving 100% height to the HTML and min-heigh to the body but it didn't work either.

A: You can try this to add style="display: block;" to your img

Youtube

Malvinas 1715, Libertad, Merlo (0220) 497-5100 Bs. As. Copyright © 2021


text:
Q: Limit connections per user using FreeRADIUS I'm here because after a good time searching how to limit the simultaneous connections of a user with FreeRADIUS I haven't achieved it...
My intention is that each user connects only once and that when they try to access again with that account, if it is already in use, it does not allow them to connect to the network, but I do not find how to do it??

A: If you are authenticating your users from a database, just insert this to the radreply table for each user:
username = "ABC"      i.e the username of the user
attribute = "Port-Limit"     i.e Radius attribute for limiting simultaneous connections
op = ":="                   i.e The radius operator
value = "1"                 i.e The number of simultaneous connections you want to allow for the user
See how it looks on my database
You can read more about Port-Limit here
You can read more about Radius attributes here too
Port-Limit Attribute: This Attribute sets the maximum number of ports to be provided to the user by the NAS. The value you set for this attribute will be sent by the server to the client in the Access-Accept packet


text:
Q: building c++ code into a shared library I have some c++ code which i use as shared library in a java application.My c++ code uses some libraries like ffmpeg and boost. and ffmpeg libraries in turn depend on libx264. my first question is - can i build my c++ into a "fat" shared library which contains all the symbols from all libraries used so that on a new machine if i just copy the fat .so file everything works.
If thats not possible then can you help me fix my current build process. This is what i am doing currently -
1)on a local VM(ubuntu 64) i compile ffmpeg code using -fPIC flag and install h264 and boost using apt-get commands.
2) on the same VM i compile my code using make file which looks like this-
INCLUDES =   -I/opt/ffmpeg/include -I/usr/lib/jvm/java-7-openjdk-   amd64/include -I/usr/lib/jvm/java-7-openjdk-amd64/include/linux

LDFLAGS =   -L/home/ubuntu/ffmpeg_shared

LIBRARIES = -lavformat -lavcodec -lswscale -lavutil -lpthread  -lx264 -lboost_system -lboost_thread -lboost_chrono

CC = g++ -std=c++11 -fPIC

all:clean final

final:Api.o ImageSequence.o OverlayAnimation.o Utils.o ImageFrame.o
$(CC)  -o final.so Api.o ImageSequence.o OverlayAnimation.o Utils.o  ImageFrame.o $(LDFLAGS) $(LIBRARIES) -shared

3) on a new machine where java app will run. i install h264 and boost using apt-get commands and copy ffmpeg's compiled library files to /usr/local/lib.
4) copy the final.so file to this new machine. but when the java code tries to use the final.so file i see it tries to use wierdly named files. for example - it tries to find libavcodec.so.57 , libavformat.so.57 etc. to fix this i just created a copy of these files ie  libavcodec.so copied to libavcodec.so.57.
5)But these ffmpeg libraries in turn uses a differently named lib264.so file. on my new machine the apt-get command for x264 installed a file named libx264.so.148 but one of ffmpeg libraries is searching for file libx264.so.142 even if i rename this libx264.so file i get new errors where ffmpeg libraries tries to call libx264's methods which has these numbers attached.
6) at this time the only working option for me is to bring the c++ code on every new machine and build final.so file locally. this is something i want to avoid since i want to distribute the .so file along with jar file to my clients which they can easily use without having to build and install stuff.

A: I may have a solution for a 'fat' library, but I'm not 100% sure if it will work.
In general, it is possible to link together static libraries into a shared library by specifying these linker flags.
g++ -Wl,--whole-archive some_static_lib.a -Wl,--no-whole-archive

Therefore you would have to compile all your libraries into static libraries. If you think it's worth the effort to do this, you can give it a try.
To the second part:
It seems that your other machine is using different versions of the libraries. In example libx264.so.148 might be reffering to version 1.4.8 or something like that.
Therefore your libx264.so should be a symbolic link to libx264.so.148. You can verify that with
ln -l

to visualize, where your symbolic link is reffering to.
I recommend to manually compile all needed libraries on both machines. Then these problems should be solved.


text:
Q: Historically, who realized the inverse function theorem could be proved with the use of contraction mappings? Historically, who realized the inverse function theorem could be proved with the use of contraction mappings? And moreover, how was the connection between contraction mappings and the inverse function theorem made?
I understand the outline of the proof, and I can see it logically flows very easily from the mean value theorem and a few other basic multivariable analysis principles. But I am having trouble seeing how I could have ever 'invented it myself'. How could you know a priori that a clever choice of definition for $\phi_y(x)$ will simultaneously give me a contraction mapping and that $\phi_y(x) = x$ would imply $f(x) = y$.
I feel like there is some standard technique and way of thinking about fixedpoints (or maybe even just smooth functions) that I'm missing.