code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def get_file_size(file_object): position = file_object.tell() file_object.seek(0, 2) file_size = file_object.tell() file_object.seek(position, 0) return file_size
Returns the size, in bytes, of a file. Expects an object that supports seek and tell methods. Args: file_object (file_object) - The object that represents the file Returns: (int): size of the file, in bytes
def _readse(self, pos): codenum, pos = self._readue(pos) m = (codenum + 1) // 2 if not codenum % 2: return -m, pos else: return m, pos
Return interpretation of next bits as a signed exponential-Golomb code. Advances position to after the read code. Raises ReadError if the end of the bitstring is encountered while reading the code.
def fetch_class(full_class_name): (module_name, class_name) = full_class_name.rsplit('.', 1) module = importlib.import_module(module_name) return getattr(module, class_name)
Fetches the given class. :param string full_class_name: Name of the class to be fetched.
def tree_render(request, upy_context, vars_dictionary): page = upy_context['PAGE'] return render_to_response(page.template.file_name, vars_dictionary, context_instance=RequestContext(request))
It renders template defined in upy_context's page passed in arguments
def remove_object_from_list(self, obj, list_element): list_element = self._handle_location(list_element) if isinstance(obj, JSSObject): results = [item for item in list_element.getchildren() if item.findtext("id") == obj.id] elif isinstance(obj, (int, basestring)): results = [item for item in list_element.getchildren() if item.findtext("id") == str(obj) or item.findtext("name") == obj] if len(results) == 1: list_element.remove(results[0]) elif len(results) > 1: raise ValueError("There is more than one matching object at that " "path!")
Remove an object from a list element. Args: obj: Accepts JSSObjects, id's, and names list_element: Accepts an Element or a string path to that element
def cmp(cls, v1: 'VersionBase', v2: 'VersionBase') -> int: if v1._version > v2._version: return 1 elif v1._version == v2._version: return 0 else: return -1
Compares two instances.
def frequency(self, context): channels = self._manager.spectral_window_table.getcol(MS.CHAN_FREQ) return channels.reshape(context.shape).astype(context.dtype)
Frequency data source
def view_assets_by_site(token, dstore): taxonomies = dstore['assetcol/tagcol/taxonomy'].value assets_by_site = dstore['assetcol'].assets_by_site() data = ['taxonomy mean stddev min max num_sites num_assets'.split()] num_assets = AccumDict() for assets in assets_by_site: num_assets += {k: [len(v)] for k, v in group_array( assets, 'taxonomy').items()} for taxo in sorted(num_assets): val = numpy.array(num_assets[taxo]) data.append(stats(taxonomies[taxo], val, val.sum())) if len(num_assets) > 1: n_assets = numpy.array([len(assets) for assets in assets_by_site]) data.append(stats('*ALL*', n_assets, n_assets.sum())) return rst_table(data)
Display statistical information about the distribution of the assets
def forwards(apps, schema_editor): Event = apps.get_model('spectator_events', 'Event') for ev in Event.objects.filter(kind='movie'): ev.kind = 'cinema' ev.save() for ev in Event.objects.filter(kind='play'): ev.kind = 'theatre' ev.save()
Change Events with kind 'movie' to 'cinema' and Events with kind 'play' to 'theatre'. Purely for more consistency.
def get_subgraph_from_edge_list(graph, edge_list): node_list = get_vertices_from_edge_list(graph, edge_list) subgraph = make_subgraph(graph, node_list, edge_list) return subgraph
Transforms a list of edges into a subgraph.
def captcha_refresh(request): if not request.is_ajax(): raise Http404 new_key = CaptchaStore.pick() to_json_response = { 'key': new_key, 'image_url': captcha_image_url(new_key), 'audio_url': captcha_audio_url(new_key) if settings.CAPTCHA_FLITE_PATH else None } return HttpResponse(json.dumps(to_json_response), content_type='application/json')
Return json with new captcha for ajax refresh request
def getMapScale(self, latitude, level, dpi=96): dpm = dpi / 0.0254 return self.getGroundResolution(latitude, level) * dpm
returns the map scale on the dpi of the screen
def reinit_configurations(self, request): now = timezone.now() changed_resources = [] for resource_model in CostTrackingRegister.registered_resources: for resource in resource_model.objects.all(): try: pe = models.PriceEstimate.objects.get(scope=resource, month=now.month, year=now.year) except models.PriceEstimate.DoesNotExist: changed_resources.append(resource) else: new_configuration = CostTrackingRegister.get_configuration(resource) if new_configuration != pe.consumption_details.configuration: changed_resources.append(resource) for resource in changed_resources: models.PriceEstimate.update_resource_estimate(resource, CostTrackingRegister.get_configuration(resource)) message = _('Configuration was reinitialized for %(count)s resources') % {'count': len(changed_resources)} self.message_user(request, message) return redirect(reverse('admin:cost_tracking_defaultpricelistitem_changelist'))
Re-initialize configuration for resource if it has been changed. This method should be called if resource consumption strategy was changed.
def postprocess_subject(self, entry): if type(entry.subject) not in [str, unicode]: subject = u' '.join([unicode(k) for k in entry.subject]) else: subject = entry.subject entry.subject = [k.strip().upper() for k in subject.split(';')]
Parse subject keywords. Subject keywords are usually semicolon-delimited.
def reset(self, configuration: dict) -> None: self.clean(0) self.backend.store_config(configuration)
Whenever there was anything stored in the database or not, purge previous state and start new training process from scratch.
def stop_listening(self): self._halt_threads = True for name, queue_waker in self.recieved_signals.items(): q, wake_event = queue_waker wake_event.set()
Stop listener threads for acquistion queues
def _set_mpl_backend(self, backend, pylab=False): import traceback from IPython.core.getipython import get_ipython generic_error = ( "\n" + "="*73 + "\n" "NOTE: The following error appeared when setting " "your Matplotlib backend!!\n" + "="*73 + "\n\n" "{0}" ) magic = 'pylab' if pylab else 'matplotlib' error = None try: get_ipython().run_line_magic(magic, backend) except RuntimeError as err: if "GUI eventloops" in str(err): import matplotlib previous_backend = matplotlib.get_backend() if not backend in previous_backend.lower(): error = ( "\n" "NOTE: Spyder *can't* set your selected Matplotlib " "backend because there is a previous backend already " "in use.\n\n" "Your backend will be {0}".format(previous_backend) ) del matplotlib else: error = generic_error.format(traceback.format_exc()) except Exception: error = generic_error.format(traceback.format_exc()) self._mpl_backend_error = error
Set a backend for Matplotlib. backend: A parameter that can be passed to %matplotlib (e.g. 'inline' or 'tk').
def define_new(cls, name, members, is_abstract=False): m = OrderedDict(cls._members) if set(m.keys()) & set(members.keys()): raise ValueError("'members' contains keys that overlap with parent") m.update(members) dct = { '_members' : m, '_is_abstract': is_abstract, } newcls = type(name, (cls,), dct) return newcls
Define a new struct type derived from the current type. Parameters ---------- name: str Name of the struct type members: {member_name : type} Dictionary of struct member types. is_abstract: bool If set, marks the struct as abstract.
def format_single_dict(dictionary, output_name): output_payload = {} if dictionary: for (k, v) in dictionary.items(): output_payload[output_name + '[' + k + ']'] = v return output_payload
Currently used for metadata fields
def abort_keepalive_pings(self) -> None: assert self.state is State.CLOSED exc = ConnectionClosed(self.close_code, self.close_reason) exc.__cause__ = self.transfer_data_exc for ping in self.pings.values(): ping.set_exception(exc) if self.pings: pings_hex = ", ".join( binascii.hexlify(ping_id).decode() or "[empty]" for ping_id in self.pings ) plural = "s" if len(self.pings) > 1 else "" logger.debug( "%s - aborted pending ping%s: %s", self.side, plural, pings_hex )
Raise ConnectionClosed in pending keepalive pings. They'll never receive a pong once the connection is closed.
def verification_digit(numbers): a = sum(numbers[::2]) b = a * 3 c = sum(numbers[1::2]) d = b + c e = d % 10 if e == 0: return e return 10 - e
Returns the verification digit for a given numbre. The verification digit is calculated as follows: * A = sum of all even-positioned numbers * B = A * 3 * C = sum of all odd-positioned numbers * D = B + C * The results is the smallset number N, such that (D + N) % 10 == 0 NOTE: Afip's documentation seems to have odd an even mixed up in the explanation, but all examples follow the above algorithm. :param list(int) numbers): The numbers for which the digits is to be calculated. :return: int
def map_unicode_string(self, unicode_string, ignore=False, single_char_parsing=False, return_as_list=False, return_can_map=False): if unicode_string is None: return None ipa_string = IPAString(unicode_string=unicode_string, ignore=ignore, single_char_parsing=single_char_parsing) return self.map_ipa_string( ipa_string=ipa_string, ignore=ignore, return_as_list=return_as_list, return_can_map=return_can_map )
Convert the given Unicode string, representing an IPA string, to a string containing the corresponding mapped representation. Return ``None`` if ``unicode_string`` is ``None``. :param str unicode_string: the Unicode string to be parsed :param bool ignore: if ``True``, ignore Unicode characters that are not IPA valid :param bool single_char_parsing: if ``True``, parse one Unicode character at a time :param bool return_as_list: if ``True``, return as a list of strings, one for each IPAChar, instead of their concatenation (single str) :param bool return_can_map: if ``True``, return a pair ``(bool, str)``, where the first element says if the mapper can map all the IPA characters in the given IPA string, and the second element is either ``None`` or the mapped string/list :rtype: str or (bool, str) or (bool, list)
def get_values(self, config_manager, ignore_mismatches, obj_hook=DotDict): if self.delayed_parser_instantiation: try: app = config_manager._get_option('admin.application') source = "%s%s" % (app.value.app_name, file_name_extension) self.config_obj = configobj.ConfigObj(source) self.delayed_parser_instantiation = False except AttributeError: return obj_hook() if isinstance(self.config_obj, obj_hook): return self.config_obj return obj_hook(initializer=self.config_obj)
Return a nested dictionary representing the values in the ini file. In the case of this ValueSource implementation, both parameters are dummies.
def day_fraction(time): hour = int(time.split(":")[0]) minute = int(time.split(":")[1]) return hour/24 + minute/1440
Convert a 24-hour time to a fraction of a day. For example, midnight corresponds to 0.0, and noon to 0.5. :param time: Time in the form of 'HH:MM' (24-hour time) :type time: string :return: A day fraction :rtype: float :Examples: .. code-block:: python day_fraction("18:30")
def _idx_to_bits(self, i): bits = bin(i)[2:].zfill(self.nb_hyperplanes) return [-1.0 if b == "0" else 1.0 for b in bits]
Convert an group index to its bit representation.
def run(self, change): if self._formats is None: self.setup() entry = self.entry for fmt in self._formats: fmt.run(change, entry) self.clear()
runs the report format instances in this reporter. Will call setup if it hasn't been called already
def sheets(self): data = Dict() for src in [src for src in self.zipfile.namelist() if 'xl/worksheets/' in src]: name = os.path.splitext(os.path.basename(src))[0] xml = self.xml(src) data[name] = xml return data
return the sheets of data.
def get_coherent_next_tag(prev_label: str, cur_label: str) -> str: if cur_label == "O": return "O" if prev_label == cur_label: return f"I-{cur_label}" else: return f"B-{cur_label}"
Generate a coherent tag, given previous tag and current label.
def values(self): dtypes = [col.dtype for col in self.columns] if len(set(dtypes)) > 1: dtype = object else: dtype = None return np.array(self.columns, dtype=dtype).T
Return data in `self` as a numpy array. If all columns are the same dtype, the resulting array will have this dtype. If there are >1 dtypes in columns, then the resulting array will have dtype `object`.
def validate(self, sources): if not isinstance(sources, Root): raise Exception("Source object expected") parameters = self.get_uri_with_missing_parameters(sources) for parameter in parameters: logging.getLogger().warn('Missing parameter "%s" in uri of method "%s" in versions "%s"' % (parameter["name"], parameter["method"], parameter["version"]))
Validate the format of sources
def add_ref(self, ref): self.refs[ref.insn_addr].append(ref) self.data_addr_to_ref[ref.memory_data.addr].append(ref)
Add a reference to a memory data object. :param CodeReference ref: The reference. :return: None
def dasopr(fname): fname = stypes.stringToCharP(fname) handle = ctypes.c_int() libspice.dasopr_c(fname, ctypes.byref(handle)) return handle.value
Open a DAS file for reading. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasopr_c.html :param fname: Name of a DAS file to be opened. :type fname: str :return: Handle assigned to the opened DAS file. :rtype: int
def average_price(quantity_1, price_1, quantity_2, price_2): return (quantity_1 * price_1 + quantity_2 * price_2) / \ (quantity_1 + quantity_2)
Calculates the average price between two asset states.
def lookup_controller(obj, remainder, request=None): if request is None: warnings.warn( ( "The function signature for %s.lookup_controller is changing " "in the next version of pecan.\nPlease update to: " "`lookup_controller(self, obj, remainder, request)`." % ( __name__, ) ), DeprecationWarning ) notfound_handlers = [] while True: try: obj, remainder = find_object(obj, remainder, notfound_handlers, request) handle_security(obj) return obj, remainder except (exc.HTTPNotFound, exc.HTTPMethodNotAllowed, PecanNotFound) as e: if isinstance(e, PecanNotFound): e = exc.HTTPNotFound() while notfound_handlers: name, obj, remainder = notfound_handlers.pop() if name == '_default': return obj, remainder else: result = handle_lookup_traversal(obj, remainder) if result: if ( remainder == [''] and len(obj._pecan['argspec'].args) > 1 ): raise e obj_, remainder_ = result return lookup_controller(obj_, remainder_, request) else: raise e
Traverses the requested url path and returns the appropriate controller object, including default routes. Handles common errors gracefully.
def new_tag(self, name: str, category: str=None) -> models.Tag: new_tag = self.Tag(name=name, category=category) return new_tag
Create a new tag.
def get_atoms(self, ligands=True, pseudo_group=False, inc_alt_states=False): atoms = itertools.chain( *(list(m.get_atoms(inc_alt_states=inc_alt_states)) for m in self.get_monomers(ligands=ligands, pseudo_group=pseudo_group))) return atoms
Flat list of all the `Atoms` in the `Assembly`. Parameters ---------- ligands : bool, optional Include ligand `Atoms`. pseudo_group : bool, optional Include pseudo_group `Atoms`. inc_alt_states : bool, optional Include alternate sidechain conformations. Returns ------- atoms : itertools.chain All the `Atoms` as a iterator.
def list_security_groups_in_vpc(self, vpc_id=None): log = logging.getLogger(self.cls_logger + '.list_security_groups_in_vpc') if vpc_id is None and self.vpc_id is not None: vpc_id = self.vpc_id else: msg = 'Unable to determine VPC ID to use to create the Security Group' log.error(msg) raise EC2UtilError(msg) filters = [ { 'Name': 'vpc-id', 'Values': [vpc_id] } ] log.info('Querying for a list of security groups in VPC ID: {v}'.format(v=vpc_id)) try: security_groups = self.client.describe_security_groups(DryRun=False, Filters=filters) except ClientError: _, ex, trace = sys.exc_info() msg = 'Unable to query AWS for a list of security groups in VPC ID: {v}\n{e}'.format( v=vpc_id, e=str(ex)) raise AWSAPIError, msg, trace return security_groups
Lists security groups in the VPC. If vpc_id is not provided, use self.vpc_id :param vpc_id: (str) VPC ID to list security groups for :return: (list) Security Group info :raises: AWSAPIError, EC2UtilError
def get_locations(self, ip, detailed=False): if isinstance(ip, str): ip = [ip] seek = map(self._get_pos, ip) return [self._parse_location(elem, detailed=detailed) if elem > 0 else False for elem in seek]
Returns a list of dictionaries with location data or False on failure. Argument `ip` must be an iterable object. Amount of information about IP contained in the dictionary depends upon `detailed` flag state.
def history_add(self, value): if self._history_max_size is None or self.history_len() < self._history_max_size: self._history.append(value) else: self._history = self._history[1:] + [value]
Add a value in the history
def _apply_transformation(inputs): ts, transformation, extend_collection, clear_redo = inputs new = ts.append_transformation(transformation, extend_collection, clear_redo=clear_redo) o = [ts] if new: o.extend(new) return o
Helper method for multiprocessing of apply_transformation. Must not be in the class so that it can be pickled. Args: inputs: Tuple containing the transformed structure, the transformation to be applied, a boolean indicating whether to extend the collection, and a boolean indicating whether to clear the redo Returns: List of output structures (the modified initial structure, plus any new structures created by a one-to-many transformation)
def populate_readme( version, circleci_build, appveyor_build, coveralls_build, travis_build ): with open(RELEASE_README_FILE, "r") as file_obj: template = file_obj.read() contents = template.format( version=version, circleci_build=circleci_build, appveyor_build=appveyor_build, coveralls_build=coveralls_build, travis_build=travis_build, ) with open(README_FILE, "w") as file_obj: file_obj.write(contents)
Populates ``README.rst`` with release-specific data. This is because ``README.rst`` is used on PyPI. Args: version (str): The current version. circleci_build (Union[str, int]): The CircleCI build ID corresponding to the release. appveyor_build (str): The AppVeyor build ID corresponding to the release. coveralls_build (Union[str, int]): The Coveralls.io build ID corresponding to the release. travis_build (int): The Travis CI build ID corresponding to the release.
def addResourceFile(self, pid, resource_file, resource_filename=None, progress_callback=None): url = "{url_base}/resource/{pid}/files/".format(url_base=self.url_base, pid=pid) params = {} close_fd = self._prepareFileForUpload(params, resource_file, resource_filename) encoder = MultipartEncoder(params) if progress_callback is None: progress_callback = default_progress_callback monitor = MultipartEncoderMonitor(encoder, progress_callback) r = self._request('POST', url, data=monitor, headers={'Content-Type': monitor.content_type}) if close_fd: fd = params['file'][1] fd.close() if r.status_code != 201: if r.status_code == 403: raise HydroShareNotAuthorized(('POST', url)) elif r.status_code == 404: raise HydroShareNotFound((pid,)) else: raise HydroShareHTTPException((url, 'POST', r.status_code)) response = r.json() return response
Add a new file to an existing resource :param pid: The HydroShare ID of the resource :param resource_file: a read-only binary file-like object (i.e. opened with the flag 'rb') or a string representing path to file to be uploaded as part of the new resource :param resource_filename: string representing the filename of the resource file. Must be specified if resource_file is a file-like object. If resource_file is a string representing a valid file path, and resource_filename is not specified, resource_filename will be equal to os.path.basename(resource_file). is a string :param progress_callback: user-defined function to provide feedback to the user about the progress of the upload of resource_file. For more information, see: http://toolbelt.readthedocs.org/en/latest/uploading-data.html#monitoring-your-streaming-multipart-upload :return: Dictionary containing 'resource_id' the ID of the resource to which the file was added, and 'file_name' the filename of the file added. :raises: HydroShareNotAuthorized if user is not authorized to perform action. :raises: HydroShareNotFound if the resource was not found. :raises: HydroShareHTTPException if an unexpected HTTP response code is encountered.
def component_doi(soup): component_doi = [] object_id_tags = raw_parser.object_id(soup, pub_id_type = "doi") component_list = components(soup) position = 1 for tag in object_id_tags: component_object = {} component_object["doi"] = doi_uri_to_doi(tag.text) component_object["position"] = position for component in component_list: if "doi" in component and component["doi"] == component_object["doi"]: component_object["type"] = component["type"] component_doi.append(component_object) position = position + 1 return component_doi
Look for all object-id of pub-type-id = doi, these are the component DOI tags
def create_geometry(self, input_geometry, upper_depth, lower_depth): self._check_seismogenic_depths(upper_depth, lower_depth) if not isinstance(input_geometry, Point): if not isinstance(input_geometry, np.ndarray): raise ValueError('Unrecognised or unsupported geometry ' 'definition') self.geometry = Point(input_geometry[0], input_geometry[1]) else: self.geometry = input_geometry
If geometry is defined as a numpy array then create instance of nhlib.geo.point.Point class, otherwise if already instance of class accept class :param input_geometry: Input geometry (point) as either i) instance of nhlib.geo.point.Point class ii) numpy.ndarray [Longitude, Latitude] :param float upper_depth: Upper seismogenic depth (km) :param float lower_depth: Lower seismogenic depth (km)
def config_babel(app): " Init application with babel. " babel.init_app(app) def get_locale(): return request.accept_languages.best_match(app.config['BABEL_LANGUAGES']) babel.localeselector(get_locale)
Init application with babel.
def post_article_content(self, content, url, max_pages=25): params = { 'doc': content, 'max_pages': max_pages } url = self._generate_url('parser', {"url": url}) return self.post(url, post_params=params)
POST content to be parsed to the Parser API. Note: Even when POSTing content, a url must still be provided. :param content: the content to be parsed :param url: the url that represents the content :param max_pages (optional): the maximum number of pages to parse and combine. Default is 25.
def _expand_users(device_users, common_users): expected_users = deepcopy(common_users) expected_users.update(device_users) return expected_users
Creates a longer list of accepted users on the device.
def generate(data, dimOrder, maxWindowSize, overlapPercent, transforms = []): width = data.shape[dimOrder.index('w')] height = data.shape[dimOrder.index('h')] return generateForSize(width, height, dimOrder, maxWindowSize, overlapPercent, transforms)
Generates a set of sliding windows for the specified dataset.
def call_fan(tstat): old_fan = tstat.fan tstat.write({ 'fan': not old_fan, }) def restore(): tstat.write({ 'fan': old_fan, }) return restore
Toggles the fan
def camera_to_rays(camera): half = np.radians(camera.fov / 2.0) half *= (camera.resolution - 2) / camera.resolution angles = util.grid_linspace(bounds=[-half, half], count=camera.resolution) vectors = util.unitize(np.column_stack(( np.sin(angles), np.ones(len(angles))))) transform = np.dot( camera.transform, align_vectors([1, 0, 0], [-1, 0, 0])) vectors = transformations.transform_points( vectors, transform, translate=False) origin = transformations.translation_from_matrix(transform) origins = np.ones_like(vectors) * origin return origins, vectors, angles
Convert a trimesh.scene.Camera object to ray origins and direction vectors. Will return one ray per pixel, as set in camera.resolution. Parameters -------------- camera : trimesh.scene.Camera Camera with transform defined Returns -------------- origins : (n, 3) float Ray origins in space vectors : (n, 3) float Ray direction unit vectors angles : (n, 2) float Ray spherical coordinate angles in radians
def generate_filename(self, requirement): return FILENAME_PATTERN % (self.config.cache_format_revision, requirement.name, requirement.version, get_python_version())
Generate a distribution archive filename for a package. :param requirement: A :class:`.Requirement` object. :returns: The filename of the distribution archive (a string) including a single leading directory component to indicate the cache format revision.
def _auth(url): user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, user=user, passwd=password ) digest = _HTTPDigestAuthHandler() digest.add_password( realm=realm, uri=url, user=user, passwd=password ) _install_opener( _build_opener(basic, digest) )
Install an auth handler for urllib2
def set_edge_weight(self, edge, wt): self.set_edge_properties(edge, weight=wt ) if not self.DIRECTED: self.set_edge_properties((edge[1], edge[0]) , weight=wt )
Set the weight of an edge. @type edge: edge @param edge: One edge. @type wt: number @param wt: Edge weight.
def parseArgsPy26(): from gsmtermlib.posoptparse import PosOptionParser, Option parser = PosOptionParser(description='Simple script for sending SMS messages') parser.add_option('-i', '--port', metavar='PORT', help='port to which the GSM modem is connected; a number or a device name.') parser.add_option('-b', '--baud', metavar='BAUDRATE', default=115200, help='set baud rate') parser.add_option('-p', '--pin', metavar='PIN', default=None, help='SIM card PIN') parser.add_option('-d', '--deliver', action='store_true', help='wait for SMS delivery report') parser.add_positional_argument(Option('--destination', metavar='DESTINATION', help='destination mobile number')) options, args = parser.parse_args() if len(args) != 1: parser.error('Incorrect number of arguments - please specify a DESTINATION to send to, e.g. {0} 012789456'.format(sys.argv[0])) else: options.destination = args[0] return options
Argument parser for Python 2.6
def type(self, newtype): self._type = newtype if self.is_multi: for sibling in self.multi_rep.siblings: sibling._type = newtype
If the feature is a multifeature, update all entries.
def regexp_extract(str, pattern, idx): r sc = SparkContext._active_spark_context jc = sc._jvm.functions.regexp_extract(_to_java_column(str), pattern, idx) return Column(jc)
r"""Extract a specific group matched by a Java regex, from the specified string column. If the regex did not match, or the specified group did not match, an empty string is returned. >>> df = spark.createDataFrame([('100-200',)], ['str']) >>> df.select(regexp_extract('str', r'(\d+)-(\d+)', 1).alias('d')).collect() [Row(d=u'100')] >>> df = spark.createDataFrame([('foo',)], ['str']) >>> df.select(regexp_extract('str', r'(\d+)', 1).alias('d')).collect() [Row(d=u'')] >>> df = spark.createDataFrame([('aaaac',)], ['str']) >>> df.select(regexp_extract('str', '(a+)(b)?(c)', 2).alias('d')).collect() [Row(d=u'')]
def read_config(file_name): dirname = os.path.dirname( os.path.abspath(file_name) ) dirname = os.path.relpath(dirname) def custom_str_constructor(loader, node): return loader.construct_scalar(node).encode('utf-8') yaml.add_constructor(u'tag:yaml.org,2002:str', custom_str_constructor) config = [] with open(file_name) as f: for item in yaml.load_all(f.read()): config.append( _process_config_item(item, dirname) ) return config
Read YAML file with configuration and pointers to example data. Args: file_name (str): Name of the file, where the configuration is stored. Returns: dict: Parsed and processed data (see :func:`_process_config_item`). Example YAML file:: html: simple_xml.xml first: data: i wan't this required: true notfoundmsg: Can't find variable $name. second: data: and this --- html: simple_xml2.xml first: data: something wanted required: true notfoundmsg: Can't find variable $name. second: data: another wanted thing
def set_data(self, index, value): acces, field = self.get_item(index), self.header[index.column()] self.beginResetModel() self.set_data_hook(acces, field, value) self.endResetModel()
Uses given data setter, and emit modelReset signal
def code(self): if self._code is not None: return self._code elif self._defcode is not None: return self._defcode return 200
The HTTP response code associated with this ResponseObject. If instantiated directly without overriding the code, returns 200 even if the default for the method is some other value. Can be set or deleted; in the latter case, the default will be restored.
def cli(ctx): level = logger.level try: level_to_name = logging._levelToName except AttributeError: level_to_name = logging._levelNames level_name = level_to_name.get(level, level) logger.debug('Verbosity set to {}.'.format(level_name)) if ctx.invoked_subcommand is None: click.echo(ctx.get_help()) ctx.exit() ctx.obj = {}
CLI for maildirs content analysis and deletion.
def gen_for(self, node, target, local_iter, local_iter_decl, loop_body): local_target = "__target{0}".format(id(node)) local_target_decl = self.types.builder.IteratorOfType(local_iter_decl) if node.target.id in self.scope[node] and not hasattr(self, 'yields'): local_type = "auto&&" else: local_type = "" loop_body_prelude = Statement("{} {}= *{}".format(local_type, target, local_target)) assign = self.make_assign(local_target_decl, local_target, local_iter) loop = For("{}.begin()".format(assign), "{0} < {1}.end()".format(local_target, local_iter), "++{0}".format(local_target), Block([loop_body_prelude, loop_body])) return [self.process_omp_attachements(node, loop)]
Create For representation on iterator for Cxx generation. Examples -------- >> "omp parallel for" >> for i in xrange(10): >> ... do things ... Becomes >> "omp parallel for shared(__iterX)" >> for(decltype(__iterX)::iterator __targetX = __iterX.begin(); __targetX < __iterX.end(); ++__targetX) >> auto&& i = *__targetX; >> ... do things ... It the case of not local variable, typing for `i` disappear and typing is removed for iterator in case of yields statement in function.
def submit(self, stanza): body = _encode(**stanza) self.service.post(self.path, body=body) return self
Adds keys to the current configuration stanza as a dictionary of key-value pairs. :param stanza: A dictionary of key-value pairs for the stanza. :type stanza: ``dict`` :return: The :class:`Stanza` object.
def _output_tags(self): for class_name, properties in sorted(self.resources.items()): for key, value in sorted(properties.items()): validator = self.override.get_validator(class_name, key) if key == 'Tags' and validator is None: print("from troposphere import Tags") return for class_name, properties in sorted(self.properties.items()): for key, value in sorted(properties.items()): validator = self.override.get_validator(class_name, key) if key == 'Tags' and validator is None: print("from troposphere import Tags") return
Look for a Tags object to output a Tags import
def get_supported_currency_choices(api_key): import stripe stripe.api_key = api_key account = stripe.Account.retrieve() supported_payment_currencies = stripe.CountrySpec.retrieve(account["country"])[ "supported_payment_currencies" ] return [(currency, currency.upper()) for currency in supported_payment_currencies]
Pull a stripe account's supported currencies and returns a choices tuple of those supported currencies. :param api_key: The api key associated with the account from which to pull data. :type api_key: str
def vary_name(name: Text): snake = re.match(r'^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$', name) if not snake: fail('The project name is not a valid snake-case Python variable name') camel = [x[0].upper() + x[1:] for x in name.split('_')] return { 'project_name_snake': name, 'project_name_camel': ''.join(camel), 'project_name_readable': ' '.join(camel), }
Validates the name and creates variations
def print_math(math_expression_lst, name = "math.html", out='html', formatter = lambda x: x): try: shutil.rmtree('viz') except: pass pth = get_cur_path()+print_math_template_path shutil.copytree(pth, 'viz') html_loc = None if out == "html": html_loc = pth+"standalone_index.html" if out == "notebook": from IPython.display import display, HTML html_loc = pth+"notebook_index.html" html = open(html_loc).read() html = html.replace("__MATH_LIST__", json.dumps(math_expression_lst)) if out == "notebook": display(HTML(html)) elif out == "html": with open(name, "w+") as out_f: out_f.write(html)
Converts LaTeX math expressions into an html layout. Creates a html file in the directory where print_math is called by default. Displays math to jupyter notebook if "notebook" argument is specified. Args: math_expression_lst (list): A list of LaTeX math (string) to be rendered by KaTeX out (string): {"html"|"notebook"}: HTML by default. Specifies output medium. formatter (function): function that cleans up the string for KaTeX. Returns: A HTML file in the directory where this function is called, or displays HTML output in a notebook.
def least_upper_bound(*intervals_to_join): assert len(intervals_to_join) > 0, "No intervals to join" all_same = all(x.bits == intervals_to_join[0].bits for x in intervals_to_join) assert all_same, "All intervals to join should be same" if len(intervals_to_join) == 1: return intervals_to_join[0].copy() if len(intervals_to_join) == 2: return StridedInterval.pseudo_join(intervals_to_join[0], intervals_to_join[1]) sorted_intervals = sorted(intervals_to_join, key=lambda x: x.lower_bound) ret = None for i in xrange(len(sorted_intervals)): si = reduce(lambda x, y: StridedInterval.pseudo_join(x, y, False), sorted_intervals[i:] + sorted_intervals[0:i]) if ret is None or ret.n_values > si.n_values: ret = si if any([x for x in intervals_to_join if x.uninitialized]): ret.uninitialized = True return ret
Pseudo least upper bound. Join the given set of intervals into a big interval. The resulting strided interval is the one which in all the possible joins of the presented SI, presented the least number of values. The number of joins to compute is linear with the number of intervals to join. Draft of proof: Considering three generic SI (a,b, and c) ordered from their lower bounds, such that a.lower_bund <= b.lower_bound <= c.lower_bound, where <= is the lexicographic less or equal. The only joins which have sense to compute are: * a U b U c * b U c U a * c U a U b All the other combinations fall in either one of these cases. For example: b U a U c does not make make sense to be calculated. In fact, if one draws this union, the result is exactly either (b U c U a) or (a U b U c) or (c U a U b). :param intervals_to_join: Intervals to join :return: Interval that contains all intervals
def get_callee_account( global_state: GlobalState, callee_address: str, dynamic_loader: DynLoader ): environment = global_state.environment accounts = global_state.accounts try: return global_state.accounts[callee_address] except KeyError: log.debug("Module with address " + callee_address + " not loaded.") if dynamic_loader is None: raise ValueError() log.debug("Attempting to load dependency") try: code = dynamic_loader.dynld(callee_address) except ValueError as error: log.debug("Unable to execute dynamic loader because: {}".format(str(error))) raise error if code is None: log.debug("No code returned, not a contract account?") raise ValueError() log.debug("Dependency loaded: " + callee_address) callee_account = Account( callee_address, code, callee_address, dynamic_loader=dynamic_loader ) accounts[callee_address] = callee_account return callee_account
Gets the callees account from the global_state. :param global_state: state to look in :param callee_address: address of the callee :param dynamic_loader: dynamic loader to use :return: Account belonging to callee
def get_report(self): ostr = '' ostr += "target\tquery\tcnt\ttotal\n" poss = ['-','A','C','G','T'] for target in poss: for query in poss: ostr += target+ "\t"+query+"\t"+str(self.matrix[target][query])+"\t"+str(self.alignment_length)+"\n" return ostr
Another report, but not context based
def _autorestart_components(self, bundle): with self.__instances_lock: instances = self.__auto_restart.get(bundle) if not instances: return for factory, name, properties in instances: try: self.instantiate(factory, name, properties) except Exception as ex: _logger.exception( "Error restarting component '%s' ('%s') " "from bundle %s (%d): %s", name, factory, bundle.get_symbolic_name(), bundle.get_bundle_id(), ex, )
Restart the components of the given bundle :param bundle: A Bundle object
def get_access_token(self): if self.token_info and not self.is_token_expired(self.token_info): return self.token_info['access_token'] token_info = self._request_access_token() token_info = self._add_custom_values_to_token_info(token_info) self.token_info = token_info return self.token_info['access_token']
If a valid access token is in memory, returns it Else feches a new token and returns it
def _get_pos(self, key): p = bisect(self.runtime._keys, self.hashi(key)) if p == len(self.runtime._keys): return 0 else: return p
Get the index of the given key in the sorted key list. We return the position with the nearest hash based on the provided key unless we reach the end of the continuum/ring in which case we return the 0 (beginning) index position. :param key: the key to hash and look for.
def storage_volume_templates(self): if not self.__storage_volume_templates: self.__storage_volume_templates = StorageVolumeTemplates(self.__connection) return self.__storage_volume_templates
Gets the StorageVolumeTemplates API client. Returns: StorageVolumeTemplates:
def rename_datastore(datastore_ref, new_datastore_name): ds_name = get_managed_object_name(datastore_ref) log.trace("Renaming datastore '%s' to '%s'", ds_name, new_datastore_name) try: datastore_ref.RenameDatastore(new_datastore_name) except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( 'Not enough permissions. Required privilege: ' '{}'.format(exc.privilegeId)) except vim.fault.VimFault as exc: log.exception(exc) raise salt.exceptions.VMwareApiError(exc.msg) except vmodl.RuntimeFault as exc: log.exception(exc) raise salt.exceptions.VMwareRuntimeError(exc.msg)
Renames a datastore datastore_ref vim.Datastore reference to the datastore object to be changed new_datastore_name New datastore name
def generic_visit(self, node): assert isinstance(node, ast.expr) res = self.assign(node) return res, self.explanation_param(self.display(res))
Handle expressions we don't have custom code for.
def get_hw_virt_ex_property(self, property_p): if not isinstance(property_p, HWVirtExPropertyType): raise TypeError("property_p can only be an instance of type HWVirtExPropertyType") value = self._call("getHWVirtExProperty", in_p=[property_p]) return value
Returns the value of the specified hardware virtualization boolean property. in property_p of type :class:`HWVirtExPropertyType` Property type to query. return value of type bool Property value. raises :class:`OleErrorInvalidarg` Invalid property.
def files(self): self._check_session() status, data = self._rest.get_request('files') return data
Get list of files, for this session, on server.
def _perform_radius_auth(self, client, packet): try: reply = client.SendPacket(packet) except Timeout as e: logging.error("RADIUS timeout occurred contacting %s:%s" % ( client.server, client.authport)) return False except Exception as e: logging.error("RADIUS error: %s" % e) return False if reply.code == AccessReject: logging.warning("RADIUS access rejected for user '%s'" % ( packet['User-Name'])) return False elif reply.code != AccessAccept: logging.error("RADIUS access error for user '%s' (code %s)" % ( packet['User-Name'], reply.code)) return False logging.info("RADIUS access granted for user '%s'" % ( packet['User-Name'])) return True
Perform the actual radius authentication by passing the given packet to the server which `client` is bound to. Returns True or False depending on whether the user is authenticated successfully.
def neighbor_difference(self): differences = np.zeros(self.num_neurons) num_neighbors = np.zeros(self.num_neurons) distance, _ = self.distance_function(self.weights, self.weights) for x, y in self.neighbors(): differences[x] += distance[x, y] num_neighbors[x] += 1 return differences / num_neighbors
Get the euclidean distance between a node and its neighbors.
def iter_format_modules(lang): if check_for_language(lang): format_locations = [] for path in CUSTOM_FORMAT_MODULE_PATHS: format_locations.append(path + '.%s') format_locations.append('django.conf.locale.%s') locale = to_locale(lang) locales = [locale] if '_' in locale: locales.append(locale.split('_')[0]) for location in format_locations: for loc in locales: try: yield import_module('.formats', location % loc) except ImportError: pass
Does the heavy lifting of finding format modules.
def get_interface(self, interface='eth0'): LOG.info("RPC: get_interface interfae: %s" % interface) code, message, data = agent_utils.get_interface(interface) return agent_utils.make_response(code, message, data)
Interface info. ifconfig interface
def get_currency_aggregate_by_symbol(self, symbol: str) -> CurrencyAggregate: currency = self.get_by_symbol(symbol) result = self.get_currency_aggregate(currency) return result
Creates currency aggregate for the given currency symbol
def get_bit_width(self, resource): datatype = resource.datatype if "uint" in datatype: bit_width = int(datatype.split("uint")[1]) else: raise ValueError("Unsupported datatype: {}".format(datatype)) return bit_width
Method to return the bit width for blosc based on the Resource
def Emailer(recipients, sender=None): import smtplib hostname = socket.gethostname() if not sender: sender = 'lggr@{0}'.format(hostname) smtp = smtplib.SMTP('localhost') try: while True: logstr = (yield) try: smtp.sendmail(sender, recipients, logstr) except smtplib.SMTPException: pass except GeneratorExit: smtp.quit()
Sends messages as emails to the given list of recipients.
def next(self): return self.iterator.next(task=self.task, timeout=self.timeout, block=self.block)
Returns a result if availble within "timeout" else raises a ``TimeoutError`` exception. See documentation for ``NuMap.next``.
async def execute(self, sql: str, parameters: Iterable[Any] = None) -> None: if parameters is None: parameters = [] await self._execute(self._cursor.execute, sql, parameters)
Execute the given query.
def run(self): while True: try: self.perform_iteration() except Exception: traceback.print_exc() pass time.sleep(ray_constants.REPORTER_UPDATE_INTERVAL_MS / 1000)
Run the reporter.
def startup(api=None): def startup_wrapper(startup_function): apply_to_api = hug.API(api) if api else hug.api.from_object(startup_function) apply_to_api.add_startup_handler(startup_function) return startup_function return startup_wrapper
Runs the provided function on startup, passing in an instance of the api
def register(): signals.article_generator_finalized.connect(link_source_files) signals.page_generator_finalized.connect(link_source_files) signals.page_writer_finalized.connect(write_source_files)
Calls the shots, based on signals
def standardize(self, axis=1): if axis == 1: return self.map(lambda x: x / std(x)) elif axis == 0: stdval = self.std().toarray() return self.map(lambda x: x / stdval) else: raise Exception('Axis must be 0 or 1')
Divide by standard deviation either within or across records. Parameters ---------- axis : int, optional, default = 0 Which axis to standardize along, within (1) or across (0) records
def path(self, *args: typing.List[str]) -> typing.Union[None, str]: if not self._project: return None return environ.paths.clean(os.path.join( self._project.source_directory, *args ))
Creates an absolute path in the project source directory from the relative path components. :param args: Relative components for creating a path within the project source directory :return: An absolute path to the specified file or directory within the project source directory.
def open(self): self.device = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.device.connect((self.host, self.port)) if self.device is None: print "Could not open socket for %s" % self.host
Open TCP socket and set it as escpos device
def _dictionary(self): retval = {} for variant in self._override_order: retval.update(self._config[variant]) return retval
A dictionary representing the loaded configuration.
def GetDefaultContract(self): try: return self.GetContracts()[0] except Exception as e: logger.error("Could not find default contract: %s" % str(e)) raise
Get the default contract. Returns: contract (Contract): if Successful, a contract of type neo.SmartContract.Contract, otherwise an Exception. Raises: Exception: if no default contract is found. Note: Prints a warning to the console if the default contract could not be found.
def join_filter(sep, seq, pred=bool): return sep.join([text_type(i) for i in seq if pred(i)])
Join with a filter.
def get_attachments(self): attachments = [] for attachment in self.context.getAttachment(): attachment_info = self.get_attachment_info(attachment) attachments.append(attachment_info) for analysis in self.context.getAnalyses(full_objects=True): for attachment in analysis.getAttachment(): attachment_info = self.get_attachment_info(attachment) attachment_info["analysis"] = analysis.Title() attachment_info["analysis_uid"] = api.get_uid(analysis) attachments.append(attachment_info) return attachments
Returns a list of attachments info dictionaries Original code taken from bika.lims.analysisrequest.view
def fit(self, X, y=None): if self.normalize: X = normalize(X) self._check_force_weights() random_state = check_random_state(self.random_state) X = self._check_fit_data(X) ( self.cluster_centers_, self.labels_, self.inertia_, self.weights_, self.concentrations_, self.posterior_, ) = movMF( X, self.n_clusters, posterior_type=self.posterior_type, force_weights=self.force_weights, n_init=self.n_init, n_jobs=self.n_jobs, max_iter=self.max_iter, verbose=self.verbose, init=self.init, random_state=random_state, tol=self.tol, copy_x=self.copy_x, ) return self
Compute mixture of von Mises Fisher clustering. Parameters ---------- X : array-like or sparse matrix, shape=(n_samples, n_features)
def all(self, axis=None, *args, **kwargs): nv.validate_all(args, kwargs) values = self.sp_values if len(values) != len(self) and not np.all(self.fill_value): return False return values.all()
Tests whether all elements evaluate True Returns ------- all : bool See Also -------- numpy.all
def _encrypt_data_key( self, data_key: DataKey, algorithm: AlgorithmSuite, encryption_context: Dict[Text, Text] ) -> NoReturn: raise NotImplementedError("CountingMasterKey does not support encrypt_data_key")
Encrypt a data key and return the ciphertext. :param data_key: Unencrypted data key :type data_key: :class:`aws_encryption_sdk.structures.RawDataKey` or :class:`aws_encryption_sdk.structures.DataKey` :param algorithm: Algorithm object which directs how this Master Key will encrypt the data key :type algorithm: aws_encryption_sdk.identifiers.Algorithm :param dict encryption_context: Encryption context to use in encryption :raises NotImplementedError: when called
def __dict_to_pod_spec(spec): spec_obj = kubernetes.client.V1PodSpec() for key, value in iteritems(spec): if hasattr(spec_obj, key): setattr(spec_obj, key, value) return spec_obj
Converts a dictionary into kubernetes V1PodSpec instance.