code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if self._mode:
if self._mode != mode:
raise RuntimeError('Can\'t change mode (from %s to %s)' % (self._mode, mode))
self._require_version(major=major, minor=minor)
self._mode = mode
# when setting mode, we reset all flags
self.ticket_flags = Y... | def _change_mode(self, mode, major, minor) | Change mode of operation, with some sanity checks. | 4.660625 | 4.404648 | 1.058115 |
if data.startswith(b'h:'):
new = binascii.unhexlify(data[2:])
else:
new = data
if len(new) == 20:
self.key = new[:16]
self.uid = new[16:]
else:
raise yubico_exception.InputError('HMAC key must be exactly 20 bytes') | def _set_20_bytes_key(self, data) | Set a 20 bytes key. This is used in CHAL_HMAC and OATH_HOTP mode.
Supply data as either a raw bytestring, or a hexlified bytestring prefixed by 'h:'.
The result, after any hex decoding, must be 20 bytes. | 4.082398 | 3.191911 | 1.278983 |
m_crc = 0xffff
for this in data:
m_crc ^= ord_byte(this)
for _ in range(8):
j = m_crc & 1
m_crc >>= 1
if j:
m_crc ^= 0x8408
return m_crc | def crc16(data) | Calculate an ISO13239 CRC checksum of the input buffer (bytestring). | 2.813412 | 2.775177 | 1.013778 |
if not src:
return str(src)
if type(src) is not bytes:
raise yubico_exception.InputError('Hexdump \'src\' must be bytestring (got %s)' % type(src))
offset = 0
result = ''
for this in group(src, length):
if colorize:
last, this = this[-1], this[:-1]
... | def hexdump(src, length=8, colorize=False) | Produce a string hexdump of src, for debug output.
Input: bytestring; output: text string | 3.594849 | 3.603586 | 0.997575 |
return [data[i:i+num] for i in range(0, len(data), num)] | def group(data, num) | Split data into chunks of num chars each | 2.148152 | 1.817497 | 1.181929 |
try:
maketrans = string.maketrans
except AttributeError:
# Python 3
maketrans = bytes.maketrans
t_map = maketrans(b"cbdefghijklnrtuv", b"0123456789abcdef")
return data.translate(t_map) | def modhex_decode(data) | Convert a modhex bytestring to ordinary hex. | 3.322766 | 3.179406 | 1.04509 |
if len(hmac_result) != 20:
raise yubico_exception.YubicoError("HMAC-SHA-1 not 20 bytes long")
offset = ord_byte(hmac_result[19]) & 0xf
bin_code = (ord_byte(hmac_result[offset]) & 0x7f) << 24 \
| (ord_byte(hmac_result[offset+1]) & 0xff) << 16 \
| (ord_byte(hmac_result[offset+2... | def hotp_truncate(hmac_result, length=6) | Perform the HOTP Algorithm truncating.
Input is a bytestring. | 2.373089 | 2.318232 | 1.023663 |
parsed = {}
while data:
t, l, data = ord_byte(data[0]), ord_byte(data[1]), data[2:]
parsed[t], data = data[:l], data[l:]
return parsed | def tlv_parse(data) | Parses a bytestring of TLV values into a dict with the tags as keys. | 3.682592 | 3.274867 | 1.124501 |
if self.enabled:
if what in self.colors:
return self.colors[what]
return '' | def get(self, what) | Get the ANSI code for 'what'
Returns an empty string if disabled/not found | 5.716873 | 4.211459 | 1.357457 |
modes = set([
cls.OTP,
cls.CCID,
cls.OTP_CCID,
cls.U2F,
cls.OTP_U2F,
cls.U2F_CCID,
cls.OTP_U2F_CCID
])
if otp:
modes.difference_update(set([
cls.CCID,
cls.U2F... | def all(cls, otp=False, ccid=False, u2f=False) | Returns a set of all USB modes, with optional filtering | 1.656334 | 1.588964 | 1.042399 |
pids = set([
cls.YUBIKEY,
cls.NEO_OTP,
cls.NEO_OTP_CCID,
cls.NEO_CCID,
cls.NEO_U2F,
cls.NEO_OTP_U2F,
cls.NEO_U2F_CCID,
cls.NEO_OTP_U2F_CCID,
cls.NEO_SKY,
cls.YK4_OTP,
cls.... | def all(cls, otp=False, ccid=False, u2f=False) | Returns a set of all PIDs, with optional filtering | 1.579374 | 1.553209 | 1.016845 |
# From ykdef.h :
#
# // Frame structure
# #define SLOT_DATA_SIZE 64
# typedef struct {
# unsigned char payload[SLOT_DATA_SIZE];
# unsigned char slot;
# unsigned short crc;
# unsigned char filler[3];
# } YKFRAME;
f... | def to_string(self) | Return the frame as a 70 byte string. | 7.739853 | 6.236627 | 1.241032 |
rest = self.to_string()
seq = 0
out = []
# When sending a frame to the YubiKey, we can (should) remove any
# 7-byte serie that only consists of '\x00', besides the first
# and last serie.
while rest:
this, rest = rest[:7], rest[7:]
... | def to_feature_reports(self, debug=False) | Return the frame as an array of 8-byte parts, ready to be sent to a YubiKey. | 5.57162 | 4.792833 | 1.16249 |
if not debug:
return data
if self.command in [
SLOT.CONFIG,
SLOT.CONFIG2,
SLOT.UPDATE1,
SLOT.UPDATE2,
SLOT.SWAP,
]:
# annotate according to config_st (see ykdef.h)
if yubico_util.ord_byte(dat... | def _debug_string(self, debug, data) | Annotate a frames data, if debug is True. | 3.214959 | 3.170337 | 1.014075 |
with open('yubico/yubico_version.py', 'r') as f:
match = VERSION_PATTERN.search(f.read())
return match.group(1) | def get_version() | Return the current version as defined by yubico/yubico_version.py. | 4.519567 | 2.561615 | 1.764343 |
if not self.capabilities.have_nfc_ndef(slot):
raise yubikey_base.YubiKeyVersionError("NDEF slot %i unsupported in %s" % (slot, self))
return self._device._write_config(ndef, _NDEF_SLOTS[slot]) | def write_ndef(self, ndef, slot=1) | Write an NDEF tag configuration to the YubiKey NEO. | 9.491994 | 8.19062 | 1.158886 |
if not self.capabilities.have_usb_mode(device_config._mode):
raise yubikey_base.YubiKeyVersionError("USB mode: %02x not supported for %s" % (device_config._mode, self))
return self._device._write_config(device_config, SLOT.DEVICE_CONFIG) | def write_device_config(self, device_config) | Write a DEVICE_CONFIG to the YubiKey NEO. | 8.090198 | 6.904888 | 1.171662 |
self.ndef_type = _NDEF_TEXT_TYPE
self.ndef_text_lang = language
self.ndef_text_enc = encoding
return self | def text(self, encoding = 'UTF-8', language = 'en') | Configure parameters for NDEF type TEXT.
@param encoding: The encoding used. Should be either 'UTF-8' or 'UTF16'.
@param language: ISO/IANA language code (see RFC 3066). | 6.142476 | 5.067643 | 1.212097 |
if (url, text, other) == (True, False, None):
self.ndef_type = _NDEF_URI_TYPE
elif (url, text, other) == (False, True, None):
self.ndef_type = _NDEF_TEXT_TYPE
elif (url, text, type(other)) == (False, False, int):
self.ndef_type = other
else:
... | def type(self, url = False, text = False, other = None) | Change the NDEF type. | 4.061687 | 3.511692 | 1.156618 |
data = self.ndef_str
if self.ndef_type == _NDEF_URI_TYPE:
data = self._encode_ndef_uri_type(data)
elif self.ndef_type == _NDEF_TEXT_TYPE:
data = self._encode_ndef_text_params(data)
if len(data) > _NDEF_DATA_SIZE:
raise YubiKeyNEO_USBHIDError("... | def to_string(self) | Return the current NDEF as a string (always 64 bytes). | 4.321102 | 4.113316 | 1.050515 |
t = 0x0
for (code, prefix) in uri_identifiers:
if data[:len(prefix)].decode('latin-1').lower() == prefix:
t = code
data = data[len(prefix):]
break
data = yubico_util.chr_byte(t) + data
return data | def _encode_ndef_uri_type(self, data) | Implement NDEF URI Identifier Code.
This is a small hack to replace some well known prefixes (such as http://)
with a one byte code. If the prefix is not known, 0x00 is used. | 5.879209 | 4.727969 | 1.243496 |
status = len(self.ndef_text_lang)
if self.ndef_text_enc == 'UTF16':
status = status & 0b10000000
return yubico_util.chr_byte(status) + self.ndef_text_lang + data | def _encode_ndef_text_params(self, data) | Prepend language and enconding information to data, according to
nfcforum-ts-rtd-text-1-0.pdf | 6.904408 | 5.945524 | 1.161278 |
fmt = '<BBH'
first = struct.pack(
fmt,
self._mode,
self._cr_timeout,
self._auto_eject_time
)
#crc = 0xffff - yubico_util.crc16(first)
#second = first + struct.pack('<H', crc)
return first | def to_string(self) | Return the current DEVICE_CONFIG as a string (always 4 bytes). | 8.593469 | 7.59204 | 1.131905 |
data = self.to_string()
payload = data.ljust(64, b'\0')
return yubikey_frame.YubiKeyFrame(command=slot, payload=payload) | def to_frame(self, slot=SLOT.DEVICE_CONFIG) | Return the current configuration as a YubiKeyFrame object. | 7.46137 | 5.113393 | 1.459182 |
payload = self.scanmap.ljust(64, b'\0')
return yubikey_frame.YubiKeyFrame(command=slot, payload=payload) | def to_frame(self, slot=SLOT.SCAN_MAP) | Return the current configuration as a YubiKeyFrame object. | 9.972184 | 6.689688 | 1.49068 |
try:
hid_device = YubiKeyHIDDevice(debug, skip)
yk_version = hid_device.status().ykver()
if (2, 1, 4) <= yk_version <= (2, 1, 9):
return YubiKeyNEO_USBHID(debug, skip, hid_device)
if yk_version < (3, 0, 0):
return YubiKeyUSBHID(debug, skip, hid_device)
... | def find_key(debug=False, skip=0) | Locate a connected YubiKey. Throws an exception if none is found.
This function is supposed to be possible to extend if any other YubiKeys
appear in the future.
Attributes :
skip -- number of YubiKeys to skip
debug -- True or False | 3.280476 | 3.176752 | 1.032651 |
if version:
version = ','.join(v.strip() for v in version.split(',')).strip()
if version.startswith('(') and version.endswith(')'):
version = version[1:-1]
version = ''.join(v for v in version if v.strip())
else:
version = ''
return version | def norm_package_version(version) | Normalize a version by removing extra spaces and parentheses. | 2.949528 | 2.46721 | 1.195492 |
parts = spec.rsplit(sep, 1)
spec_start = parts[0].strip()
spec_end = ''
if len(parts) == 2:
spec_end = parts[-1].strip()
return spec_start, spec_end | def split_spec(spec, sep) | Split a spec by separator and return stripped start and end parts. | 2.259202 | 2.009001 | 1.12454 |
name, extras, const = spec, [], ''
# Remove excess whitespace
spec = ' '.join(p for p in spec.split(' ') if p).strip()
# Extract marker (Assumes that there can only be one ';' inside the spec)
spec, marker = split_spec(spec, ';')
# Extract url (Assumes that there can only be one '@' insi... | def parse_specification(spec) | Parse a requirement from a python distribution metadata and return a
tuple with name, extras, constraints, marker and url components.
This method does not enforce strict specifications but extracts the
information which is assumed to be *correct*. As such no errors are raised.
Example
-------
... | 3.601392 | 3.238176 | 1.112167 |
python_version = sys.version_info.major
if python_version == 3:
filedata = Parser().parsestr(filedata)
else:
filedata = Parser().parsestr(filedata.encode("UTF-8", "replace"))
payload = filedata.get_payload()
lines = payload.split('\n')
while True:
if lines and lines... | def get_header_description(filedata) | Get description from metadata file and remove any empty lines at end. | 3.065003 | 2.77771 | 1.103428 |
description = get_header_description(data)
config_items = python_version_check(data)
attrs = dict(config_items)
name = pop_key(attrs, 'Name', None)
basename = path.basename(filename)
if name is None:
name = basename.split('-')[0]
package_data = {
'name': name,
... | def format_sdist_header_metadata(data, filename) | Format the metadata of pypi packages stored in email header format.
Currently only used as backup on the wheel (compressed) file format. | 2.762466 | 2.740291 | 1.008092 |
if args.package_type:
package_type = args.package_type
else:
logger.info('Detecting file type...')
package_type = detect_package_type(filename)
if package_type is None:
message = 'Could not detect package type of file %r please specify package type with option ... | def determine_package_type(filename, args) | return the file type from the inspected package or from the
-t/--package-type argument | 3.1353 | 3.000591 | 1.044894 |
string = transliterate(string)
# Turn unwanted chars into the separator
string = re.sub(r"(?i)[^a-z0-9\-_]+", separator, string)
if separator:
re_sep = re.escape(separator)
# No more than one of the separator in a row.
string = re.sub(r'%s{2,}' % re_sep, separator, string)
... | def parameterize(string, separator='-') | Replace special characters in a string so that it may be used as part of a
'pretty' URL.
Example::
>>> parameterize(u"Donald E. Knuth")
'donald-e-knuth' | 3.546467 | 4.094602 | 0.866132 |
try:
normalized = unicodedata.normalize('NFKD', unicode(string))
except NameError:
normalized = unicodedata.normalize('NFKD', string)
return normalized.encode('ascii', 'ignore').decode('ascii') | def transliterate(string) | Replace non-ASCII characters with an ASCII approximation. If no
approximation exists, the non-ASCII character is ignored. The string must
be ``unicode``.
Examples::
>>> transliterate(u'älämölö')
u'alamolo'
>>> transliterate(u'Ærøskøbing')
u'rskbing' | 2.357898 | 2.705071 | 0.871659 |
'''List the channels for owner
If owner is none, the currently logged in user is used
'''
url = '%s/channels/%s' % (self.domain, owner)
res = self.session.get(url)
self._check_response(res, [200])
return res.json() | def list_channels(self, owner) | List the channels for owner
If owner is none, the currently logged in user is used | 4.382034 | 3.008479 | 1.456561 |
'''List the channels for owner
If owner is none, the currently logged in user is used
'''
url = '%s/channels/%s/%s' % (self.domain, owner, channel)
res = self.session.get(url)
self._check_response(res, [200])
return res.json() | def show_channel(self, channel, owner) | List the channels for owner
If owner is none, the currently logged in user is used | 4.629345 | 2.916937 | 1.587057 |
'''
Add a channel to the specified files
:param channel: channel to add
:param owner: The user to add the channel to (all files of all packages for this user)
:param package: The package to add the channel to (all files in this package)
:param version: The versio... | def add_channel(self, channel, owner, package=None, version=None, filename=None) | Add a channel to the specified files
:param channel: channel to add
:param owner: The user to add the channel to (all files of all packages for this user)
:param package: The package to add the channel to (all files in this package)
:param version: The version to add the channel... | 3.404836 | 2.163675 | 1.573636 |
'''
Remove a channel from the specified files
:param channel: channel to remove
:param owner: The user to remove the channel from (all files of all packages for this user)
:param package: The package to remove the channel from (all files in this package)
:param v... | def remove_channel(self, channel, owner, package=None, version=None, filename=None) | Remove a channel from the specified files
:param channel: channel to remove
:param owner: The user to remove the channel from (all files of all packages for this user)
:param package: The package to remove the channel from (all files in this package)
:param version: The version ... | 3.624302 | 2.22842 | 1.6264 |
'''
Tag all files in channel <channel> also as channel <to_channel>
:param channel: channel to copy
:param owner: Perform this operation on all packages of this user
:param to_channel: Destination name (may be a channel that already exists)
'''
... | def copy_channel(self, channel, owner, to_channel) | Tag all files in channel <channel> also as channel <to_channel>
:param channel: channel to copy
:param owner: Perform this operation on all packages of this user
:param to_channel: Destination name (may be a channel that already exists) | 6.200861 | 2.251131 | 2.754553 |
'''
Tag all files in channel <channel> also as channel <to_channel>
:param channel: channel to copy
:param owner: Perform this operation on all packages of this user
:param to_channel: Destination name (may be a channel that already exists)
'''
... | def lock_channel(self, channel, owner) | Tag all files in channel <channel> also as channel <to_channel>
:param channel: channel to copy
:param owner: Perform this operation on all packages of this user
:param to_channel: Destination name (may be a channel that already exists) | 8.794956 | 2.30053 | 3.823013 |
'''
Tag all files in channel <channel> also as channel <to_channel>
:param channel: channel to copy
:param owner: Perform this operation on all packages of this user
:param to_channel: Destination name (may be a channel that already exists)
'''
... | def unlock_channel(self, channel, owner) | Tag all files in channel <channel> also as channel <to_channel>
:param channel: channel to copy
:param owner: Perform this operation on all packages of this user
:param to_channel: Destination name (may be a channel that already exists) | 9.19551 | 2.424556 | 3.792657 |
components = handle.split('/', 1)
if len(components) == 1:
return None, components[0]
elif len(components) == 2:
return components[0], components[1]
else:
raise BinstarError("{} can't be parsed".format(handle)) | def parse(handle) | >>> parse("user/notebook")
('user', 'notebook')
>>> parse("notebook")
(None, 'notebook')
:param handle: String
:return: username, notebooks | 3.557425 | 2.815602 | 1.263469 |
self.package and self.release
try:
return self.aserver_api.upload(self.username, self.project, self.version,
basename(self.filepath), open(self.filepath, 'rb'),
self.filepath.split('.')[-1])
except... | def upload(self, force=False) | Uploads a notebook
:param force: True/False
:returns {} | 5.403233 | 5.349661 | 1.010014 |
try:
return authenticate(**kwargs)
except errors.BinstarError as err:
if kwargs.get('fail_if_already_exists') and len(err.args) > 1 and err.args[1] == 400:
logger.warning('It appears you are already logged in from host %s' % socket.gethostname())
logger.warning('Log... | def try_replace_token(authenticate, **kwargs) | Authenticates using the given *authenticate*, retrying if the token needs
to be replaced. | 5.896866 | 5.965511 | 0.988493 |
msg = 'API server not found. Please check your API url configuration.'
try:
response = self.session.head(self.domain)
except Exception as e:
raise_from(errors.ServerError(msg), e)
try:
self._check_response(response)
except errors.Not... | def check_server(self) | Checks if the server is reachable and throws
and exception if it isn't | 4.545583 | 4.309509 | 1.05478 |
'''
Use basic authentication to create an authentication token using the interface below.
With this technique, a username and password need not be stored permanently, and the user can
revoke access at any time.
:param username: The users name
:param password: The users p... | def _authenticate(self,
auth,
application,
application_url=None,
for_user=None,
scopes=None,
created_with=None,
max_age=None,
strength='strong',
... | Use basic authentication to create an authentication token using the interface below.
With this technique, a username and password need not be stored permanently, and the user can
revoke access at any time.
:param username: The users name
:param password: The users password
:par... | 4.481331 | 2.105772 | 2.128118 |
'''
Retrieve information on the current authentication token
'''
url = '%s/authentication' % (self.domain)
res = self.session.get(url)
self._check_response(res)
return res.json() | def authentication(self) | Retrieve information on the current authentication token | 5.219183 | 3.357515 | 1.554478 |
if auth_name:
if organization:
url = '%s/authentications/org/%s/name/%s' % (self.domain, organization, auth_name)
else:
url = '%s/authentications/name/%s' % (self.domain, auth_name)
else:
url = '%s/authentications' % (self.doma... | def remove_authentication(self, auth_name=None, organization=None) | Remove the current authentication or the one given by `auth_name` | 2.272301 | 2.29331 | 0.990839 |
'''
Get user information.
:param login: (optional) the login name of the user or None. If login is None
this method will return the information of the authenticated user.
'''
if login:
url = '%s/user/%s' % (self.domain, login)
else:
... | def user(self, login=None) | Get user information.
:param login: (optional) the login name of the user or None. If login is None
this method will return the information of the authenticated user. | 3.127795 | 2.047396 | 1.527694 |
'''
Returns a list of packages for a given user and optionally filter
by `platform`, `package_type` and `type_`.
:param login: (optional) the login name of the user or None. If login
is None this method will return the packages for the
authent... | def user_packages(
self,
login=None,
platform=None,
package_type=None,
type_=None,
access=None) | Returns a list of packages for a given user and optionally filter
by `platform`, `package_type` and `type_`.
:param login: (optional) the login name of the user or None. If login
is None this method will return the packages for the
authenticated user.
... | 2.797098 | 1.351099 | 2.070239 |
'''
Get information about a specific package
:param login: the login of the package owner
:param package_name: the name of the package
'''
url = '%s/package/%s/%s' % (self.domain, login, package_name)
res = self.session.get(url)
self._check_response(res)
... | def package(self, login, package_name) | Get information about a specific package
:param login: the login of the package owner
:param package_name: the name of the package | 2.657761 | 2.344721 | 1.133509 |
'''
Add a new package to a users account
:param login: the login of the package owner
:param package_name: the name of the package to be created
:param package_type: A type identifier for the package (eg. 'pypi' or 'conda', etc.)
:param summary: A short summary about the... | def add_package(self, login, package_name,
summary=None,
license=None,
public=True,
license_url=None,
license_family=None,
attrs=None,
package_type=None) | Add a new package to a users account
:param login: the login of the package owner
:param package_name: the name of the package to be created
:param package_type: A type identifier for the package (eg. 'pypi' or 'conda', etc.)
:param summary: A short summary about the package
:pa... | 3.10018 | 1.93344 | 1.603453 |
'''
Get information about a specific release
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the name of the package
'''
url = '%s/release/%s/%s/%s' % (self.domain, login, package_name, version)
re... | def release(self, login, package_name, version) | Get information about a specific release
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the name of the package | 2.552151 | 2.035885 | 1.253583 |
'''
remove a release and all files under it
:param username: the login of the package owner
:param package_name: the name of the package
:param version: the name of the package
'''
url = '%s/release/%s/%s/%s' % (self.domain, username, package_name, version)
... | def remove_release(self, username, package_name, version) | remove a release and all files under it
:param username: the login of the package owner
:param package_name: the name of the package
:param version: the name of the package | 3.126438 | 2.221902 | 1.4071 |
'''
Add a new release to a package.
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the version string of the release
:param requirements: A dict of requirements TODO: describe
:param announce: An announce... | def add_release(self, login, package_name, version, requirements, announce, release_attrs) | Add a new release to a package.
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the version string of the release
:param requirements: A dict of requirements TODO: describe
:param announce: An announcement that will be po... | 3.251024 | 2.206589 | 1.473326 |
'''
Download a package distribution
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the version string of the release
:param basename: the basename of the distribution to download
:param md5: (optional) an... | def download(self, login, package_name, release, basename, md5=None) | Download a package distribution
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the version string of the release
:param basename: the basename of the distribution to download
:param md5: (optional) an md5 hash of the dow... | 3.56023 | 2.532854 | 1.40562 |
'''
Upload a new distribution to a package release.
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the version string of the release
:param basename: the basename of the distribution to download
:param fd... | def upload(self, login, package_name, release, basename, fd, distribution_type,
description='', md5=None, size=None, dependencies=None, attrs=None, channels=('main',), callback=None) | Upload a new distribution to a package release.
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the version string of the release
:param basename: the basename of the distribution to download
:param fd: a file like object... | 3.04795 | 2.36726 | 1.287543 |
url = '{domain}/license'.format(domain=self.domain)
res = self.session.get(url)
self._check_response(res)
return res.json() | def user_licenses(self) | Download the user current trial/paid licenses. | 3.805312 | 3.224639 | 1.180074 |
depends = []
for dep in deps:
dep = dep.strip()
name_spec = dep.split(' ', 1)
if len(name_spec) == 1:
name, = name_spec
depends.append({'name':name, 'specs': []})
elif len(name_spec) == 2:
name, spec = name_spec
if spec.endswit... | def transform_conda_deps(deps) | Format dependencies into a common binstar format | 2.286448 | 2.255272 | 1.013824 |
try:
return index['subdir']
except KeyError:
arch = index.get('arch')
if arch is None:
return 'noarch'
intel_map = {'x86': '32', 'x86_64': '64'}
return '%s-%s' % (index.get('platform'), intel_map.get(arch, arch)) | def get_subdir(index) | Return the sub-directory given the index dictionary. The return
value is obtained in the following order:
1. when the 'subdir' key exists, it's value is returned
2. if the 'arch' is None, or does not exist, 'noarch' is returned
3. otherwise, the return value is constructed from the 'platform' key
... | 3.323016 | 2.153645 | 1.542973 |
'''
* Check if project already exists
* if it doesn't, then create it
* stage a new revision
* upload
* commit revision
'''
if not self.exists():
self.create()
data = self.stage().json()
self.file_upload(data['post_url'], d... | def upload(self) | * Check if project already exists
* if it doesn't, then create it
* stage a new revision
* upload
* commit revision | 8.276697 | 4.04393 | 2.046697 |
if isfile(value):
with open(value) as fd:
return fd.read().strip()
if any(char in value for char in '/\\.'):
# This chars will never be in a token value, but may be in a path
# The error message will be handled by the parser
raise ValueError()
return value | def file_or_token(value) | If value is a file path and the file exists its contents are stripped and returned,
otherwise value is returned. | 7.519579 | 7.328047 | 1.026137 |
body = []
def body_write(item):
if isinstance(item, six.binary_type):
item = BytesIO(item)
elif isinstance(item, six.text_type):
item = StringIO(item)
body.append(item)
body_write_encode = lambda item: body.append(BytesIO(item.encode('utf-8')))
if ... | def encode_multipart_formdata_stream(fields, boundary=None) | Encode a dictionary of ``fields`` using the multipart/form-data MIME format.
:param fields:
Dictionary of fields or list of (key, value) or (key, value, MIME type)
field tuples. The key is treated as the field name, and the value as
the body of the form-data bytes. If the value is a tuple ... | 1.873844 | 1.934843 | 0.968474 |
if not cls:
from binstar_client import Binstar
cls = Binstar
config = config if config is not None else get_config(site=site)
url = config.get('url', DEFAULT_URL)
logger.info("Using Anaconda API: %s", url)
if token:
logger.debug("Using token from command line args")
... | def get_server_api(token=None, site=None, cls=None, config=None, **kwargs) | Get the anaconda server api class | 2.24574 | 2.123023 | 1.057803 |
warnings.warn(
'method get_binstar is deprecated, please use `get_server_api`',
DeprecationWarning
)
token = getattr(args, 'token', None)
log_level = getattr(args, 'log_level', logging.INFO)
site = getattr(args, 'site', None)
aserver_api = get_server_api(token=token, site... | def get_binstar(args=None, cls=None) | DEPRECATED METHOD,
use `get_server_api` | 3.079575 | 2.790348 | 1.103653 |
try:
# Fast-path
# We're in the root environment
conda_root = _import_conda_root()
except ImportError:
# We're not in the root environment.
envs_dir = dirname(CONDA_PREFIX)
if basename(envs_dir) == 'envs':
# We're in a named environment: `conda cr... | def get_conda_root() | Get the PREFIX of the conda installation.
Returns:
str: the ROOT_PREFIX of the conda installation | 4.575685 | 4.722445 | 0.968923 |
'''<organization>/<group_name>/<member>'''
org = spec
group = member = None
if '/' in org:
org, group = org.split('/', 1)
if group and '/' in group:
group, member = group.split('/', 1)
if member and '/' in member:
raise UserError('Invalid group specification "%s" (unexpec... | def group_spec(spec) | <organization>/<group_name>/<member> | 4.500564 | 3.689795 | 1.219733 |
self.output = output
self.ensure_output()
files = OrderedDict()
for f in self.list_files():
# Check type
pkg_type = f.get('type') or ''
if pkg_type in package_types:
if self.can_download(f, force):
files[f['... | def list_download_files(self, package_types, output='.', force=False) | This additional method was created to better handle the log output
as files are downloaded one by one on the commands/download.py. | 4.869733 | 5.046602 | 0.964953 |
filename = dist['basename']
requests_handle = self.aserver_api.download(
self.username, self.notebook, dist['version'], filename
)
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
e... | def download(self, dist) | Download file into location. | 3.427811 | 3.285431 | 1.043337 |
return not os.path.exists(os.path.join(self.output, dist['basename'])) or force | def can_download(self, dist, force=False) | Can download if location/file does not exist or if force=True
:param dist:
:param force:
:return: True/False | 6.097331 | 6.812665 | 0.894999 |
if not os.path.exists(self.output):
os.makedirs(self.output) | def ensure_output(self) | Ensure output's directory exists | 3.210577 | 2.183945 | 1.470082 |
output = []
tmp = {}
files = self.aserver_api.package(self.username, self.notebook)['files']
for f in files:
if f['basename'] in tmp:
tmp[f['basename']].append(f)
else:
tmp[f['basename']] = [f]
for basename, vers... | def list_files(self) | List available files in a project (aka notebook).
:return: list | 3.680999 | 3.626343 | 1.015072 |
if exif[0:6] != b"\x45\x78\x69\x66\x00\x00":
raise ValueError("Given data is not exif data")
output_file = False
# Prevents "UnicodeWarning: Unicode equal comparison failed" warnings on Python 2
maybe_image = sys.version_info >= (3,0,0) or isinstance(image, str)
if maybe_image and ima... | def insert(exif, image, new_file=None) | py:function:: piexif.insert(exif_bytes, filename)
Insert exif into JPEG.
:param bytes exif_bytes: Exif as bytes
:param str filename: JPEG | 2.307893 | 2.404873 | 0.959673 |
if exif_src[0:2] == b"\xff\xd8":
src_data = exif_src
else:
with open(exif_src, 'rb') as f:
src_data = f.read()
segments = split_into_segments(src_data)
exif = get_exif_seg(segments)
if exif is None:
raise ValueError("not found exif in input")
output_file... | def transplant(exif_src, image, new_file=None) | py:function:: piexif.transplant(filename1, filename2)
Transplant exif from filename1 to filename2.
:param str filename1: JPEG
:param str filename2: JPEG | 2.252783 | 2.335513 | 0.964577 |
if data[0:2] != b"\xff\xd8":
raise InvalidImageDataError("Given data isn't JPEG.")
head = 2
segments = [b"\xff\xd8"]
while 1:
if data[head: head + 2] == b"\xff\xda":
segments.append(data[head:])
break
else:
length = struct.unpack(">H", da... | def split_into_segments(data) | Slices JPEG meta data into a list from JPEG binary data. | 3.023748 | 2.711797 | 1.115035 |
f = open(filename, "rb")
data = f.read(6)
if data[0:2] != b"\xff\xd8":
raise InvalidImageDataError("Given data isn't JPEG.")
head = data[2:6]
HEAD_LENGTH = 4
exif = None
while 1:
length = struct.unpack(">H", head[2: 4])[0]
if head[:2] == b"\xff\xe1":
... | def read_exif_from_file(filename) | Slices JPEG meta data into a list from JPEG binary data. | 2.936468 | 2.889963 | 1.016092 |
if segments[1][0:2] == b"\xff\xe0" and \
segments[2][0:2] == b"\xff\xe1" and \
segments[2][4:10] == b"Exif\x00\x00":
if exif:
segments[2] = exif
segments.pop(1)
elif exif is None:
segments.pop(2)
else:
segments.pop(1)
eli... | def merge_segments(segments, exif=b"") | Merges Exif with APP0 and APP1 manipulations. | 1.850876 | 1.761465 | 1.050759 |
output_is_file = False
if src[0:2] == b"\xff\xd8":
src_data = src
file_type = "jpeg"
elif src[0:4] == b"RIFF" and src[8:12] == b"WEBP":
src_data = src
file_type = "webp"
else:
with open(src, 'rb') as f:
src_data = f.read()
output_is_file =... | def remove(src, new_file=None) | py:function:: piexif.remove(filename)
Remove exif from JPEG.
:param str filename: JPEG | 2.085224 | 2.105924 | 0.990171 |
exif_dict = {"0th":{},
"Exif":{},
"GPS":{},
"Interop":{},
"1st":{},
"thumbnail":None}
exifReader = _ExifReader(input_data)
if exifReader.tiftag is None:
return exif_dict
if exifReader.tiftag[0:2] == LITTLE... | def load(input_data, key_is_name=False) | py:function:: piexif.load(filename)
Return exif data as dict. Keys(IFD name), be contained, are "0th", "Exif", "GPS", "Interop", "1st", and "thumbnail". Without "thumbnail", the value is dict(tag name/tag value). "thumbnail" value is JPEG as bytes.
:param str filename: JPEG or TIFF
:return: Exif data({"0t... | 1.796237 | 1.77236 | 1.013472 |
if len(data) < cls._PREFIX_SIZE:
raise ValueError('not enough data to decode UserComment')
prefix = data[:cls._PREFIX_SIZE]
body = data[cls._PREFIX_SIZE:]
if prefix == cls._UNDEFINED_PREFIX:
raise ValueError('prefix is UNDEFINED, unable to decode UserComm... | def load(cls, data) | Convert "UserComment" value in exif format to str.
:param bytes data: "UserComment" value from exif
:return: u"foobar"
:rtype: str(Unicode)
:raises: ValueError if the data does not conform to the EXIF specification,
or the encoding is unsupported. | 3.899987 | 3.311928 | 1.177558 |
if encoding not in cls.ENCODINGS:
raise ValueError('encoding {!r} must be one of {!r}'.format(encoding, cls.ENCODINGS))
prefix = {cls.ASCII: cls._ASCII_PREFIX, cls.JIS: cls._JIS_PREFIX, cls.UNICODE: cls._UNICODE_PREFIX}[encoding]
internal_encoding = {cls.UNICODE: cls._UNICOD... | def dump(cls, data, encoding="ascii") | Convert str to appropriate format for "UserComment".
:param data: Like u"foobar"
:param str encoding: "ascii", "jis", or "unicode"
:return: b"ASCII\x00\x00\x00foobar"
:rtype: bytes
:raises: ValueError if the encoding is unsupported. | 2.847294 | 2.603054 | 1.093828 |
scheme = ''
if '://' in path:
scheme = path.partition('://')[0]
for schemes, fs_class in FILE_EXTENSIONS:
if scheme in schemes:
return fs_class
return FileSystem | def get_fs(path) | Find the file system implementation for this path. | 4.953274 | 4.668703 | 1.060953 |
if timeout is not None:
IOLoop.current().call_later(timeout, self.stop)
IOLoop.current().start()
IOLoop.clear_current() | def awaitTermination(self, timeout=None) | Wait for context to stop.
:param float timeout: in seconds | 3.142584 | 3.933281 | 0.798973 |
deserializer = FileBinaryStreamDeserializer(self._context,
recordLength)
file_stream = FileStream(directory, process_all)
self._on_stop_cb.append(file_stream.stop)
return DStream(file_stream, self, deserializer) | def binaryRecordsStream(self, directory, recordLength=None,
process_all=False) | Monitor a directory and process all binary files.
File names starting with ``.`` are ignored.
:param string directory: a path
:param recordLength: None, int or struct format string
:param bool process_all: whether to process pre-existing files
:rtype: DStream
.. warnin... | 6.696771 | 7.46916 | 0.89659 |
deserializer = QueueStreamDeserializer(self._context)
if default is not None:
default = deserializer(default)
if Queue is False:
log.error('Run "pip install tornado" to install tornado.')
q = Queue()
for i in rdds:
q.put(i)
... | def queueStream(self, rdds, oneAtATime=True, default=None) | Create stream iterable over RDDs.
:param rdds: Iterable over RDDs or lists.
:param oneAtATime: Process one at a time or all.
:param default: If no more RDDs in ``rdds``, return this. Can be None.
:rtype: DStream
Example:
>>> import pysparkling
>>> sc = pyspark... | 6.179222 | 7.808352 | 0.791361 |
deserializer = TCPDeserializer(self._context)
tcp_binary_stream = TCPBinaryStream(length)
tcp_binary_stream.listen(port, hostname)
self._on_stop_cb.append(tcp_binary_stream.stop)
return DStream(tcp_binary_stream, self, deserializer) | def socketBinaryStream(self, hostname, port, length) | Create a TCP socket server for binary input.
.. warning::
This is not part of the PySpark API.
:param string hostname: Hostname of TCP server.
:param int port: Port of TCP server.
:param length:
Message length. Length in bytes or a format string for
... | 5.810345 | 6.462332 | 0.89911 |
deserializer = TCPDeserializer(self._context)
tcp_text_stream = TCPTextStream()
tcp_text_stream.listen(port, hostname)
self._on_stop_cb.append(tcp_text_stream.stop)
return DStream(tcp_text_stream, self, deserializer) | def socketTextStream(self, hostname, port) | Create a TCP socket server.
:param string hostname: Hostname of TCP server.
:param int port: Port of TCP server.
:rtype: DStream | 5.851413 | 5.492525 | 1.065341 |
def cb():
time_ = time.time()
log.debug('Step {}'.format(time_))
# run a step on all streams
for d in self._dstreams:
d._step(time_)
self._pcb = PeriodicCallback(cb, self.batch_duration * 1000.0)
self._pcb.start()
... | def start(self) | Start processing streams. | 7.990711 | 7.348031 | 1.087463 |
while self._on_stop_cb:
cb = self._on_stop_cb.pop()
log.debug('calling on_stop_cb {}'.format(cb))
cb()
IOLoop.current().stop()
StreamingContext._activeContext = None | def stop(self, stopSparkContext=True, stopGraceFully=False) | Stop processing streams.
:param stopSparkContext: stop the SparkContext (NOT IMPLEMENTED)
:param stopGracefully: stop gracefully (NOT IMPLEMENTED) | 6.356348 | 5.973366 | 1.064115 |
deserializer = FileTextStreamDeserializer(self._context)
file_stream = FileStream(directory, process_all)
self._on_stop_cb.append(file_stream.stop)
return DStream(file_stream, self, deserializer) | def textFileStream(self, directory, process_all=False) | Monitor a directory and process all text files.
File names starting with ``.`` are ignored.
:param string directory: a path
:param bool process_all: whether to process pre-existing files
:rtype: DStream
.. warning::
The ``process_all`` parameter does not exist in t... | 6.625426 | 6.981114 | 0.94905 |
if '.' not in path or path.rfind('/') > path.rfind('.'):
return Codec
for endings, codec_class in FILE_ENDINGS:
if any(path.endswith(e) for e in endings):
log.debug('Using {0} codec: {1}'.format(endings, path))
return codec_class
return NoCodec | def get_codec(path) | Find the codec implementation for this path. | 4.230358 | 4.042235 | 1.046539 |
stream = self.fs.load_text(encoding, encoding_errors)
else:
stream = self.fs.load()
stream = self.codec.decompress(stream)
stream = TextIOWrapper(stream, encoding, encoding_errors)
return stream | def load(self, encoding='utf8', encoding_errors='ignore'): # pylint: disable=arguments-differ
if isinstance(self.codec, codec.NoCodec) and \
self.fs.load_text != FileSystem.load_text | Load the data from a file.
:param str encoding: The character encoding of the file.
:param str encoding_errors: How to handle encoding errors.
:rtype: io.StringIO | 3.463455 | 3.56829 | 0.97062 |
stream = StringIO()
if isinstance(stream, string_types):
stream = StringIO(stream)
stream = self.codec.compress(
BytesIO(stream.read().encode(encoding, encoding_errors))
)
self.fs.dump(stream)
return self | def dump(self, stream=None, encoding='utf8', encoding_errors='ignore'): # pylint: disable=arguments-differ
if stream is None | Writes a stream to a file.
:param stream:
An ``io.StringIO`` instance. A ``basestring`` is also possible and
get converted to ``io.StringIO``.
:param encoding: (optional)
The character encoding of the file.
:rtype: TextFile | 6.244003 | 6.674204 | 0.935543 |
return (
self
.mapPartitions(lambda p: [sum(1 for _ in p)])
.reduce(operator.add)
) | def count(self) | Count elements per RDD.
Creates a new RDD stream where each RDD has a single entry that
is the count of the elements.
:rtype: DStream | 6.839178 | 6.790569 | 1.007158 |
return self.transform(
lambda rdd: self._context._context.parallelize(
rdd.countByValue().items())) | def countByValue(self) | Apply countByValue to every RDD.abs
:rtype: DStream
.. warning::
Implemented as a local operation.
Example:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
>>> (
... ssc
... | 10.794239 | 9.388669 | 1.149709 |
return self.mapPartitions(
lambda p: (e for pp in p for e in f(pp)),
preservesPartitioning,
) | def flatMap(self, f, preservesPartitioning=False) | Apply function f and flatten.
:param f: mapping function
:rtype: DStream | 5.120873 | 6.361431 | 0.804988 |
return (
self
.mapPartitions(lambda p: (f(e) for e in p), preservesPartitioning)
.transform(lambda rdd:
rdd.setName('{}:{}'.format(rdd.prev.name(), f)))
) | def map(self, f, preservesPartitioning=False) | Apply function f
:param f: mapping function
:rtype: DStream
Example:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
>>> (
... ssc
... .queueStream([[4], [2], [7]])
... | 7.601686 | 9.687358 | 0.784702 |
return (
self
.mapPartitionsWithIndex(lambda i, p: f(p), preservesPartitioning)
.transform(lambda rdd:
rdd.setName('{}:{}'.format(rdd.prev.name(), f)))
) | def mapPartitions(self, f, preservesPartitioning=False) | Map partitions.
:param f: mapping function
:rtype: DStream | 8.306323 | 9.191928 | 0.903654 |
def pprint_map(time_, rdd):
print('>>> Time: {}'.format(time_))
data = rdd.take(num + 1)
for d in data[:num]:
py_pprint.pprint(d)
if len(data) > num:
print('...')
print('')
self.foreachRDD(pprint_map) | def pprint(self, num=10) | Print the first ``num`` elements of each RDD.
:param int num: Set number of elements to be printed. | 6.255997 | 5.457289 | 1.146356 |
# avoid RDD.reduce() which does not return an RDD
return self.transform(
lambda rdd: (
rdd
.map(lambda i: (None, i))
.reduceByKey(func)
.map(lambda none_i: none_i[1])
)
) | def reduce(self, func) | Return a new DStream where each RDD was reduced with ``func``.
:rtype: DStream | 5.703359 | 5.523572 | 1.032549 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.