Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
347,900
def bind_protocol(self, proto): LOG.debug(, proto, self) if not isinstance(proto, BgpProtocol): raise ValueError( ) if proto.state != const.BGP_FSM_OPEN_CONFIRM: raise ValueError( ) ...
Tries to bind given protocol to this peer. Should only be called by `proto` trying to bind. Once bound this protocol instance will be used to communicate with peer. If another protocol is already bound, connection collision resolution takes place.
347,901
def _packto(self, stream): total_size = 0 current = self while current is not None: total_size += current._parser.packto(current, stream) last = current current = getattr(current, , None) if hasattr(last, ): _extra = last....
Pack current struct into stream. For parser internal use. :param stream: a buffered stream (File or BytesIO) :return: packed bytes length
347,902
def get_csv(filename): check_if_this_file_exist(filename) filename = os.path.abspath(filename) s = command_line([, , , , filename]) if s: s = s.decode() return s else: return 0
Return a csv representation of the exif get a filename and returns a unicode string with a CSV format Arguments: filename {string} -- your filename Returns: [unicode] -- unicode string
347,903
def remove_subproducts(self): if not self.fullpath or not self.archived: raise RuntimeError() for root, dirs, files in os.walk(self.subproduct_dir(), topdown=False): for name in files: try: os.remove(os.path.join(root, name)) ...
Removes all archived files subproducts associated with this DP
347,904
def stat(self, entry_path, dir_fd=None, follow_symlinks=None): if follow_symlinks is None: follow_symlinks = True elif sys.version_info < (3, 3): raise TypeError( "stat() got an unexpected keyword argument ") entry_path = self._path_with_dir_fd(en...
Return the os.stat-like tuple for the FakeFile object of entry_path. Args: entry_path: path to filesystem object to retrieve. dir_fd: (int) If not `None`, the file descriptor of a directory, with `entry_path` being relative to this directory. New in Pyth...
347,905
def generate(graph, feasible_configurations, decision_variables, linear_energy_ranges, quadratic_energy_ranges, min_classical_gap, smt_solver_name=None): if len(graph) == 0: return dimod.BinaryQuadraticModel.empty(dimod.SPIN), float() table = Table(graph, decision_va...
Generates the Ising model that induces the given feasible configurations. The code is based on the papers [#do]_ and [#mc]_. Args: graph (nx.Graph): The target graph on which the Ising model is to be built. feasible_configurations (dict): The set of feasible configurations of the de...
347,906
def get_print_list(): profiler = start_profile() meth1() meth2() meth3() meth4() return end_profile(profiler, returnvalue=True)
get_print_list
347,907
def get_ratings(self): return Vote.objects.filter(content_type=self.get_content_type(), object_id=self.instance.pk, key=self.field.key)
get_ratings() Returns a Vote QuerySet for this rating field.
347,908
def get_load_balancer(load_balancer, flags=FLAGS.ALL ^ FLAGS.POLICY_TYPES, **conn): try: basestring except NameError as _: basestring = str if isinstance(load_balancer, basestring): load_balancer = dict(LoadBalancerName=load_balancer) return registry.build_out(flags, ...
Fully describes an ELB. :param loadbalancer: Could be an ELB Name or a dictionary. Likely the return value from a previous call to describe_load_balancers. At a minimum, must contain a key titled 'LoadBalancerName'. :param flags: Flags describing which sections should be included in the return value. Default i...
347,909
def isostr_to_datetime(dt_str): if len(dt_str) <= 20: return datetime.datetime.strptime(dt_str, "%Y-%m-%dT%H:%M:%SZ") else: dt_str = dt_str.split(".") return isostr_to_datetime("%sZ" % dt_str[0])
Converts iso formated text string into a datetime object Args: dt_str (str): ISO formated text string Returns: :obj:`datetime.datetime`
347,910
def sample(self, rstate=None, return_q=False): if rstate is None: rstate = np.random if self.nells == 1: x = self.ells[0].sample(rstate=rstate) idx = 0 q = 1 if return_q: return x, idx, q else: ...
Sample a point uniformly distributed within the *union* of ellipsoids. Returns ------- x : `~numpy.ndarray` with shape (ndim,) A coordinate within the set of ellipsoids. idx : int The index of the ellipsoid `x` was sampled from. q : int, optional ...
347,911
def logout_user(f): @functools.wraps(f) def deco(*a, **kw): signals.user_logout(lambda: flask_login.current_user) flask_login.logout_user() return f(*a, **kw) return deco
Decorator to logout user :param f: :return:
347,912
def netconf_state_datastores_datastore_transaction_id(self, **kwargs): config = ET.Element("config") netconf_state = ET.SubElement(config, "netconf-state", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring") datastores = ET.SubElement(netconf_state, "datastores") datast...
Auto Generated Code
347,913
def cancelAll(self): cancel = self.cancel result = [] for block, _ in self._submitted.itervalues(): try: result.append(cancel(block)) except OSError as exc: if exc.errno != errno.E...
Cancel all submitted IO blocks. Blocks until all submitted transfers have been finalised. Submitting more transfers or processing completion events while this method is running produces undefined behaviour. Returns the list of values returned by individual cancellations. See "ca...
347,914
def _export_table(table, fname): import os.path as op extension = op.splitext(fname.lower())[1] if extension == : fname = fname + table.to_csv(fname, index=None, sep=, encoding=, float_format=, decimal=)
Export DataFrame to .csv
347,915
def text(self): if capybara.ignore_hidden_elements or capybara.visible_text_only: return self.visible_text else: return self.all_text
Retrieve the text of the element. If :data:`capybara.ignore_hidden_elements` is ``True``, which it is by default, then this will return only text which is visible. The exact semantics of this may differ between drivers, but generally any text within elements with ``display: none`` is ignored. ...
347,916
def container_get(name=None, remote_addr=None, cert=None, key=None, verify_cert=True, _raw=False): client = pylxd_client_get(remote_addr, cert, key, verify_cert) if name is None: containers = client.containers.all() if _raw: return containers else: ...
Gets a container from the LXD name : The name of the container to get. remote_addr : An URL to a remote Server, you also have to give cert and key if you provide remote_addr and its a TCP Address! Examples: https://myserver.lan:8443 ...
347,917
def plugin_categories_to_choices(categories): choices = [] for category, items in categories.items(): if items: plugin_tuples = tuple((plugin.type_name, plugin.verbose_name) for plugin in items) if category: choices.append((category, plugin_tuples)) ...
Return a tuple of plugin model choices, suitable for a select field. Each tuple is a ("TypeName", "Title") value.
347,918
def get_collections(self, ignore=None): if ignore is None: return self.collections return [c for c in self.collections if getattr(c, , None) == ignore]
Return the collections matching the given `_ignore` value Parameters ---------- ignore : `bool`, or `None` value of `_ignore` to match Returns ------- collections : `list` if `ignore=None`, simply returns all collections, otherwise re...
347,919
def timer_tick(self): self.process_timers() delta = datetime.timedelta(milliseconds=self.base_interval_msec) self._timeout = IOLoop.current().add_timeout(delta, self.timer_tick)
Callback executed every self.base_interval_msec to check timer expirations.
347,920
def predict_topk(self, dataset, output_type="probability", k=3, missing_value_action=): _check_categorical_option_type(, output_type, [, , ]) if missing_value_action == : missing_value_action = _sl.select_default_missing_value_policy(self, ) if isinstance(dataset, ...
Return top-k predictions for the ``dataset``, using the trained model. Predictions are returned as an SFrame with three columns: `id`, `class`, and `probability`, `margin`, or `rank`, depending on the ``output_type`` parameter. Input dataset size must be the same as for training of the model. ...
347,921
def merge_lvm_data(primary, secondary, name_key): pri_data = to_name_key_dict(primary, name_key) combined_data = to_name_key_dict(secondary, name_key) for name in pri_data: if name not in combined_data: combined_data[name] = pri_data[name] else: ...
Returns a dictionary containing the set of data from primary and secondary where values in primary will always be returned if present, and values in secondary will only be returned if not present in primary, or if the value in primary is `None`. Sample input Data:: primary = [ {'a'...
347,922
def dump(self): print("Relation " + self.relation) print(" With attributes") for n in self.attributes: if self.attribute_types[n] != TYPE_NOMINAL: print(" %s of type %s" % (n, self.attribute_types[n])) else: print(" " + n + ...
Print an overview of the ARFF file.
347,923
def _write_jsonl(filepath, data, kwargs): with io_stl.open(filepath, , encoding=) as outfile: kwargs[] = None if not in kwargs: kwargs[] = True if not in kwargs: kwargs[] = (, ) if not in kwargs: kwargs[] = False for line in data:...
See documentation of mpu.io.write.
347,924
def to_evenly_discretized_mfd(self): return EvenlyDiscretizedMFD(self.mmin + self.bin_width / 2., self.bin_width, self.occurrence_rate.tolist())
Returns the activity rate as an instance of the :class: openquake.hazardlib.mfd.evenly_discretized.EvenlyDiscretizedMFD
347,925
def instance(self, instance_id, display_name=None, instance_type=None, labels=None): return Instance( instance_id, self, display_name=display_name, instance_type=instance_type, labels=labels, )
Factory to create a instance associated with this client. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_create_prod_instance] :end-before: [END bigtable_create_prod_instance] :type instance_id: str :param instance_id: The ID of the ...
347,926
def plotpdf(self, x=None, xmin=None, alpha=None, nbins=50, dolog=True, dnds=False, drawstyle=, histcolor=, plcolor=, fill=False, dohist=True, **kwargs): if x is None: x=self.data if xmin is None: xmin=self._xmin if alpha is None: ...
Plots PDF and powerlaw. kwargs is passed to pylab.hist and pylab.plot
347,927
def get_cognitive_process(self): if not self.has_cognitive_process(): raise IllegalState() else: return Grade(self._get_grade_map(self._my_map[])),
Gets the grade associated with the cognitive process. return: (osid.grading.Grade) - the grade raise: IllegalState - has_cognitive_process() is false raise: OperationFailed - unable to complete request compliance: mandatory - This method must be implemented.
347,928
def get_merkle_proof(self, tx_hash: str, is_full: bool = False) -> dict: payload = self.generate_json_rpc_payload(RpcMethod.GET_MERKLE_PROOF, [tx_hash, 1]) response = self.__post(self.__url, payload) if is_full: return response return response[]
This interface is used to get the corresponding merkle proof based on the specified hexadecimal hash value. :param tx_hash: an hexadecimal transaction hash value. :param is_full: :return: the merkle proof in dictionary form.
347,929
def create_partitions(self, new_partitions, **kwargs): f, futmap = AdminClient._make_futures([x.topic for x in new_partitions], None, AdminClient._make_topics_result) super(AdminClient, self).create_pa...
Create additional partitions for the given topics. The future result() value is None. :param list(NewPartitions) new_partitions: New partitions to be created. :param float operation_timeout: Set broker's operation timeout in seconds, controlling how long the CreatePartitions ...
347,930
def get_range_string(self): return self.left.chr+":"+str(self.left.end)++self.right.chr+":"+str(self.right.start)
Another string representation of the junction. these may be redundant.
347,931
def o3(df): polluant = if not isinstance(df.index.freq, pdoffset.Hour): raise FreqException("df doit être en heure.") res = {"Seuil de RI sur 1H: 180u": depassement(df, valeur=180), "Seuil dAlerte sur 1H: 360u": depassement(df, valeur=360), "Seuil dAlerte sur 3H c...
Calculs réglementaires pour l'ozone Paramètres: df: DataFrame contenant les mesures, avec un index temporel (voir xair.get_mesure) Retourne: Une série de résultats dans un DataFrame : ****** unité (u): µg/m3 (microgramme par mètre cube) Seuil de RI sur 1H: 180u Seuil d'Alerte sur ...
347,932
def iter_tree_with_handed_function(self, function, *function_args): def iter_all_children(row_iter, function, function_args): if isinstance(row_iter, Gtk.TreeIter): function(row_iter, *function_args) for n in reversed(range(self.tree_store.iter_n_children(row...
Iterate tree view with condition check function
347,933
def change_directory(self, path, *args, **kwargs): client = self.dav_client() previous_path = self.session_path() try: if client.is_dir(self.session_path(path)) is False: raise ValueError() except Exception: self.session_path(previous_path) raise
:meth:`.WNetworkClientProto.change_directory` method implementation
347,934
def modify(self, vals): self.vals = vals.view(np.ndarray).copy() y = self.model.predict(self.vals)[0] self.data_visualize.modify(y) self.latent_handle.set_data(self.vals[0,self.latent_index[0]], self.vals[0,self.latent_index[1]]) self.axes.figure.canvas.draw()
When latent values are modified update the latent representation and ulso update the output visualization.
347,935
def prepend_rez_path(self): if system.rez_bin_path: self.env.PATH.prepend(system.rez_bin_path)
Prepend rez path to $PATH.
347,936
def parameters(self, value): if len(value) != self.n_parameters: raise ValueError("Incorrect length of parameter vector. " "Model has %d parameters, but got %d" % (self.n_parameters, len(value))) i = 0 for hl in...
Used to set all of the model's parameters to new values. **Parameters:** value : array_like New values for the model parameters. Must be of length ``self.n_parameters``.
347,937
def get_commenting_agent(self): if not self.has_commentor(): raise errors.IllegalState() try: from ..authentication import managers except ImportError: raise errors.OperationFailed() try: mgr = managers.AuthenticationManager() ...
Gets the agent who created this comment. return: (osid.authentication.Agent) - the ``Agent`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*
347,938
def local(): logger.info("Loading requirements from local file.") with open(REQUIREMENTS_FILE, ) as f: requirements = parse(f) for r in requirements: logger.debug("Creating new package: %r", r) create_package_version(r)
Load local requirements file.
347,939
def get_connection(self, name): name = quote(name, ) path = Client.urls[] % name conn = self._call(path, ) return conn
Get a connection by name. To get the names, use get_connections. :param string name: Name of connection to get :returns dict conn: A connection attribute dictionary.
347,940
def clean_protocol(self, protocol): if protocol is not None: try: return self.PROTOCOL_MAP[protocol] except KeyError: self._handle_malformation( .format( protocol=protocol ) ...
A lot of measurement types make use of a protocol value, so we handle that here.
347,941
def remove_listener(self, uid): self.listeners[:] = (listener for listener in self.listeners if listener[] != uid)
Remove listener with given uid.
347,942
def find_revision_id(self, revision=None): self.create() revision = self.expand_branch_name(revision) output = self.context.capture(, , revision)
Find the global revision id of the given revision.
347,943
def update_application_metadata(template, application_id, sar_client=None): if not template or not application_id: raise ValueError() if not sar_client: sar_client = boto3.client() template_dict = _get_template_dict(template) app_metadata = get_app_metadata(template_dict) requ...
Update the application metadata. :param template: Content of a packaged YAML or JSON SAM template :type template: str_or_dict :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param sar_client: The boto3 client used to access SAR :type sar_clien...
347,944
def _set_topMargin(self, value): bounds = self.bounds if bounds is None: self.height = value else: xMin, yMin, xMax, yMax = bounds self.height = yMax + value
value will be an int or float. Subclasses may override this method.
347,945
def fetch_project(self, project_id): project = self.new_project(project_id) project.reload() return project
Fetch an existing project and it's relevant metadata by ID. .. note:: If the project does not exist, this will raise a :class:`NotFound <google.cloud.exceptions.NotFound>` error. :type project_id: str :param project_id: The ID for this project. :rtype: :class:...
347,946
def impute_knn(df, k=3): imputed_matrix = KNN(k=k).complete(df.values) imputed_df = pd.DataFrame(imputed_matrix, df.index, df.columns) return imputed_df
Nearest neighbour imputations which weights samples using the mean squared difference on features for which two rows both have observed data. :param df: The input dataframe that contains missing values :param k: The number of neighbours :return: the imputed dataframe
347,947
def matchfirst(self, event): if self.depth < len(event.indices): ind = event.indices[self.depth] if ind in self.index: m = self.index[ind].matchfirst(event) if m is not None: return m if h...
Return first match for this event :param event: an input event
347,948
def remove(self, resource, **kwargs): log.info( "Removing {} ...".format(self._model_name, resource.name)) resource.remove(**kwargs) self._ids.remove(resource.id)
Remove an instance of this resource type.
347,949
def generate_list_view(self): name = model_class_form(self.model + ) list_args = dict( model=self.get_model_class, context_object_name=plural(self.model), template_name=self.get_template(), table_class=self.get_actual_table(), context...
Generate class based view for ListView
347,950
def register_event_listener(coro): if not asyncio.iscoroutinefunction(coro): raise TypeError("Function is not a coroutine.") if coro not in _event_listeners: _event_listeners.append(coro)
Registers a coroutine to receive lavalink event information. This coroutine will accept three arguments: :py:class:`Player`, :py:class:`LavalinkEvents`, and possibly an extra. The value of the extra depends on the value of the second argument. If the second argument is :py:attr:`LavalinkEvents.TRACK_E...
347,951
def set_l2cap_options (sock, options): s = struct.pack ("HHHBBBH", *options) sock.setsockopt (SOL_L2CAP, L2CAP_OPTIONS, s)
set_l2cap_options (sock, options) Sets L2CAP options for the specified L2CAP socket. The option list must be in the same format supplied by get_l2cap_options().
347,952
def merge(self, po_file, source_files): pot_file = tempfile.NamedTemporaryFile(mode=, prefix=, delete=False) pot_filename = pot_file.name slog.info(, pot_filename) xargs = [self._xgettext, "--package-name=main", "--package-version=0.1", ...
从源码中获取所有条目,合并到 po_file 中。 :param string po_file: 待写入的 po 文件路径。 :param list source_files : 所有待处理的原文件路径 list。
347,953
def resolve(self, method, path): if method in self._literal and path in self._literal[method]: return self._literal[method][path], [], {} else: return self._resolve_non_literal_route(method, path)
Resolve a request to a route handler. Arguments: method (str): HTTP method, e.g. GET, POST, etc. (type: str) path (str): Request path Returns: tuple or None: A tuple of three items: 1. Route handler (callable) 2. Positional arguments (list) ...
347,954
def get_subjects_with_equal_or_higher_perm(self, perm_str): self._assert_valid_permission(perm_str) return { s for p in self._equal_or_higher_perm(perm_str) for s in self._perm_dict.get(p, set()) }
Args: perm_str : str Permission, ``read``, ``write`` or ``changePermission``. Returns: set of str : Subj that have perm equal or higher than ``perm_str``. Since the lowest permission a subject can have is ``read``, passing ``read`` will return all subjects.
347,955
def ifconfig_inet (iface): res = pipecmd(["ifconfig", iface], ["grep", "inet "]) info = {} lastpart = None for part in res.split(): if part.startswith("addr:"): info["address"] = part[5:] elif part.startswith("Bcast:"): info["broadcast"] = part[6:] ...
Return parsed IPv4 info from ifconfig(8) binary.
347,956
def central_widget(self): if self._central_widget is None: self._central_widget = Widget(size=self.size, parent=self.scene) return self._central_widget
Returns the default widget that occupies the entire area of the canvas.
347,957
async def get_encryption_aes_key(self) -> Tuple[bytes, Dict[str, str], str]: if self.public_key is None: raise ValueError() random_bytes = os.urandom(32) ciphertext = await self._loop.run_in_executor( None, lambda: (self.public_key.encrypt(random_bytes, padding...
Get encryption key to encrypt an S3 object :return: Raw AES key bytes, Stringified JSON x-amz-matdesc, Base64 encoded x-amz-key
347,958
def initialize_app(self, argv): super(NeutronShell, self).initialize_app(argv) self.api_version = {: self.api_version} cmd_name = None if argv: cmd_info = self.command_manager.find_command(argv) cmd_factory, cmd_name, sub_argv = cmd_i...
Global app init bits: * set up API versions * validate authentication info
347,959
def login(self, username, password, token): t explicitly tell you to append it when it gives you a login error. Folks that are new to the API may not know this. : Username : Password : Token return LoginResult loginSessionHeadersessionIdsessionIduserIdmetadataServerUrlserverUrlssl.sale...
Login to Salesforce.com and starts a client session. Unlike other toolkits, token is a separate parameter, because Salesforce doesn't explicitly tell you to append it when it gives you a login error. Folks that are new to the API may not know this. 'username' : Username 'password' : Password ...
347,960
def intersects(self, b): return max(self.x, b.x) < min(self.x+self.width, b.x+b.width) \ and max(self.y, b.y) < min(self.y+self.height, b.y+b.height)
Return True if a part of the two bounds overlaps.
347,961
def Ctrl_Fn(self, n, dl = 0): self.Delay(dl) self.keyboard.press_key(self.keyboard.control_key) self.keyboard.tap_key(self.keyboard.function_keys[n]) self.keyboard.release_key(self.keyboard.control_key)
Ctrl + Fn1~12 组合键
347,962
def filter_table(table, filter_series, ignore=None): with log_start_finish(, logger): ignore = ignore if ignore else set() filters = [_filterize(name, val) for name, val in filter_series.iteritems() if not (name in ignore or (isi...
Filter a table based on a set of restrictions given in Series of column name / filter parameter pairs. The column names can have suffixes `_min` and `_max` to indicate "less than" and "greater than" constraints. Parameters ---------- table : pandas.DataFrame Table to filter. filter_...
347,963
def InitSampCheck(self): self.sample_window += 1 self.panel = wx.Panel(self, style=wx.SIMPLE_BORDER) if self.sample_window == 1: text = step_label = wx.StaticText(self.panel, label=text) else: text = step_label = wx.StaticText(s...
make an interactive grid in which users can edit sample names as well as which site a sample belongs to
347,964
def count(self, objectType, *args, **coolArgs) : return self._makeLoadQuery(objectType, *args, **coolArgs).count()
Returns the number of elements satisfying the query
347,965
def getrecord(**kwargs): record_dumper = serializer(kwargs[]) pid = OAIIDProvider.get(pid_value=kwargs[]).pid record = Record.get_record(pid.object_uuid) e_tree, e_getrecord = verb(**kwargs) e_record = SubElement(e_getrecord, etree.QName(NS_OAIPMH, )) header( e_record, ide...
Create OAI-PMH response for verb Identify.
347,966
def roots(self, init_concs, varied_data, varied, x0=None, NumSys=NumSysLog, plot_kwargs=None, neqsys_type=, **kwargs): _plot = plot_kwargs is not None if _plot: latex_names = plot_kwargs.pop(, False) conc_unit_str = plot_kwargs.pop(, ) ...
Parameters ---------- init_concs : array or dict varied_data : array varied_idx : int or str x0 : array NumSys : _NumSys subclass See :class:`NumSysLin`, :class:`NumSysLog`, etc. plot_kwargs : dict See py:meth:`pyneqsys.NeqSys.solve`. Two a...
347,967
def describe_configs(self, config_resources, include_synonyms=False): version = self._matching_api_version(DescribeConfigsRequest) if version == 0: if include_synonyms: raise IncompatibleBrokerVersion( "include_synonyms requires DescribeConfigsReq...
Fetch configuration parameters for one or more Kafka resources. :param config_resources: An list of ConfigResource objects. Any keys in ConfigResource.configs dict will be used to filter the result. Setting the configs dict to None will get all values. An empty dict will get...
347,968
def ensure_is_date_object(x): error_msg = f"Cannot convert input to date object: {x} (type: {type(x)})" if isinstance(x, dt.date): if isinstance(x, pd.Timestamp): if x.freq != : raise TohuDateError("Pandas Timestamp must have freq= set. Got: freq={x.freq!r}") ...
Ensure input represents a valid date and return the corresponding `datetime.date` object. Valid inputs: - string of the form "YYYY-MM-DD" - dt.date object - pd.Timestamp of the form "YYYY-MM-DD 00:00:00" with freq='D' (as is generated by pd.date_range())
347,969
def parse_FreqDist_interChr(self, f): parsed_data = dict() firstline = True for l in f[]: if firstline: firstline = False interChr = float(re.sub("\)", "", l.split(":")[1])) else: break parsed_data[] = inter...
Parse HOMER tagdirectory petag.FreqDistribution_1000 file to get inter-chromosomal interactions.
347,970
def createCategoryFilter(self, positiveExamples): categoryFilter = self._fullClient.createCategoryFilter("CategoryFilter", positiveExamples) return categoryFilter.positions
Creates a filter fingerprint. Args: positiveExamples, list(str): The list of positive example texts. Returns: list of int: the positions representing the filter representing the texts Raises: CorticalioException: if the request was not successful
347,971
def error_handler_404(request): from django.template import Context, loader from django.http import HttpResponseServerError t = loader.get_template() return HttpResponseServerError(t.render(Context({ : request, : settings, })))
500 error handler which includes ``request`` in the context. Templates: `500.html` Context: None
347,972
def on_mouse_press(self, x: int, y: int, button, mods): if button in [1, 4]: self.example.mouse_press_event( x, self.buffer_height - y, 1 if button == 1 else 2, )
Handle mouse press events and forward to example window
347,973
def _to_dict(self): _dict = {} if hasattr(self, ) and self.custom_pronunciation is not None: _dict[] = self.custom_pronunciation if hasattr(self, ) and self.voice_transformation is not None: _dict[] = self.voice_transformatio...
Return a json dictionary representing this model.
347,974
def read_config(conf_dir=DEFAULT_CONFIG_DIR): "Find and read config file for a directory, return None if not found." conf_path = os.path.expanduser(conf_dir) if not os.path.exists(conf_path): if conf_dir != DEFAULT_CONFIG_DIR: raise IOError("Config directory not found at %s" % ...
Find and read config file for a directory, return None if not found.
347,975
def toBCD (n): bcd = 0 bits = 0 while True: n, r = divmod(n, 10) bcd |= (r << bits) if n is 0: break bits += 4 return bcd
Converts the number n into Binary Coded Decimal.
347,976
def can_add(self, dist): return (self.python is None or dist.py_version is None or dist.py_version==self.python) \ and compatible_platforms(dist.platform, self.platform)
Is distribution `dist` acceptable for this environment? The distribution must match the platform and python version requirements specified when this environment was created, or False is returned.
347,977
def postproc(self): self.do_file_sub( "/etc/ovirt-engine/engine-config/engine-config.properties", r"Password.type=(.*)", r"Password.type=********" ) self.do_file_sub( "/etc/rhevm/rhevm-config/rhevm-config.properties", r"Passwor...
Obfuscate sensitive keys.
347,978
def FastaIter(handle): header = None for line in handle: if line.startswith(">"): if header is not None: yield header, "".join(seq_lines) seq_lines = list() header = line[1:].rstrip() else: if header is not None: ...
generator that returns (header, sequence) tuples from an open FASTA file handle Lines before the start of the first record are ignored.
347,979
def search_meta_specific(self, **avargs): qry = self.ses.query(Symbol).join(SymbolMeta.symbol) for attr, value in avargs.iteritems(): SMA = aliased(SymbolMeta) if "%" in value: acrit = SMA.value.like(value) else: ...
Search list of Symbol objects by by querying specific meta attributes and their respective values. Parameters ---------- avargs The attributes and values passed as key word arguments. If more than one criteria is specified, AND logic is applied. ...
347,980
def format_table(table, column_names=None, column_specs=None, max_col_width=32, report_dimensions=False): AB if len(table) > 0: col_widths = [0] * len(list(table)[0]) elif column_specs is not None: col_widths = [0] * (len(column_specs) + 1) elif column_names is not None:...
Table pretty printer. Expects tables to be given as arrays of arrays. Example: print format_table([[1, "2"], [3, "456"]], column_names=['A', 'B'])
347,981
def write_table(self, table): table_sql, serial_key_sql = super(PostgresDbWriter, self).write_table(table) for sql in serial_key_sql + table_sql: self.execute(sql)
Send DDL to create the specified `table` :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. Returns None
347,982
def inject_into_urllib3(): _validate_dependencies_met() util.ssl_.SSLContext = PyOpenSSLContext util.HAS_SNI = HAS_SNI util.ssl_.HAS_SNI = HAS_SNI util.IS_PYOPENSSL = True util.ssl_.IS_PYOPENSSL = True
Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.
347,983
def levinson_1d(r, order): r = np.atleast_1d(r) if r.ndim > 1: raise ValueError("Only rank 1 are supported for now.") n = r.size if n < 1: raise ValueError("Cannot operate on empty array !") elif order > n - 1: raise ValueError("Order should be <= size-1") if not n...
Levinson-Durbin recursion, to efficiently solve symmetric linear systems with toeplitz structure. Parameters --------- r : array-like input array to invert (since the matrix is symmetric Toeplitz, the corresponding pxp matrix is defined by p items only). Generally the autocorrel...
347,984
def log_to_file(self, message): with self.build_fs.open(self.log_file, ) as f: f.write(unicode(message + ))
Write a log message only to the file
347,985
def fit(self, vecs, iter=20, seed=123): assert vecs.dtype == np.float32 assert vecs.ndim == 2 N, D = vecs.shape assert self.Ks < N, "the number of training vector should be more than Ks" assert D % self.M == 0, "input dimension must be dividable by M" self.Ds = i...
Given training vectors, run k-means for each sub-space and create codewords for each sub-space. This function should be run once first of all. Args: vecs (np.ndarray): Training vectors with shape=(N, D) and dtype=np.float32. iter (int): The number of iteration for k-mea...
347,986
def launch(self, resource): schema = JobSchema(exclude=(, , , , , , , , , )) json = self.service.encode(schema, resource) schema = JobSchema() resp = self.service.create(self.base, json) return self.service.decode(schema, resp)
Launch a new job. :param resource: :class:`jobs.Job <jobs.Job>` object :return: :class:`jobs.Job <jobs.Job>` object :rtype: jobs.Job
347,987
def turn_off(self, channel, callback=None): if callback is None: def callb(): pass callback = callb message = velbus.SwitchRelayOffMessage(self._address) message.relay_channels = [channel] self._controller.send(message, ca...
Turn off switch. :return: None
347,988
def on_background_source(self, *args): if self.background_source: self.background_image = Image(source=self.background_source)
When I get a new ``background_source``, load it as an :class:`Image` and store that in ``background_image``.
347,989
def join(self, other): if self.field == other.field: return self, other _, f1, f2 = Constructible.join_fields(self.field, other.field) return f1(self), f2(other)
return a tuple (new_self, new_other) such that new_self == self, new_other == other, and new_self.field == new_other.field
347,990
def list_(saltenv=, test=None): sevent = salt.utils.event.get_event( , __opts__[], __opts__[], opts=__opts__, listen=True) master_key = salt.utils.master.get_master_key(, __opts__) __jid_event__.fire_event({: master_key}, ) results = se...
List currently configured reactors CLI Example: .. code-block:: bash salt-run reactor.list
347,991
def crossover_template(cls, length, points=2): assert isinstance(length, int) and length >= 0 assert isinstance(points, int) and points >= 0 points = random.sample(range(length + 1), points) points.sort() points.append(length) ...
Create a crossover template with the given number of points. The crossover template can be used as a mask to crossover two bitstrings of the same length. Usage: assert len(parent1) == len(parent2) template = BitString.crossover_template(len(parent1)) inv_temp...
347,992
def load_env_directory(): for var in glob.glob(os.path.join(ENV_DIRECTORY, )): if os.path.isfile(var): os.environ[os.path.basename(var)] = os.path.expandvars(open(var, encoding=).read())
Adds environment variables defined in :any:`ENV_DIRECTORY` to os.environ. Each file will be added to os.environ via filename = contents. Supports bash style comments and variable interpolation.
347,993
def get_closest_mac_host_platform_pair(darwin_version_upper_bound, platform_name_map=SUPPORTED_PLATFORM_NORMALIZED_NAMES): darwin_versions = [int(x[1]) for x in platform_name_map if x[0] == ] bounded_darwin_versions = [v for v in darwin_versions if v <= int(darwin_version_u...
Return the (host, platform) pair for the highest known darwin version less than the bound.
347,994
def extract_images(data, plugin): if not settings.TEXT_SAVE_IMAGE_FUNCTION: return data tree_builder = html5lib.treebuilders.getTreeBuilder() parser = html5lib.html5parser.HTMLParser(tree=tree_builder) dom = parser.parse(data) found = False for img in dom.getElementsByTagName(): ...
extracts base64 encoded images from drag and drop actions in browser and saves those images as plugins
347,995
def set_header(self, port, channel): self._port = port self.channel = channel self._update_header()
Set the port and channel for this packet.
347,996
async def generate_credentials(self): identifier, seed = new_credentials() return .format(identifier, seed.decode().upper())
Create new credentials for authentication. Credentials that have been authenticated shall be saved and loaded with load_credentials before playing anything. If credentials are lost, authentication must be performed again.
347,997
def new_tile(self, num=1): for _ in range(num): if random.random() > .5: new_tile = self.pieces[0] else: new_tile = self.pieces[1] blanks = self.count_blank_positions() ...
Create a new tile in a randomly selected empty square. The tile should be 2 90% of the time and 4 10% of the time.
347,998
def createSign(pParams, method, host_url, request_path, secret_key): sorted_params = sorted(pParams.items(), key=lambda d: d[0], reverse=False) encode_params = urllib.parse.urlencode(sorted_params) payload = [method, host_url, request_path, encode_params] payload = .join(payload) payload = payl...
from 火币demo, 构造签名 :param pParams: :param method: :param host_url: :param request_path: :param secret_key: :return:
347,999
def make_executable(path_str): try: mode = os.stat(path_str).st_mode os.chmod(path_str, mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) except Exception as e: print % e return None return path_str
Performs the equivalent of `chmod +x` on the file at path_str. :returns: path_str if success, else None