text
stringlengths
78
104k
score
float64
0
0.18
def profile_tilt(data, mask): """Fit a 2D tilt to `data[mask]`""" params = lmfit.Parameters() params.add(name="mx", value=0) params.add(name="my", value=0) params.add(name="off", value=np.average(data[mask])) fr = lmfit.minimize(tilt_residual, params, args=(data, mask)) bg = tilt_model(fr.pa...
0.002849
def get_all_activities(self, autoscale_group, activity_ids=None, max_records=None, next_token=None): """ Get all activities for the given autoscaling group. This action supports pagination by returning a token if there are more pages to retrieve. To get the ne...
0.002946
def _downloads_for_num_days(self, num_days): """ Given a number of days of historical data to look at (starting with today and working backwards), return the total number of downloads for that time range, and the number of days of data we had (in cases where we had less data than...
0.001843
def setup(): """ Set up the database """ try: db.bind(**config.database_config) except OSError: # Attempted to connect to a file-based database where the file didn't # exist db.bind(**config.database_config, create_db=True) rebuild = True try: db.generate_ma...
0.002933
def get_postgres_encoding(python_encoding: str) -> str: """Python to postgres encoding map.""" encoding = normalize_encoding(python_encoding.lower()) encoding_ = aliases.aliases[encoding.replace('_', '', 1)].upper() pg_encoding = PG_ENCODING_MAP[encoding_.replace('_', '')] return pg_encoding
0.003185
def to_kaf(self): """ Converts the coreference layer to KAF """ if self.type == 'NAF': for node_coref in self.__get_corefs_nodes(): node_coref.set('coid',node_coref.get('id')) del node_coref.attrib['id']
0.010753
def _begin_connection_action(self, action): """Begin a connection attempt Args: action (ConnectionAction): the action object describing what we are connecting to """ conn_id = action.data['connection_id'] int_id = action.data['internal_id'] c...
0.004
def set_title(self, title=None): """Sets the title. :param title: the new title :type title: ``string`` :raise: ``InvalidArgument`` -- ``title`` is invalid :raise: ``NoAccess`` -- ``Metadata.isReadOnly()`` is ``true`` :raise: ``NullArgument`` -- ``title`` is ``null`` ...
0.002692
def _change_secure_boot_settings(self, property, value): """Change secure boot settings on the server.""" system = self._get_host_details() # find the BIOS URI if ('links' not in system['Oem']['Hp'] or 'SecureBoot' not in system['Oem']['Hp']['links']): msg = (' "Se...
0.001608
def _build_generator_list(network): """Builds DataFrames with all generators in MV and LV grids Returns ------- :pandas:`pandas.DataFrame<dataframe>` A DataFrame with id of and reference to MV generators :pandas:`pandas.DataFrame<dataframe>` A DataFrame with id of and refere...
0.004633
def _open(file_, mode='r'): """Open file object given filenames, open files or even archives.""" if isinstance(file_, string_types): _, ext = path.splitext(file_) if ext in {'.bz2', '.gz'}: s = tarfile.open(file_) return s.extractfile(s.next()) else: return open(file_, mode) return f...
0.021605
def seek(self, offset, whence=os.SEEK_SET): """Set the file's current offset. Note if the new offset is out of bound, it is adjusted to either 0 or EOF. Args: offset: seek offset as number. whence: seek mode. Supported modes are os.SEEK_SET (absolute seek), os.SEEK_CUR (seek relative t...
0.005775
def preprX(*attributes, address=True, full_name=False, pretty=False, keyless=False, **kwargs): """ `Creates prettier object representations` @*attributes: (#str) instance attributes within the object you wish to display. Attributes can be recursive e.g. |one.two.three| fo...
0.000514
def write_data(self, chunksize, dropna=False): """ we form the data into a 2-d including indexes,values,mask write chunk-by-chunk """ names = self.dtype.names nrows = self.nrows_expected # if dropna==True, then drop ALL nan rows masks = [] if dropna: ...
0.000763
def calibrate_band_pass_N1(self): """ One way to calibrate the band pass is to take the median value for every frequency fine channel, and divide by it. """ band_pass = np.median(self.data.squeeze(),axis=0) self.data = self.data/band_pass
0.010601
def assert_headers(context): """ :type context: behave.runner.Context """ expected_headers = [(k, v) for k, v in row_table(context).items()] request = httpretty.last_request() actual_headers = request.headers.items() for expected_header in expected_headers: assert_in(expected_hea...
0.002941
def template_exists_db(self, template): """ Receives a template and checks if it exists in the database using the template name and language """ name = utils.camel_to_snake(template[0]).upper() language = utils.camel_to_snake(template[3]) try: models.E...
0.004264
def version(serial=None): """ Returns version information for MicroPython running on the connected device. If such information is not available or the device is not running MicroPython, raise a ValueError. If any other exception is thrown, the device was running MicroPython but there was a...
0.000845
def read_midc_raw_data_from_nrel(site, start, end): """Request and read MIDC data directly from the raw data api. Parameters ---------- site: string The MIDC station id. start: datetime Start date for requested data. end: datetime End date for requested data. Return...
0.001045
async def receive_json(self, content: typing.Dict, **kwargs): """ Called with decoded JSON content. """ # TODO assert format, if does not match return message. request_id = content.pop('request_id') action = content.pop('action') await self.handle_action(action, r...
0.005682
def getAllSystemVariables(self, remote): """Get all system variables from CCU / Homegear""" variables = {} if self.remotes[remote]['username'] and self.remotes[remote]['password']: LOG.debug( "ServerThread.getAllSystemVariables: Getting all System variables via JSON-R...
0.005358
def fromFile(filename): """ Parses the inputted xml file information and generates a builder for it. :param filename | <str> :return <Builder> || None """ xdata = None ydata = None # try parsing an XML file try: ...
0.002503
def format_auto_patching_settings(result): ''' Formats the AutoPatchingSettings object removing arguments that are empty ''' from collections import OrderedDict # Only display parameters that have content order_dict = OrderedDict() if result.enable is not None: order_dict['enable'] =...
0.004038
def process_view(self, request, view_func, view_args, view_kwargs): """ Capture details about the view_func that is about to execute """ try: if ignore_path(request.path): TrackedRequest.instance().tag("ignore_transaction", True) view_name = reque...
0.003695
def member_present(ip, port, balancer_id, profile, **libcloud_kwargs): ''' Ensure a load balancer member is present :param ip: IP address for the new member :type ip: ``str`` :param port: Port for the new member :type port: ``int`` :param balancer_id: id of a load balancer you want to a...
0.004228
def _create_chrome_options(self): """Create and configure a chrome options object :returns: chrome options object """ # Create Chrome options options = webdriver.ChromeOptions() if self.config.getboolean_optional('Driver', 'headless'): self.logger.debug("Run...
0.002535
def copy(self): '''Create a copy of the current instance. :returns: A safely-editable copy of the current sequence. :rtype: coral.DNA ''' # Significant performance improvements by skipping alphabet check features_copy = [feature.copy() for feature in self.features] ...
0.003752
def start(self) -> asyncio.Future: """Starts an RTM Session with Slack. Makes an authenticated call to Slack's RTM API to retrieve a websocket URL and then connects to the message server. As events stream-in we run any associated callbacks stored on the client. If 'auto...
0.002844
def _pdf(self, xloc, left, right, cache): """ Probability density function. Example: >>> print(chaospy.Uniform().pdf([-0.5, 0.5, 1.5, 2.5])) [0. 1. 0. 0.] >>> print(chaospy.Pow(chaospy.Uniform(), 2).pdf([-0.5, 0.5, 1.5, 2.5])) [0. 0.707106...
0.005631
def add_apt_key(filename=None, url=None, keyid=None, keyserver='subkeys.pgp.net', update=False): """ Trust packages signed with this public key. Example:: import burlap # Varnish signing key from URL and verify fingerprint) burlap.deb.add_apt_key(keyid='C4DEFFEB', url='http://repo...
0.004152
def description(self): """:class:`str`: Returns the cog's description, typically the cleaned docstring.""" try: return self.__cog_cleaned_doc__ except AttributeError: self.__cog_cleaned_doc__ = cleaned = inspect.getdoc(self) return cleaned
0.010033
def porttree_matches(name): ''' Returns a list containing the matches for a given package name from the portage tree. Note that the specific version of the package will not be provided for packages that have several versions in the portage tree, but rather the name of the package (i.e. "dev-python/p...
0.001869
async def check_record(self, record, timeout=60): """Measures the time for a DNS record to become available. Query a provided DNS server multiple times until the reply matches the information in the record or until timeout is reached. Args: record (dict): DNS record as a di...
0.001324
def set_note_attribute(data): """ add the link of the 'source' in the note """ na = False if data.get('link'): na = Types.NoteAttributes() # add the url na.sourceURL = data.get('link') # add the object to the note return ...
0.006211
def json_call(cls, method, url, **kwargs): """ Call a remote api using json format """ # retrieve api key if needed empty_key = kwargs.pop('empty_key', False) send_key = kwargs.pop('send_key', True) return_header = kwargs.pop('return_header', False) try: apike...
0.001499
def turbulent_Petukhov_Kirillov_Popov(Re=None, Pr=None, fd=None): r'''Calculates internal convection Nusselt number for turbulent flows in pipe according to [2]_ and [3]_ as in [1]_. .. math:: Nu = \frac{(f/8)RePr}{C+12.7(f/8)^{1/2}(Pr^{2/3}-1)}\\ C = 1.07 + 900/Re - [0.63/(1+10Pr)] Pa...
0.000695
def export(context, keywords, module, update): """Operate on libraries and exported functions. Query the module name containing the function by default. Windows database must be prepared before using this. """ logging.info(_('Export Mode')) database = context.obj['sense'] none = True i...
0.000713
def _handle_register_response(self, response): """Called when a register response (RegisterInstanceResponse) arrives""" if response.status.status != common_pb2.StatusCode.Value("OK"): raise RuntimeError("Stream Manager returned a not OK response for register") Log.info("We registered ourselves to the ...
0.010204
def ste(command, nindent, mdir, fpointer, env=None): """ Print STDOUT of a shell command formatted in reStructuredText. This is a simplified version of :py:func:`pmisc.term_echo`. :param command: Shell command (relative to **mdir** if **env** is not given) :type command: string :param ninden...
0.001108
def knot_removal_kv(knotvector, span, r): """ Computes the knot vector of the rational/non-rational spline after knot removal. Part of Algorithm A5.8 of The NURBS Book by Piegl & Tiller, 2nd Edition. :param knotvector: knot vector :type knotvector: list, tuple :param span: knot span :type span...
0.002433
def luminosity_within_ellipse_in_units(self, major_axis : dim.Length, unit_luminosity='eps', kpc_per_arcsec=None, exposure_time=None): """Compute the total luminosity of the galaxy's light profiles, within an ellipse of specified major axis. This is performed via integration of each light profile and i...
0.00873
def execute_async(self, output_options=None, sampling=None, context=None, query_params=None): """ Initiate the query and return a QueryJob. Args: output_options: a QueryOutput object describing how to execute the query sampling: sampling function to use. No sampling is done if None. See bigquery.Sa...
0.007816
def fix_multi_T1w_source_name(in_files): """ Make up a generic source name when there are multiple T1s >>> fix_multi_T1w_source_name([ ... '/path/to/sub-045_ses-test_T1w.nii.gz', ... '/path/to/sub-045_ses-retest_T1w.nii.gz']) '/path/to/sub-045_T1w.nii.gz' """ import os from...
0.001792
def log_shapes(logger): """ Decorator to log the shapes of input and output dataframes It considers all the dataframes passed either as arguments or keyword arguments as inputs and all the dataframes returned as outputs. """ def decorator(func): @wraps(func) def wrapper(*args, *...
0.003175
def get_rollup_ttl(self, use_cached=True): """Retrieve the rollupTtl for this stream The rollupTtl is the time to live (TTL) in seconds for the aggregate roll-ups of data points stored in the stream. A roll-up expires after the configured amount of time and is automatically deleted. ...
0.009677
def convert_characteristicFaultSource(self, node): """ Convert the given node into a characteristic fault object. :param node: a node with tag areaGeometry :returns: a :class:`openquake.hazardlib.source.CharacteristicFaultSource` instance """ ...
0.002825
def WriteEventBody(self, event): """Writes the body of an event to the output. Args: event (EventObject): event. """ # sqlite seems to support milli seconds precision but that seems # not to be used by 4n6time row = self._GetSanitizedEventValues(event) self._cursor.execute(self._INSE...
0.005208
def _get_query_argument(args, cell, env): """ Get a query argument to a cell magic. The query is specified with args['query']. We look that up and if it is a BQ query object, just return it. If it is a string, build a query object out of it and return that Args: args: the dictionary of magic arguments. ...
0.010967
def _impopts(self, opts): """ :param opts: a dictionary containing any of the following Proc Import options(datarow, delimiter, getnames, guessingrows): - datarow is a number - delimiter is a character - getnames is a boolean - guessingrows is...
0.002468
def __merge_json_values(current, previous): """Merges the values between the current and previous run of the script.""" for value in current: name = value['name'] # Find the previous value previous_value = __find_and_remove_value(previous, value) if previous_value is not None: ...
0.001147
def getMetricsColumnLengths(self): """ Gets the maximum length of each column """ displayLen = 0 descLen = 0 for m in self.metrics: displayLen = max(displayLen, len(m['displayName'])) descLen = max(descLen, len(m['description'])) return (di...
0.005917
def get(self, bucket: str, key: str) -> bytes: """ Retrieves the data for a given object in a given bucket. :param bucket: the bucket the object resides in. :param key: the key of the object for which metadata is being retrieved. :return: the data """ buck...
0.003534
def enterprise_login_required(view): """ View decorator for allowing authenticated user with valid enterprise UUID. This decorator requires enterprise identifier as a parameter `enterprise_uuid`. This decorator will throw 404 if no kwarg `enterprise_uuid` is provided to the decorated view . ...
0.000429
def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return ErrorCode(key) if key not in ErrorCode._member_map_: extend_enum(ErrorCode, key, default) return ErrorCode[key]
0.007463
def fit(self, X, y=None): """Compute the Deterministic Shared Response Model Parameters ---------- X : list of 2D arrays, element i has shape=[voxels_i, samples] Each element in the list contains the fMRI data of one subject. y : not used """ logger....
0.001592
def get_neighbor_out_filter(neigh_ip_address): """Returns a neighbor out_filter for given ip address if exists.""" core = CORE_MANAGER.get_core_service() ret = core.peer_manager.get_by_addr(neigh_ip_address).out_filters return ret
0.004065
def worker(): """ Initialize the distributed environment. """ import torch import torch.distributed as dist from torch.multiprocessing import Process import numpy as np print("Initializing distributed pytorch") os.environ['MASTER_ADDR'] = str(args.master_addr) os.environ['MASTER_PORT'] = str(args.mast...
0.017787
def _get_local_image_id(docker_binary, docker_tag): """ Get the image id of the local docker layer with the passed tag :param docker_tag: docker tag :return: Image id as string or None if tag does not exist """ cmd = [docker_binary, "images", "-q", docker_tag] image_id_b = check_output(cmd) ...
0.003914
def __make_thumbnail(self, width, height): """ Create the page's thumbnail """ (w, h) = self.size factor = max( (float(w) / width), (float(h) / height) ) w /= factor h /= factor return self.get_image((round(w), round(h)))
0.006309
def viz_live_trace(view): """ Given a Manticore trace file, highlight the basic blocks. """ tv = TraceVisualizer(view, None, live=True) if tv.workspace is None: tv.workspace = get_workspace() # update due to singleton in case we are called after a clear tv.live_update = True tv.v...
0.00303
def iter_items(cls, repo, common_path=None): """Find all refs in the repository :param repo: is the Repo :param common_path: Optional keyword argument to the path which is to be shared by all returned Ref objects. Defaults to class specific portion if None a...
0.006075
def __check_mem(self): ''' raise exception on RAM exceeded ''' mem_free = psutil.virtual_memory().available / 2**20 self.log.debug("Memory free: %s/%s", mem_free, self.mem_limit) if mem_free < self.mem_limit: raise RuntimeError( "Not enough resources: free mem...
0.005076
def filter(self, source_file, encoding): # noqa A001 """Parse XML file.""" sources = [] if encoding: with codecs.open(source_file, 'r', encoding=encoding) as f: src = f.read() sources.extend(self._filter(src, source_file, encoding)) else: ...
0.004167
def _eval(self, m: EvalParam) -> object: """ Evaluate m returning the method / function invocation or value. Kind of like a static method :param m: object to evaluate :return: return """ if inspect.ismethod(m) or inspect.isroutine(m): return m() elif ...
0.006726
def set_banner(self, banner_type, value=None, default=False, disable=False): """Configures system banners Args: banner_type(str): banner to be changed (likely login or motd) value(str): value to set for the banner default (bool): Controls the use o...
0.003
def search_ip(self, searchterm): """Search for ips :type searchterm: str :rtype: list """ return self.__search(type_attribute=self.__mispiptypes(), value=searchterm)
0.018692
def download_file_insecure(url, target): """Use Python to download the file, without connection authentication.""" src = urlopen(url) try: # Read all the data in one block. data = src.read() finally: src.close() # Write all the data in one block to avoid creating a partial f...
0.002604
def metadata(sceneid, pmin=2, pmax=98, **kwargs): """ Return band bounds and statistics. Attributes ---------- sceneid : str CBERS sceneid. pmin : int, optional, (default: 2) Histogram minimum cut. pmax : int, optional, (default: 98) Histogram maximum cut. kwargs...
0.002793
def send_ready(self): """ Returns true if data can be written to this channel without blocking. This means the channel is either closed (so any write attempt would return immediately) or there is at least one byte of space in the outbound buffer. If there is at least one byte of ...
0.002532
def param_help(self, args): '''show help on a parameter''' if len(args) == 0: print("Usage: param help PARAMETER_NAME") return htree = self.param_help_tree() if htree is None: return for h in args: h = h.upper() if h i...
0.001368
async def create_authenticator_async(self, connection, debug=False, loop=None, **kwargs): """Create the async AMQP session and the CBS channel with which to negotiate the token. :param connection: The underlying AMQP connection on which to create the session. :type connection: ...
0.001839
def GetHostMemMappedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemMappedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
0.014388
def hourly_dew_point_values(self, dry_bulb_condition): """Get a list of dew points (C) at each hour over the design day. args: dry_bulb_condition: The dry bulb condition for the day. """ hourly_dew_point = [] max_dpt = self.dew_point(dry_bulb_condition.dry_bulb_max) ...
0.003676
def Parse(self): """Iterator returning a list for each entry in history. We store all the download events in an array (choosing this over visits since there are likely to be less of them). We later interleave them with visit events to get an overall correct time order. Yields: a list of attr...
0.00565
def maybe_2to3(filename, modname=None): """Returns a python3 version of filename.""" need_2to3 = False filename = os.path.abspath(filename) if any(filename.startswith(d) for d in DIRS): need_2to3 = True elif modname is not None and any(modname.startswith(p) for p in PACKAGES): need_2...
0.00199
def dictionary(self, value): """Set dictionary""" self._dictionary = value or {} if not isinstance(self._dictionary, dict): raise BadArgumentError("dictionary must be dict: {}".format( self._dictionary))
0.007843
def _get_running_workers_names(running_workers: list): """May contain sensitive info (like user ids). Use with care.""" return FormattedText().join( [ FormattedText().newline().normal(" - {name}").start_format().bold(name=worker.name).end_format() for worker i...
0.00831
def get_topic(self): """ Returns the topic to consider. """ if not hasattr(self, 'topic'): self.topic = get_object_or_404( Topic.objects.select_related('forum').all(), pk=self.kwargs['pk'], ) return self.topic
0.010989
def remove_successor(self, successor): """! @brief Remove successor from the node. @param[in] successor (cfnode): Successor for removing. """ self.feature -= successor.feature; self.successors.append(successor); succe...
0.026549
def _add_goterms_kws(self, go2obj_user, kws_gos): """Add more GOTerms to go2obj_user, if requested and relevant.""" if 'go2color' in kws_gos: for goid in kws_gos['go2color'].keys(): self._add_goterms(go2obj_user, goid)
0.007634
def find_longest_match(self, alo, ahi, blo, bhi): """Find longest matching block in a[alo:ahi] and b[blo:bhi]. Wrapper for the C implementation of this function. """ besti, bestj, bestsize = _cdifflib.find_longest_match(self, alo, ahi, blo, bhi) return _Match(besti, bestj, bests...
0.009259
def _computeArray(self, funcTilde, R, z, phi): """ NAME: _computeArray PURPOSE: evaluate the density or potential for a given array of coordinates INPUT: funcTidle - must be _rhoTilde or _phiTilde R - Cylindrical Galactocentric radius ...
0.020677
def get_instance(self, payload): """ Build an instance of SampleInstance :param dict payload: Payload response from the API :returns: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance :rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance """ ...
0.003876
def process_view(self, request, view_func, view_args, view_kwargs): """ Forwards unauthenticated requests to the admin page to the CAS login URL, as well as calls to django.contrib.auth.views.login and logout. """ if view_func == login: return cas_login(reque...
0.001509
def csv2yaml(in_file, out_file=None): """Convert a CSV SampleSheet to YAML run_info format. """ if out_file is None: out_file = "%s.yaml" % os.path.splitext(in_file)[0] barcode_ids = _generate_barcode_ids(_read_input_csv(in_file)) lanes = _organize_lanes(_read_input_csv(in_file), barcode_ids...
0.002179
def create_token(secret, data, options=None): """ Generates a secure authentication token. Our token format follows the JSON Web Token (JWT) standard: header.claims.signature Where: 1) "header" is a stringified, base64-encoded JSON object containing version and algorithm information. 2)...
0.007765
def update(self, dct): """Update the configuration with new parameters. Must use same kwargs as __init__""" d = self.__dict__.copy() d.update(dct) self.set_attrs(**d)
0.009709
def rating(request): """ Handle a ``RatingForm`` submission and redirect back to its related object. """ response = initial_validation(request, "rating") if isinstance(response, HttpResponse): return response obj, post_data = response url = add_cache_bypass(obj.get_absolute_url()...
0.000846
def _mappingGetValueSet(mapping, keys): """Return a combined set of values from the mapping. :param mapping: dict, for each key contains a set of entries returns a set of combined entries """ setUnion = set() for k in keys: setUnion = setUnion.union(mapping[k]) return setUnion
0.003175
def is_connectable(host: str, port: Union[int, str]) -> bool: """Tries to connect to the device to see if it is connectable. Args: host: The host to connect. port: The port to connect. Returns: True or False. """ socket_ = None try: socket_ = socket.create_conne...
0.002028
def create_snapshot(config='root', snapshot_type='single', pre_number=None, description=None, cleanup_algorithm='number', userdata=None, **kwargs): ''' Creates an snapshot config Configuration name. snapshot_type Specifies the type of the new snap...
0.001176
def issuer_type(self, issuer_type): """ Sets the issuer_type of this CertificateIssuerInfo. The type of the certificate issuer. - GLOBAL_SIGN: Certificates are issued by GlobalSign service. The users must provide their own GlobalSign account credentials. - CFSSL_AUTH: Certificates are issued...
0.005176
def _fix_up_fields(cls): """Add names to all of the Resource fields. This method will get called on class declaration because of Resource's metaclass. The functionality is based on Google's NDB implementation. `Endpoint` does something similar for `arguments`. """ ...
0.004583
def set_reason(self, reason): """ Set the reason of this revocation. If :data:`reason` is ``None``, delete the reason instead. :param reason: The reason string. :type reason: :class:`bytes` or :class:`NoneType` :return: ``None`` .. seealso:: :meth...
0.001535
def to_kraus(self): """ Compute the Kraus operator representation of the estimated process. :return: The process as a list of Kraus operators. :rytpe: List[np.array] """ return [k.data.toarray() for k in qt.to_kraus(self.sop)]
0.007273
def create_graph_from_data(self, data): """Run the algorithm on data. Args: data (pandas.DataFrame): DataFrame containing the data Returns: networkx.DiGraph: Solution given by the algorithm. """ # Building setup w/ arguments. self.arguments['{SC...
0.002786
def verify(self, anchors): """ Return True if the CRL is signed by one of the provided anchors. False on error (invalid signature, missing anchorand, ...) """ cafile = create_temporary_ca_file(anchors) if cafile is None: return False try: c...
0.005291
def update_id(self, sequence_id=None, force=True): """Alter the sequence id, and all of the names and ids derived from it. This often needs to be don after an IntegrityError in a multiprocessing run""" from ..identity import ObjectNumber if sequence_id: self.sequence_id = se...
0.005435
def write_file(filename, text): """Write text to a file.""" logging.debug(_('Writing file: %s'), filename) try: with open(filename, 'w') as writable: writable.write(text) except (PermissionError, NotADirectoryError): logging.error(_('Error writing file: %s'), filename) ...
0.002857
def from_dict(cls, d, identifier_str=None): """Load a `ResolvedContext` from a dict. Args: d (dict): Dict containing context data. identifier_str (str): String identifying the context, this is only used to display in an error string if a serialization version ...
0.001263