code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if (dt is None):
return None
elif (dt == 'now'):
dt = time.time()
if (no_fractions):
dt = int(dt)
else:
dt += 0.0000001 # improve rounding to microseconds
return datetime.utcfromtimestamp(dt).isoformat() + 'Z' | def datetime_to_str(dt='now', no_fractions=False) | The Last-Modified data in ISO8601 syntax, Z notation.
The lastmod is stored as unix timestamp which is already
in UTC. At preesent this code will return 6 decimal digits
if any fraction of a second is given. It would perhaps be
better to return only the number of decimal digits necessary,
up to a r... | 3.058172 | 3.219246 | 0.949965 |
need_geocoding = False
for attribute, component in self.required_address_components.items():
if not getattr(self, attribute):
need_geocoding = True
break # skip extra loops
return need_geocoding | def need_geocoding(self) | Returns True if any of the required address components is missing | 6.437055 | 3.984749 | 1.615423 |
if self.need_geocoding() or force:
result = get_cached(getattr(self, self.geocoded_by), provider='google')
if result.status == 'OK':
for attribute, components in self.required_address_components.items():
for component in components:
... | def geocode(self, commit=False, force=False) | Do a backend geocoding if needed | 4.217455 | 4.103932 | 1.027662 |
self.geocode()
return super(GeoMixin, self).save(*args, **kwargs) | def save(self, *args, **kwargs) | Extends model ``save()`` to allow dynamic geocoding | 6.870787 | 4.319654 | 1.590588 |
for link in self.ln:
if ('rel' in link and
link['rel'] == rel):
return(link)
return(None) | def link(self, rel) | Look for link with specified rel, return else None. | 5.825344 | 4.608027 | 1.264173 |
link = self.link(rel)
if (link is not None):
link = link['href']
return(link) | def link_href(self, rel) | Look for link with specified rel, return href from it or None. | 4.852941 | 3.747933 | 1.294831 |
if ('capability' not in self.md and self.capability_name is not None):
self.md['capability'] = self.capability_name | def default_capability(self) | Set capability name in md.
Every ResourceSync document should have the top-level
capability attributes. | 5.67281 | 4.109109 | 1.380545 |
if isinstance(resource, collections.Iterable):
for r in resource:
self.resources.append(r)
else:
self.resources.append(resource) | def add(self, resource) | Add a resource or an iterable collection of resources to this container.
Must be implemented in derived class. | 2.556469 | 2.333735 | 1.095441 |
n = 0
pruned = []
for r in self.resources:
if (r.timestamp is None):
raise Exception("Entry %s has no timestamp" % (r.uri))
elif (r.timestamp >= timestamp):
pruned.append(r)
else:
n += 1
self.res... | def prune_before(self, timestamp) | Remove all resources with timestamp earlier than that given.
Returns the number of entries removed. Will raise an excpetion
if there are any entries without a timestamp. | 3.268654 | 2.642682 | 1.23687 |
n = 0
pruned1 = []
seen = set()
deletes = {}
for r in reversed(self.resources):
if (r.uri in seen):
n += 1
if (r.uri in deletes):
deletes[r.uri] = r.change
else:
pruned1.append(r)... | def prune_dupes(self) | Remove all but the last entry for a given resource URI.
Returns the number of entries removed. Also removes all entries for a
given URI where the first entry is a create and the last entry is a
delete. | 3.101266 | 2.757387 | 1.124712 |
if (x == 'now'):
# Now, this is wht datetime_to_str() with no arg gives
return(datetime_to_str())
try:
# Test for number
junk = x + 0.0
return datetime_to_str(x)
except TypeError:
# Didn't look like a number, treat ... | def _str_datetime_now(self, x=None) | Return datetime string for use with time attributes.
Handling depends on input:
'now' - returns datetime for now
number - assume datetime values, generate string
other - no change, return same value | 10.695012 | 9.909116 | 1.07931 |
result = cache.get(location)
# Result is not cached or wrong
if not result or not result.ok:
result = geocoder.get(location, **kwargs)
if result.ok:
cache.set(location, result)
return result | def get_cached(location, **kwargs) | Simple wrapper that adds Django caching support to 'geocoder.get()'. | 4.137015 | 3.046745 | 1.357848 |
template = ti.load(os.path.join(script_dir, 'assets', 'template.tmx'))['map0']
#template.set_view(0, 0, template.px_width, template.px_height)
template.set_view(0, 0, width*template.tw, height*template.th)
# TODO: Save the generated map.
#epoch = int(time.time())
... | def map(self, width, height) | Creates and returns a new randomly generated map | 4.039258 | 3.89187 | 1.037871 |
(cred, providers) = config_read()
cmd_mode = True
conn_objs = cld.get_conns(cred, providers)
while cmd_mode:
nodes = cld.get_data(conn_objs, providers)
node_dict = make_node_dict(nodes, "name")
idx_tbl = table.indx_table(node_dict, True)
cmd_mode = ui.ui_main(idx_tbl... | def main() | Command-Mode: Retrieve and display data then process commands. | 7.542587 | 7.135512 | 1.057049 |
(cred, providers) = config_read()
conn_objs = cld.get_conns(cred, providers)
nodes = cld.get_data(conn_objs, providers)
node_dict = make_node_dict(nodes, "name")
table.indx_table(node_dict) | def list_only() | List-Mode: Retrieve and display data then exit. | 10.796093 | 10.429679 | 1.035132 |
raw_dict = {}
x = 1
for inner_list in outer_list:
for node in inner_list:
raw_dict[x] = node
x += 1
if sort == "name": # sort by provider - name
srt_dict = OrderedDict(sorted(raw_dict.items(), key=lambda k:
(k[1].cloud, k[1].na... | def make_node_dict(outer_list, sort="zone") | Convert node data from nested-list to sorted dict. | 2.365743 | 2.353779 | 1.005083 |
config_file = (u"{0}config.ini".format(CONFIG_DIR))
if not os.path.isfile(config_file):
config_make(config_file)
config = configparser.ConfigParser(allow_no_value=True)
try:
config.read(config_file, encoding='utf-8')
except IOError:
print("Error reading config file: {}".... | def config_read() | Read config info from config file. | 4.142668 | 4.135731 | 1.001677 |
try:
providers = [e.strip() for e in (config['info']
['providers']).split(',')]
except KeyError as e:
print("Error reading config item: {}".format(e))
sys.exit()
providers = list(OrderedDict.fromkeys(providers))
return providers | def config_prov(config) | Read providers from configfile and de-duplicate it. | 4.704619 | 3.753724 | 1.25332 |
expected = ['aws', 'azure', 'gcp', 'alicloud']
cred = {}
to_remove = []
for item in providers:
if any(item.startswith(itemb) for itemb in expected):
try:
cred[item] = dict(list(config[item].items()))
except KeyError as e:
print("No cre... | def config_cred(config, providers) | Read credentials from configfile. | 4.215343 | 4.024936 | 1.047307 |
from pkg_resources import resource_filename
import shutil
if not os.path.exists(CONFIG_DIR):
os.makedirs(CONFIG_DIR)
filename = resource_filename("mcc", "config.ini")
try:
shutil.copyfile(filename, config_file)
except IOError:
print("Error copying sample config file:... | def config_make(config_file) | Create config.ini on first use, make dir and copy sample. | 3.229836 | 2.985057 | 1.082001 |
hashvals = []
if (self.md5 is not None):
hashvals.append('md5:' + self.md5)
if (self.sha1 is not None):
hashvals.append('sha-1:' + self.sha1)
if (self.sha256 is not None):
hashvals.append('sha-256:' + self.sha256)
if (len(hashvals) > 0... | def hash(self) | Provide access to the complete hash string.
The hash string may have zero or more hash values with
appropriate prefixes. All hash values are assumed to be
strings | 1.843292 | 1.912204 | 0.963962 |
self.md5 = None
self.sha1 = None
self.sha256 = None
if (hash is None):
return
hash_seen = set()
errors = []
for entry in hash.split():
(hash_type, value) = entry.split(':', 1)
if (hash_type in hash_seen):
... | def hash(self, hash) | Parse space separated set of values.
See specification at:
http://tools.ietf.org/html/draft-snell-atompub-link-extensions-09
which defines many types. We implement md5, sha-1, sha-256 | 2.046625 | 1.954806 | 1.046971 |
if (self.ln is None):
# automagically create a self.ln list
self.ln = []
link = None
else:
link = self.link(rel)
if (link is not None and not allow_duplicates):
# overwrite current value
link['href'] = href
... | def link_set(self, rel, href, allow_duplicates=False, **atts) | Set/create link with specified rel, set href and any other attributes.
Any link element must have both rel and href values, the specification
also defines the type attributes and others are permitted also. See
description of allowed formats in
http://www.openarchives.org/rs/resourcesyn... | 3.353548 | 3.320836 | 1.009851 |
self.link_set(rel, href, allow_duplicates=True, **atts) | def link_add(self, rel, href, **atts) | Create an link with specified rel.
Will add a link even if one with that rel already exists. | 5.168567 | 6.188107 | 0.835242 |
if (other is None):
return False
if (self.uri != other.uri):
return(False)
if (self.timestamp is not None or other.timestamp is not None):
# not equal if only one timestamp specified
if (self.timestamp is None or
other.... | def equal(self, other, delta=0.0) | Equality or near equality test for resources.
Equality means:
1. same uri, AND
2. same timestamp WITHIN delta if specified for either, AND
3. same md5 if specified for both, AND
4. same length if specified for both | 2.295747 | 1.958893 | 1.171961 |
def inner(text):
text = ''.join(text)
return -chi_squared(frequency_analyze(text), target_frequency)
return inner | def ChiSquared(target_frequency) | Score a text by comparing its frequency distribution against another.
Note:
It is easy to be penalised without knowing it when using this scorer.
English frequency ngrams are capital letters, meaning when using it
any text you score against must be all capitals for it to give correct result... | 9.408833 | 10.521256 | 0.894269 |
if PY3:
if isinstance(otp, bytes):
raise ValueError("otp must be unicode")
if isinstance(to, bytes):
raise ValueError("to must be unicode")
else:
if not isinstance(otp, unicode):
raise ValueError("otp must be unicode")
if not isinstance(to... | def translate(otp, to=MODHEX) | Return set() of possible modhex interpretations of a Yubikey otp.
If otp uses all 16 characters in its alphabet, there will be only
one possible interpretation of that Yubikey otp (except for two
Armenian keyboard layouts).
otp: Yubikey output.
to: 16-character target alphabet, default MODHEX. | 2.815545 | 2.787876 | 1.009925 |
rl = ResourceList( resources=iter(my_resources), count=len(my_resources) )
rl.max_sitemap_entries = max_sitemap_entries
return(rl) | def my_resource_list() | Simulate the generator used by simulator | 8.76527 | 8.623705 | 1.016416 |
uri = resource.uri
if (uri in self and not replace):
raise ResourceListDupeError(
"Attempt to add resource already in resource_list")
self[uri] = resource | def add(self, resource, replace=False) | Add just a single resource. | 7.993989 | 7.124005 | 1.12212 |
uris = []
for r in self:
uris.append(r.uri)
return(uris) | def uris(self) | Extract list of all resource URIs (in the order added). | 3.996873 | 2.823162 | 1.415743 |
uri = resource.uri
for r in self:
if (uri == r.uri):
if (replace):
r = resource
return
else:
raise ResourceListDupeError(
"Attempt to add resource already in resource_... | def add(self, resource, replace=False) | Add a single resource, check for dupes. | 5.640049 | 4.906435 | 1.149521 |
if isinstance(resource, collections.Iterable):
for r in resource:
self.resources.add(r, replace)
else:
self.resources.add(resource, replace) | def add(self, resource, replace=False) | Add a resource or an iterable collection of resources.
Will throw a ValueError if the resource (ie. same uri) already
exists in the ResourceList, unless replace=True. | 2.56877 | 2.451685 | 1.047757 |
dst_iter = iter(self.resources)
src_iter = iter(src.resources)
same = ResourceList()
updated = ResourceList()
deleted = ResourceList()
created = ResourceList()
dst_cur = next(dst_iter, None)
src_cur = next(src_iter, None)
while ((dst_cur i... | def compare(self, src) | Compare this ResourceList object with that specified as src.
The parameter src must also be a ResourceList object, it is assumed
to be the source, and the current object is the destination. This
written to work for any objects in self and sc, provided that the
== operator can be used to... | 1.999392 | 1.937922 | 1.031719 |
hashes = set()
if (self.resources is not None):
for resource in self:
if (resource.md5 is not None):
hashes.add('md5')
if (resource.sha1 is not None):
hashes.add('sha-1')
if (resource.sha256 is n... | def hashes(self) | Return set of hashes uses in this resource_list. | 2.450786 | 2.040829 | 1.200877 |
'''_fromstring
Convert XML string value to None, boolean, int or float.
'''
if not value:
return None
std_value = value.strip().lower()
if std_value == 'true':
return 'true'
elif std_value == 'false':
return 'false'
# try:
# return int(std_value)
# e... | def _fromstring(value) | _fromstring
Convert XML string value to None, boolean, int or float. | 2.817619 | 2.261215 | 1.246064 |
'''get_config_nodes
High-level api: get_config_nodes returns a list of config nodes. Each
config node is an Element node in the config tree, which is
corresponding to one 'update' in the gNMI GetResponse.
Returns
-------
list
A list of config nodes.... | def get_config_nodes(self) | get_config_nodes
High-level api: get_config_nodes returns a list of config nodes. Each
config node is an Element node in the config tree, which is
corresponding to one 'update' in the gNMI GetResponse.
Returns
-------
list
A list of config nodes.
Co... | 7.728087 | 2.822596 | 2.737936 |
'''get_json
High-level api: get_json returns json_val of the config node.
Parameters
----------
instance : `bool`
True if only one instance of list or leaf-list is required. False if
all instances of list or leaf-list are needed.
Returns
... | def get_json(self, instance=True, origin='openconfig') | get_json
High-level api: get_json returns json_val of the config node.
Parameters
----------
instance : `bool`
True if only one instance of list or leaf-list is required. False if
all instances of list or leaf-list are needed.
Returns
-------
... | 4.443637 | 3.407306 | 1.30415 |
'''get_path
High-level api: get_path returns gNMI path object of the config node.
Note that gNMI Path can specify list instance but cannot specify
leaf-list instance.
Parameters
----------
instance : `bool`
True if the gNMI Path object refers to onl... | def get_path(self, instance=True, origin='openconfig') | get_path
High-level api: get_path returns gNMI path object of the config node.
Note that gNMI Path can specify list instance but cannot specify
leaf-list instance.
Parameters
----------
instance : `bool`
True if the gNMI Path object refers to only one insta... | 3.661194 | 2.672993 | 1.369698 |
root = os.path.splitext(filename)[0]
ext = os.path.splitext(filename)[1]
new_filepath = ''.join((root, str(slice_count), ext))
return _build_filepath_for_phantomcss(new_filepath) | def _build_sliced_filepath(filename, slice_count) | append slice_count to the end of a filename | 3.881233 | 3.807525 | 1.019359 |
try:
if os.path.exists(filepath):
new_root = '.'.join((os.path.splitext(filepath)[0], 'diff'))
ext = os.path.splitext(filepath)[1]
diff_filepath = ''.join((new_root, ext))
if os.path.exists(diff_filepath):
print 'removing stale diff: {0}'.... | def _build_filepath_for_phantomcss(filepath) | Prepare screenshot filename for use with phantomcss.
ie, append 'diff' to the end of the file if a baseline exists | 2.624119 | 2.48723 | 1.055037 |
filename = ''
device = j['device'] if j['device'] else 'Desktop'
if j['state'] == 'done' and j['image_url']:
detail = [device, j['os'], j['os_version'],
j['browser'], j['browser_version'], '.jpg']
filename = '_'.join(item.replace(" ", "_") for item in detail if item)
... | def _build_filename_from_browserstack_json(j) | Build a useful filename for an image from the screenshot json metadata | 5.317415 | 4.557173 | 1.166823 |
print 'slicing image: {0}'.format(in_filepath)
img = Image.open(in_filepath)
width, height = img.size
upper = 0
left = 0
slices = int(math.ceil(height / slice_size))
count = 1
for slice in range(slices):
# if we are at the end, set the lower bound to be the bottom of the im... | def _long_image_slice(in_filepath, out_filepath, slice_size) | Slice an image into parts slice_size tall. | 3.32346 | 3.281952 | 1.012647 |
for f in os.listdir(dir):
if re.search(pattern, f):
print "Purging file {0}. {1}".format(f, reason)
os.remove(os.path.join(dir, f)) | def _purge(dir, pattern, reason='') | delete files in dir that match pattern | 2.231468 | 2.264674 | 0.985337 |
if backoff <= 1:
raise ValueError("backoff must be greater than 1")
tries = math.floor(tries)
if tries < 0:
raise ValueError("tries must be 0 or greater")
if delay <= 0:
raise ValueError("delay must be greater than 0")
def deco_retry(f):
def f_retry(*args, **... | def retry(tries, delay=3, backoff=2) | Retries a function or method until it returns True. | 2.24949 | 2.089258 | 1.076693 |
if ntrials <= 0 or nswaps <= 0:
raise ValueError("ntrials and nswaps must be positive integers")
# Find a local maximum by swapping two letters and scoring the decryption
def next_node_inner_climb(node):
# Swap 2 characters in the key
a, b = random.sample(range(len(node)), 2)
... | def crack(ciphertext, *fitness_functions, ntrials=30, nswaps=3000) | Break ``ciphertext`` using hill climbing.
Note:
Currently ntrails and nswaps default to magic numbers.
Generally the trend is, the longer the text, the lower the number of trials
you need to run, because the hill climbing will lead to the best answer faster.
Because randomness is in... | 4.389207 | 3.952996 | 1.11035 |
# TODO: Is it worth keeping this here I should I only accept strings?
key = ''.join(key)
alphabet = string.ascii_letters
cipher_alphabet = key.lower() + key.upper()
return ciphertext.translate(str.maketrans(cipher_alphabet, alphabet)) | def decrypt(key, ciphertext) | Decrypt Simple Substitution enciphered ``ciphertext`` using ``key``.
Example:
>>> decrypt("PQSTUVWXYZCODEBRAKINGFHJLM", "XUOOB")
HELLO
Args:
key (iterable): The key to use
ciphertext (str): The text to decrypt
Returns:
Decrypted ciphertext | 8.240488 | 9.244047 | 0.891437 |
return self.write(request.SetDeviceName(self.seq, *self.prep_str(newname))) | def set_device_name(self, newname) | Sets internal device name. (not announced bluetooth name).
requires utf-8 encoded string. | 16.330469 | 14.489242 | 1.127075 |
return self.write(request.SetHeading(self.seq, value)) | def set_heading(self, value) | value can be between 0 and 359 | 17.660255 | 15.734804 | 1.122369 |
return self.write(request.SetRotationRate(self.seq, val)) | def set_rotation_rate(self, val) | value ca be between 0x00 and 0xFF:
value is a multiplied with 0.784 degrees/s except for:
0 --> 1 degrees/s
255 --> jumps to 400 degrees/s | 17.096073 | 16.856501 | 1.014212 |
return self.write(request.SetBackLEDOutput(self.seq, value)) | def set_back_led_output(self, value) | value can be between 0x00 and 0xFF | 18.553654 | 15.733642 | 1.179235 |
return self.write(request.Roll(self.seq, speed, heading, state )) | def roll(self, speed, heading, state=1) | speed can have value between 0x00 and 0xFF
heading can have value between 0 and 359 | 17.875443 | 13.473653 | 1.326696 |
isbn_to_check = raw_isbn.replace('-', '').replace(' ', '')
if not isinstance(isbn_to_check, string_types):
raise ValidationError(_(u'Invalid ISBN: Not a string'))
if len(isbn_to_check) != 10 and len(isbn_to_check) != 13:
raise ValidationError(_(u'Invalid ISBN: Wrong length'))
... | def ISBNValidator(raw_isbn) | Check string is a valid ISBN number | 2.09845 | 2.117657 | 0.99093 |
'''get_xpath
High-level api: Delete four attributes from an Element node if they
exist: operation, insert, value and key.
Parameters
----------
element : `Element`
The Element node needs to be looked at.
Returns
-------
Element
... | def get_xpath(self, type, instance=True) | get_xpath
High-level api: Delete four attributes from an Element node if they
exist: operation, insert, value and key.
Parameters
----------
element : `Element`
The Element node needs to be looked at.
Returns
-------
Element
Th... | 5.36177 | 3.51052 | 1.527344 |
'''_del_attrib
Low-level api: Delete four attributes from an Element node if they
exist: operation, insert, value and key.
Parameters
----------
element : `Element`
The Element node needs to be looked at.
Returns
-------
Element
... | def _del_attrib(element) | _del_attrib
Low-level api: Delete four attributes from an Element node if they
exist: operation, insert, value and key.
Parameters
----------
element : `Element`
The Element node needs to be looked at.
Returns
-------
Element
T... | 8.069989 | 2.080822 | 3.87827 |
'''_get_sequence
Low-level api: Return a list of children of a parent with the same tag
within the scope.
Parameters
----------
scope : `list`
List members can be an element, or a tuple of two elements.
tag : `str`
Identifier in `{url}t... | def _get_sequence(scope, tag, parent) | _get_sequence
Low-level api: Return a list of children of a parent with the same tag
within the scope.
Parameters
----------
scope : `list`
List members can be an element, or a tuple of two elements.
tag : `str`
Identifier in `{url}tagname` not... | 3.968162 | 1.684965 | 2.355042 |
'''_group_kids
Low-level api: Consider an Element node in a Config instance. Now
we have two Config instances and we want to compare two corresponding
Element nodes. This method group children of these nodes in three
categories: some only exist in node_one, some only exist in no... | def _group_kids(self, node_one, node_two) | _group_kids
Low-level api: Consider an Element node in a Config instance. Now
we have two Config instances and we want to compare two corresponding
Element nodes. This method group children of these nodes in three
categories: some only exist in node_one, some only exist in node_two,
... | 2.585263 | 1.50888 | 1.713366 |
'''_get_list_keys
Low-level api: Given a schema node, in particular, a list type schema
node, it returns a list of keys.
Parameters
----------
schema_node : `Element`
A schema node.
Returns
-------
list
A list of tags o... | def _get_list_keys(schema_node) | _get_list_keys
Low-level api: Given a schema node, in particular, a list type schema
node, it returns a list of keys.
Parameters
----------
schema_node : `Element`
A schema node.
Returns
-------
list
A list of tags of keys in `... | 6.849548 | 2.014543 | 3.400051 |
'''_get_peers
Low-level api: Given a config node, find peers under a parent node.
Parameters
----------
child_self : `Element`
An Element node on this side.
parent_other : `Element`
An Element node on the other side.
Returns
--... | def _get_peers(self, child_self, parent_other) | _get_peers
Low-level api: Given a config node, find peers under a parent node.
Parameters
----------
child_self : `Element`
An Element node on this side.
parent_other : `Element`
An Element node on the other side.
Returns
-------
... | 3.596451 | 2.142166 | 1.678885 |
'''_is_peer
Low-level api: Return True if node_self and node_other are considered
as peer with regards to a set of keys.
Parameters
----------
keys : `list`
A list of keys in `{url}tagname` notation.
node_self : `Element`
An Element nod... | def _is_peer(self, keys, node_self, node_other) | _is_peer
Low-level api: Return True if node_self and node_other are considered
as peer with regards to a set of keys.
Parameters
----------
keys : `list`
A list of keys in `{url}tagname` notation.
node_self : `Element`
An Element node on this s... | 3.284558 | 1.755662 | 1.870837 |
'''_node_le
Low-level api: Return True if all descendants of one node exist in the
other node. Otherwise False. This is a recursive method.
Parameters
----------
node_self : `Element`
A node to be compared.
node_other : `Element`
Anothe... | def _node_le(self, node_self, node_other) | _node_le
Low-level api: Return True if all descendants of one node exist in the
other node. Otherwise False. This is a recursive method.
Parameters
----------
node_self : `Element`
A node to be compared.
node_other : `Element`
Another node to b... | 2.485284 | 2.073076 | 1.198839 |
if not 'battery' in self.mode:
return
mode = self.mode['battery']
if mode and mode and self.__test_cond(mode):
self.logger.debug('Battery out')
self.player.stats['reward'] += mode['reward']
self.player.game_over = self.player.game_over or... | def reward_battery(self) | Add a battery level reward | 7.956666 | 7.241563 | 1.09875 |
assert isinstance(item_type, str)
if not 'items' in self.mode:
return
mode = self.mode['items']
if mode and mode[item_type] and self.__test_cond(mode[item_type]):
self.logger.debug("{item_type} consumed".format(item_type=item_type))
self.play... | def reward_item(self, item_type) | Add a food collision reward | 3.820712 | 3.770123 | 1.013418 |
if not 'wall' in self.mode:
return
mode = self.mode['wall']
if mode and mode and self.__test_cond(mode):
self.logger.debug("Wall {x}/{y}'".format(x=self.bumped_x, y=self.bumped_y))
self.player.stats['reward'] += mode['reward']
self.player... | def reward_wall(self) | Add a wall collision reward | 6.761467 | 6.625952 | 1.020452 |
if not 'explore' in self.mode:
return
mode = self.mode['explore']
if mode and mode['reward'] and self.__test_cond(mode):
self.player.stats['reward'] += mode['reward']
self.player.stats['score'] += mode['reward']
self.player.game_over = se... | def reward_explore(self) | Add an exploration reward | 5.136724 | 4.782306 | 1.07411 |
if not 'goal' in self.mode:
return
mode = self.mode['goal']
if mode and mode['reward'] and self.__test_cond(mode):
if mode['reward'] > 0:
self.logger.info("Escaped!!")
self.player.stats['reward'] += mode['reward']
self.play... | def reward_goal(self) | Add an end goal reward | 5.2538 | 4.999976 | 1.050765 |
if not 'proximity' in self.mode:
return
mode = self.mode['proximity']
# Calculate proximity reward
reward = 0
for sensor in self.player.sensors:
if sensor.sensed_type == 'wall':
reward += sensor.proximity_norm()
else:
... | def reward_proximity(self) | Add a wall proximity reward | 5.817356 | 5.428926 | 1.071548 |
for key, value in self.labels.iteritems():
str_val = str(int(self.stats[key]))
self.msgs[key][0].element.text = self.labels[key] + str_val
self.msgs[key][1].element.text = self.labels[key] + str_val | def update(self, dt) | Responsabilities:
Updates game engine each tick
Copies new stats into labels | 3.753441 | 3.245442 | 1.156527 |
op.drop_constraint('fk_oauth2server_client_user_id_accounts_user',
'oauth2server_client', type_='foreignkey')
op.create_foreign_key(op.f('fk_oauth2server_client_user_id_accounts_user'),
'oauth2server_client', 'accounts_user', ['user_id'],
... | def upgrade() | Upgrade database. | 1.290053 | 1.276074 | 1.010955 |
op.drop_constraint(op.f('fk_oauth2server_token_user_id_accounts_user'),
'oauth2server_token', type_='foreignkey')
op.drop_index(op.f('ix_oauth2server_token_user_id'),
table_name='oauth2server_token')
op.create_foreign_key('fk_oauth2server_token_user_id_accounts_... | def downgrade() | Downgrade database. | 1.332368 | 1.319484 | 1.009764 |
if (re.match(r"\w+:", basename)):
# looks like URI
return(basename)
elif (re.match(r"/", basename)):
# looks like full path
return(basename)
else:
# build from mapping with name appended
return(self.mapper.default_s... | def sitemap_uri(self, basename) | Get full URI (filepath) for sitemap based on basename. | 7.308597 | 6.720675 | 1.087479 |
if (self.sitemap_name is not None):
return(self.sitemap_name)
return(self.sitemap_uri(self.resource_list_name)) | def sitemap(self) | Return the sitemap URI based on maps or explicit settings. | 7.595013 | 5.198501 | 1.461001 |
self.logger.info("Reading resource list %s" % (uri))
try:
resource_list = ResourceList(allow_multifile=self.allow_multifile,
mapper=self.mapper)
resource_list.read(uri=uri)
except Exception as e:
raise ClientEr... | def read_resource_list(self, uri) | Read resource list from specified URI else raise exception. | 3.373687 | 3.227976 | 1.04514 |
self.logger.info("Reading source description %s" % (uri))
try:
sd = SourceDescription()
sd.read(uri=uri)
except Exception as e:
raise ClientError(
"Can't read source description from %s (%s)" %
(uri, str(e)))
if... | def find_resource_list_from_source_description(self, uri) | Read source description to find resource list.
Raises a ClientError in cases where the client might look for a
source description in another location, but a ClientFatalError if
a source description is found but there is some problem using it. | 4.154493 | 3.751285 | 1.107485 |
self.logger.info("Reading capability list %s" % (uri))
try:
cl = CapabilityList()
cl.read(uri=uri)
except Exception as e:
raise ClientError(
"Can't read capability list from %s (%s)" %
(uri, str(e)))
if (not cl.... | def find_resource_list_from_capability_list(self, uri) | Read capability list to find resource list.
Raises a ClientError in cases where the client might look for a
capability list in another location, but a ClientFatalError if
a capability list is found but there is some problem using it. | 3.713563 | 3.08008 | 1.205671 |
# 1 & 2
if (self.sitemap_name is not None):
return(self.read_resource_list(self.sitemap_name))
if (self.capability_list_uri is not None):
rluri = self.find_resource_list_from_capability_list(self.capability_list_uri)
return(self.read_resource_list(rlu... | def find_resource_list(self) | Finf resource list by hueristics, returns ResourceList object.
1. Use explicitly specified self.sitemap_name (and
fail if that doesn't work)
2. Use explicitly specified self.capability_list_uri (and
fail is that doesn't work)
3. Look for base_url/.well-known/resourcesync... | 3.047404 | 2.484891 | 1.226373 |
# 0. Sanity checks, parse paths is specified
if (len(self.mapper) < 1):
raise ClientFatalError(
"No source to destination mapping specified")
if (paths is not None):
# Expect comma separated list of paths
paths = paths.split(',')
... | def build_resource_list(self, paths=None, set_path=False) | Return a resource list for files on local disk.
The set of files is taken by disk scan from the paths specified or
else defaults to the paths specified in the current mappings
paths - override paths from mappings if specified
set_path - set true to set the path information for each re... | 5.006546 | 4.765444 | 1.050594 |
path = os.path.dirname(filename)
distutils.dir_util.mkpath(path)
num_updated = 0
if (self.dryrun):
self.logger.info(
"dryrun: would GET %s --> %s" %
(resource.uri, filename))
else:
# 1. GET
for try_i in ... | def update_resource(self, resource, filename, change=None) | Update resource from uri to filename on local system.
Update means three things:
1. GET resources
2. set mtime in local time to be equal to timestamp in UTC (should perhaps
or at least warn if different from LastModified from the GET response instead
but maybe warn if different ... | 2.591817 | 2.476306 | 1.046646 |
# which hashes to calculate?
hashes = []
if ('md5' in self.hashes and resource.md5 is not None):
hashes.append('md5')
if ('sha-1' in self.hashes and resource.sha1 is not None):
hashes.append('sha-1')
if ('sha-256' in self.hashes and resource.sha25... | def check_hashes(self, filename, resource) | Check all hashes present in self.hashes _and_ resource object.
Simply shows warning for mismatch, does not raise exception or
otherwise stop process. | 1.626791 | 1.637406 | 0.993518 |
num_deleted = 0
uri = resource.uri
if (resource.timestamp is not None and
resource.timestamp > self.last_timestamp):
self.last_timestamp = resource.timestamp
if (allow_deletion):
if (self.dryrun):
self.logger.info(
... | def delete_resource(self, resource, filename, allow_deletion=False) | Delete copy of resource in filename on local system.
Will only actually do the deletion if allow_deletion is True. Regardless
of whether the deletion occurs, self.last_timestamp will be updated
if the resource.timestamp is later than the current value.
Returns the number of files actua... | 3.225201 | 3.052155 | 1.056696 |
s = Sitemap()
self.logger.info("Reading sitemap(s) from %s ..." % (self.sitemap))
try:
list = s.parse_xml(url_or_file_open(self.sitemap))
except IOError as e:
raise ClientFatalError("Cannot read document (%s)" % str(e))
num_entries = len(list.reso... | def parse_document(self) | Parse any ResourceSync document and show information.
Will use sitemap URI taken either from explicit self.sitemap_name
or derived from the mappings supplied. | 4.143334 | 3.852054 | 1.075617 |
rl = self.build_resource_list(paths=paths, set_path=dump)
if (links is not None):
rl.ln = links
if (dump):
if (outfile is None):
outfile = self.default_resource_dump
self.logger.info("Writing resource dump to %s..." % (dump))
... | def write_resource_list(
self, paths=None, outfile=None, links=None, dump=None) | Write a Resource List or a Resource Dump for files on local disk.
Set of resources included is based on paths setting or else the mappings.
Optionally links can be added. Output will be to stdout unless outfile
is specified.
If dump is true then a Resource Dump is written instead of a ... | 5.242809 | 5.297143 | 0.989743 |
cl = ChangeList(ln=links)
if (not empty):
# 1. Get and parse reference sitemap
old_rl = self.read_reference_resource_list(ref_sitemap)
# 2. Depending on whether a newref_sitemap was specified, either read that
# or build resource list from files o... | def write_change_list(self, paths=None, outfile=None, ref_sitemap=None, newref_sitemap=None,
empty=None, links=None, dump=None) | Write a change list.
Unless the both ref_sitemap and newref_sitemap are specified then the Change
List is calculated between the reference an the current state of files on
disk. The files on disk are scanned based either on the paths setting or
else on the mappings. | 3.833019 | 3.964255 | 0.966895 |
capl = CapabilityList(ln=links)
capl.pretty_xml = self.pretty_xml
if (capabilities is not None):
for name in capabilities.keys():
capl.add_capability(name=name, uri=capabilities[name])
if (outfile is None):
print(capl.as_xml())
els... | def write_capability_list(self, capabilities=None,
outfile=None, links=None) | Write a Capability List to outfile or STDOUT. | 3.880349 | 3.502121 | 1.108 |
rsd = SourceDescription(ln=links)
rsd.pretty_xml = self.pretty_xml
if (capability_lists is not None):
for uri in capability_lists:
rsd.add_capability_list(uri)
if (outfile is None):
print(rsd.as_xml())
else:
rsd.write(b... | def write_source_description(
self, capability_lists=None, outfile=None, links=None) | Write a ResourceSync Description document to outfile or STDOUT. | 4.398908 | 4.002857 | 1.098942 |
rl = ResourceList()
self.logger.info(
"Reading %s resource list from %s ..." %
(name, ref_sitemap))
rl.mapper = self.mapper
rl.read(uri=ref_sitemap, index_only=(not self.allow_multifile))
num_entries = len(rl.resources)
self.logger.info(
... | def read_reference_resource_list(self, ref_sitemap, name='reference') | Read reference resource list and return the ResourceList object.
The name parameter is used just in output messages to say what type
of resource list is being read. | 3.234314 | 3.206002 | 1.008831 |
discarded = []
for hash in hashes:
if (hash in self.hashes):
self.hashes.discard(hash)
discarded.append(hash)
self.logger.info("Not calculating %s hash(es) on destination as not present "
"in source %s list" % (', '.jo... | def prune_hashes(self, hashes, list_type) | Prune any hashes not in source resource or change list. | 5.252602 | 4.912129 | 1.069313 |
if (audit):
words = {'created': 'to create',
'updated': 'to update',
'deleted': 'to delete'}
else:
words = {'created': 'created',
'updated': 'updated',
'deleted': 'deleted'}
if in... | def log_status(self, in_sync=True, incremental=False, audit=False,
same=None, created=0, updated=0, deleted=0, to_delete=0) | Write log message regarding status in standard form.
Split this off so all messages from baseline/audit/incremental
are written in a consistent form. | 3.768832 | 3.882968 | 0.970606 |
'''_fromstring
Convert XML string value to None, boolean, int or float.
'''
if not value:
return [None]
std_value = value.strip().lower()
if std_value == 'true':
return True
elif std_value == 'false':
return False
try:
return int(std_value)
except Va... | def _fromstring(value) | _fromstring
Convert XML string value to None, boolean, int or float. | 3.015511 | 2.316614 | 1.301689 |
'''get_config_node
High-level api: get_config_node returns an Element node in the config
tree, which is corresponding to the URL in the Restconf GET reply.
Returns
-------
Element
A config node.
'''
default_ns = ''
config_node = etr... | def get_config_node(self) | get_config_node
High-level api: get_config_node returns an Element node in the config
tree, which is corresponding to the URL in the Restconf GET reply.
Returns
-------
Element
A config node. | 4.51148 | 3.373732 | 1.337237 |
'''get_json
High-level api: get_json returns json_val of the config node.
Parameters
----------
instance : `bool`
True if only one instance of list or leaf-list is required. False if
all instances of list or leaf-list are needed.
Returns
... | def get_json(self, instance=True) | get_json
High-level api: get_json returns json_val of the config node.
Parameters
----------
instance : `bool`
True if only one instance of list or leaf-list is required. False if
all instances of list or leaf-list are needed.
Returns
-------
... | 4.503932 | 3.349234 | 1.344765 |
'''get_url
High-level api: get_url returns a Restconf URL of the config node.
Parameters
----------
instance : `bool`
True if the Restconf URL refers to only one instance of a list or
leaf-list. False if the Restconf URL refers to all instances of a
... | def get_url(self, instance=True) | get_url
High-level api: get_url returns a Restconf URL of the config node.
Parameters
----------
instance : `bool`
True if the Restconf URL refers to only one instance of a list or
leaf-list. False if the Restconf URL refers to all instances of a
li... | 4.620981 | 3.067482 | 1.506441 |
'''Render a latex template, filling in its template variables
:param path_templates: the path to the template directory
:param template_filename: the name, rooted at the path_template_directory,
of the desired template for rendering
:param template_vars: dictionary of key:val for jinja2 variabl... | def render_latex_template(path_templates, template_filename,
template_vars=None) | Render a latex template, filling in its template variables
:param path_templates: the path to the template directory
:param template_filename: the name, rooted at the path_template_directory,
of the desired template for rendering
:param template_vars: dictionary of key:val for jinja2 variables
... | 4.394063 | 2.237442 | 1.963879 |
if year < MIN_YEAR or year > MAX_YEAR:
raise ValueError("Year out of range (%d..%d)" % (MIN_YEAR, MAX_YEAR))
if month < 1 or month > 12:
raise ValueError("Month out of range (1..12)")
days_in_month = DAYS_IN_MONTH[(year, month)]
if day in (days_in_month, -1):
return year, mo... | def _normalize_day(year, month, day) | Coerce the day of the month to an internal value that may or
may not match the "public" value.
With the exception of the last three days of every month, all
days are stored as-is. The last three days are instead stored
as -1 (the last), -2 (first from last) and -3 (second from last).
Therefore, fo... | 2.070612 | 2.076777 | 0.997031 |
minutes, seconds = symmetric_divmod(self[2], 60)
hours, minutes = symmetric_divmod(minutes, 60)
return hours, minutes, float(seconds) + self[3] | def hours_minutes_seconds(self) | A 3-tuple of (hours, minutes, seconds). | 4.491427 | 3.710987 | 1.210305 |
if ordinal == 0:
return ZeroDate
if ordinal >= 736695:
year = 2018 # Project release year
month = 1
day = int(ordinal - 736694)
elif ordinal >= 719163:
year = 1970 # Unix epoch
month = 1
day = in... | def from_ordinal(cls, ordinal) | Return the :class:`.Date` that corresponds to the proleptic
Gregorian ordinal, where ``0001-01-01`` has ordinal 1 and
``9999-12-31`` has ordinal 3,652,059. Values outside of this
range trigger a :exc:`ValueError`. The corresponding instance
method for the reverse date-to-ordinal transfor... | 2.747765 | 2.642675 | 1.039766 |
try:
numbers = map(int, s.split("-"))
except (ValueError, AttributeError):
raise ValueError("Date string must be in format YYYY-MM-DD")
else:
numbers = list(numbers)
if len(numbers) == 3:
return cls(*numbers)
ra... | def parse(cls, s) | Parse a string to produce a :class:`.Date`.
Accepted formats:
'YYYY-MM-DD'
:param s:
:return: | 2.764037 | 2.722177 | 1.015378 |
try:
clock_time = ClockTime(*clock_time)
except (TypeError, ValueError):
raise ValueError("Clock time must be a 2-tuple of (s, ns)")
else:
ordinal = clock_time.seconds // 86400
return Date.from_ordinal(ordinal + epoch.date().to_ordinal()) | def from_clock_time(cls, clock_time, epoch) | Convert from a ClockTime relative to a given epoch. | 4.727358 | 4.473238 | 1.056809 |
return Date(kwargs.get("year", self.__year),
kwargs.get("month", self.__month),
kwargs.get("day", self.__day)) | def replace(self, **kwargs) | Return a :class:`.Date` with one or more components replaced
with new values. | 3.711584 | 3.100985 | 1.196905 |
second = (1000000 * t.second + t.microsecond) / 1000000
return Time(t.hour, t.minute, second, t.tzinfo) | def from_native(cls, t) | Convert from a native Python `datetime.time` value. | 3.994939 | 2.882347 | 1.386002 |
clock_time = ClockTime(*clock_time)
ts = clock_time.seconds % 86400
nanoseconds = int(1000000000 * ts + clock_time.nanoseconds)
return Time.from_ticks(epoch.time().ticks + nanoseconds / 1000000000) | def from_clock_time(cls, clock_time, epoch) | Convert from a `.ClockTime` relative to a given epoch. | 3.790074 | 3.467327 | 1.093082 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.