text
stringlengths
78
104k
score
float64
0
0.18
def meas_gate(self, circuit, qreg, op): """ Add measurement gates to a circuit. Args: circuit (QuantumCircuit): circuit to add measurement to. qreg (tuple(QuantumRegister,int)): quantum register being measured. op (str): the basis label for the measurement. ...
0.004545
def color_generator(seed=None): """ Generates random colors for control and evaluated curve/surface points plots. The ``seed`` argument is used to set the random seed by directly passing the value to ``random.seed()`` function. Please see the Python documentation for more details on the ``random`` module ....
0.006849
def clear(self): """ Reset the config object to its initial state """ with self._lock: self._config = { CacheConfig.Morlist: {'last': defaultdict(float), 'intl': {}}, CacheConfig.Metadata: {'last': defaultdict(float), 'intl': {}}, }
0.00625
def convert_decimal(value, parameter): ''' Converts to decimal.Decimal: '', '-', None convert to parameter default Anything else uses Decimal constructor ''' value = _check_default(value, parameter, ( '', '-', None )) if value is None or isinstance(value, decimal.Decimal): re...
0.006865
def _waiting_expect(self): '''``True`` when the client is waiting for 100 Continue. ''' if self._expect_sent is None: if self.environ.get('HTTP_EXPECT', '').lower() == '100-continue': return True self._expect_sent = '' return False
0.006601
def validation_error_message(cls, spec, backends=None): """ Returns an options validation error message if there are any invalid keywords. Otherwise returns None. """ try: cls.validate_spec(spec, backends=backends) except OptionError as e: return e...
0.005831
def action_aggregate(reader, *args): """Aggregate flow records by 5-tuple and print a tab-separated stream""" all_aggregated = aggregated_records(reader) first_row = next(all_aggregated) keys = sorted(first_row.keys()) print(*keys, sep='\t') # Join the first row with the rest of the rows and pr...
0.002203
def login(self, password='', captcha='', email_code='', twofactor_code='', language='english'): """Attempts web login and returns on a session with cookies set :param password: password, if it wasn't provided on instance init :type password: :class:`str` :param captcha: text reponse fo...
0.003427
def set_default_decoder_parameters(dparams_p): """Wrapper for opj_set_default_decoder_parameters. """ argtypes = [ctypes.POINTER(DecompressionParametersType)] OPENJPEG.opj_set_default_decoder_parameters.argtypes = argtypes OPENJPEG.opj_set_default_decoder_parameters(dparams_p)
0.003367
def clean(s, lowercase=True, replace_by_none=r'[^ \-\_A-Za-z0-9]+', replace_by_whitespace=r'[\-\_]', strip_accents=None, remove_brackets=True, encoding='utf-8', decode_error='strict'): """Clean string variables. Clean strings in the Series by removing unwanted tokens, whitespace and bra...
0.000257
def disambiguate_fname(files_path_list, filename): """Get tab title without ambiguation.""" fname = os.path.basename(filename) same_name_files = get_same_name_files(files_path_list, fname) if len(same_name_files) > 1: compare_path = shortest_path(same_name_files) if compare_path ==...
0.006547
def _deserialize_uint(data, nbytes=32, padding=0, offset=0): """ Read a `nbytes` bytes long big endian unsigned integer from `data` starting at `offset` :param data: sliceable buffer; symbolic buffer of Eth ABI encoded data :param nbytes: number of bytes to read starting from least sign...
0.006814
def handle_shutdown_signal(self, *_): """ Handles the reception of a shutdown signal. """ if self.shutting_down: self.logger.warning('Received double interrupt, forcing shutdown') sys.exit(1) else: self.logger.warning('Received interrupt, initi...
0.005348
def loadPrsOrd(vecRunLngth, strPathPresOrd, vecVslStim): """Load presentation order of motion directions. Parameters ---------- vecRunLngth : list Number of volumes in every run strPathPresOrd : str Path to the npy vector containing order of presented motion directions. vecVslSt...
0.000675
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: SyncListItemContext for this SyncListItemInstance :rtype: twilio.rest.preview.sync.service.sync_l...
0.007289
def text2lm(text, output_file, vocab_file=None, text2idngram_kwargs={}, idngram2lm_kwargs={}): """ Convienience function to directly convert text (and vocabulary) into a language model. """ if vocab_file: used_vocab_file = vocab_file else: # Create temporary vocab file wi...
0.004425
def find_substring(substring, suffix_tree, edge_repo): """Returns the index if substring in tree, otherwise -1. """ assert isinstance(substring, str) assert isinstance(suffix_tree, SuffixTree) assert isinstance(edge_repo, EventSourcedRepository) if not substring: return -1 if suffix_...
0.002137
def get_zone(self, zone_name): """ Get the information about a particular zone """ for zone in self.get_zones(): if zone_name == zone['name']: return zone raise RuntimeError("Unknown zone")
0.007752
def pop(self, key): """Pops dict_grid with undo and redo support Parameters ---------- key: 3-tuple of Integer \tCell key that shall be popped """ try: self.result_cache.pop(repr(key)) except KeyError: pass return DataA...
0.0059
def _type_digest(self, config: bool) -> Dict[str, Any]: """Return receiver's type digest. Args: config: Specifies whether the type is on a configuration node. """ res = {"base": self.yang_type()} if self.name is not None: res["derived"] = self.name ...
0.006024
def merge_data(*data_frames, **kwargs): """ Merge DataFrames by column. Number of rows in tables must be the same. This method can be called both outside and as a DataFrame method. :param list[DataFrame] data_frames: DataFrames to be merged. :param bool auto_rename: if True, fields in source DataF...
0.002802
def reorder_categories(self, new_categories, ordered=None, inplace=False): """ Reorder categories as specified in new_categories. `new_categories` need to include all old categories and no new category items. Parameters ---------- new_categories : Index-like ...
0.00133
def is_active_trail(self, start, end, observed=None): """ Returns True if there is any active trail between start and end node Parameters ---------- start : Graph Node end : Graph Node observed : List of nodes (optional) If given the active trail would...
0.005029
def xmlobjectform_factory(model, form=XmlObjectForm, fields=None, exclude=None, widgets=None, max_num=None, label=None, can_delete=True, extra=None, can_order=False): """Dynamically generate a new :class:`XmlObjectForm` class using the specified :class:`eulxml...
0.001294
def set_ram(self, ram): """ Sets amount of RAM allocated to this router :param ram: amount of RAM in Mbytes (integer) """ if self._ram == ram: return yield from self._hypervisor.send('vm set_ram "{name}" {ram}'.format(name=self._name, ram=ram)) log....
0.009091
def _get_optimizer(self): """Uses Adagrad to optimize the GloVe/Mittens objective, as specified in the GloVe paper. """ optim = tf.train.AdagradOptimizer(self.learning_rate) gradients = optim.compute_gradients(self.cost) if self.log_dir: for name, (g, v) in zi...
0.003752
def joint(self, table, fields, join_table, join_fields, condition_field, condition_join_field, join_method='left_join'): """.. :py:method:: Usage:: >>> joint('user', 'name, id_number', 'medical_card', 'number', 'id', 'user_id', 'i...
0.014122
def nfw_angle2physical(self, Rs_angle, theta_Rs): """ converts the angular parameters into the physical ones for an NFW profile :param theta_Rs: observed bending angle at the scale radius in units of arcsec :param Rs: scale radius in units of arcsec :return: M200, r200, Rs_physi...
0.006369
def get_DIR(self, WD=None): """ open dialog box for choosing a working directory """ if "-WD" in sys.argv and FIRST_RUN: ind = sys.argv.index('-WD') self.WD = sys.argv[ind + 1] elif not WD: # if no arg was passed in for WD, make a dialog to choose one ...
0.003846
def plot_dist( values, values2=None, color="C0", kind="auto", cumulative=False, label=None, rotated=False, rug=False, bw=4.5, quantiles=None, contour=True, fill_last=True, textsize=None, plot_kwargs=None, fill_kwargs=None, rug_kwargs=None, contour_kwar...
0.003045
def env_int(name, required=False, default=empty): """Pulls an environment variable out of the environment and casts it to an integer. If the name is not present in the environment and no default is specified then a ``ValueError`` will be raised. Similarly, if the environment value is not castable to an ...
0.002681
def get_glance_url(url_base, tenant_id, user, password, region): """It get the glance url :param url_base: keystone url :param tenand_id: the id of the tenant :param user: the user :param paassword: the password """ get_url(url_base, tenant_id, user, password, 'image', region)
0.003279
def add_fs(self, name, fs, write=False, priority=0): # type: (Text, FS, bool, int) -> None """Add a filesystem to the MultiFS. Arguments: name (str): A unique name to refer to the filesystem being added. fs (FS or str): The filesystem (instance or URL) to...
0.002396
def _artifacts(self): """Retrieve the artifacts json object""" if '_artifacts' not in self._memo: json = _get_url(self._artifacts_url).json() self._memo['_artifacts'] = json['artifacts'] return self._memo['_artifacts']
0.007519
def _create_attrcontent_class(name, fields, inheritance=(object,), data_structure=None, extra_functions=None, docstring=""): '''Helper function that creates a class for attribute contents. This function creates is a boilerplate to create all the expected methods of an attributes. The basic methods work in ...
0.004995
def _get_technologies(): ''' Returns the technologies of connman ''' tech = '' technologies = pyconnman.ConnManager().get_technologies() for path, params in technologies: tech += '{0}\n\tName = {1}\n\tType = {2}\n\tPowered = {3}\n\tConnected = {4}\n'.format( path, params['Nam...
0.007389
def publish_command_failure(self, duration, failure, command_name, request_id, connection_id, op_id=None): """Publish a CommandFailedEvent to all command listeners. :Parameters: - `duration`: The command duration as a datetime.timedelta. - `failure`: ...
0.002907
def apply_repulsion(repulsion, nodes, barnes_hut_optimize=False, region=None, barnes_hut_theta=1.2): """ Iterate through the nodes or edges and apply the forces directly to the node objects. """ if not barnes_hut_optimize: for i in range(0, len(nodes)): for j in range(0, i): ...
0.006061
def get_orientation(width, height): # type: (int, int) -> Orientation """Get viewport orientation from given width and height. :type width: int :type height: int :return: viewport orientation enum :rtype: Orientation """ if width > height: return Orientation.LANDSCAPE elif w...
0.002421
def load_cache(self): """Load the cached Zotero data.""" with open(self.cache_path, "rb") as f: print("Loading cached Zotero data...") cache = pickle.load(f) self._references = cache[self.CACHE_REFERENCE_LIST] self.reference_types = cache[self.CACHE_REFERE...
0.004396
def Townsend_Hales(T, Tc, Vc, omega): r'''Calculates saturation liquid density, using the Townsend and Hales CSP method as modified from the original Riedel equation. Uses chemical critical volume and temperature, as well as acentric factor The density of a liquid is given by: .. math:: Vs...
0.000787
def maybe_start_recording(tokens, index): """Return a new _RSTCommentBlockRecorder when its time to record.""" if tokens[index].type == TokenType.BeginRSTComment: return _RSTCommentBlockRecorder(index, tokens[index].line) return None
0.007407
def modify_access(src, dst='any', port=None, proto=None, action='allow', index=None): """ Grant access to an address or subnet :param src: address (e.g. 192.168.1.234) or subnet (e.g. 192.168.1.0/24). :param dst: destiny of the connection, if the machine has multiple I...
0.000602
def parse(self, text, *, metadata=None, filename="input"): """ Parses a string. Appends a list of blurb ENTRIES to self, as tuples: (metadata, body) metadata is a dict. body is a string. """ metadata = metadata or {} body = [] in_metadata = True ...
0.001631
def run_module(uri, args, env_vars=None, name=DEFAULT_MODULE_NAME, cache=None, wait=True, capture_error=False): # type: (str, list, dict, str, bool, bool, bool) -> subprocess.Popen """Download, prepare and executes a compressed tar file from S3 or provided directory as a module. SageMaker Python SDK saves ...
0.006484
def delete(self): """Removes the entire ospf process from the running configuration Args: None Returns: bool: True if the command completed succssfully """ config = self.get() if not config: return True command = 'n...
0.004878
def by_id(cls, _id, engine_or_session): """ Get one object by primary_key value. """ ses, auto_close = ensure_session(engine_or_session) obj = ses.query(cls).get(_id) if auto_close: ses.close() return obj
0.007353
def parse_date(ims): """ Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch. """ try: ts = email.utils.parsedate_tz(ims) return time.mktime(ts[:8] + (0,)) - (ts[9] or 0) - time.timezone except (TypeError, ValueError, IndexError): return None
0.003425
def catch_errors(f): """ Catches specific errors in admin actions and shows a friendly error. """ @functools.wraps(f) def wrapper(self, request, *args, **kwargs): try: return f(self, request, *args, **kwargs) except exceptions.CertificateExpired: self.message...
0.000842
def notebook_authenticate(cmd_args, force=False, silent=True): """ Similiar to authenticate but prints student emails after all calls and uses a different way to get codes. If SILENT is True, it will suppress the error message and redirect to FORCE=True """ server = server_url(cmd_args) network....
0.000756
def filter(self, resource_manager, **params): """Query a set of resources.""" m = self.resolve(resource_manager.resource_type) client = local_session(self.session_factory).client(m.service) enum_op, path, extra_args = m.enum_spec if extra_args: params.update(extra_ar...
0.002005
def list(self, count=10): """List models under the current project in a table view. Args: count: upper limit of the number of models to list. Raises: Exception if it is called in a non-IPython environment. """ import IPython data = [] # Add range(count) to loop so it will stop e...
0.007177
def _exec_cmd(command): """Call a CMD command and return the output and returncode""" proc = sp.Popen(command, stdout=sp.PIPE, shell=True) if six.PY2: res = proc.communicate()[0] else: res = proc.communicate(timeout=5)[0] return res, proc.retur...
0.003077
def GetValue( self, Channel, Parameter): """ Retrieves a PCAN Channel value Remarks: Parameters can be present or not according with the kind of Hardware (PCAN Channel) being used. If a parameter is not available, a PCAN_ERROR_ILLPARAMTYP...
0.007391
def _get_cand_values(candidate, key_table): """Get the corresponding values for the key_table.""" # NOTE: Import just before checking to avoid circular imports. from fonduer.features.models import FeatureKey from fonduer.supervision.models import GoldLabelKey, LabelKey if key_table == FeatureKey: ...
0.001767
def fetch_token(self, client_secret, code, context, scope, redirect_uri, token_url='https://login.bigcommerce.com/oauth2/token'): """ Fetches a token from given token_url, using given parameters, and sets up session headers for future requests. redirect_uri should be ...
0.005983
def _calculate_H(self, T): """ Calculate the enthalpy of the package at the specified temperature. :param T: Temperature. [°C] :returns: Enthalpy. [kWh] """ if self.isCoal: return self._calculate_Hfr_coal(T) H = 0.0 for compound in self.mat...
0.003937
def set_perspective(self, fov, aspect, near, far): """Set the perspective Parameters ---------- fov : float Field of view. aspect : float Aspect ratio. near : float Near location. far : float Far location. "...
0.005115
def _try_parse_reaction(self, reaction_id, s, parser=parse_reaction, **kwargs): """Try to parse the given reaction equation string. Returns the parsed Reaction object, or raises an error if the reaction could not be parsed. """ try: return...
0.004847
def DEFINE_list(self, name, default, help, constant=False): """A helper for defining lists of strings options.""" self.AddOption( type_info.List( name=name, default=default, description=help, validator=type_info.String()), constant=constant)
0.003195
def run(namespace=None, action_prefix='action_', args=None): """Run the script. Participating actions are looked up in the caller's namespace if no namespace is given, otherwise in the dict provided. Only items that start with action_prefix are processed as actions. If you want to use all items in the...
0.000332
def conversion_handler(self, name): u""" Возвращает обработчик конвертации с указанным именем :param name: Имя обработчика :return: callable """ try: handler = self.conversion_table[name] except KeyError: raise KeyError(( u...
0.004348
def score(check=None): """Compute the linter's score on the corpus. Proselint's score reflects the desire to have a linter that catches many errors, but which takes false alarms seriously. It is better not to say something than to say the wrong thing, and the harm from saying the wrong thing is gre...
0.000417
def get_admin_urls_for_registration(self): """ Utilised by Wagtail's 'register_admin_urls' hook to register urls for our the views that class offers. """ urls = ( url(get_url_pattern(self.opts), self.index_view, name=get_url_name(self.opts)), ...
0.001005
def _create_training_directories(): """Creates the directory structure and files necessary for training under the base path """ logger.info('Creating a new training folder under %s .' % base_dir) os.makedirs(model_dir) os.makedirs(input_config_dir) os.makedirs(output_data_dir) _write_json(...
0.003407
def _update_context(context, postdata): ''' Updates the default selections with user's selections. ''' listCheck = lambda el: el[0] if type(el) == list else el # For handling lists of size 1 widget_id = listCheck(postdata.get('widget_id')) context.target_table = listCheck(postdata.get('target_t...
0.006443
def _do_update_callback(self, msg): """Call registered callback functions.""" for callback, device in self._update_callbacks: if device == msg: _LOGGER.debug('Update callback %s for device %s by %s', callback, device, msg) self._e...
0.00565
def read(path): """ Reads a file located at the given path. """ data = None with open(path, 'r') as f: data = f.read() f.close() return data
0.005952
async def delete(self, *, reason=None): """|coro| Deletes the channel. You must have :attr:`~.Permissions.manage_channels` permission to use this. Parameters ----------- reason: Optional[:class:`str`] The reason for deleting this channel. Shows ...
0.004386
def rate_of_change(data, period): """ Rate of Change. Formula: (Close - Close n periods ago) / (Close n periods ago) * 100 """ catch_errors.check_for_period_error(data, period) rocs = [((data[idx] - data[idx - (period - 1)]) / data[idx - (period - 1)]) * 100 for idx in range(perio...
0.007407
def preformat_plain_description(testcase): """Creates a preformatted HTML version of the description.""" description = testcase.get("description") if not description: return # naive approach to removing indent from pytest docstrings nodeid = testcase.get("nodeid") or "" indent = None ...
0.00128
def node(name, **kwargs): ''' Return the details of the node identified by the specified name CLI Examples:: salt '*' kubernetes.node name='minikube' ''' cfg = _setup_conn(**kwargs) try: api_instance = kubernetes.client.CoreV1Api() api_response = api_instance.list_node(...
0.001312
def with_sample_weight(clf, sample_weight, fit_params): """ Return fit_params with added "sample_weight" argument. Unlike `fit_params['sample_weight'] = sample_weight` it handles a case where ``clf`` is a pipeline. """ param_name = _get_classifier_prefix(clf) + "sample_weight" params = {para...
0.002564
def Open(self): """Opens the USB device for this setting, and claims the interface.""" # Make sure we close any previous handle open to this usb device. port_path = tuple(self.port_path) with self._HANDLE_CACHE_LOCK: old_handle = self._HANDLE_CACHE.get(port_path) ...
0.001775
def BiLSTM(nO, nI): """Create a bidirectional LSTM layer. Args: number out, number in""" return Bidirectional(LSTM(nO // 2, nI), LSTM(nO // 2, nI))
0.006452
def skus(self): """Instance depends on the API version: * 2017-06-01: :class:`SkusOperations<azure.mgmt.storage.v2017_06_01.operations.SkusOperations>` * 2017-10-01: :class:`SkusOperations<azure.mgmt.storage.v2017_10_01.operations.SkusOperations>` * 2018-02-01: :class:`SkusOper...
0.008969
def dict_to_querystring(dictionary): """Converts a dict to a querystring suitable to be appended to a URL.""" s = u"" for d in dictionary.keys(): s = unicode.format(u"{0}{1}={2}&", s, d, dictionary[d]) return s[:-1]
0.004184
def unschedule_events(self, events, lambda_arn=None, lambda_name=None, excluded_source_services=None): excluded_source_services = excluded_source_services or [] """ Given a list of events, unschedule these CloudWatch Events. 'events' is a list of dictionaries, where the dict must contai...
0.005679
def log_status (self): """Log a status message.""" duration = time.time() - self.start_time checked, in_progress, queue = self.aggregator.urlqueue.status() num_urls = len(self.aggregator.result_cache) self.logger.log_status(checked, in_progress, queue, duration, num_urls)
0.009615
def api_user_techgroup_list(request, userPk, key, hproPk): """Return the list of techgroup of a user""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden # From UUID to Pk from users.models import TechUser user = get_object_or_404(TechUser, pk=userPk) retour = ...
0.002183
async def cities(self, country: str, state: str) -> list: """Return a list of supported cities in a country/state.""" data = await self._request( 'get', 'cities', params={ 'state': state, 'country': country }) return [d['city'] for d in dat...
0.006061
def imsize(fname): """ return image size (height, width) :param fname: :return: """ from PIL import Image im = Image.open(fname) return im.size[1], im.size[0]
0.005263
def get_value(self, label): """ Get value from a single fully-qualified name """ for (key, value) in self.items: if key == label: return value
0.018182
def verify_fun(lazy_obj, fun): ''' Check that the function passed really exists ''' if not fun: raise salt.exceptions.SaltInvocationError( 'Must specify a function to run!\n' 'ex: manage.up' ) if fun not in lazy_obj: # If the requested function isn't a...
0.004673
def oncvpsp_header(filename, ppdesc): """ Parse the ONCVPSP abinit header. Example: Li ONCVPSP r_core= 2.01 3.02 3.0000 3.0000 140504 zatom,zion,pspd 8 2 1 4 600 0 pspcod,pspxc,lmax,lloc,mmax,r2well 5.99000000 0.00000...
0.00277
def tls_session_update(self, msg_str): """ Either for parsing or building, we store the client_random along with the raw string representing this handshake message. """ super(TLSClientHello, self).tls_session_update(msg_str) self.tls_session.advertised_tls_version = self...
0.002169
def get_map_values(self, lons, lats, ibin=None): """Return the indices in the flat array corresponding to a set of coordinates Parameters ---------- lons : array-like 'Longitudes' (RA or GLON) lats : array-like 'Latitidues' (DEC or GLAT) ibin : ...
0.004343
def addStencilBranch(self, disp, weight): """ Set or overwrite the stencil weight for the given direction @param disp displacement vector @param weight stencil weight """ self.stencil[tuple(disp)] = weight self.__setPartionLogic(disp)
0.006897
def _query_sample(sample, operators='__eq__'): """Create a TinyDB query that looks for items that have each field in `sample` with a value compared with the correspondent operation in `operators`. Parameters ---------- sample: dict The sample data operators: str or list of str ...
0.004354
def get_property(self, property_name): """ Get a property's value. property_name -- the property to get the value of Returns the properties value, if found, else None. """ prop = self.find_property(property_name) if prop: return prop.get_value() ...
0.005952
def use_trump_data(self, symbols): """ Use trump data to build conversion table symbols : list of symbols: will attempt to use units to build the conversion table, strings represent symbol names. """ dfs = {sym.units : sym.df[...
0.014778
def get_free_mb(folder): """ Return folder/drive free space (in bytes) """ if platform.system() == 'Windows': free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(folder), None, None, ctypes.pointer(free_bytes)) return free_bytes.value/1024/1...
0.004808
def child_begin_handler(self,scache,*args): ''' _creat_child_desc update depth,parent_breadth_path,parent_path,sib_seq,path,lsib_path,rsib_path,lcin_path,rcin_path ''' pdesc = self.pdesc depth = scache.depth sib_seq = self.sib_seq sibs_len = self.s...
0.009424
def bgp_summary_parser(bgp_summary): """Parse 'show bgp all summary vrf' output information from NX-OS devices.""" bgp_summary_dict = {} # Check for BGP summary information lines that have no data if len(bgp_summary.strip().splitlines()) <= 1: return {} allowed_afi = ["ipv4", "ipv6", "l2vp...
0.002149
def iter_processes(self, proc_filter=None): """Yields processes from psutil.process_iter with an optional filter and swallows psutil errors. If a psutil exception is raised during execution of the filter, that process will not be yielded but subsequent processes will. On the other hand, if psutil.process_i...
0.009331
def format_repeated_pair_list(self, key, root_list, level): """ Process (possibly) repeated lists of pairs e.g. POINTs blocks """ lines = [] def depth(L): return isinstance(L, (tuple, list)) and max(map(depth, L)) + 1 if depth(root_list) == 2: #...
0.003945
def should_add_ClientCertificate(self): """ If the server sent a CertificateRequest, we send a Certificate message. If no certificate is available, an empty Certificate message is sent: - this is a SHOULD in RFC 4346 (Section 7.4.6) - this is a MUST in RFC 5246 (Section 7.4.6) ...
0.002869
def colorsat(l,m): """ Returns color for given l,m Designed to look like a color wheel that is more saturated in middle. """ lm = np.zeros(len(l), dtype='complex') lm.real = l lm.imag = m red = 0.5*(1+np.cos(np.angle(lm))) green = 0.5*(1+np.cos(np.angle(lm) + 2*3.14/3)) blue = 0.5*(...
0.007561
def make_ar_transition_matrix(coefficients): """Build transition matrix for an autoregressive StateSpaceModel. When applied to a vector of previous values, this matrix computes the expected new value (summing the previous states according to the autoregressive coefficients) in the top dimension of the state sp...
0.005961
def parse_config(init_func): """Decorator wrapping the environment to use a config file""" @functools.wraps(init_func) def new_func(env, *args, **kwargs): config_interpreter = ConfigInterpreter(kwargs) # Pass the config data to the kwargs new_kwargs = config_interpreter.interpret() ...
0.002016