repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
pythongssapi/python-gssapi
gssapi/mechs.py
Mechanism.from_attrs
python
def from_attrs(cls, desired_attrs=None, except_attrs=None, critical_attrs=None): if isinstance(desired_attrs, roids.OID): desired_attrs = set([desired_attrs]) if isinstance(except_attrs, roids.OID): except_attrs = set([except_attrs]) if isinstance(criti...
Get a generator of mechanisms supporting the specified attributes. See RFC 5587's :func:`indicate_mechs_by_attrs` for more information. Args: desired_attrs ([OID]): Desired attributes except_attrs ([OID]): Except attributes critical_attrs ([OID]): Critical attributes...
train
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/mechs.py#L167-L200
null
class Mechanism(roids.OID): """ A GSSAPI Mechanism This class represents a mechanism and centralizes functions dealing with mechanisms and can be used with any calls. It inherits from the low-level GSSAPI :class:`~gssapi.raw.oids.OID` class, and thus can be used with both low-level and high-le...
pythongssapi/python-gssapi
gssapi/_utils.py
import_gssapi_extension
python
def import_gssapi_extension(name): try: path = 'gssapi.raw.ext_{0}'.format(name) __import__(path) return sys.modules[path] except ImportError: return None
Import a GSSAPI extension module This method imports a GSSAPI extension module based on the name of the extension (not including the 'ext_' prefix). If the extension is not available, the method retuns None. Args: name (str): the name of the extension Returns: module: Either ...
train
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/_utils.py#L10-L30
null
import sys import types import six import decorator as deco from gssapi.raw.misc import GSSError def flag_property(flag): def setter(self, val): if val: self.flags.add(flag) else: self.flags.discard(flag) def getter(self): return flag in self.flags retu...
pythongssapi/python-gssapi
gssapi/_utils.py
inquire_property
python
def inquire_property(name, doc=None): def inquire_property(self): if not self._started: msg = ("Cannot read {0} from a security context whose " "establishment has not yet been started.") raise AttributeError(msg) return getattr(self._inquire(**{name: True...
Creates a property based on an inquire result This method creates a property that calls the :python:`_inquire` method, and return the value of the requested information. Args: name (str): the name of the 'inquire' result information Returns: property: the created property
train
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/_utils.py#L46-L68
null
import sys import types import six import decorator as deco from gssapi.raw.misc import GSSError def import_gssapi_extension(name): """Import a GSSAPI extension module This method imports a GSSAPI extension module based on the name of the extension (not including the 'ext_' prefix). If the extensi...
pythongssapi/python-gssapi
gssapi/_utils.py
_encode_dict
python
def _encode_dict(d): def enc(x): if isinstance(x, six.text_type): return x.encode(_ENCODING) else: return x return dict((enc(k), enc(v)) for k, v in six.iteritems(d))
Encodes any relevant strings in a dict
train
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/_utils.py#L101-L109
null
import sys import types import six import decorator as deco from gssapi.raw.misc import GSSError def import_gssapi_extension(name): """Import a GSSAPI extension module This method imports a GSSAPI extension module based on the name of the extension (not including the 'ext_' prefix). If the extensi...
pythongssapi/python-gssapi
gssapi/_utils.py
catch_and_return_token
python
def catch_and_return_token(func, self, *args, **kwargs): try: return func(self, *args, **kwargs) except GSSError as e: if e.token is not None and self.__DEFER_STEP_ERRORS__: self._last_err = e # skip the "return func" line above in the traceback if six.PY2: ...
Optionally defer exceptions and return a token instead When `__DEFER_STEP_ERRORS__` is set on the implementing class or instance, methods wrapped with this wrapper will catch and save their :python:`GSSError` exceptions and instead return the result token attached to the exception. The exception c...
train
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/_utils.py#L114-L139
null
import sys import types import six import decorator as deco from gssapi.raw.misc import GSSError def import_gssapi_extension(name): """Import a GSSAPI extension module This method imports a GSSAPI extension module based on the name of the extension (not including the 'ext_' prefix). If the extensi...
pythongssapi/python-gssapi
gssapi/_utils.py
check_last_err
python
def check_last_err(func, self, *args, **kwargs): if self._last_err is not None: try: if six.PY2: six.reraise(type(self._last_err), self._last_err, self._last_tb) else: # NB(directxman12): not using six.reraise in Python 3 l...
Check and raise deferred errors before running the function This method checks :python:`_last_err` before running the wrapped function. If present and not None, the exception will be raised with its original traceback.
train
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/_utils.py#L143-L177
null
import sys import types import six import decorator as deco from gssapi.raw.misc import GSSError def import_gssapi_extension(name): """Import a GSSAPI extension module This method imports a GSSAPI extension module based on the name of the extension (not including the 'ext_' prefix). If the extensi...
workhorsy/py-cpuinfo
cpuinfo/cpuinfo.py
_actual_get_cpu_info_from_cpuid
python
def _actual_get_cpu_info_from_cpuid(queue): ''' Warning! This function has the potential to crash the Python runtime. Do not call it directly. Use the _get_cpu_info_from_cpuid function instead. It will safely call this function in another process. ''' # Pipe all output to nothing sys.stdout = open(os.devnull, '...
Warning! This function has the potential to crash the Python runtime. Do not call it directly. Use the _get_cpu_info_from_cpuid function instead. It will safely call this function in another process.
train
https://github.com/workhorsy/py-cpuinfo/blob/c15afb770c1139bf76215852e17eb4f677ca3d2f/cpuinfo/cpuinfo.py#L1294-L1356
null
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright (c) 2014-2019, Matthew Brennan Jones <matthew.brennan.jones@gmail.com> # Py-cpuinfo gets CPU info with pure Python 2 & 3 # It uses the MIT License # It is hosted at: https://github.com/workhorsy/py-cpuinfo # # Permission is hereby granted, free of charge, to an...
workhorsy/py-cpuinfo
cpuinfo/cpuinfo.py
_get_cpu_info_from_cpuid
python
def _get_cpu_info_from_cpuid(): ''' Returns the CPU info gathered by querying the X86 cpuid register in a new process. Returns {} on non X86 cpus. Returns {} if SELinux is in enforcing mode. ''' from multiprocessing import Process, Queue # Return {} if can't cpuid if not DataSource.can_cpuid: return {} # G...
Returns the CPU info gathered by querying the X86 cpuid register in a new process. Returns {} on non X86 cpus. Returns {} if SELinux is in enforcing mode.
train
https://github.com/workhorsy/py-cpuinfo/blob/c15afb770c1139bf76215852e17eb4f677ca3d2f/cpuinfo/cpuinfo.py#L1358-L1399
[ "def _parse_arch(arch_string_raw):\n\timport re\n\n\tarch, bits = None, None\n\tarch_string_raw = arch_string_raw.lower()\n\n\t# X86\n\tif re.match('^i\\d86$|^x86$|^x86_32$|^i86pc$|^ia32$|^ia-32$|^bepc$', arch_string_raw):\n\t\tarch = 'X86_32'\n\t\tbits = 32\n\telif re.match('^x64$|^x86_64$|^x86_64t$|^i686-64$|^amd...
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright (c) 2014-2019, Matthew Brennan Jones <matthew.brennan.jones@gmail.com> # Py-cpuinfo gets CPU info with pure Python 2 & 3 # It uses the MIT License # It is hosted at: https://github.com/workhorsy/py-cpuinfo # # Permission is hereby granted, free of charge, to an...
workhorsy/py-cpuinfo
cpuinfo/cpuinfo.py
_get_cpu_info_from_proc_cpuinfo
python
def _get_cpu_info_from_proc_cpuinfo(): ''' Returns the CPU info gathered from /proc/cpuinfo. Returns {} if /proc/cpuinfo is not found. ''' try: # Just return {} if there is no cpuinfo if not DataSource.has_proc_cpuinfo(): return {} returncode, output = DataSource.cat_proc_cpuinfo() if returncode != 0: ...
Returns the CPU info gathered from /proc/cpuinfo. Returns {} if /proc/cpuinfo is not found.
train
https://github.com/workhorsy/py-cpuinfo/blob/c15afb770c1139bf76215852e17eb4f677ca3d2f/cpuinfo/cpuinfo.py#L1401-L1472
[ "def has_proc_cpuinfo():\n\treturn os.path.exists('/proc/cpuinfo')\n" ]
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright (c) 2014-2019, Matthew Brennan Jones <matthew.brennan.jones@gmail.com> # Py-cpuinfo gets CPU info with pure Python 2 & 3 # It uses the MIT License # It is hosted at: https://github.com/workhorsy/py-cpuinfo # # Permission is hereby granted, free of charge, to an...
workhorsy/py-cpuinfo
cpuinfo/cpuinfo.py
_get_cpu_info_from_cpufreq_info
python
def _get_cpu_info_from_cpufreq_info(): ''' Returns the CPU info gathered from cpufreq-info. Returns {} if cpufreq-info is not found. ''' try: hz_brand, scale = '0.0', 0 if not DataSource.has_cpufreq_info(): return {} returncode, output = DataSource.cpufreq_info() if returncode != 0: return {} hz...
Returns the CPU info gathered from cpufreq-info. Returns {} if cpufreq-info is not found.
train
https://github.com/workhorsy/py-cpuinfo/blob/c15afb770c1139bf76215852e17eb4f677ca3d2f/cpuinfo/cpuinfo.py#L1474-L1512
[ "def has_cpufreq_info():\n\treturn len(_program_paths('cpufreq-info')) > 0\n" ]
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright (c) 2014-2019, Matthew Brennan Jones <matthew.brennan.jones@gmail.com> # Py-cpuinfo gets CPU info with pure Python 2 & 3 # It uses the MIT License # It is hosted at: https://github.com/workhorsy/py-cpuinfo # # Permission is hereby granted, free of charge, to an...
workhorsy/py-cpuinfo
cpuinfo/cpuinfo.py
_get_cpu_info_from_lscpu
python
def _get_cpu_info_from_lscpu(): ''' Returns the CPU info gathered from lscpu. Returns {} if lscpu is not found. ''' try: if not DataSource.has_lscpu(): return {} returncode, output = DataSource.lscpu() if returncode != 0: return {} info = {} new_hz = _get_field(False, output, None, None, 'CPU ma...
Returns the CPU info gathered from lscpu. Returns {} if lscpu is not found.
train
https://github.com/workhorsy/py-cpuinfo/blob/c15afb770c1139bf76215852e17eb4f677ca3d2f/cpuinfo/cpuinfo.py#L1514-L1585
[ "def has_lscpu():\n\treturn len(_program_paths('lscpu')) > 0\n" ]
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright (c) 2014-2019, Matthew Brennan Jones <matthew.brennan.jones@gmail.com> # Py-cpuinfo gets CPU info with pure Python 2 & 3 # It uses the MIT License # It is hosted at: https://github.com/workhorsy/py-cpuinfo # # Permission is hereby granted, free of charge, to an...
workhorsy/py-cpuinfo
cpuinfo/cpuinfo.py
_get_cpu_info_from_dmesg
python
def _get_cpu_info_from_dmesg(): ''' Returns the CPU info gathered from dmesg. Returns {} if dmesg is not found or does not have the desired info. ''' # Just return {} if there is no dmesg if not DataSource.has_dmesg(): return {} # If dmesg fails return {} returncode, output = DataSource.dmesg_a() if output ...
Returns the CPU info gathered from dmesg. Returns {} if dmesg is not found or does not have the desired info.
train
https://github.com/workhorsy/py-cpuinfo/blob/c15afb770c1139bf76215852e17eb4f677ca3d2f/cpuinfo/cpuinfo.py#L1587-L1601
[ "def has_dmesg():\n\treturn len(_program_paths('dmesg')) > 0\n" ]
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright (c) 2014-2019, Matthew Brennan Jones <matthew.brennan.jones@gmail.com> # Py-cpuinfo gets CPU info with pure Python 2 & 3 # It uses the MIT License # It is hosted at: https://github.com/workhorsy/py-cpuinfo # # Permission is hereby granted, free of charge, to an...
workhorsy/py-cpuinfo
cpuinfo/cpuinfo.py
_get_cpu_info_from_ibm_pa_features
python
def _get_cpu_info_from_ibm_pa_features(): ''' Returns the CPU info gathered from lsprop /proc/device-tree/cpus/*/ibm,pa-features Returns {} if lsprop is not found or ibm,pa-features does not have the desired info. ''' try: # Just return {} if there is no lsprop if not DataSource.has_ibm_pa_features(): retur...
Returns the CPU info gathered from lsprop /proc/device-tree/cpus/*/ibm,pa-features Returns {} if lsprop is not found or ibm,pa-features does not have the desired info.
train
https://github.com/workhorsy/py-cpuinfo/blob/c15afb770c1139bf76215852e17eb4f677ca3d2f/cpuinfo/cpuinfo.py#L1606-L1724
[ "def has_ibm_pa_features():\n\treturn len(_program_paths('lsprop')) > 0\n" ]
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright (c) 2014-2019, Matthew Brennan Jones <matthew.brennan.jones@gmail.com> # Py-cpuinfo gets CPU info with pure Python 2 & 3 # It uses the MIT License # It is hosted at: https://github.com/workhorsy/py-cpuinfo # # Permission is hereby granted, free of charge, to an...
workhorsy/py-cpuinfo
cpuinfo/cpuinfo.py
_get_cpu_info_from_cat_var_run_dmesg_boot
python
def _get_cpu_info_from_cat_var_run_dmesg_boot(): ''' Returns the CPU info gathered from /var/run/dmesg.boot. Returns {} if dmesg is not found or does not have the desired info. ''' # Just return {} if there is no /var/run/dmesg.boot if not DataSource.has_var_run_dmesg_boot(): return {} # If dmesg.boot fails r...
Returns the CPU info gathered from /var/run/dmesg.boot. Returns {} if dmesg is not found or does not have the desired info.
train
https://github.com/workhorsy/py-cpuinfo/blob/c15afb770c1139bf76215852e17eb4f677ca3d2f/cpuinfo/cpuinfo.py#L1727-L1741
[ "def has_var_run_dmesg_boot():\n\tuname = platform.system().strip().strip('\"').strip(\"'\").strip().lower()\n\treturn 'linux' in uname and os.path.exists('/var/run/dmesg.boot')\n" ]
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright (c) 2014-2019, Matthew Brennan Jones <matthew.brennan.jones@gmail.com> # Py-cpuinfo gets CPU info with pure Python 2 & 3 # It uses the MIT License # It is hosted at: https://github.com/workhorsy/py-cpuinfo # # Permission is hereby granted, free of charge, to an...
workhorsy/py-cpuinfo
cpuinfo/cpuinfo.py
_get_cpu_info_from_sysctl
python
def _get_cpu_info_from_sysctl(): ''' Returns the CPU info gathered from sysctl. Returns {} if sysctl is not found. ''' try: # Just return {} if there is no sysctl if not DataSource.has_sysctl(): return {} # If sysctl fails return {} returncode, output = DataSource.sysctl_machdep_cpu_hw_cpufrequency() ...
Returns the CPU info gathered from sysctl. Returns {} if sysctl is not found.
train
https://github.com/workhorsy/py-cpuinfo/blob/c15afb770c1139bf76215852e17eb4f677ca3d2f/cpuinfo/cpuinfo.py#L1744-L1798
[ "def has_sysctl():\n\treturn len(_program_paths('sysctl')) > 0\n" ]
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright (c) 2014-2019, Matthew Brennan Jones <matthew.brennan.jones@gmail.com> # Py-cpuinfo gets CPU info with pure Python 2 & 3 # It uses the MIT License # It is hosted at: https://github.com/workhorsy/py-cpuinfo # # Permission is hereby granted, free of charge, to an...
workhorsy/py-cpuinfo
cpuinfo/cpuinfo.py
_get_cpu_info_from_sysinfo_v1
python
def _get_cpu_info_from_sysinfo_v1(): ''' Returns the CPU info gathered from sysinfo. Returns {} if sysinfo is not found. ''' try: # Just return {} if there is no sysinfo if not DataSource.has_sysinfo(): return {} # If sysinfo fails return {} returncode, output = DataSource.sysinfo_cpu() if output == ...
Returns the CPU info gathered from sysinfo. Returns {} if sysinfo is not found.
train
https://github.com/workhorsy/py-cpuinfo/blob/c15afb770c1139bf76215852e17eb4f677ca3d2f/cpuinfo/cpuinfo.py#L1810-L1866
null
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright (c) 2014-2019, Matthew Brennan Jones <matthew.brennan.jones@gmail.com> # Py-cpuinfo gets CPU info with pure Python 2 & 3 # It uses the MIT License # It is hosted at: https://github.com/workhorsy/py-cpuinfo # # Permission is hereby granted, free of charge, to an...
workhorsy/py-cpuinfo
cpuinfo/cpuinfo.py
_get_cpu_info_from_sysinfo_v2
python
def _get_cpu_info_from_sysinfo_v2(): ''' Returns the CPU info gathered from sysinfo. Returns {} if sysinfo is not found. ''' try: # Just return {} if there is no sysinfo if not DataSource.has_sysinfo(): return {} # If sysinfo fails return {} returncode, output = DataSource.sysinfo_cpu() if output == ...
Returns the CPU info gathered from sysinfo. Returns {} if sysinfo is not found.
train
https://github.com/workhorsy/py-cpuinfo/blob/c15afb770c1139bf76215852e17eb4f677ca3d2f/cpuinfo/cpuinfo.py#L1868-L1941
null
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright (c) 2014-2019, Matthew Brennan Jones <matthew.brennan.jones@gmail.com> # Py-cpuinfo gets CPU info with pure Python 2 & 3 # It uses the MIT License # It is hosted at: https://github.com/workhorsy/py-cpuinfo # # Permission is hereby granted, free of charge, to an...
workhorsy/py-cpuinfo
cpuinfo/cpuinfo.py
_get_cpu_info_from_wmic
python
def _get_cpu_info_from_wmic(): ''' Returns the CPU info gathered from WMI. Returns {} if not on Windows, or wmic is not installed. ''' try: # Just return {} if not Windows or there is no wmic if not DataSource.is_windows or not DataSource.has_wmic(): return {} returncode, output = DataSource.wmic_cpu() ...
Returns the CPU info gathered from WMI. Returns {} if not on Windows, or wmic is not installed.
train
https://github.com/workhorsy/py-cpuinfo/blob/c15afb770c1139bf76215852e17eb4f677ca3d2f/cpuinfo/cpuinfo.py#L1943-L2020
[ "def has_wmic():\n\treturncode, output = _run_and_get_stdout(['wmic', 'os', 'get', 'Version'])\n\treturn returncode == 0 and len(output) > 0\n" ]
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright (c) 2014-2019, Matthew Brennan Jones <matthew.brennan.jones@gmail.com> # Py-cpuinfo gets CPU info with pure Python 2 & 3 # It uses the MIT License # It is hosted at: https://github.com/workhorsy/py-cpuinfo # # Permission is hereby granted, free of charge, to an...
workhorsy/py-cpuinfo
cpuinfo/cpuinfo.py
_get_cpu_info_from_registry
python
def _get_cpu_info_from_registry(): ''' FIXME: Is missing many of the newer CPU flags like sse3 Returns the CPU info gathered from the Windows Registry. Returns {} if not on Windows. ''' try: # Just return {} if not on Windows if not DataSource.is_windows: return {} # Get the CPU name processor_brand =...
FIXME: Is missing many of the newer CPU flags like sse3 Returns the CPU info gathered from the Windows Registry. Returns {} if not on Windows.
train
https://github.com/workhorsy/py-cpuinfo/blob/c15afb770c1139bf76215852e17eb4f677ca3d2f/cpuinfo/cpuinfo.py#L2022-L2120
[ "def _to_decimal_string(ticks):\n\ttry:\n\t\t# Convert to string\n\t\tticks = '{0}'.format(ticks)\n\n\t\t# Strip off non numbers and decimal places\n\t\tticks = \"\".join(n for n in ticks if n.isdigit() or n=='.').strip()\n\t\tif ticks == '':\n\t\t\tticks = '0'\n\n\t\t# Add decimal if missing\n\t\tif '.' not in tic...
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright (c) 2014-2019, Matthew Brennan Jones <matthew.brennan.jones@gmail.com> # Py-cpuinfo gets CPU info with pure Python 2 & 3 # It uses the MIT License # It is hosted at: https://github.com/workhorsy/py-cpuinfo # # Permission is hereby granted, free of charge, to an...
workhorsy/py-cpuinfo
cpuinfo/cpuinfo.py
_get_cpu_info_from_kstat
python
def _get_cpu_info_from_kstat(): ''' Returns the CPU info gathered from isainfo and kstat. Returns {} if isainfo or kstat are not found. ''' try: # Just return {} if there is no isainfo or kstat if not DataSource.has_isainfo() or not DataSource.has_kstat(): return {} # If isainfo fails return {} returnc...
Returns the CPU info gathered from isainfo and kstat. Returns {} if isainfo or kstat are not found.
train
https://github.com/workhorsy/py-cpuinfo/blob/c15afb770c1139bf76215852e17eb4f677ca3d2f/cpuinfo/cpuinfo.py#L2122-L2180
[ "def has_isainfo():\n\treturn len(_program_paths('isainfo')) > 0\n" ]
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright (c) 2014-2019, Matthew Brennan Jones <matthew.brennan.jones@gmail.com> # Py-cpuinfo gets CPU info with pure Python 2 & 3 # It uses the MIT License # It is hosted at: https://github.com/workhorsy/py-cpuinfo # # Permission is hereby granted, free of charge, to an...
workhorsy/py-cpuinfo
cpuinfo/cpuinfo.py
_get_cpu_info_internal
python
def _get_cpu_info_internal(): ''' Returns the CPU info by using the best sources of information for your OS. Returns {} if nothing is found. ''' # Get the CPU arch and bits arch, bits = _parse_arch(DataSource.arch_string_raw) friendly_maxsize = { 2**31-1: '32 bit', 2**63-1: '64 bit' }.get(sys.maxsize) or 'unkn...
Returns the CPU info by using the best sources of information for your OS. Returns {} if nothing is found.
train
https://github.com/workhorsy/py-cpuinfo/blob/c15afb770c1139bf76215852e17eb4f677ca3d2f/cpuinfo/cpuinfo.py#L2211-L2273
[ "def _parse_arch(arch_string_raw):\n\timport re\n\n\tarch, bits = None, None\n\tarch_string_raw = arch_string_raw.lower()\n\n\t# X86\n\tif re.match('^i\\d86$|^x86$|^x86_32$|^i86pc$|^ia32$|^ia-32$|^bepc$', arch_string_raw):\n\t\tarch = 'X86_32'\n\t\tbits = 32\n\telif re.match('^x64$|^x86_64$|^x86_64t$|^i686-64$|^amd...
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright (c) 2014-2019, Matthew Brennan Jones <matthew.brennan.jones@gmail.com> # Py-cpuinfo gets CPU info with pure Python 2 & 3 # It uses the MIT License # It is hosted at: https://github.com/workhorsy/py-cpuinfo # # Permission is hereby granted, free of charge, to an...
workhorsy/py-cpuinfo
cpuinfo/cpuinfo.py
get_cpu_info_json
python
def get_cpu_info_json(): ''' Returns the CPU info by using the best sources of information for your OS. Returns the result in a json string ''' import json output = None # If running under pyinstaller, run normally if getattr(sys, 'frozen', False): info = _get_cpu_info_internal() output = json.dumps(info...
Returns the CPU info by using the best sources of information for your OS. Returns the result in a json string
train
https://github.com/workhorsy/py-cpuinfo/blob/c15afb770c1139bf76215852e17eb4f677ca3d2f/cpuinfo/cpuinfo.py#L2275-L2306
[ "def _get_cpu_info_internal():\n\t'''\n\tReturns the CPU info by using the best sources of information for your OS.\n\tReturns {} if nothing is found.\n\t'''\n\n\t# Get the CPU arch and bits\n\tarch, bits = _parse_arch(DataSource.arch_string_raw)\n\n\tfriendly_maxsize = { 2**31-1: '32 bit', 2**63-1: '64 bit' }.get(...
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright (c) 2014-2019, Matthew Brennan Jones <matthew.brennan.jones@gmail.com> # Py-cpuinfo gets CPU info with pure Python 2 & 3 # It uses the MIT License # It is hosted at: https://github.com/workhorsy/py-cpuinfo # # Permission is hereby granted, free of charge, to an...
workhorsy/py-cpuinfo
cpuinfo/cpuinfo.py
get_cpu_info
python
def get_cpu_info(): ''' Returns the CPU info by using the best sources of information for your OS. Returns the result in a dict ''' import json output = get_cpu_info_json() # Convert JSON to Python with non unicode strings output = json.loads(output, object_hook = _utf_to_str) return output
Returns the CPU info by using the best sources of information for your OS. Returns the result in a dict
train
https://github.com/workhorsy/py-cpuinfo/blob/c15afb770c1139bf76215852e17eb4f677ca3d2f/cpuinfo/cpuinfo.py#L2308-L2321
[ "def get_cpu_info_json():\n\t'''\n\tReturns the CPU info by using the best sources of information for your OS.\n\tReturns the result in a json string\n\t'''\n\n\timport json\n\n\toutput = None\n\n\t# If running under pyinstaller, run normally\n\tif getattr(sys, 'frozen', False):\n\t\tinfo = _get_cpu_info_internal()...
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright (c) 2014-2019, Matthew Brennan Jones <matthew.brennan.jones@gmail.com> # Py-cpuinfo gets CPU info with pure Python 2 & 3 # It uses the MIT License # It is hosted at: https://github.com/workhorsy/py-cpuinfo # # Permission is hereby granted, free of charge, to an...
yuma-m/pychord
pychord/quality.py
Quality.get_components
python
def get_components(self, root='C', visible=False): root_val = note_to_val(root) components = [v + root_val for v in self.components] if visible: components = [val_to_note(c, scale=root) for c in components] return components
Get components of chord quality :param str root: the root note of the chord :param bool visible: returns the name of notes if True :rtype: list[str|int] :return: components of chord quality
train
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/quality.py#L40-L54
[ "def note_to_val(note):\n \"\"\" Convert note to int\n\n >>> note_to_val(\"C\")\n 0\n >>> note_to_val(\"B\")\n 11\n\n :type note: str\n :rtype: int\n \"\"\"\n if note not in NOTE_VAL_DICT:\n raise ValueError(\"Unknown note {}\".format(note))\n return NOTE_VAL_DICT[note]\n" ]
class Quality(object): """ Chord quality :param str _quality: str expression of chord quality """ def __init__(self, quality): """ Constructor of chord quality :param str quality: name of quality """ if quality not in QUALITY_DICT: raise ValueError("unknown ...
yuma-m/pychord
pychord/quality.py
Quality.append_on_chord
python
def append_on_chord(self, on_chord, root): root_val = note_to_val(root) on_chord_val = note_to_val(on_chord) - root_val list_ = list(self.components) for idx, val in enumerate(list_): if val % 12 == on_chord_val: self.components.remove(val) br...
Append on chord To create Am7/G q = Quality('m7') q.append_on_chord('G', root='A') :param str on_chord: bass note of the chord :param str root: root note of the chord
train
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/quality.py#L56-L79
[ "def note_to_val(note):\n \"\"\" Convert note to int\n\n >>> note_to_val(\"C\")\n 0\n >>> note_to_val(\"B\")\n 11\n\n :type note: str\n :rtype: int\n \"\"\"\n if note not in NOTE_VAL_DICT:\n raise ValueError(\"Unknown note {}\".format(note))\n return NOTE_VAL_DICT[note]\n" ]
class Quality(object): """ Chord quality :param str _quality: str expression of chord quality """ def __init__(self, quality): """ Constructor of chord quality :param str quality: name of quality """ if quality not in QUALITY_DICT: raise ValueError("unknown ...
yuma-m/pychord
pychord/quality.py
Quality.append_note
python
def append_note(self, note, root, scale=0): root_val = note_to_val(root) note_val = note_to_val(note) - root_val + scale * 12 if note_val not in self.components: self.components.append(note_val) self.components.sort()
Append a note to quality :param str note: note to append on quality :param str root: root note of chord :param int scale: key scale
train
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/quality.py#L81-L92
[ "def note_to_val(note):\n \"\"\" Convert note to int\n\n >>> note_to_val(\"C\")\n 0\n >>> note_to_val(\"B\")\n 11\n\n :type note: str\n :rtype: int\n \"\"\"\n if note not in NOTE_VAL_DICT:\n raise ValueError(\"Unknown note {}\".format(note))\n return NOTE_VAL_DICT[note]\n" ]
class Quality(object): """ Chord quality :param str _quality: str expression of chord quality """ def __init__(self, quality): """ Constructor of chord quality :param str quality: name of quality """ if quality not in QUALITY_DICT: raise ValueError("unknown ...
yuma-m/pychord
pychord/quality.py
Quality.append_notes
python
def append_notes(self, notes, root, scale=0): for note in notes: self.append_note(note, root, scale)
Append notes to quality :param list[str] notes: notes to append on quality :param str root: root note of chord :param int scale: key scale
train
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/quality.py#L94-L102
[ "def append_note(self, note, root, scale=0):\n \"\"\" Append a note to quality\n\n :param str note: note to append on quality\n :param str root: root note of chord\n :param int scale: key scale\n \"\"\"\n root_val = note_to_val(root)\n note_val = note_to_val(note) - root_val + scale * 12\n i...
class Quality(object): """ Chord quality :param str _quality: str expression of chord quality """ def __init__(self, quality): """ Constructor of chord quality :param str quality: name of quality """ if quality not in QUALITY_DICT: raise ValueError("unknown ...
yuma-m/pychord
pychord/progression.py
ChordProgression.insert
python
def insert(self, index, chord): self._chords.insert(index, as_chord(chord))
Insert a chord to chord progressions :param int index: Index to insert a chord :type chord: str|pychord.Chord :param chord: A chord to insert :return:
train
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/progression.py#L81-L89
[ "def as_chord(chord):\n \"\"\" convert from str to Chord instance if input is str\n\n :type chord: str|pychord.Chord\n :param chord: Chord name or Chord instance\n :rtype: pychord.Chord\n :return: Chord instance\n \"\"\"\n if isinstance(chord, Chord):\n return chord\n elif isinstance(...
class ChordProgression(object): """ Class to handle chord progressions. :param list[pychord.Chord] _chords: component chords of chord progression. """ def __init__(self, initial_chords=None): """ Constructor of ChordProgression instance. :type initial_chords: str|pychord.Chord|list ...
yuma-m/pychord
pychord/chord.py
as_chord
python
def as_chord(chord): if isinstance(chord, Chord): return chord elif isinstance(chord, str): return Chord(chord) else: raise TypeError("input type should be str or Chord instance.")
convert from str to Chord instance if input is str :type chord: str|pychord.Chord :param chord: Chord name or Chord instance :rtype: pychord.Chord :return: Chord instance
train
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/chord.py#L130-L143
null
# -*- coding: utf-8 -*- from .parser import parse from .utils import transpose_note, display_appended, display_on, note_to_val class Chord(object): """ Class to handle a chord. :param str _chord: Name of the chord. (e.g. C, Am7, F#m7-5/A) :param str _root: The root note of chord. :param pychord.Qua...
yuma-m/pychord
pychord/chord.py
Chord.info
python
def info(self): return """{} root={} quality={} appended={} on={}""".format(self._chord, self._root, self._quality, self._appended, self._on)
Return information of chord to display
train
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/chord.py#L77-L83
null
class Chord(object): """ Class to handle a chord. :param str _chord: Name of the chord. (e.g. C, Am7, F#m7-5/A) :param str _root: The root note of chord. :param pychord.Quality _quality: The quality of chord. (e.g. m7, 6, M9, ...) :param list[str] _appended: The appended notes on chord. :param ...
yuma-m/pychord
pychord/chord.py
Chord.transpose
python
def transpose(self, trans, scale="C"): if not isinstance(trans, int): raise TypeError("Expected integers, not {}".format(type(trans))) self._root = transpose_note(self._root, trans, scale) if self._on: self._on = transpose_note(self._on, trans, scale) self._reconf...
Transpose the chord :param int trans: Transpose key :param str scale: key scale :return:
train
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/chord.py#L85-L97
[ "def transpose_note(note, transpose, scale=\"C\"):\n \"\"\" Transpose a note\n\n :param str note: note to transpose\n :type transpose: int\n :param str scale: key scale\n :rtype: str\n :return: transposed note\n \"\"\"\n val = note_to_val(note)\n val += transpose\n return val_to_note(v...
class Chord(object): """ Class to handle a chord. :param str _chord: Name of the chord. (e.g. C, Am7, F#m7-5/A) :param str _root: The root note of chord. :param pychord.Quality _quality: The quality of chord. (e.g. m7, 6, M9, ...) :param list[str] _appended: The appended notes on chord. :param ...
yuma-m/pychord
pychord/chord.py
Chord.components
python
def components(self, visible=True): if self._on: self._quality.append_on_chord(self.on, self.root) return self._quality.get_components(root=self._root, visible=visible)
Return the component notes of chord :param bool visible: returns the name of notes if True else list of int :rtype: list[(str or int)] :return: component notes of chord
train
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/chord.py#L99-L109
null
class Chord(object): """ Class to handle a chord. :param str _chord: Name of the chord. (e.g. C, Am7, F#m7-5/A) :param str _root: The root note of chord. :param pychord.Quality _quality: The quality of chord. (e.g. m7, 6, M9, ...) :param list[str] _appended: The appended notes on chord. :param ...
yuma-m/pychord
pychord/chord.py
Chord._parse
python
def _parse(self, chord): root, quality, appended, on = parse(chord) self._root = root self._quality = quality self._appended = appended self._on = on
parse a chord :param str chord: Name of chord.
train
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/chord.py#L111-L120
[ "def parse(chord):\n \"\"\" Parse a string to get chord component\n\n :param str chord: str expression of a chord\n :rtype: (str, pychord.Quality, str, str)\n :return: (root, quality, appended, on)\n \"\"\"\n if len(chord) > 1 and chord[1] in (\"b\", \"#\"):\n root = chord[:2]\n rest...
class Chord(object): """ Class to handle a chord. :param str _chord: Name of the chord. (e.g. C, Am7, F#m7-5/A) :param str _root: The root note of chord. :param pychord.Quality _quality: The quality of chord. (e.g. m7, 6, M9, ...) :param list[str] _appended: The appended notes on chord. :param ...
yuma-m/pychord
pychord/utils.py
transpose_note
python
def transpose_note(note, transpose, scale="C"): val = note_to_val(note) val += transpose return val_to_note(val, scale)
Transpose a note :param str note: note to transpose :type transpose: int :param str scale: key scale :rtype: str :return: transposed note
train
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/utils.py#L38-L49
[ "def note_to_val(note):\n \"\"\" Convert note to int\n\n >>> note_to_val(\"C\")\n 0\n >>> note_to_val(\"B\")\n 11\n\n :type note: str\n :rtype: int\n \"\"\"\n if note not in NOTE_VAL_DICT:\n raise ValueError(\"Unknown note {}\".format(note))\n return NOTE_VAL_DICT[note]\n", "d...
# -*- coding: utf-8 -*- from .constants import NOTE_VAL_DICT, SCALE_VAL_DICT def note_to_val(note): """ Convert note to int >>> note_to_val("C") 0 >>> note_to_val("B") 11 :type note: str :rtype: int """ if note not in NOTE_VAL_DICT: raise ValueError("Unknown note {}".for...
yuma-m/pychord
pychord/parser.py
parse
python
def parse(chord): if len(chord) > 1 and chord[1] in ("b", "#"): root = chord[:2] rest = chord[2:] else: root = chord[:1] rest = chord[1:] check_note(root, chord) on_chord_idx = rest.find("/") if on_chord_idx >= 0: on = rest[on_chord_idx + 1:] rest = re...
Parse a string to get chord component :param str chord: str expression of a chord :rtype: (str, pychord.Quality, str, str) :return: (root, quality, appended, on)
train
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/parser.py#L8-L35
[ "def check_note(note, chord):\n \"\"\" Return True if the note is valid.\n\n :param str note: note to check its validity\n :param str chord: the chord which includes the note\n :rtype: bool\n \"\"\"\n if note not in NOTE_VAL_DICT:\n raise ValueError(\"Invalid chord {}: Unknown note {}\".for...
# -*- coding: utf-8 -*- from .quality import Quality from .constants import QUALITY_DICT from .utils import NOTE_VAL_DICT def check_note(note, chord): """ Return True if the note is valid. :param str note: note to check its validity :param str chord: the chord which includes the note :rtype: bool ...
yuma-m/pychord
pychord/parser.py
check_note
python
def check_note(note, chord): if note not in NOTE_VAL_DICT: raise ValueError("Invalid chord {}: Unknown note {}".format(chord, note)) return True
Return True if the note is valid. :param str note: note to check its validity :param str chord: the chord which includes the note :rtype: bool
train
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/parser.py#L38-L47
null
# -*- coding: utf-8 -*- from .quality import Quality from .constants import QUALITY_DICT from .utils import NOTE_VAL_DICT def parse(chord): """ Parse a string to get chord component :param str chord: str expression of a chord :rtype: (str, pychord.Quality, str, str) :return: (root, quality, appended...
yuma-m/pychord
pychord/analyzer.py
note_to_chord
python
def note_to_chord(notes): if not notes: raise ValueError("Please specify notes which consist a chord.") root = notes[0] root_and_positions = [] for rotated_notes in get_all_rotated_notes(notes): rotated_root = rotated_notes[0] root_and_positions.append([rotated_root, notes_to_pos...
Convert note list to chord list :param list[str] notes: list of note arranged from lower note. ex) ["C", "Eb", "G"] :rtype: list[pychord.Chord] :return: list of chord
train
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/analyzer.py#L8-L32
[ "def get_all_rotated_notes(notes):\n \"\"\" Get all rotated notes\n\n get_all_rotated_notes([1,3,5]) -> [[1,3,5],[3,5,1],[5,1,3]]\n\n :type notes: list[str]\n :rtype: list[list[str]]\n \"\"\"\n notes_list = []\n for x in range(len(notes)):\n notes_list.append(notes[x:] + notes[:x])\n ...
# -*- coding: utf-8 -*- from .chord import Chord from .constants.qualities import QUALITY_DICT from .utils import note_to_val def notes_to_positions(notes, root): """ Get notes positions. ex) notes_to_positions(["C", "E", "G"], "C") -> [0, 4, 7] :param list[str] notes: list of notes :param str roo...
yuma-m/pychord
pychord/analyzer.py
notes_to_positions
python
def notes_to_positions(notes, root): root_pos = note_to_val(root) current_pos = root_pos positions = [] for note in notes: note_pos = note_to_val(note) if note_pos < current_pos: note_pos += 12 * ((current_pos - note_pos) // 12 + 1) positions.append(note_pos - root_po...
Get notes positions. ex) notes_to_positions(["C", "E", "G"], "C") -> [0, 4, 7] :param list[str] notes: list of notes :param str root: the root note :rtype: list[int] :return: list of note positions
train
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/analyzer.py#L35-L54
[ "def note_to_val(note):\n \"\"\" Convert note to int\n\n >>> note_to_val(\"C\")\n 0\n >>> note_to_val(\"B\")\n 11\n\n :type note: str\n :rtype: int\n \"\"\"\n if note not in NOTE_VAL_DICT:\n raise ValueError(\"Unknown note {}\".format(note))\n return NOTE_VAL_DICT[note]\n" ]
# -*- coding: utf-8 -*- from .chord import Chord from .constants.qualities import QUALITY_DICT from .utils import note_to_val def note_to_chord(notes): """ Convert note list to chord list :param list[str] notes: list of note arranged from lower note. ex) ["C", "Eb", "G"] :rtype: list[pychord.Chord] ...
yuma-m/pychord
pychord/analyzer.py
get_all_rotated_notes
python
def get_all_rotated_notes(notes): notes_list = [] for x in range(len(notes)): notes_list.append(notes[x:] + notes[:x]) return notes_list
Get all rotated notes get_all_rotated_notes([1,3,5]) -> [[1,3,5],[3,5,1],[5,1,3]] :type notes: list[str] :rtype: list[list[str]]
train
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/analyzer.py#L57-L68
null
# -*- coding: utf-8 -*- from .chord import Chord from .constants.qualities import QUALITY_DICT from .utils import note_to_val def note_to_chord(notes): """ Convert note list to chord list :param list[str] notes: list of note arranged from lower note. ex) ["C", "Eb", "G"] :rtype: list[pychord.Chord] ...
yuma-m/pychord
pychord/analyzer.py
find_quality
python
def find_quality(positions): for q, p in QUALITY_DICT.items(): if positions == list(p): return q return None
Find a quality consists of positions :param list[int] positions: note positions :rtype: str|None
train
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/analyzer.py#L71-L80
null
# -*- coding: utf-8 -*- from .chord import Chord from .constants.qualities import QUALITY_DICT from .utils import note_to_val def note_to_chord(notes): """ Convert note list to chord list :param list[str] notes: list of note arranged from lower note. ex) ["C", "Eb", "G"] :rtype: list[pychord.Chord] ...
Linaro/squad
squad/core/statistics.py
geomean
python
def geomean(values): values = [v for v in values if v > 0] if len(values) == 0: return 0 n = len(values) log_sum = 0.0 for v in values: log_sum = log_sum + log(v) return exp(log_sum / n)
The intuitive/naive way of calculating a geometric mean (first multiply the n values, then take the nth-root of the result) does not work in practice. When you multiple an large enough amount of large enough numbers, their product will oferflow the float representation, and the result will be Infinity. ...
train
https://github.com/Linaro/squad/blob/27da5375e119312a86f231df95f99c979b9f48f0/squad/core/statistics.py#L4-L30
null
from math import log, exp
Linaro/squad
squad/core/notification.py
Notification.message
python
def message(self, do_html=True, custom_email_template=None): context = { 'build': self.build, 'important_metadata': self.important_metadata, 'metadata': self.metadata, 'notification': self, 'previous_build': self.previous_build, 'regression...
Returns a tuple with (text_message,html_message)
train
https://github.com/Linaro/squad/blob/27da5375e119312a86f231df95f99c979b9f48f0/squad/core/notification.py#L113-L151
null
class Notification(object): """ Represents a notification about a project status change, that may or may not need to be sent. """ def __init__(self, status, previous=None): self.status = status self.build = status.build if previous is None: previous = status.get_...
Linaro/squad
squad/api/filters.py
decode_complex_ops
python
def decode_complex_ops(encoded_querystring, operators=None, negation=True): complex_op_re = COMPLEX_OP_NEG_RE if negation else COMPLEX_OP_RE if operators is None: operators = COMPLEX_OPERATORS # decode into: (a%3D1) & (b%3D2) | ~(c%3D3) decoded_querystring = unquote(encoded_querystring) mat...
Returns a list of (querystring, negate, op) tuples that represent complex operations. This function will raise a `ValidationError`s if: - the individual querystrings are not wrapped in parentheses - the set operators do not match the provided `operators` - there is trailing content after the ending quer...
train
https://github.com/Linaro/squad/blob/27da5375e119312a86f231df95f99c979b9f48f0/squad/api/filters.py#L71-L121
[ "def lookahead(iterable):\n it = iter(iterable)\n try:\n current = next(it)\n except StopIteration:\n return\n\n for value in it:\n yield current, True\n current = value\n yield current, False\n" ]
""" Copyright (c) 2013-2015 Philip Neustrom <philipn@gmail.com>, 2016-2017 Ryan P Kilby <rpkilby@ncsu.edu> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without li...
Linaro/squad
squad/core/management/commands/users.py
Command.handle
python
def handle(self, *args, **options): if options["sub_command"] == "add": self.handle_add(options) elif options["sub_command"] == "update": self.handle_update(options) elif options["sub_command"] == "details": self.handle_details(options["username"]) eli...
Forward to the right sub-handler
train
https://github.com/Linaro/squad/blob/27da5375e119312a86f231df95f99c979b9f48f0/squad/core/management/commands/users.py#L148-L157
null
class Command(BaseCommand): help = "Manage users" def add_arguments(self, parser): cmd = self class SubParser(CommandParser): """ Sub-parsers constructor that mimic Django constructor. See http://stackoverflow.com/a/37414551 """ def ...
Linaro/squad
squad/core/management/commands/users.py
Command.handle_add
python
def handle_add(self, options): username = options["username"] passwd = options["passwd"] if passwd is None: passwd = User.objects.make_random_password() user = User.objects.create_user(username, options["email"], passwd) if options["staff"]: user.is_staff...
Create a new user
train
https://github.com/Linaro/squad/blob/27da5375e119312a86f231df95f99c979b9f48f0/squad/core/management/commands/users.py#L159-L174
null
class Command(BaseCommand): help = "Manage users" def add_arguments(self, parser): cmd = self class SubParser(CommandParser): """ Sub-parsers constructor that mimic Django constructor. See http://stackoverflow.com/a/37414551 """ def ...
Linaro/squad
squad/core/management/commands/users.py
Command.handle_update
python
def handle_update(self, options): # pylint: disable=no-self-use username = options["username"] try: user = User.objects.get(username=username) except User.DoesNotExist: raise CommandError("User %s does not exist" % username) if options["email"]: user....
Update existing user
train
https://github.com/Linaro/squad/blob/27da5375e119312a86f231df95f99c979b9f48f0/squad/core/management/commands/users.py#L176-L192
null
class Command(BaseCommand): help = "Manage users" def add_arguments(self, parser): cmd = self class SubParser(CommandParser): """ Sub-parsers constructor that mimic Django constructor. See http://stackoverflow.com/a/37414551 """ def ...
Linaro/squad
squad/core/management/commands/users.py
Command.handle_details
python
def handle_details(self, username): try: user = User.objects.get(username=username) except User.DoesNotExist: raise CommandError("Unable to find user '%s'" % username) self.stdout.write("username : %s" % username) self.stdout.write("is_active : %s" % user.is...
Print user details
train
https://github.com/Linaro/squad/blob/27da5375e119312a86f231df95f99c979b9f48f0/squad/core/management/commands/users.py#L194-L206
null
class Command(BaseCommand): help = "Manage users" def add_arguments(self, parser): cmd = self class SubParser(CommandParser): """ Sub-parsers constructor that mimic Django constructor. See http://stackoverflow.com/a/37414551 """ def ...
Linaro/squad
squad/core/management/commands/users.py
Command.handle_list
python
def handle_list(self, show_all, format_as_csv): users = User.objects.all().order_by("username") if not show_all: users = users.exclude(is_active=False) if format_as_csv: fields = ["username", "fullname", "email", "staff", "superuser"] writer = csv.DictWriter(...
List users
train
https://github.com/Linaro/squad/blob/27da5375e119312a86f231df95f99c979b9f48f0/squad/core/management/commands/users.py#L208-L238
null
class Command(BaseCommand): help = "Manage users" def add_arguments(self, parser): cmd = self class SubParser(CommandParser): """ Sub-parsers constructor that mimic Django constructor. See http://stackoverflow.com/a/37414551 """ def ...
Linaro/squad
squad/core/plugins.py
get_plugins_by_feature
python
def get_plugins_by_feature(features): if not features: return get_all_plugins() plugins = PluginLoader.load_all().items() names = set([f.__name__ for f in features]) return [e for e, plugin in plugins if names & set(plugin.__dict__.keys())]
Returns a list of plugin names where the plugins implement at least one of the *features*. *features* must a list of Plugin methods, e.g. [Plugin.postprocess_testrun, Plugin.postprocess_testjob]
train
https://github.com/Linaro/squad/blob/27da5375e119312a86f231df95f99c979b9f48f0/squad/core/plugins.py#L48-L58
[ "def get_all_plugins():\n plugins = PluginLoader.load_all()\n return plugins.keys()\n", "def load_all(cls):\n if cls.__plugins__ is not None:\n return cls.__plugins__\n\n entry_points = []\n\n # builtin plugins\n for _, m, _ in iter_modules(['squad/plugins']):\n e = EntryPoint(m, '...
from django.db import models from django.forms import MultipleChoiceField, ChoiceField, CheckboxSelectMultiple from pkg_resources import EntryPoint, iter_entry_points from pkgutil import iter_modules class PluginNotFound(Exception): pass class PluginLoader(object): __plugins__ = None @classmethod ...
Linaro/squad
squad/core/plugins.py
apply_plugins
python
def apply_plugins(plugin_names): if plugin_names is None: return for p in plugin_names: try: plugin = get_plugin_instance(p) yield(plugin) except PluginNotFound: pass
This function should be used by code in the SQUAD core to trigger functionality from plugins. The ``plugin_names`` argument is list of plugins names to be used. Most probably, you will want to pass the list of plugins enabled for a given project, e.g. ``project.enabled_plugins``. Example:: ...
train
https://github.com/Linaro/squad/blob/27da5375e119312a86f231df95f99c979b9f48f0/squad/core/plugins.py#L61-L88
[ "def get_plugin_instance(name):\n try:\n plugin_class = PluginLoader.load_all()[name]\n except KeyError:\n raise PluginNotFound(name)\n return plugin_class()\n" ]
from django.db import models from django.forms import MultipleChoiceField, ChoiceField, CheckboxSelectMultiple from pkg_resources import EntryPoint, iter_entry_points from pkgutil import iter_modules class PluginNotFound(Exception): pass class PluginLoader(object): __plugins__ = None @classmethod ...
Linaro/squad
squad/core/models.py
Build.metadata
python
def metadata(self): if self.__metadata__ is None: metadata = {} for test_run in self.test_runs.defer(None).all(): for key, value in test_run.metadata.items(): metadata.setdefault(key, []) if value not in metadata[key]: ...
The build metadata is the union of the metadata in its test runs. Common keys with different values are transformed into a list with each of the different values.
train
https://github.com/Linaro/squad/blob/27da5375e119312a86f231df95f99c979b9f48f0/squad/core/models.py#L352-L371
null
class Build(models.Model): project = models.ForeignKey(Project, related_name='builds') version = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) datetime = models.DateTimeField() patch_source = models.ForeignKey(PatchSource, null=True, blank=True) patch_bas...
Linaro/squad
squad/core/models.py
Build.finished
python
def finished(self): reasons = [] # XXX note that by using test_jobs here, we are adding an implicit # dependency on squad.ci, what in theory violates our architecture. testjobs = self.test_jobs if testjobs.count() > 0: if testjobs.filter(fetched=False).count() > 0: ...
A finished build is a build that satisfies one of the following conditions: * it has no pending CI test jobs. * it has no submitted CI test jobs, and has at least N test runs for each of the project environments, where N is configured in Environment.expected_test_runs. Environment.e...
train
https://github.com/Linaro/squad/blob/27da5375e119312a86f231df95f99c979b9f48f0/squad/core/models.py#L389-L450
null
class Build(models.Model): project = models.ForeignKey(Project, related_name='builds') version = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) datetime = models.DateTimeField() patch_source = models.ForeignKey(PatchSource, null=True, blank=True) patch_bas...
Linaro/squad
squad/core/models.py
ProjectStatus.create_or_update
python
def create_or_update(cls, build): test_summary = build.test_summary metrics_summary = MetricsSummary(build) now = timezone.now() test_runs_total = build.test_runs.count() test_runs_completed = build.test_runs.filter(completed=True).count() test_runs_incomplete = build.te...
Creates (or updates) a new ProjectStatus for the given build and returns it.
train
https://github.com/Linaro/squad/blob/27da5375e119312a86f231df95f99c979b9f48f0/squad/core/models.py#L917-L983
null
class ProjectStatus(models.Model, TestSummaryBase): """ Represents a "checkpoint" of a project status in time. It is used by the notification system to know what was the project status at the time of the last notification. """ build = models.OneToOneField('Build', related_name='status') crea...
Linaro/squad
squad/api/rest.py
ModelViewSet.get_project_ids
python
def get_project_ids(self): user = self.request.user projects = Project.objects.accessible_to(user).values('id') return [p['id'] for p in projects]
Determines which projects the current user is allowed to visualize. Returns a list of project ids to be used in get_queryset() for filtering.
train
https://github.com/Linaro/squad/blob/27da5375e119312a86f231df95f99c979b9f48f0/squad/api/rest.py#L200-L208
null
class ModelViewSet(viewsets.ModelViewSet):
Linaro/squad
squad/api/rest.py
ProjectViewSet.builds
python
def builds(self, request, pk=None): builds = self.get_object().builds.prefetch_related('test_runs').order_by('-datetime') page = self.paginate_queryset(builds) serializer = BuildSerializer(page, many=True, context={'request': request}) return self.get_paginated_response(serializer.data)
List of builds for the current project.
train
https://github.com/Linaro/squad/blob/27da5375e119312a86f231df95f99c979b9f48f0/squad/api/rest.py#L356-L363
null
class ProjectViewSet(viewsets.ModelViewSet): """ List of projects. Includes public projects and projects that the current user has access to. """ queryset = Project.objects serializer_class = ProjectSerializer filter_fields = ('group', 'slug', 'name'...
Linaro/squad
squad/api/rest.py
ProjectViewSet.suites
python
def suites(self, request, pk=None): suites_names = self.get_object().suites.values_list('slug') suites_metadata = SuiteMetadata.objects.filter(kind='suite', suite__in=suites_names) page = self.paginate_queryset(suites_metadata) serializer = SuiteMetadataSerializer(page, many=True, contex...
List of test suite names available in this project
train
https://github.com/Linaro/squad/blob/27da5375e119312a86f231df95f99c979b9f48f0/squad/api/rest.py#L366-L374
null
class ProjectViewSet(viewsets.ModelViewSet): """ List of projects. Includes public projects and projects that the current user has access to. """ queryset = Project.objects serializer_class = ProjectSerializer filter_fields = ('group', 'slug', 'name'...
Linaro/squad
squad/api/rest.py
BuildViewSet.email
python
def email(self, request, pk=None): force = request.query_params.get("force", False) delayed_report, created = self.__return_delayed_report(request) if created or force: delayed_report = prepare_report(delayed_report.pk) if delayed_report.status_code != status.HTTP_200_OK: ...
This method produces the body of email notification for the build. By default it uses the project settings for HTML and template. These settings can be overwritten by using GET parameters: * output - sets the output format (text/plan, text/html) * template - sets the template used (id ...
train
https://github.com/Linaro/squad/blob/27da5375e119312a86f231df95f99c979b9f48f0/squad/api/rest.py#L620-L639
[ "def __return_delayed_report(self, request):\n output_format = request.query_params.get(\"output\", \"text/plain\")\n template_id = request.query_params.get(\"template\", None)\n baseline_id = request.query_params.get(\"baseline\", None)\n email_recipient = request.query_params.get(\"email_recipient\", ...
class BuildViewSet(ModelViewSet): """ List of all builds in the system. Only builds belonging to public projects and to projects you have access to are available. """ queryset = Build.objects.prefetch_related('status', 'test_runs').order_by('-datetime').all() serializer_class = BuildSerializer ...
ska-sa/spead2
spead2/send/__init__.py
HeapGenerator.add_to_heap
python
def add_to_heap(self, heap, descriptors='stale', data='stale'): if descriptors not in ['stale', 'all', 'none']: raise ValueError("descriptors must be one of 'stale', 'all', 'none'") if data not in ['stale', 'all', 'none']: raise ValueError("data must be one of 'stale', 'all', 'no...
Update a heap to contains all the new items and item descriptors since the last call. Parameters ---------- heap : :py:class:`Heap` The heap to update. descriptors : {'stale', 'all', 'none'} Which descriptors to send. The default ('stale') sends only ...
train
https://github.com/ska-sa/spead2/blob/cac95fd01d8debaa302d2691bd26da64b7828bc6/spead2/send/__init__.py#L83-L124
[ "def _get_info(self, item):\n if item.id not in self._info:\n self._info[item.id] = _ItemInfo(item)\n return self._info[item.id]\n", "def _descriptor_stale(self, item, info):\n if info.descriptor_cnt is None:\n # Never been sent before\n return True\n if self._descriptor_frequency...
class HeapGenerator(object): """Tracks which items and item values have previously been sent and generates delta heaps. Parameters ---------- item_group : :py:class:`spead2.ItemGroup` Item group to monitor. descriptor_frequency : int, optional If specified, descriptors will be r...
ska-sa/spead2
spead2/send/__init__.py
HeapGenerator.get_heap
python
def get_heap(self, *args, **kwargs): heap = Heap(self._flavour) self.add_to_heap(heap, *args, **kwargs) return heap
Return a new heap which contains all the new items and item descriptors since the last call. This is a convenience wrapper around :meth:`add_to_heap`.
train
https://github.com/ska-sa/spead2/blob/cac95fd01d8debaa302d2691bd26da64b7828bc6/spead2/send/__init__.py#L126-L133
[ "def add_to_heap(self, heap, descriptors='stale', data='stale'):\n \"\"\"Update a heap to contains all the new items and item descriptors\n since the last call.\n\n Parameters\n ----------\n heap : :py:class:`Heap`\n The heap to update.\n descriptors : {'stale', 'all', 'none'}\n Whic...
class HeapGenerator(object): """Tracks which items and item values have previously been sent and generates delta heaps. Parameters ---------- item_group : :py:class:`spead2.ItemGroup` Item group to monitor. descriptor_frequency : int, optional If specified, descriptors will be r...
ska-sa/spead2
spead2/send/trollius.py
TcpStream.connect
python
def connect(cls, *args, **kwargs): loop = kwargs.get('loop') if loop is None: loop = trollius.get_event_loop() future = trollius.Future(loop=loop) def callback(arg): if not future.done(): if isinstance(arg, Exception): loop.cal...
Open a connection. The arguments are the same as for the constructor of :py:class:`spead2.send.TcpStream`.
train
https://github.com/ska-sa/spead2/blob/cac95fd01d8debaa302d2691bd26da64b7828bc6/spead2/send/trollius.py#L132-L152
null
class TcpStream(_TcpStreamBase): """SPEAD over TCP with asynchronous connect and sends. Most users will use :py:meth:`connect` to asynchronously create a stream. The constructor should only be used if you wish to provide your own socket and take care of connecting yourself. Parameters --------...
ska-sa/spead2
spead2/recv/trollius.py
Stream._clear_done_waiters
python
def _clear_done_waiters(self): while self._waiters and self._waiters[0].done(): self._waiters.popleft() if not self._waiters: self._stop_listening()
Remove waiters that are done (should only happen if they are cancelled)
train
https://github.com/ska-sa/spead2/blob/cac95fd01d8debaa302d2691bd26da64b7828bc6/spead2/recv/trollius.py#L83-L88
null
class Stream(spead2.recv.Stream): """Stream where `get` is a coroutine that yields the next heap. Internally, it maintains a queue of waiters, each represented by a future. When a heap becomes available, it is passed to the first waiter. We use a callback on a file descriptor being readable, which happ...
ska-sa/spead2
spead2/recv/trollius.py
Stream.get
python
def get(self, loop=None): self._clear_done_waiters() if not self._waiters: # If something is available directly, we can avoid going back to # the scheduler try: heap = self.get_nowait() except spead2.Empty: pass ...
Coroutine that waits for a heap to become available and returns it.
train
https://github.com/ska-sa/spead2/blob/cac95fd01d8debaa302d2691bd26da64b7828bc6/spead2/recv/trollius.py#L113-L135
null
class Stream(spead2.recv.Stream): """Stream where `get` is a coroutine that yields the next heap. Internally, it maintains a queue of waiters, each represented by a future. When a heap becomes available, it is passed to the first waiter. We use a callback on a file descriptor being readable, which happ...
ska-sa/spead2
spead2/__init__.py
parse_range_list
python
def parse_range_list(ranges): if not ranges: return [] parts = ranges.split(',') out = [] for part in parts: fields = part.split('-', 1) if len(fields) == 2: start = int(fields[0]) end = int(fields[1]) out.extend(range(start, end + 1)) ...
Split a string like 2,3-5,8,9-11 into a list of integers. This is intended to ease adding command-line options for dealing with affinity.
train
https://github.com/ska-sa/spead2/blob/cac95fd01d8debaa302d2691bd26da64b7828bc6/spead2/__init__.py#L81-L97
null
# Copyright 2015 SKA South Africa # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) any # later version. # # This program is distribut...
ska-sa/spead2
spead2/__init__.py
Descriptor._parse_format
python
def _parse_format(cls, fmt): fields = [] if not fmt: raise ValueError('empty format') for code, length in fmt: if length == 0: raise ValueError('zero-length field (bug_compat mismatch?)') if ((code in ('u', 'i') and length in (8, 16, 32, 64)) o...
Attempt to convert a SPEAD format specification to a numpy dtype. Where necessary, `O` is used. Raises ------ ValueError If the format is illegal
train
https://github.com/ska-sa/spead2/blob/cac95fd01d8debaa302d2691bd26da64b7828bc6/spead2/__init__.py#L209-L235
null
class Descriptor(object): """Metadata for a SPEAD item. There are a number of restrictions in the way the parameters combine, which will cause `ValueError` to be raised if violated: - At most one element of `shape` can be `None`. - Exactly one of `dtype` and `format` must be non-`None`. - If `...
ska-sa/spead2
spead2/__init__.py
Descriptor.itemsize_bits
python
def itemsize_bits(self): if self.dtype is not None: return self.dtype.itemsize * 8 else: return sum(x[1] for x in self.format)
Number of bits per element
train
https://github.com/ska-sa/spead2/blob/cac95fd01d8debaa302d2691bd26da64b7828bc6/spead2/__init__.py#L238-L243
null
class Descriptor(object): """Metadata for a SPEAD item. There are a number of restrictions in the way the parameters combine, which will cause `ValueError` to be raised if violated: - At most one element of `shape` can be `None`. - Exactly one of `dtype` and `format` must be non-`None`. - If `...
ska-sa/spead2
spead2/__init__.py
Descriptor.dynamic_shape
python
def dynamic_shape(self, max_elements): known = 1 unknown_pos = -1 for i, x in enumerate(self.shape): if x is not None: known *= x else: assert unknown_pos == -1, 'Shape has multiple unknown dimensions' unknown_pos = i ...
Determine the dynamic shape, given incoming data that is big enough to hold `max_elements` elements.
train
https://github.com/ska-sa/spead2/blob/cac95fd01d8debaa302d2691bd26da64b7828bc6/spead2/__init__.py#L262-L282
null
class Descriptor(object): """Metadata for a SPEAD item. There are a number of restrictions in the way the parameters combine, which will cause `ValueError` to be raised if violated: - At most one element of `shape` can be `None`. - Exactly one of `dtype` and `format` must be non-`None`. - If `...
ska-sa/spead2
spead2/__init__.py
Descriptor.compatible_shape
python
def compatible_shape(self, shape): if len(shape) != len(self.shape): return False for x, y in zip(self.shape, shape): if x is not None and x != y: return False return True
Determine whether `shape` is compatible with the (possibly variable-sized) shape for this descriptor
train
https://github.com/ska-sa/spead2/blob/cac95fd01d8debaa302d2691bd26da64b7828bc6/spead2/__init__.py#L284-L292
null
class Descriptor(object): """Metadata for a SPEAD item. There are a number of restrictions in the way the parameters combine, which will cause `ValueError` to be raised if violated: - At most one element of `shape` can be `None`. - Exactly one of `dtype` and `format` must be non-`None`. - If `...
ska-sa/spead2
spead2/__init__.py
Item._read_bits
python
def _read_bits(cls, raw_value): have_bits = 0 bits = 0 byte_source = iter(raw_value) result = 0 while True: need_bits = yield result while have_bits < need_bits: try: bits = (bits << 8) | int(next(byte_source)) ...
Generator that takes a memory view and provides bitfields from it. After creating the generator, call `send(None)` to initialise it, and thereafter call `send(need_bits)` to obtain that many bits.
train
https://github.com/ska-sa/spead2/blob/cac95fd01d8debaa302d2691bd26da64b7828bc6/spead2/__init__.py#L367-L386
null
class Item(Descriptor): """A SPEAD item with a value and a version number. Parameters ---------- value : object, optional Initial value """ def __init__(self, *args, **kw): value = kw.pop('value', None) super(Item, self).__init__(*args, **kw) self._value = value...
ska-sa/spead2
spead2/__init__.py
Item._write_bits
python
def _write_bits(cls, array): pos = 0 current = 0 # bits not yet written into array current_bits = 0 try: while True: (value, bits) = yield if value < 0 or value >= (1 << bits): raise ValueError('Value is out of range for ...
Generator that fills a `bytearray` with provided bits. After creating the generator, call `send(None)` to initialise it, and thereafter call `send((value, bits))` to add that many bits into the array. You must call `close()` to flush any partial bytes.
train
https://github.com/ska-sa/spead2/blob/cac95fd01d8debaa302d2691bd26da64b7828bc6/spead2/__init__.py#L389-L412
null
class Item(Descriptor): """A SPEAD item with a value and a version number. Parameters ---------- value : object, optional Initial value """ def __init__(self, *args, **kw): value = kw.pop('value', None) super(Item, self).__init__(*args, **kw) self._value = value...
ska-sa/spead2
spead2/__init__.py
Item._load_recursive
python
def _load_recursive(self, shape, gen): if len(shape) > 0: ans = [] for i in range(shape[0]): ans.append(self._load_recursive(shape[1:], gen)) else: fields = [] for code, length in self.format: field = None ra...
Recursively create a multidimensional array (as lists of lists) from a bit generator.
train
https://github.com/ska-sa/spead2/blob/cac95fd01d8debaa302d2691bd26da64b7828bc6/spead2/__init__.py#L414-L452
[ "def _load_recursive(self, shape, gen):\n \"\"\"Recursively create a multidimensional array (as lists of lists)\n from a bit generator.\n \"\"\"\n if len(shape) > 0:\n ans = []\n for i in range(shape[0]):\n ans.append(self._load_recursive(shape[1:], gen))\n else:\n fie...
class Item(Descriptor): """A SPEAD item with a value and a version number. Parameters ---------- value : object, optional Initial value """ def __init__(self, *args, **kw): value = kw.pop('value', None) super(Item, self).__init__(*args, **kw) self._value = value...
ska-sa/spead2
spead2/__init__.py
Item._transform_value
python
def _transform_value(self): value = self.value if value is None: raise ValueError('Cannot send a value of None') if (isinstance(value, (six.binary_type, six.text_type)) and len(self.shape) == 1): # This is complicated by Python 3 not providing a simple way...
Mangle the value into a numpy array. This does several things: - If it is stringlike (bytes or unicode) and the expected shape is 1D, it is split into an array of characters. - It is coerced to a numpy array, enforcing the dtype and order. Where possible, no copy is made. - ...
train
https://github.com/ska-sa/spead2/blob/cac95fd01d8debaa302d2691bd26da64b7828bc6/spead2/__init__.py#L557-L592
[ "def compatible_shape(self, shape):\n \"\"\"Determine whether `shape` is compatible with the (possibly\n variable-sized) shape for this descriptor\"\"\"\n if len(shape) != len(self.shape):\n return False\n for x, y in zip(self.shape, shape):\n if x is not None and x != y:\n retu...
class Item(Descriptor): """A SPEAD item with a value and a version number. Parameters ---------- value : object, optional Initial value """ def __init__(self, *args, **kw): value = kw.pop('value', None) super(Item, self).__init__(*args, **kw) self._value = value...
ska-sa/spead2
spead2/__init__.py
Item.to_buffer
python
def to_buffer(self): value = self._transform_value() if self._fastpath != _FASTPATH_NUMPY: bit_length = self.itemsize_bits * self._num_elements() out = bytearray((bit_length + 7) // 8) gen = self._write_bits(out) gen.send(None) # Initialise the generator ...
Returns an object that implements the buffer protocol for the value. It can be either the original value (on the numpy fast path), or a new temporary object.
train
https://github.com/ska-sa/spead2/blob/cac95fd01d8debaa302d2691bd26da64b7828bc6/spead2/__init__.py#L594-L619
[ "def _write_bits(cls, array):\n \"\"\"Generator that fills a `bytearray` with provided bits. After\n creating the generator, call `send(None)` to initialise it, and\n thereafter call `send((value, bits))` to add that many bits into\n the array. You must call `close()` to flush any partial bytes.\"\"\"\n...
class Item(Descriptor): """A SPEAD item with a value and a version number. Parameters ---------- value : object, optional Initial value """ def __init__(self, *args, **kw): value = kw.pop('value', None) super(Item, self).__init__(*args, **kw) self._value = value...
ska-sa/spead2
spead2/__init__.py
ItemGroup.add_item
python
def add_item(self, *args, **kwargs): item = Item(*args, **kwargs) if item.id is None: item.id = _UNRESERVED_ID while item.id in self._by_id: item.id += 1 self._add_item(item) return item
Add a new item to the group. The parameters are used to construct an :py:class:`Item`. If `id` is `None`, it will be automatically populated with an ID that is not already in use. See the class documentation for the behaviour when the name or ID collides with an existing one. In additio...
train
https://github.com/ska-sa/spead2/blob/cac95fd01d8debaa302d2691bd26da64b7828bc6/spead2/__init__.py#L692-L708
[ "def _add_item(self, item):\n try:\n old = self._by_id[item.id]\n except KeyError:\n old = None\n try:\n old_by_name = self._by_name[item.name]\n except KeyError:\n old_by_name = None\n\n # Check if this is just the same thing\n if (old is not None and\n old....
class ItemGroup(object): """ Items are collected into sets called *item groups*, which can be indexed by either item ID or item name. There are some subtleties with respect to re-issued item descriptors. There are two cases: 1. The item descriptor is identical to a previous seen one. In this c...
ska-sa/spead2
spead2/__init__.py
ItemGroup.update
python
def update(self, heap): for descriptor in heap.get_descriptors(): item = Item.from_raw(descriptor, flavour=heap.flavour) self._add_item(item) updated_items = {} for raw_item in heap.get_items(): if raw_item.id <= STREAM_CTRL_ID: continue # ...
Update the item descriptors and items from an incoming heap. Parameters ---------- heap : :class:`spead2.recv.Heap` Incoming heap Returns ------- dict Items that have been updated from this heap, indexed by name
train
https://github.com/ska-sa/spead2/blob/cac95fd01d8debaa302d2691bd26da64b7828bc6/spead2/__init__.py#L744-L772
[ "def from_raw(cls, raw_descriptor, flavour):\n dtype = None\n format = None\n if raw_descriptor.numpy_header:\n header = _bytes_to_str_ascii(raw_descriptor.numpy_header)\n shape, order, dtype = cls._parse_numpy_header(header)\n if flavour.bug_compat & BUG_COMPAT_SWAP_ENDIAN:\n ...
class ItemGroup(object): """ Items are collected into sets called *item groups*, which can be indexed by either item ID or item name. There are some subtleties with respect to re-issued item descriptors. There are two cases: 1. The item descriptor is identical to a previous seen one. In this c...
quantmind/ccy
ccy/core/country.py
countries
python
def countries(): ''' get country dictionar from pytz and add some extra. ''' global _countries if not _countries: v = {} _countries = v try: from pytz import country_names for k, n in country_names.items(): v[k.upper()] = n exce...
get country dictionar from pytz and add some extra.
train
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/core/country.py#L41-L55
null
# # Requires pytz 2008i or higher # from .currency import currencydb # Eurozone countries (officially the euro area) # see http://en.wikipedia.org/wiki/Eurozone # using ISO 3166-1 alpha-2 country codes # see http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 # eurozone = tuple(('AT BE CY DE EE ES FI FR GR IE IT LU LV LT ...
quantmind/ccy
ccy/core/country.py
countryccys
python
def countryccys(): ''' Create a dictionary with keys given by countries ISO codes and values given by their currencies ''' global _country_ccys if not _country_ccys: v = {} _country_ccys = v ccys = currencydb() for c in eurozone: v[c] = 'EUR' f...
Create a dictionary with keys given by countries ISO codes and values given by their currencies
train
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/core/country.py#L58-L73
null
# # Requires pytz 2008i or higher # from .currency import currencydb # Eurozone countries (officially the euro area) # see http://en.wikipedia.org/wiki/Eurozone # using ISO 3166-1 alpha-2 country codes # see http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 # eurozone = tuple(('AT BE CY DE EE ES FI FR GR IE IT LU LV LT ...
quantmind/ccy
ccy/core/country.py
set_country_map
python
def set_country_map(cfrom, cto, name=None, replace=True): ''' Set a mapping between a country code to another code ''' global _country_maps cdb = countries() cfrom = str(cfrom).upper() c = cdb.get(cfrom) if c: if name: c = name cto = str(cto).upper() i...
Set a mapping between a country code to another code
train
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/core/country.py#L76-L104
[ "def countries():\n '''\n get country dictionar from pytz and add some extra.\n '''\n global _countries\n if not _countries:\n v = {}\n _countries = v\n try:\n from pytz import country_names\n for k, n in country_names.items():\n v[k.upper()] ...
# # Requires pytz 2008i or higher # from .currency import currencydb # Eurozone countries (officially the euro area) # see http://en.wikipedia.org/wiki/Eurozone # using ISO 3166-1 alpha-2 country codes # see http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 # eurozone = tuple(('AT BE CY DE EE ES FI FR GR IE IT LU LV LT ...
quantmind/ccy
ccy/core/country.py
set_new_country
python
def set_new_country(code, ccy, name): ''' Add new country code to database ''' code = str(code).upper() cdb = countries() if code in cdb: raise CountryError('Country %s already in database' % code) ccys = currencydb() ccy = str(ccy).upper() if ccy not in ccys: raise C...
Add new country code to database
train
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/core/country.py#L107-L121
[ "def currencydb():\n global _ccys\n if not _ccys:\n _ccys = ccydb()\n make_ccys(_ccys)\n return _ccys\n", "def countries():\n '''\n get country dictionar from pytz and add some extra.\n '''\n global _countries\n if not _countries:\n v = {}\n _countries = v\n ...
# # Requires pytz 2008i or higher # from .currency import currencydb # Eurozone countries (officially the euro area) # see http://en.wikipedia.org/wiki/Eurozone # using ISO 3166-1 alpha-2 country codes # see http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 # eurozone = tuple(('AT BE CY DE EE ES FI FR GR IE IT LU LV LT ...
quantmind/ccy
ccy/core/country.py
country_map
python
def country_map(code): ''' Country mapping ''' code = str(code).upper() global _country_maps return _country_maps.get(code, code)
Country mapping
train
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/core/country.py#L124-L130
null
# # Requires pytz 2008i or higher # from .currency import currencydb # Eurozone countries (officially the euro area) # see http://en.wikipedia.org/wiki/Eurozone # using ISO 3166-1 alpha-2 country codes # see http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 # eurozone = tuple(('AT BE CY DE EE ES FI FR GR IE IT LU LV LT ...
quantmind/ccy
docs/_ext/table.py
TableDirective.run
python
def run(self): # Get content and options data_path = self.arguments[0] header = self.options.get('header', True) bits = data_path.split('.') name = bits[-1] path = '.'.join(bits[:-1]) node = table_node() code = None try: module = import...
Implements the directive
train
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/docs/_ext/table.py#L35-L78
null
class TableDirective(Directive): """ ExcelTableDirective implements the directive. Directive allows to create RST tables from the contents of the Excel sheet. The functionality is very similar to csv-table (docutils) and xmltable (:mod:`sphinxcontrib.xmltable`). Example of the directive: ....
quantmind/ccy
ccy/dates/converters.py
todate
python
def todate(val): '''Convert val to a datetime.date instance by trying several conversion algorithm. If it fails it raise a ValueError exception. ''' if not val: raise ValueError("Value not provided") if isinstance(val, datetime): return val.date() elif isinstance(val, date): ...
Convert val to a datetime.date instance by trying several conversion algorithm. If it fails it raise a ValueError exception.
train
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/dates/converters.py#L12-L38
null
import time from datetime import datetime, date try: from dateutil.parser import parse as date_from_string except ImportError: # noqa def date_from_string(dte): raise NotImplementedError def date2timestamp(dte): return time.mktime(dte.timetuple()) def jstimestamp(dte): '''Convert a date t...
quantmind/ccy
ccy/dates/converters.py
timestamp2date
python
def timestamp2date(tstamp): "Converts a unix timestamp to a Python datetime object" dt = datetime.fromtimestamp(tstamp) if not dt.hour+dt.minute+dt.second+dt.microsecond: return dt.date() else: return dt
Converts a unix timestamp to a Python datetime object
train
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/dates/converters.py#L53-L59
null
import time from datetime import datetime, date try: from dateutil.parser import parse as date_from_string except ImportError: # noqa def date_from_string(dte): raise NotImplementedError def todate(val): '''Convert val to a datetime.date instance by trying several conversion algorithm. I...
quantmind/ccy
ccy/dates/converters.py
juldate2date
python
def juldate2date(val): '''Convert from a Julian date/datetime to python date or datetime''' ival = int(val) dec = val - ival try: val4 = 4*ival yd = val4 % 1461 st = 1899 if yd >= 4: st = 1900 yd1 = yd - 241 y = val4 // 1461 + st if yd1...
Convert from a Julian date/datetime to python date or datetime
train
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/dates/converters.py#L77-L110
null
import time from datetime import datetime, date try: from dateutil.parser import parse as date_from_string except ImportError: # noqa def date_from_string(dte): raise NotImplementedError def todate(val): '''Convert val to a datetime.date instance by trying several conversion algorithm. I...
quantmind/ccy
ccy/dates/converters.py
date2juldate
python
def date2juldate(val): '''Convert from a python date/datetime to a Julian date & time''' f = 12*val.year + val.month - 22803 fq = f // 12 fr = f % 12 dt = (fr*153 + 302)//5 + val.day + fq*1461//4 if isinstance(val, datetime): return dt + (val.hour + (val.minute + ( val.second...
Convert from a python date/datetime to a Julian date & time
train
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/dates/converters.py#L113-L123
null
import time from datetime import datetime, date try: from dateutil.parser import parse as date_from_string except ImportError: # noqa def date_from_string(dte): raise NotImplementedError def todate(val): '''Convert val to a datetime.date instance by trying several conversion algorithm. I...
quantmind/ccy
ccy/dates/period.py
Period.components
python
def components(self): '''The period string''' p = '' neg = self.totaldays < 0 y = self.years m = self.months w = self.weeks d = self.days if y: p = '%sY' % abs(y) if m: p = '%s%sM' % (p, abs(m)) if w: p =...
The period string
train
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/dates/period.py#L79-L95
null
class Period: def __init__(self, months=0, days=0): self._months = months self._days = days @classmethod def make(cls, pstr=''): if isinstance(pstr, cls): return pstr else: return cls().add_tenure(pstr) def isempty(self): return self._mo...
quantmind/ccy
ccy/dates/period.py
Period.simple
python
def simple(self): '''A string representation with only one period delimiter.''' if self._days: return '%sD' % self.totaldays elif self.months: return '%sM' % self._months elif self.years: return '%sY' % self.years else: return ''
A string representation with only one period delimiter.
train
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/dates/period.py#L97-L106
null
class Period: def __init__(self, months=0, days=0): self._months = months self._days = days @classmethod def make(cls, pstr=''): if isinstance(pstr, cls): return pstr else: return cls().add_tenure(pstr) def isempty(self): return self._mo...
quantmind/ccy
ccy/core/data.py
make_ccys
python
def make_ccys(db): ''' Create the currency dictionary ''' dfr = 4 dollar = r'\u0024' peso = r'\u20b1' kr = r'kr' insert = db.insert # G10 & SCANDI insert('EUR', '978', 'EU', 1, 'Euro', dfr, 'EU', '30/360', 'ACT/360', future='FE', symbol=r'\u20ac', html='&#x...
Create the currency dictionary
train
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/core/data.py#L2-L169
[ "def insert(self, *args, **kwargs):\n c = ccy(*args, **kwargs)\n self[c.code] = c\n" ]
quantmind/ccy
ccy/core/currency.py
currency_pair
python
def currency_pair(code): '''Construct a :class:`ccy_pair` from a six letter string.''' c = str(code) c1 = currency(c[:3]) c2 = currency(c[3:]) return ccy_pair(c1, c2)
Construct a :class:`ccy_pair` from a six letter string.
train
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/core/currency.py#L211-L216
[ "def currency(code):\n c = currencydb()\n return c.get(str(code).upper())\n" ]
import sys from .data import make_ccys usd_order = 5 def to_string(v): if isinstance(v, bytes): return v.decode('utf-8') else: return '%s' % v def overusdfun(v1): return v1 def overusdfuni(v1): return 1./v1 class ccy(object): ''' Currency object ''' def __init_...
quantmind/ccy
ccy/core/currency.py
ccy.swap
python
def swap(self, c2): ''' put the order of currencies as market standard ''' inv = False c1 = self if c1.order > c2.order: ct = c1 c1 = c2 c2 = ct inv = True return inv, c1, c2
put the order of currencies as market standard
train
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/core/currency.py#L100-L111
null
class ccy(object): ''' Currency object ''' def __init__(self, code, isonumber, twoletterscode, order, name, roundoff=4, default_country=None, fixeddc=None, floatdc=None, fixedfreq=None, floatfreq=None, ...
quantmind/ccy
ccy/core/currency.py
ccy.as_cross
python
def as_cross(self, delimiter=''): ''' Return a cross rate representation with respect USD. @param delimiter: could be '' or '/' normally ''' if self.order > usd_order: return 'USD%s%s' % (delimiter, self.code) else: return '%s%sUSD' % (self.code, d...
Return a cross rate representation with respect USD. @param delimiter: could be '' or '/' normally
train
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/core/currency.py#L125-L133
null
class ccy(object): ''' Currency object ''' def __init__(self, code, isonumber, twoletterscode, order, name, roundoff=4, default_country=None, fixeddc=None, floatdc=None, fixedfreq=None, floatfreq=None, ...
quantmind/ccy
ccy/core/currency.py
ccy_pair.over
python
def over(self, name='usd'): '''Returns a new currency pair with the *over* currency as second part of the pair (Foreign currency).''' name = name.upper() if self.ccy1.code == name.upper(): return ccy_pair(self.ccy2, self.ccy1) else: return self
Returns a new currency pair with the *over* currency as second part of the pair (Foreign currency).
train
https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/core/currency.py#L169-L176
null
class ccy_pair(object): ''' Currency pair such as EURUSD, USDCHF XXXYYY - XXX is the foreign currency, while YYY is the base currency XXXYYY means 1 unit of of XXX cost XXXYYY units of YYY ''' def __init__(self, c1, c2): self.ccy1 = c1 self.ccy2 = c2 self.code = '%s%s' ...
Feneric/doxypypy
doxypypy/doxypypy.py
coroutine
python
def coroutine(func): def __start(*args, **kwargs): """Automatically calls next() on the internal generator function.""" __cr = func(*args, **kwargs) next(__cr) return __cr return __start
Basic decorator to implement the coroutine pattern.
train
https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L25-L32
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Filters Python code for use with Doxygen, using a syntax-aware approach. Rather than implementing a partial Python parser with regular expressions, this script uses Python's own abstract syntax tree walker to isolate meaningful constructs. It passes along namespace in...
Feneric/doxypypy
doxypypy/doxypypy.py
main
python
def main(): from optparse import OptionParser, OptionGroup from os import sep from os.path import basename, getsize from sys import argv, exit as sysExit from chardet import detect from codecs import BOM_UTF8, open as codecsOpen def optParse(): """ Parses command line option...
Starts the parser on the file given by the filename as the first argument on the command line.
train
https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L779-L892
[ "def parseLines(self):\n \"\"\"Form an AST for the code and produce a new version of the source.\"\"\"\n inAst = parse(''.join(self.lines), self.inFilename)\n # Visit all the nodes in our tree and apply Doxygen tags to the source.\n self.visit(inAst)\n", "def getLines(self):\n \"\"\"Return the modi...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Filters Python code for use with Doxygen, using a syntax-aware approach. Rather than implementing a partial Python parser with regular expressions, this script uses Python's own abstract syntax tree walker to isolate meaningful constructs. It passes along namespace in...
Feneric/doxypypy
doxypypy/doxypypy.py
AstWalker._endCodeIfNeeded
python
def _endCodeIfNeeded(line, inCodeBlock): assert isinstance(line, str) if inCodeBlock: line = '# @endcode{0}{1}'.format(linesep, line.rstrip()) inCodeBlock = False return line, inCodeBlock
Simple routine to append end code marker if needed.
train
https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L112-L118
null
class AstWalker(NodeVisitor): """ A walker that'll recursively progress through an AST. Given an abstract syntax tree for Python code, walk through all the nodes looking for significant types (for our purposes we only care about module starts, class definitions, function definitions, variable a...
Feneric/doxypypy
doxypypy/doxypypy.py
AstWalker._checkIfCode
python
def _checkIfCode(self, inCodeBlockObj): while True: line, lines, lineNum = (yield) testLineNum = 1 currentLineNum = 0 testLine = line.strip() lineOfCode = None while lineOfCode is None: match = AstWalker.__errorLineRE.match(...
Checks whether or not a given line appears to be Python code.
train
https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L121-L176
null
class AstWalker(NodeVisitor): """ A walker that'll recursively progress through an AST. Given an abstract syntax tree for Python code, walk through all the nodes looking for significant types (for our purposes we only care about module starts, class definitions, function definitions, variable a...
Feneric/doxypypy
doxypypy/doxypypy.py
AstWalker.__alterDocstring
python
def __alterDocstring(self, tail='', writer=None): assert isinstance(tail, str) and isinstance(writer, GeneratorType) lines = [] timeToSend = False inCodeBlock = False inCodeBlockObj = [False] inSection = False prefix = '' firstLineNum = -1 section...
Runs eternally, processing docstring lines. Parses docstring lines as they get fed in via send, applies appropriate Doxygen tags, and passes them along in batches for writing.
train
https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L179-L368
null
class AstWalker(NodeVisitor): """ A walker that'll recursively progress through an AST. Given an abstract syntax tree for Python code, walk through all the nodes looking for significant types (for our purposes we only care about module starts, class definitions, function definitions, variable a...
Feneric/doxypypy
doxypypy/doxypypy.py
AstWalker.__writeDocstring
python
def __writeDocstring(self): while True: firstLineNum, lastLineNum, lines = (yield) newDocstringLen = lastLineNum - firstLineNum + 1 while len(lines) < newDocstringLen: lines.append('') # Substitute the new block of lines for the original block of l...
Runs eternally, dumping out docstring line batches as they get fed in. Replaces original batches of docstring lines with modified versions fed in via send.
train
https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L371-L384
null
class AstWalker(NodeVisitor): """ A walker that'll recursively progress through an AST. Given an abstract syntax tree for Python code, walk through all the nodes looking for significant types (for our purposes we only care about module starts, class definitions, function definitions, variable a...
Feneric/doxypypy
doxypypy/doxypypy.py
AstWalker._processDocstring
python
def _processDocstring(self, node, tail='', **kwargs): typeName = type(node).__name__ # Modules don't have lineno defined, but it's always 0 for them. curLineNum = startLineNum = 0 if typeName != 'Module': startLineNum = curLineNum = node.lineno - 1 # Figure out where ...
Handles a docstring for functions, classes, and modules. Basically just figures out the bounds of the docstring and sends it off to the parser to do the actual work.
train
https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L386-L515
null
class AstWalker(NodeVisitor): """ A walker that'll recursively progress through an AST. Given an abstract syntax tree for Python code, walk through all the nodes looking for significant types (for our purposes we only care about module starts, class definitions, function definitions, variable a...
Feneric/doxypypy
doxypypy/doxypypy.py
AstWalker._checkMemberName
python
def _checkMemberName(name): assert isinstance(name, str) restrictionLevel = None if not name.endswith('__'): if name.startswith('__'): restrictionLevel = 'private' elif name.startswith('_'): restrictionLevel = 'protected' return res...
See if a member name indicates that it should be private. Private variables in Python (starting with a double underscore but not ending in a double underscore) and bed lumps (variables that are not really private but are by common convention treated as protected because they begin with ...
train
https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L518-L535
null
class AstWalker(NodeVisitor): """ A walker that'll recursively progress through an AST. Given an abstract syntax tree for Python code, walk through all the nodes looking for significant types (for our purposes we only care about module starts, class definitions, function definitions, variable a...
Feneric/doxypypy
doxypypy/doxypypy.py
AstWalker._processMembers
python
def _processMembers(self, node, contextTag): restrictionLevel = self._checkMemberName(node.name) if restrictionLevel: workTag = '{0}{1}# @{2}'.format(contextTag, linesep, restrictionLevel) else: ...
Mark up members if they should be private. If the name indicates it should be private or protected, apply the appropriate Doxygen tags.
train
https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L537-L551
[ "def _checkMemberName(name):\n \"\"\"\n See if a member name indicates that it should be private.\n\n Private variables in Python (starting with a double underscore but\n not ending in a double underscore) and bed lumps (variables that\n are not really private but are by common convention treated as\...
class AstWalker(NodeVisitor): """ A walker that'll recursively progress through an AST. Given an abstract syntax tree for Python code, walk through all the nodes looking for significant types (for our purposes we only care about module starts, class definitions, function definitions, variable a...