code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if HAVE_PY26_SSL: if hasattr(self, 'sslopts'): self.sslobj = ssl.wrap_socket(self.sock, **self.sslopts) else: self.sslobj = ssl.wrap_socket(self.sock) self.sslobj.do_handshake() else: self.sslobj = socket.ssl(self.s...
def _setup_transport(self)
Wrap the socket in an SSL object, either the new Python 2.6 version, or the older Python 2.5 and lower version.
2.599326
2.214698
1.173671
if HAVE_PY26_SSL and (self.sslobj is not None): self.sock = self.sslobj.unwrap() self.sslobj = None
def _shutdown_transport(self)
Unwrap a Python 2.6 SSL socket, so we can call shutdown()
6.341451
3.715801
1.706617
result = self.sslobj.read(n) while len(result) < n: s = self.sslobj.read(n - len(result)) if not s: raise IOError('Socket closed') result += s return result
def _read(self, n)
It seems that SSL Objects read() method may not supply as much as you're asking for, at least with extremely large messages. somewhere > 16K - found this in the test_channel.py test_large unittest.
3.058014
2.525389
1.210908
while s: n = self.sslobj.write(s) if not n: raise IOError('Socket closed') s = s[n:]
def _write(self, s)
Write a string out to the SSL socket fully.
4.70937
3.357734
1.402544
self._write = self.sock.sendall self._read_buffer = bytes()
def _setup_transport(self)
Setup to _write() directly to the socket, and do our own buffered reads.
12.398004
5.620534
2.205841
while len(self._read_buffer) < n: s = self.sock.recv(65536) if not s: raise IOError('Socket closed') self._read_buffer += s result = self._read_buffer[:n] self._read_buffer = self._read_buffer[n:] return result
def _read(self, n)
Read exactly n bytes from the socket
2.140703
2.167513
0.987631
self.bitcount = self.bits = 0 tlen = unpack('>I', self.input.read(4))[0] table_data = AMQPReader(self.input.read(tlen)) result = {} while table_data.input.tell() < tlen: name = table_data.read_shortstr() ftype = ord(table_data.input.read(1)) ...
def read_table(self)
Read an AMQP table, and return as a Python dictionary.
2.778355
2.614446
1.062694
if b: b = 1 else: b = 0 shift = self.bitcount % 8 if shift == 0: self.bits.append(0) self.bits[-1] |= (b << shift) self.bitcount += 1
def write_bit(self, b)
Write a boolean value.
2.825213
2.693724
1.048813
if (n < 0) or (n > 255): raise ValueError('Octet out of range 0..255') self._flushbits() self.out.write(pack('B', n))
def write_octet(self, n)
Write an integer as an unsigned 8-bit value.
3.557909
3.352115
1.061392
if (n < 0) or (n > 65535): raise ValueError('Octet out of range 0..65535') self._flushbits() self.out.write(pack('>H', n))
def write_short(self, n)
Write an integer as an unsigned 16-bit value.
3.589092
3.454564
1.038942
if (n < 0) or (n >= (2**32)): raise ValueError('Octet out of range 0..2**31-1') self._flushbits() self.out.write(pack('>I', n))
def write_long(self, n)
Write an integer as an unsigned2 32-bit value.
5.225486
4.736729
1.103185
if (n < 0) or (n >= (2**64)): raise ValueError('Octet out of range 0..2**64-1') self._flushbits() self.out.write(pack('>Q', n))
def write_longlong(self, n)
Write an integer as an unsigned 64-bit value.
4.946817
4.607049
1.07375
self._flushbits() if isinstance(s, unicode): s = s.encode('utf-8') if len(s) > 255: raise ValueError('String too long') self.write_octet(len(s)) self.out.write(s)
def write_shortstr(self, s)
Write a string up to 255 bytes long (after any encoding). If passed a unicode string, encode with UTF-8.
3.112555
2.856287
1.089721
self._flushbits() table_data = AMQPWriter() for k, v in d.items(): table_data.write_shortstr(k) if isinstance(v, basestring): if isinstance(v, unicode): v = v.encode('utf-8') table_data.write(byte(83)) # 'S' ...
def write_table(self, d)
Write out a Python dictionary made of up string keys, and values that are strings, signed integers, Decimal, datetime.datetime, or sub-dictionaries following the same constraints.
2.404126
2.329657
1.031965
self.out.write(pack('>q', long(mktime(v.timetuple()))))
def write_timestamp(self, v)
Write out a Python datetime.datetime object as a 64-bit integer representing seconds since the Unix epoch.
8.211033
6.422171
1.278545
def on_error(e): # pragma: no cover exname = {'RuntimeError': 'Runtime error', 'Value Error': 'Value error'} sys.stderr.write('{}: {}\n'.format(exname[e.__class__.__name__], str(e))) sys.stderr.write('See file slam_error.log for additional details.\n') sys.exit(1)
Error handler RuntimeError or ValueError exceptions raised by commands will be handled by this function.
null
null
null
def on_unexpected_error(e): # pragma: no cover sys.stderr.write('Unexpected error: {} ({})\n'.format( str(e), e.__class__.__name__)) sys.stderr.write('See file slam_error.log for additional details.\n') sys.exit(1)
Catch-all error handler Unexpected errors will be handled by this function.
null
null
null
if os.path.exists(config_file): raise RuntimeError('Please delete the old version {} if you want to ' 'reconfigure your project.'.format(config_file)) module, app = function.split(':') if not name: name = module.replace('_', '-') if not re.match('^[a-zA-Z...
def init(name, description, bucket, timeout, memory, stages, requirements, function, runtime, config_file, **kwargs)
Generate a configuration file.
2.615947
2.603832
1.004653
ret = app(*args, event=event, context=context, **kwargs) except TypeError: # try again without passing the event and context ret = app(*args, **kwargs) return ret
def _run_lambda_function(event, context, app, config): # pragma: no cover args = event.get('args', []) kwargs = event.get('kwargs', {}) # first attempt to invoke the function passing the lambda event and context try
Run the function. This is the default when no plugins (such as wsgi) define an alternative run function.
4.214151
4.213008
1.000271
# Determine what the start up code is. The default is to just run the # function, but it can be overriden by a plugin such as wsgi for a more # elaborated way to run the function. run_function = _run_lambda_function for name, plugin in plugins.items(): if name in config and hasattr(plug...
def _generate_lambda_handler(config, output='.slam/handler.py')
Generate a handler.py file for the lambda function start up.
3.816543
3.700438
1.031376
config = _load_config(config_file) print("Building lambda package...") package = _build(config, rebuild_deps=rebuild_deps) print("{} has been built successfully.".format(package))
def build(rebuild_deps, config_file)
Build lambda package.
4.837713
3.872815
1.249146
config = _load_config(config_file) if stage is None: stage = config['devstage'] s3 = boto3.client('s3') cfn = boto3.client('cloudformation') region = _get_aws_region() # obtain previous deployment if it exists previous_deployment = None try: previous_deployment = c...
def deploy(stage, lambda_package, no_lambda, rebuild_deps, config_file)
Deploy the project to the development stage.
2.379226
2.371202
1.003384
config = _load_config(config_file) cfn = boto3.client('cloudformation') if version is None: version = config['devstage'] elif version not in config['stage_environments'].keys() and \ not version.isdigit(): raise ValueError('Invalid version. Use a stage name or a numeric...
def publish(version, stage, config_file)
Publish a version of the project to a stage.
2.83719
2.790464
1.016745
config = _load_config(config_file) if stage is None: stage = config['devstage'] cfn = boto3.client('cloudformation') lmb = boto3.client('lambda') try: stack = cfn.describe_stacks(StackName=config['name'])['Stacks'][0] except botocore.exceptions.ClientError: raise R...
def invoke(stage, async, dry_run, config_file, args)
Invoke the lambda function.
2.354949
2.287746
1.029375
config = _load_config(config_file) s3 = boto3.client('s3') cfn = boto3.client('cloudformation') logs = boto3.client('logs') try: stack = cfn.describe_stacks(StackName=config['name'])['Stacks'][0] except botocore.exceptions.ClientError: raise RuntimeError('This project has ...
def delete(no_logs, config_file)
Delete the project.
2.112975
2.089621
1.011176
config = _load_config(config_file) if stage is None: stage = config['devstage'] cfn = boto3.client('cloudformation') try: stack = cfn.describe_stacks(StackName=config['name'])['Stacks'][0] except botocore.exceptions.ClientError: print('{} has not been deployed yet.'.for...
def logs(stage, period, tail, config_file)
Dump logs to the console.
2.209376
2.196345
1.005933
config = _load_config(config_file) print(get_cfn_template(config, pretty=True))
def template(config_file)
Print the default Cloudformation deployment template.
6.838975
4.562149
1.499069
if pkg_resources: # pragma: no cover for ep in pkg_resources.iter_entry_points('slam_plugins'): plugin = ep.load() # add any init options to the main init command if hasattr(plugin, 'init') and hasattr(plugin.init, '_arguments'): for arg in plugin.i...
def register_plugins()
find any installed plugins and register them.
4.02255
3.745023
1.074105
payload = { 'context': device_state, 'event': { 'header': { 'namespace': 'System', 'name': 'SynchronizeState', 'messageId': '' }, 'payload': {} } } ...
def synchronise_device_state(self, device_state, authentication_headers)
Synchronizing the component states with AVS Components state must be synchronised with AVS after establishing the downchannel stream in order to create a persistent connection with AVS. Note that currently this function is paying lip-service synchronising the device state: the device s...
2.905638
2.968035
0.978977
payload = { 'context': device_state, 'event': { 'header': { 'namespace': 'SpeechRecognizer', 'name': 'Recognize', 'messageId': self.generate_message_id(), 'dialogRequestId': dialog_r...
def send_audio_file( self, audio_file, device_state, authentication_headers, dialog_request_id, distance_profile, audio_format )
Send audio to AVS The file-like object are steaming uploaded for improved latency. Returns: bytes -- wav audio bytes returned from AVS
2.287328
2.372723
0.96401
payload = self.oauth2_manager.get_access_token_params( refresh_token=self.refresh_token ) response = requests.post( self.oauth2_manager.access_token_url, json=payload ) response.raise_for_status() response_json = json.loads(response.text)...
def retrieve_api_token(self)
Retrieve the access token from AVS. This function is memoized, so the value returned by the function will be remembered and returned by subsequent calls until the memo expires. This is because the access token lasts for one hour, then a new token needs to be requested. Decorato...
2.704845
2.784259
0.971478
User = get_user_model() return '%s.%s_%s' % (User._meta.app_label, perm, User._meta.module_name)
def get_user_permission_full_codename(perm)
Returns 'app_label.<perm>_<usermodulename>'. If standard ``auth.User`` is used, for 'change' perm this would return ``auth.change_user`` and if ``myapp.CustomUser`` is used it would return ``myapp.change_customuser``.
2.848461
2.483502
1.146953
try: django.db.transaction.commit(using) except django.db.transaction.TransactionManagementError: pass
def commit(using=None)
Possibility of calling transaction.commit() in new Django versions (in atomic block).
3.243027
2.82088
1.149651
if sid: django.db.transaction.savepoint_rollback(sid) else: try: django.db.transaction.rollback(using) except django.db.transaction.TransactionManagementError: django.db.transaction.set_rollback(True, using)
def rollback(using=None, sid=None)
Possibility of calling transaction.rollback() in new Django versions (in atomic block). Important: transaction savepoint (sid) is required for Django < 1.8
3.108964
2.775463
1.12016
try: from django.template.engine import Engine except ImportError: # Django < 1.8 Engine = None if Engine: try: engine = Engine.get_default() except ImproperlyConfigured: loaders = [] else: loaders = engine.template_loaders ...
def get_template_loaders()
Compatibility method to fetch the template loaders. Source: https://github.com/django-debug-toolbar/django-debug-toolbar/blob/ece1c2775af108a92a0ef59636266b49e286e916/debug_toolbar/compat.py
2.334382
2.242955
1.040762
from compat import six, force_text # If it's a model, use get_absolute_url() if hasattr(to, 'get_absolute_url'): return to.get_absolute_url() if isinstance(to, Promise): # Expand the lazy instance, as it can cause issues when it is passed # further to some Python functions...
def resolve_url(to, *args, **kwargs)
Return a URL appropriate for the arguments passed. The arguments could be: * A model: the model's `get_absolute_url()` function will be called. * A view name, possibly with arguments: `urlresolvers.reverse()` will be used to reverse-resolve the name. * A URL, which will be returned...
4.483022
4.280472
1.04732
# TODO: allow selection of entries # Django's template system silently fails on some exceptions try: return webpack(path_to_config) except (AttributeError, ValueError) as e: raise six.reraise(BundlingError, BundlingError(*e.args), sys.exc_info()[2])
def webpack_template_tag(path_to_config)
A template tag that will output a webpack bundle. Usage: {% load webpack %} {% webpack 'path/to/webpack.config.js' as bundle %} {{ bundle.render_css|safe }} {{ bundle.render_js|safe }}
7.484653
7.745655
0.966303
if not args and not kwargs: return key items = sorted(kwargs.items()) hashable_args = (args, tuple(items)) args_key = hashlib.md5(pickle.dumps(hashable_args)).hexdigest() return "%s/args:%s" % (key, args_key)
def _prepare_key(key, *args, **kwargs)
if arguments are given, adds a hash of the args to the key.
3.660019
3.115515
1.174772
# Create the root logger. logger = logging.getLogger() logger.setLevel(logging.DEBUG) # Validate the given directory. logdir = os.path.normpath(logdir) # Create a folder for the logfiles. if not os.path.exists(logdir): os.makedirs(logdir) # Construct the logfile name. ...
def setup(logdir='log')
Set up dual logging to console and to logfile. When this function is called, it first creates the given directory. It then creates a logfile and passes all log messages to come to it. The logfile name encodes the date and time when it was created, for example "20181115-153559.txt". All messages with ...
1.696906
1.662771
1.020529
version_counter = Counter() versions_match = False version_str = None versions_discovered = OrderedDict() for version_obj in version_objects: discovered = version_obj.get_version() versions_discovered[version_obj.key_name] = discovered version_counter.update([discovere...
def get_versions() -> FileVersionResult
Search specific project files and extract versions to check. :return: A FileVersionResult object for reporting.
3.608485
3.535231
1.020721
if not version_info: raise TypeError("version_info cannot be 'None'!") if not version_info.uniform: raise ValueError("version_info is not uniform!") beta_flag = ".123." current_version = version_info.version_result # We can just split and take the first value since: # ...
def get_version_without_beta(version_info: FileVersionResult) -> str
Get the project's version string *without* any test or beta build labels. :param version_info: The current version_info of the project. :return: The current version string, without any beta build string values.
6.42473
6.031516
1.065193
if not version_info: raise TypeError("version_info cannot be 'None'!") if not version_info.uniform: raise ValueError("version_info is not uniform!") # Capture datetime as UTC for build timestamp utc_datetime = datetime.datetime.utcnow() # Setup version string information ...
def get_version_with_beta(version_info: FileVersionResult) -> str
Get the project's version string *with* a beta build label based on UTC. :param version_info: The current version_info of the project. :return: The project's version string, with a beta build number.
4.854319
4.201818
1.15529
for test in tests: try: test.encode(sys.stdout.encoding) return test except UnicodeEncodeError: pass return '?' * len(tests[0])
def supportedChars(*tests)
Takes any number of strings, and returns the first one the terminal encoding supports. If none are supported it returns '?' the length of the first string.
3.344485
2.759228
1.212109
app_templates_dirs = OrderedDict() for app_config in apps.get_app_configs(): templates_dir = os.path.join( getattr(app_config, 'path', '/'), 'templates') if os.path.isdir(templates_dir): templates_dir = upath(templates_dir) ...
def app_templates_dirs(self)
Build a cached dict with settings.INSTALLED_APPS as keys and the 'templates' directory of each application as values.
2.337659
2.005077
1.16587
try: path = self.get_app_template_path( origin.app_name, origin.template_name) with io.open(path, encoding=self.engine.file_charset) as fp: return fp.read() except KeyError: raise TemplateDoesNotExist(origin) except IOE...
def get_contents(self, origin)
Try to load the origin.
3.185847
3.124646
1.019586
if ':' not in template_name: self.reset(True) return app, template_path = template_name.split(':') if app: yield NamespaceOrigin( app_name=app, name='app_namespace:%s:%s' % (app, template_name), templat...
def get_template_sources(self, template_name)
Build a list of Origin to load 'template_name' splitted with ':'. The first item is the name of the application and the last item is the true value of 'template_name' provided by the specified application.
3.120452
2.951661
1.057185
template_name = ka[0] for origin in self.get_template_sources(template_name): try: return self.get_contents(origin), origin.name except TemplateDoesNotExist: pass raise TemplateDoesNotExist(template_name)
def load_template_source(self, *ka)
Backward compatible method for Django < 2.0.
3.317893
3.264967
1.01621
self._image = self.genImage() self._image = funcs.rotateImage(self._image, self.direction) return self._image
def image(self)
Generates the image using self.genImage(), then rotates it to self.direction and returns it.
7.301528
2.92566
2.495686
image = [list(row) for row in image] for n in range(angle % 4): image = list(zip(*image[::-1])) return image
def rotateImage(image, angle)
rotates a 2d array to a multiple of 90 deg. 0 = default 1 = 90 deg. cw 2 = 180 deg. 3 = 90 deg. ccw
3.601948
4.041214
0.891303
direction = int(direction) self.position = list(self.position) if direction == 0: self.position[1] += 1 elif direction == 1: self.position[0] -= 1 elif direction == 2: self.position[1] -= 1 elif direction == 3: sel...
def move(self, direction=0)
direction = int range(0, 4) 0 = Down 1 = Left 2 = Up 3 = Right
1.71308
1.587538
1.07908
try: sides = list(side) except TypeError: if side is None: sides = list(range(4)) else: sides = [side] # Generate rotated images for each direction. images = {} image = self.image.image() for si...
def touching(self, canvas, side=None)
Returns True if touching any pixels [on specified side]. 0 = Bottom 1 = Left 2 = Top 3 = Right None = All This works by creating a list of the image rotated so all the requested sides are facing up, then it finds the top edge for ...
4.741317
4.374756
1.08379
try: exclude = list(exclude) except TypeError: exclude = [exclude] exclude.append(self) for selfY, row in enumerate(self.image.image()): for selfX, pixel in enumerate(row): canvasPixelOn = canvas.testPixel( ...
def overlaps(self, canvas, exclude=[])
Returns True if sprite is touching any other sprite.
4.233708
3.834339
1.104156
sides = [] if int(self.position[0]) <= 0: sides.append(1) if (int(self.position[0]) + self.image.width) >= canvas.width: sides.append(3) if int(self.position[1]) <= 0: sides.append(2) if (int(self.position[1]) + self.image.height) >...
def onEdge(self, canvas)
Returns a list of the sides of the sprite which are touching the edge of the canvas. 0 = Bottom 1 = Left 2 = Top 3 = Right
2.069651
1.779959
1.162752
def getter(self): try: return getattr(self, name) except AttributeError: value = getattr(self.sendCommand(get_command()), field_name) setattr(self, name, value) return value def setter(self, value): setattr(self, name, value) ...
def remote_property(name, get_command, set_command, field_name, doc=None)
Property decorator that facilitates writing properties for values from a remote device. Arguments: name: The field name to use on the local object to store the cached property. get_command: A function that returns the remote value of the property. set_command: A function that accepts a new value ...
2.300235
2.40674
0.955747
command_data = [ord(x) for x in buffer(command)] self.hid.write(command_data) response_data = ''.join(chr(x) for x in self.hid.read(64)) response = command.RESPONSE.from_buffer_copy(response_data) if response.status != 0: raise CommandException(response.statu...
def sendCommand(self, command)
Sends a Command object to the MCP2210 and returns its response. Arguments: A commands.Command instance Returns: A commands.Response instance, or raises a CommandException on error.
3.555758
3.482266
1.021105
settings = self.transfer_settings settings.spi_tx_size = len(data) self.transfer_settings = settings response = '' for i in range(0, len(data), 60): response += self.sendCommand(commands.SPITransferCommand(data[i:i + 60])).data time.sleep(0.01) ...
def transfer(self, data)
Transfers data over SPI. Arguments: data: The data to transfer. Returns: The data returned by the SPI device.
3.732151
3.732803
0.999825
json_context = json.dumps( context_dict, cls=DjangoJSONEncoder, **self.get_json_dumps_kwargs() ).encode(u'utf-8') return HttpResponse( json_context, content_type=self.get_content_type(), status=status )
def render_json_response(self, context_dict, status=200)
Limited serialization for shipping plain data. Do not use for models or other complex or custom objects.
2.551975
2.373003
1.07542
self.object = form.save(commit=False) self.pre_save() self.object.save() if hasattr(form, 'save_m2m'): form.save_m2m() self.post_save() if self.request.is_ajax(): return self.render_json_response(self.get_success_result()) return ...
def form_valid(self, form)
If the request is ajax, save the form and return a json response. Otherwise return super as expected.
2.041818
1.905404
1.071593
if self.request.is_ajax(): return self.render_json_response(self.get_error_result(form)) return super(AjaxFormMixin, self).form_invalid(form)
def form_invalid(self, form)
We have errors in the form. If ajax, return them as json. Otherwise, proceed as normal.
2.786192
2.557796
1.089294
'''Stores a function's assumptions as an attribute.''' args = tuple(args) def decorator(func): func.assumptions = args return func return decorator
def assumes(*args)
Stores a function's assumptions as an attribute.
6.29661
4.127817
1.525409
'''Stores what assumptions a function is overridden by as an attribute.''' args = tuple(args) def decorator(func): func.overridden_by_assumptions = args return func return decorator
def overridden_by_assumptions(*args)
Stores what assumptions a function is overridden by as an attribute.
5.993403
3.315625
1.807624
kwargs['axis'] = axis kwargs['mode'] = mode if not isinstance(window_size, int): raise TypeError('window_size must be an integer') if not isinstance(kwargs['axis'], int): raise TypeError('axis must be an integer') return convolve1d(array, np.repeat(1.0, window_size)/window_size,...
def sma(array, window_size, axis=-1, mode='reflect', **kwargs)
Computes a 1D simple moving average along the given axis. Parameters ---------- array : ndarray Array on which to perform the convolution. window_size: int Width of the simple moving average window in indices. axis : int, optional Axis along which to perform the moving average mode : {‘reflect’, ‘constant’...
2.325526
2.699376
0.861505
'''Takes in an abbreviation for a quantity and a quantity dictionary, and returns a more descriptive string of the quantity as "name (units)." Raises ValueError if the name is not in quantity_dict ''' if name not in quantity_dict.keys(): raise ValueError('{0} is not present in quantity...
def quantity_string(name, quantity_dict)
Takes in an abbreviation for a quantity and a quantity dictionary, and returns a more descriptive string of the quantity as "name (units)." Raises ValueError if the name is not in quantity_dict
4.168219
1.821968
2.287757
'''Takes a list of strings presumably containing words and phrases, and returns a "list" form of those strings, like: >>> strings_to_list_string(('cats', 'dogs')) >>> 'cats and dogs' or >>> strings_to_list_string(('pizza', 'pop', 'chips')) >>> 'pizza, pop, and chips' ...
def strings_to_list_string(strings)
Takes a list of strings presumably containing words and phrases, and returns a "list" form of those strings, like: >>> strings_to_list_string(('cats', 'dogs')) >>> 'cats and dogs' or >>> strings_to_list_string(('pizza', 'pop', 'chips')) >>> 'pizza, pop, and chips' Ra...
3.044088
1.605734
1.895761
''' Takes in a list of short forms of assumptions and an assumption dictionary, and returns a "list" form of the long form of the assumptions. Raises ------ ValueError if one of the assumptions is not in assumption_dict. ''' if isinstance(assumptions, six.string_types): raise TypeError('assumpt...
def assumption_list_string(assumptions, assumption_dict)
Takes in a list of short forms of assumptions and an assumption dictionary, and returns a "list" form of the long form of the assumptions. Raises ------ ValueError if one of the assumptions is not in assumption_dict.
3.733263
2.14465
1.740733
''' Returns a quantity specification for docstrings. Example ------- >>> quantity_spec_string('Tv') >>> 'Tv : float or ndarray\n Data for virtual temperature.' ''' if name not in quantity_dict.keys(): raise ValueError('{0} not present in quantity_dict'.format(name)) s = '{0} : float or ndar...
def quantity_spec_string(name, quantity_dict)
Returns a quantity specification for docstrings. Example ------- >>> quantity_spec_string('Tv') >>> 'Tv : float or ndarray\n Data for virtual temperature.'
6.12742
2.723205
2.250077
'''Takes in a string without wrapping corresponding to a paragraph, and returns a version of that string wrapped to be at most 80 characters in length on each line. If indent is given, ensures each line is indented to that number of spaces. ''' return '\n'.join([' '*indent + l fo...
def doc_paragraph(s, indent=0)
Takes in a string without wrapping corresponding to a paragraph, and returns a version of that string wrapped to be at most 80 characters in length on each line. If indent is given, ensures each line is indented to that number of spaces.
7.171894
1.840026
3.897713
''' Assuming the string is of the form d(var1)d(var2), returns var1, var2. Raises ValueError if the string is not of this form, or if the vars are not keys in the quantity_dict, or if var2 is not a coordinate-like variable. ''' match = derivative_prog.match(string) if match is None: ...
def parse_derivative_string(string, quantity_dict)
Assuming the string is of the form d(var1)d(var2), returns var1, var2. Raises ValueError if the string is not of this form, or if the vars are not keys in the quantity_dict, or if var2 is not a coordinate-like variable.
3.771747
2.092086
1.802864
''' Finds the index value in an iterable closest to a desired value. Parameters ---------- x : object The desired value. L : iterable The iterable in which to search for the desired value. Returns ------- index : int The index of the closest value to x in L....
def closest_val(x, L)
Finds the index value in an iterable closest to a desired value. Parameters ---------- x : object The desired value. L : iterable The iterable in which to search for the desired value. Returns ------- index : int The index of the closest value to x in L. Notes ...
3.312063
2.365801
1.399975
''' Calculates the area enclosed by an arbitrary polygon on the sphere. Parameters ---------- lat : iterable The latitudes, in degrees, of the vertex locations of the polygon, in clockwise order. lon : iterable The longitudes, in degrees, of the vertex locations of the polygon, in clockwise order....
def area_poly_sphere(lat, lon, r_sphere)
Calculates the area enclosed by an arbitrary polygon on the sphere. Parameters ---------- lat : iterable The latitudes, in degrees, of the vertex locations of the polygon, in clockwise order. lon : iterable The longitudes, in degrees, of the vertex locations of the polygon, in clockwise order. Return...
3.211417
1.795704
1.78839
''' Calculates a second-order centered finite difference of data along the specified axis. Parameters ---------- data : ndarray Data on which we are taking a derivative. axis : int Index of the data array on which to take the difference. boundary : string, optional Boundary condition. If 'periodic', a...
def d_x(data, axis, boundary='forward-backward')
Calculates a second-order centered finite difference of data along the specified axis. Parameters ---------- data : ndarray Data on which we are taking a derivative. axis : int Index of the data array on which to take the difference. boundary : string, optional Boundary condition. If 'periodic', assume pe...
3.700933
2.177922
1.699296
r'''Plot data. Simple wrapper around plot so that pressure is the first (independent) input. This is essentially a wrapper around `semilogy`. Parameters ---------- p : array_like pressure values T : array_like temperature values, can also...
def semilogy(self, p, T, *args, **kwargs)
r'''Plot data. Simple wrapper around plot so that pressure is the first (independent) input. This is essentially a wrapper around `semilogy`. Parameters ---------- p : array_like pressure values T : array_like temperature values, can also be used...
2.799848
2.120748
1.320218
r'''Plot wind barbs. Adds wind barbs to the skew-T plot. This is a wrapper around the `barbs` command that adds to appropriate transform to place the barbs in a vertical line, located as a function of pressure. Parameters ---------- p : array_like pr...
def plot_barbs(self, p, u, v, xloc=1.0, x_clip_radius=0.08, y_clip_radius=0.08, **kwargs)
r'''Plot wind barbs. Adds wind barbs to the skew-T plot. This is a wrapper around the `barbs` command that adds to appropriate transform to place the barbs in a vertical line, located as a function of pressure. Parameters ---------- p : array_like pressure v...
3.703852
1.938393
1.910785
r'''Plot dry adiabats. Adds dry adiabats (lines of constant potential temperature) to the plot. The default style of these lines is dashed red lines with an alpha value of 0.5. These can be overridden using keyword arguments. Parameters ---------- p : array_like...
def plot_dry_adiabats(self, p=None, theta=None, **kwargs)
r'''Plot dry adiabats. Adds dry adiabats (lines of constant potential temperature) to the plot. The default style of these lines is dashed red lines with an alpha value of 0.5. These can be overridden using keyword arguments. Parameters ---------- p : array_like, option...
3.506378
2.244518
1.562196
r'''Plot lines of constant mixing ratio. Adds lines of constant mixing ratio (isohumes) to the plot. The default style of these lines is dashed green lines with an alpha value of 0.8. These can be overridden using keyword arguments. Parameters ---------- rv : ar...
def plot_mixing_lines(self, p=None, rv=None, **kwargs)
r'''Plot lines of constant mixing ratio. Adds lines of constant mixing ratio (isohumes) to the plot. The default style of these lines is dashed green lines with an alpha value of 0.8. These can be overridden using keyword arguments. Parameters ---------- rv : array_like...
2.828466
2.095769
1.349608
''' Given an interable of input quantity names and a methods dictionary, returns a list of output quantities that can be calculated. ''' output_quantities = [] updated = True while updated: updated = False for output in methods.keys(): if output in output_quantiti...
def get_calculatable_quantities(inputs, methods)
Given an interable of input quantity names and a methods dictionary, returns a list of output quantities that can be calculated.
3.593985
2.718905
1.32185
''' Given iterables of input variable names, output variable names, and a methods dictionary, returns the subset of the methods dictionary that can be calculated, doesn't calculate something we already have, and only contains equations that might help calculate the outputs from the inputs. '...
def _get_methods_that_calculate_outputs(inputs, outputs, methods)
Given iterables of input variable names, output variable names, and a methods dictionary, returns the subset of the methods dictionary that can be calculated, doesn't calculate something we already have, and only contains equations that might help calculate the outputs from the inputs.
5.689715
4.294141
1.324995
''' Given an iterable of input variable names and a methods dictionary, returns the subset of that methods dictionary that can be calculated and which doesn't calculate something we already have. Additionally it may only contain one method for any given output variable, which is the one with the...
def _get_calculatable_methods_dict(inputs, methods)
Given an iterable of input variable names and a methods dictionary, returns the subset of that methods dictionary that can be calculated and which doesn't calculate something we already have. Additionally it may only contain one method for any given output variable, which is the one with the fewest poss...
3.749644
2.395399
1.565353
''' Returns a methods list corresponding to the equations in the given module. Each entry is a dictionary with keys 'output', 'args', and 'func' corresponding to the output, arguments, and function of the method. The entries may optionally include 'assumptions' and 'overridden_by_assumptions' as...
def _get_module_methods(module)
Returns a methods list corresponding to the equations in the given module. Each entry is a dictionary with keys 'output', 'args', and 'func' corresponding to the output, arguments, and function of the method. The entries may optionally include 'assumptions' and 'overridden_by_assumptions' as keys, stati...
3.961838
2.257309
1.755116
'''If value is a 0-dimensional array, returns the contents of value. Otherwise, returns value. ''' if isinstance(value, np.ndarray): if value.ndim == 0: # We have a 0-dimensional array return value[None][0] return value
def _check_scalar(value)
If value is a 0-dimensional array, returns the contents of value. Otherwise, returns value.
4.899343
2.885864
1.697704
ok, err = _hack_ip() if not ok: click.secho(click.style(err, fg='red')) sys.exit(1) click.secho(click.style(err, fg='green'))
def ip()
Show ip address.
4.128615
4.000175
1.032109
if not ssid: ok, err = _detect_wifi_ssid() if not ok: click.secho(click.style(err, fg='red')) sys.exit(1) ssid = err ok, err = _hack_wifi_password(ssid) if not ok: click.secho(click.style(err, fg='red')) sys.exit(1) click.secho(click.s...
def wp(ssid)
Show wifi password.
2.625653
2.56806
1.022427
query_part_one = [] query_part_two = [] keys_to_be_removed = [] for key, value in data.items(): if key not in ['version', 'restApi', 'resourcePath']: if key == 'mapArea': query_part_one.append(','.join(str(val) for val in value)) ...
def build_url(self, data)
This method occurs after dumping the data into the class. Args: data (dict): dictionary of all the query values Returns: data (dict): ordered dict of all the values
2.41586
2.464423
0.980294
query_params = [] keys_to_be_removed = [] for key, value in data.items(): if key not in ['version', 'restApi', 'resourcePath']: if key == 'addressLine': query_params.append('{0}={1}'.format(key, ...
def build_query_string(self, data)
This method occurs after dumping the data into the class. Args: data (dict): dictionary of all the query values Returns: data (dict): ordered dict of all the values
2.673087
2.836839
0.942276
queryValues = [] keys_to_be_removed = [] for key, value in data.items(): if key not in ['version', 'restApi', 'resourcePath']: if not key == 'point': queryValues.append('{0}={1}'.format(key, value)) keys_to_be_removed.a...
def build_query_string(self, data)
This method occurs after dumping the data into the class. Args: data (dict): dictionary of all the query values Returns: data (dict): ordered dict of all the values
3.311289
3.466965
0.955097
url = '{protocol}/{url}/{rest}/{version}/{restapi}/{rscpath}/' \ '{query}'.format(protocol=self.schema.protocol, url=self.schema.main_url, rest=self.schema.rest, version=self.schema.version, ...
def build_url(self)
Builds the URL for elevations API services based on the data given by the user. Returns: url (str): URL for the elevations API services
4.109958
4.568739
0.899582
url = self.build_url() self.elevationdata = requests.get(url) if not self.elevationdata.status_code == 200: raise self.elevationdata.raise_for_status()
def get_data(self)
Gets data from the given url
3.972176
3.567135
1.113548
resources = self.get_resource() elevations = namedtuple('elevations_data', 'elevations') try: return [elevations(resource['elevations']) for resource in resources] except KeyError: return [elevations(resource['offsets']) ...
def elevations(self)
Retrieves elevations/offsets from the output response Returns: elevations/offsets (namedtuple): A named tuple of list of elevations/offsets
3.615323
3.416274
1.058265
resources = self.get_resource() zoomlevel = namedtuple('zoomlevel', 'zoomLevel') try: return [zoomlevel(resource['zoomLevel']) for resource in resources] except TypeError: try: if isinstance(resources['ElevationData'], ...
def zoomlevel(self)
Retrieves zoomlevel from the output response Returns: zoomlevel (namedtuple): A namedtuple of zoomlevel from the output response
4.028389
3.813555
1.056334
if bool(path) and os.path.isdir(path): self.write_to_json(path, file_name) else: self.write_to_json(os.getcwd(), file_name)
def to_json_file(self, path, file_name=None)
Writes output to a JSON file with the given file name
2.84914
2.756112
1.033753
url = self.build_url() self.incidents_data = requests.get(url) if not self.incidents_data.status_code == 200: raise self.incidents_data.raise_for_status()
def get_data(self)
Gets data from the given url
3.308125
2.975499
1.111788
try: return json.loads(self.incidents_data.text) except Exception: return json.loads(json.dumps(xmltodict.parse( self.incidents_data.text)))
def response_to_dict(self)
This method helps in returning the output JSON data from the URL and also it helps in converting the XML output/response (string) to a JSON object Returns: data (dict): JSON data from the output/response
4.61347
4.08673
1.12889
resource_list = self.traffic_incident() description = namedtuple('description', 'description') if len(resource_list) == 1 and resource_list[0] is None: return None else: try: return [description(resource['description']) ...
def description(self)
Retrieves the description of the incident/incidents from the output response Returns: description(namedtuple): List of named tuples of descriptions of the incident/incidents
3.616435
3.296767
1.096964
resource_list = self.traffic_incident() congestion = namedtuple('congestion', 'congestion') if len(resource_list) == 1 and resource_list[0] is None: return None else: try: return [congestion(resource['congestion']) ...
def congestion(self)
Retrieves the congestion information of the incident/incidents from the output response Returns: congestion(namedtuple): List of named tuples of congestion info of the incident/incidents
3.70461
3.224175
1.14901
resource_list = self.traffic_incident() detour_info = namedtuple('detour_info', 'detour_info') if len(resource_list) == 1 and resource_list[0] is None: return None else: try: return [detour_info(resource['detour']) ...
def detour_info(self)
Retrieves the detour information of the incident/incidents from the output response Returns: detour_info(namedtuple): List of named tuples of detour info of the incident/incidents
3.301104
2.967732
1.112332
resource_list = self.traffic_incident() start_time = namedtuple('start_time', 'start_time') if len(resource_list) == 1 and resource_list[0] is None: return None else: try: return [start_time(resource['start']) for r...
def start_time(self)
Retrieves the start time of the incident/incidents from the output response Returns: start_time(namedtuple): List of named tuples of start time of the incident/incidents
3.867607
3.446998
1.122022
resource_list = self.traffic_incident() end_time = namedtuple('end_time', 'end_time') if len(resource_list) == 1 and resource_list[0] is None: return None else: try: return [end_time(resource['end']) for resource in...
def end_time(self)
Retrieves the end time of the incident/incidents from the output response Returns: end_time(namedtuple): List of named tuples of end time of the incident/incidents
3.905612
3.555519
1.098465
resource_list = self.traffic_incident() incident_id = namedtuple('incident_id', 'incident_id') if len(resource_list) == 1 and resource_list[0] is None: return None else: try: return [incident_id(resource['incidentId']) ...
def incident_id(self)
Retrieves the incident id/ids of the incident/incidents from the output response Returns: incident_id(namedtuple): List of named tuples of incident id/ids of the incident/incidents
3.18683
3.160737
1.008255
resource_list = self.traffic_incident() lane_info = namedtuple('lane_info', 'lane_info') if len(resource_list) == 1 and resource_list[0] is None: return None else: try: return [lane_info(resource['lane']) for resour...
def lane_info(self)
Retrieves the lane info of the incident/incidents from the output response Returns: lane_info(namedtuple): List of named tuples of lane info of the incident/incidents
3.478925
3.280525
1.060478
resource_list = self.traffic_incident() last_modified = namedtuple('last_modified', 'last_modified') if len(resource_list) == 1 and resource_list[0] is None: return None else: try: return [last_modified(resource['lastModified']) ...
def last_modified(self)
Retrieves the last modified time stamp of the incident/incidents from the output response Returns: last_modified(namedtuple): List of named tuples of last modified time stamp of the incident/incidents
3.849254
3.552668
1.083483