Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
17,100
def group_by_day(self): data_by_day = OrderedDict() for d in xrange(1, 366): data_by_day[d] = [] for v, dt in zip(self._values, self.datetimes): data_by_day[dt.doy].append(v) return data_by_day
Return a dictionary of this collection's values grouped by each day of year. Key values are between 1-365.
17,101
def form_valid(self, form): response = super(FormAjaxMixin, self).form_valid(form) if self.request.is_ajax(): return self.json_to_response() return response
If form valid return response with action
17,102
def proximal_translation(prox_factory, y): r def translation_prox_factory(sigma): return (ConstantOperator(y) + prox_factory(sigma) * (IdentityOperator(y.space) - ConstantOperator(y))) return translation_prox_factory
r"""Calculate the proximal of the translated function F(x - y). Parameters ---------- prox_factory : callable A factory function that, when called with a step size, returns the proximal operator of ``F``. y : Element in domain of ``F``. Returns ------- prox_factory : functi...
17,103
def compile_less(input_file, output_file): from .modules import less if not isinstance(input_file, str): raise RuntimeError() return { : less.less_dependencies, : less.less_compile, : input_file, : output_file, : {}, }
Compile a LESS source file. Minifies the output in release mode.
17,104
def drawNormal(N, mu=0.0, sigma=1.0, seed=0): RNG = np.random.RandomState(seed) if isinstance(sigma,float): draws = sigma*RNG.randn(N) + mu else: draws=[] for t in range(len(sigma)): draws.append(sigma[t]*RNG.randn(N) + mu[t]) return draws
Generate arrays of normal draws. The mu and sigma inputs can be numbers or list-likes. If a number, output is a length N array of draws from the normal distribution with mean mu and standard deviation sigma. If a list, output is a length T list whose t-th entry is a length N array with draws from the ...
17,105
def _repr_tty_(self) -> str: header_description = [, ] header_samples = [ , , , , , ] header = SingleTable([], ) setting = SingleTable([], ) sample_main = SingleTable([header_samples], ) sample_...
Return a summary of this sample sheet in a TTY compatible codec.
17,106
def _safe_timezone(obj): if isinstance(obj, _Timezone): return obj if obj is None or obj == "local": return local_timezone() if isinstance(obj, (int, float)): obj = int(obj * 60 * 60) elif isinstance(obj, _datetime.tzinfo): if hasattr(obj, "localize")...
Creates a timezone instance from a string, Timezone, TimezoneInfo or integer offset.
17,107
def output_latex(self, filename_or_file_handle): if isinstance(filename_or_file_handle, basestring): file_handle = file(filename_or_file_handle, ) we_opened = True else: file_handle = filename_or_file_handle we_opened = False try: ...
Output the file to a latex document :param filename_or_file_handle: filename or already opened file handle to output to :return:
17,108
def disconnect(): worker = global_worker if worker.connected: worker.threads_stopped.set() if hasattr(worker, "import_thread"): worker.import_thread.join_import_thread() if hasattr(worker, "profiler") and hasattr(worker.profiler, "t"...
Disconnect this worker from the raylet and object store.
17,109
def unregister(self, alias): if alias not in self._service_objects: raise Error(self._device, % alias) service_obj = self._service_objects.pop(alias) if service_obj.is_alive: with expects.expect_no_raises( % alias): ...
Unregisters a service instance. Stops a service and removes it from the manager. Args: alias: string, the alias of the service instance to unregister.
17,110
def iter(self): if self.patterns: patterns = list(self.patterns) for pattern in patterns: yield pattern
An iteration generator that allows the loop to modify the :class:`PatternSet` during the loop
17,111
def _path2uri(self, dirpath): relpath = dirpath.replace(self.root_path, self.package_name) if relpath.startswith(os.path.sep): relpath = relpath[1:] return relpath.replace(os.path.sep, )
Convert directory path to uri
17,112
def write_biom(biomT, output_fp, fmt="hdf5", gzip=False): opener = open mode = if gzip and fmt != "hdf5": if not output_fp.endswith(".gz"): output_fp += ".gz" opener = gzip_open mode = if fmt == "hdf5": opener = h5py.File with opener(output_f...
Write the BIOM table to a file. :type biomT: biom.table.Table :param biomT: A BIOM table containing the per-sample OTU counts and metadata to be written out to file. :type output_fp str :param output_fp: Path to the BIOM-format file that will be written. :type fmt: str :param ...
17,113
def PixelsHDU(model): cards = model._mission.HDUCards(model.meta, hdu=2) cards = [] cards.append((, )) cards.append((, )) cards.append((, )) cards.append((, model.mission, )) cards.append((, EVEREST_MAJOR_MINOR, )) cards.append((, EVEREST_VERSION, )) cards.append((, ...
Construct the HDU containing the pixel-level light curve.
17,114
def generate_hexagonal_lattice(maxv1, minv1, maxv2, minv2, mindist): if minv1 > maxv1: raise ValueError("Invalid input to function.") if minv2 > maxv2: raise ValueError("Invalid input to function.") v1s = [minv1] v2s = [minv2] initPoint = [minv1,minv2] initLine = [...
This function generates a 2-dimensional lattice of points using a hexagonal lattice. Parameters ----------- maxv1 : float Largest value in the 1st dimension to cover minv1 : float Smallest value in the 1st dimension to cover maxv2 : float Largest value in the 2nd dimensi...
17,115
def change_password(self, previous_password, proposed_password): self.check_token() response = self.client.change_password( PreviousPassword=previous_password, ProposedPassword=proposed_password, AccessToken=self.access_token ) self._set_attri...
Change the User password
17,116
def split(self, fragment_height): passes = int(math.ceil(self.height/fragment_height)) fragments = [] for n in range(0, passes): left = 0 right = self.width upper = n * fragment_height lower = min((n + 1) * fragment_height, self.height) ...
Split an image into multiple fragments after fragment_height pixels :param fragment_height: height of fragment :return: list of PIL objects
17,117
def create_html_link(urlbase, urlargd, link_label, linkattrd=None, escape_urlargd=True, escape_linkattrd=True, urlhash=None): attributes_separator = output = + \ create_url(urlbase, urlargd, escape_urlargd, urlhash) + if linkattrd: outpu...
Creates a W3C compliant link. @param urlbase: base url (e.g. config.CFG_SITE_URL/search) @param urlargd: dictionary of parameters. (e.g. p={'recid':3, 'of'='hb'}) @param link_label: text displayed in a browser (has to be already escaped) @param linkattrd: dictionary of attributes (e.g. a={'class': 'img'...
17,118
def refresh(self, refresh_binary=True): updated_self = self.repo.get_resource(self.uri) if not isinstance(self, type(updated_self)): raise Exception( % (type(updated_self), type(self)) ) if updated_self: self.status_code = updated_self.status_code self.rdf.data = updated_self.rdf.data s...
Performs GET request and refreshes RDF information for resource. Args: None Returns: None
17,119
def command_runner(shell_command, force_rerun_flag, outfile_checker, cwd=None, silent=False): program_and_args = shlex.split(shell_command) if not program_exists(program_and_args[0]): raise OSError(.format(program_and_args[0])) if cwd: outfile_checker = op.join(cwd,...
Run a shell command with subprocess, with additional options to check if output file exists and printing stdout. Args: shell_command (str): Command as it would be formatted in the command-line (ie. "program -i test.in -o test.out"). force_rerun_flag: If the program should be rerun even if the outpu...
17,120
def _analyze(self, it): self._harvest_data() if not isinstance(it, CodeUnit): it = code_unit_factory(it, self.file_locator)[0] return Analysis(self, it)
Analyze a single morf or code unit. Returns an `Analysis` object.
17,121
def create_hparams(hparams_set, hparams_overrides_str="", data_dir=None, problem_name=None, hparams_path=None): hparams = registry.hparams(hparams_set) if hparams_path and tf.gfile.Exists(hparams_path): hparams = create_hparams_from_...
Create HParams with data_dir and problem hparams, if kwargs provided.
17,122
def print_success(msg, color=True): if color and is_posix(): safe_print(u"%s[INFO] %s%s" % (ANSI_OK, msg, ANSI_END)) else: safe_print(u"[INFO] %s" % (msg))
Print a success message. :param string msg: the message :param bool color: if ``True``, print with POSIX color
17,123
def set_unit_spike_features(self, unit_id, feature_name, value): if isinstance(unit_id, (int, np.integer)): if unit_id in self.get_unit_ids(): if unit_id not in self._unit_features.keys(): self._unit_features[unit_id] = {} if isinstance(fe...
This function adds a unit features data set under the given features name to the given unit. Parameters ---------- unit_id: int The unit id for which the features will be set feature_name: str The name of the feature to be stored value ...
17,124
def _resolve_folder(project, parent_folder, folder_name): if in folder_name: raise ResolutionError( + str(folder_name) + + str(parent_folder) + + str(project)) possible_folder, _skip = clean_folder_path(parent_folder + + folder_name, ) if not check_fo...
:param project: The project that the folder belongs to :type project: string :param parent_folder: Full path to the parent folder that contains folder_name :type parent_folder: string :param folder_name: Name of the folder :type folder_name: string :returns: The path to ...
17,125
def get_qubit_los(self, user_lo_config): try: _q_los = self.default_qubit_los.copy() except KeyError: raise PulseError() for channel, lo_freq in user_lo_config.qubit_lo_dict().items(): _q_los[channel.index] = lo_freq if _q_los == self.defaul...
Embed default qubit LO frequencies from backend and format them to list object. If configured lo frequency is the same as default, this method returns `None`. Args: user_lo_config (LoConfig): A dictionary of LOs to format. Returns: list: A list of qubit LOs. Ra...
17,126
def get_field_errors(self, field): identifier = format_html({1}\, self.form_name, field.name) errors = self.errors.get(field.html_name, []) return self.error_class([SafeTuple( (identifier, self.field_error_css_classes, , , , e)) for e in errors])
Return server side errors. Shall be overridden by derived forms to add their extra errors for AngularJS.
17,127
def notify_observers(self, joinpoint, post=False): _observers = tuple(self.observers) for observer in _observers: observer.notify(joinpoint=joinpoint, post=post)
Notify observers with parameter calls and information about pre/post call.
17,128
def _renew_by(name, window=None): expiry = _expires(name) if window is not None: expiry = expiry - datetime.timedelta(days=window) return expiry
Date before a certificate should be renewed :param name: Common Name of the certificate (DNS name of certificate) :param window: days before expiry date to renew :return datetime object of first renewal date
17,129
def extract_path_arguments(path): path = re.sub(, , path) args = re.findall(, path) def split_arg(arg): spl = arg.split() if len(spl) == 1: return {: spl[0], : , : } else: return {: spl[1], : spl[0], : } return list(map(spli...
Extracts a swagger path arguments from the given flask path. This /path/<parameter> extracts [{name: 'parameter'}] And this /<string(length=2):lang_code>/<string:id>/<float:probability> extracts: [ {name: 'lang_code', dataType: 'string'}, {name: 'id', dataType: 'string'} {name: 'probability', dataType...
17,130
def static(cls): r for attr in dir(cls): im_func = getattr(getattr(cls, attr), , None) if im_func: setattr(cls, attr, staticmethod(im_func)) return cls
r"""Converts the given class into a static one, by changing all the methods of it into static methods. Args: cls (class): The class to be converted.
17,131
def escape_newlines(s: str) -> str: if not s: return s s = s.replace("\\", r"\\") s = s.replace("\n", r"\n") s = s.replace("\r", r"\r") return s
Escapes CR, LF, and backslashes. Its counterpart is :func:`unescape_newlines`. ``s.encode("string_escape")`` and ``s.encode("unicode_escape")`` are alternatives, but they mess around with quotes, too (specifically, backslash-escaping single quotes).
17,132
def easter(year, method=EASTER_WESTERN): if not (1 <= method <= 3): raise ValueError("invalid method") y = year g = y % 19 e = 0 if method < 3: i = (19*g+15)%30 j = (y+y//4+i)%7 if method == 2: ...
This method was ported from the work done by GM Arts, on top of the algorithm by Claus Tondering, which was based in part on the algorithm of Ouding (1940), as quoted in "Explanatory Supplement to the Astronomical Almanac", P. Kenneth Seidelmann, editor. This algorithm implements three different e...
17,133
def _validate(self, p): if self._is_operator(p): for operator_or_filter in (p[1] if p[0] != else [p[1]]): if p[0] == : self._validate_xor_args(p) self._validate(operator_or_filter) elif not self._is_value_filter(p) and not self._i...
Recursively validates the pattern (p), ensuring it adheres to the proper key names and structure.
17,134
def trace(self, func): def wrapper(*args, **kwargs): s = self.Stanza(self.indent) s.add([self.GREEN, func.__name__, self.NORMAL, ]) s.indent += 4 sep = for arg in args: s.add([self.CYAN, self.safe_repr(arg), self...
Decorator to print out a function's arguments and return value.
17,135
def create_session_entity_type( self, parent, session_entity_type, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): if not in self._inner_api_calls: ...
Creates a session entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.SessionEntityTypesClient() >>> >>> parent = client.session_path('[PROJECT]', '[SESSION]') >>> >>> # TODO: Initialize ``session_enti...
17,136
def search_related_tags(self,series_search_text=None,tag_names=None,response_type=None,params=None): path = params[], params[] = series_search_text, tag_names response_type = response_type if response_type else self.response_type if response_type != : params[] = respon...
Function to request the related FRED tags for one or more FRED tags matching a series search. `<https://research.stlouisfed.org/docs/api/fred/series_search_related_tags.html>`_ :arg str series_search_text: The words to match against economic data series. Required. :arg str tag_names: Tag names ...
17,137
def getIcon(self, glyph, isOpen, color=None): try: fileName = self._registry[(glyph, isOpen)] except KeyError: logger.warn("Unregistered icon glyph: {} (open={})".format(glyph, isOpen)) from argos.utils.misc import log_dictionary log_dictionary(se...
Returns a QIcon given a glyph name, open/closed state and color. The reslulting icon is cached so that it only needs to be rendered once. :param glyph: name of a registered glyph (e.g. 'file', 'array') :param isOpen: boolean that indicates if the RTI is open or closed. ...
17,138
def database_list_projects(object_id, input_params={}, always_retry=True, **kwargs): return DXHTTPRequest( % object_id, input_params, always_retry=always_retry, **kwargs)
Invokes the /database-xxxx/listProjects API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Cloning#API-method%3A-%2Fclass-xxxx%2FlistProjects
17,139
def ncpos(string, chars, start): string = stypes.stringToCharP(string) chars = stypes.stringToCharP(chars) start = ctypes.c_int(start) return libspice.ncpos_c(string, chars, start)
Find the first occurrence in a string of a character NOT belonging to a collection of characters, starting at a specified location searching forward. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ncpos_c.html :param string: Any character string. :type string: str :param chars: A coll...
17,140
def _update_fps(self, event): self._frame_count += 1 diff = time() - self._basetime if (diff > self._fps_window): self._fps = self._frame_count / diff self._basetime = time() self._frame_count = 0 self._fps_callback(self.fps)
Update the fps after every window
17,141
def _create_attach_record(self, id, timed): record = super(MorphToMany, self)._create_attach_record(id, timed) record[self._morph_type] = self._morph_class return record
Create a new pivot attachement record.
17,142
def tocimxml(self, ignore_path=False): for key, value in self.properties.items(): try: assert isinstance(value, CIMProperty) except AssertionError: ...
Return the CIM-XML representation of this CIM instance, as an object of an appropriate subclass of :term:`Element`. If the instance has no instance path specified or if `ignore_path` is `True`, the returned CIM-XML representation is an `INSTANCE` element consistent with :term:`DSP0201`....
17,143
def add_user_grant(self, permission, user_id, recursive=False, headers=None): if permission not in GSPermissions: raise self.connection.provider.storage_permissions_error( % permission) acl = self.get_acl(headers=headers) acl.add_user_grant(permission, user_...
Convenience method that provides a quick way to add a canonical user grant to a bucket. This method retrieves the current ACL, creates a new grant based on the parameters passed in, adds that grant to the ACL and then PUTs the new ACL back to GS. :type permission: string :param ...
17,144
def get_current_user_ids(self, db_read=None): db_read = db_read or self.db_read return self.user_ids.using(db_read)
Returns current user ids and the count.
17,145
def on_add_cols(self, event): col_labels = self.grid.col_labels er_items = [head for head in self.grid_headers[self.grid_type][][2] if head not in col_labels] er_items = builder.remove_list_headers(er_items) pmag_headers = sorted(list(set(self.grid_headers[self...
Show simple dialog that allows user to add a new column name
17,146
def flatMapValues(self, f): flat_map_fn = lambda kv: ((kv[0], x) for x in f(kv[1])) return self.flatMap(flat_map_fn, preservesPartitioning=True)
Pass each value in the key-value pair RDD through a flatMap function without changing the keys; this also retains the original RDD's partitioning. >>> x = sc.parallelize([("a", ["x", "y", "z"]), ("b", ["p", "r"])]) >>> def f(x): return x >>> x.flatMapValues(f).collect() ...
17,147
def export_element(bpmn_graph, export_elements, node, nodes_classification, order=0, prefix="", condition="", who="", add_join=False): node_type = node[1][consts.Consts.type] node_classification = nodes_classification[node[0]] outgoing_flows = node[1].get(consts....
Export a node with "Element" classification (task, subprocess or gateway) :param bpmn_graph: an instance of BpmnDiagramGraph class, :param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that will be used in exported CSV document, :...
17,148
def getLocationRepresentation(self): activeCells = np.array([], dtype="uint32") totalPrevCells = 0 for module in self.L6aModules: activeCells = np.append(activeCells, module.getActiveCells() + totalPrevCells) totalPrevCells += module.numberOfCells() retur...
Get the full population representation of the location layer.
17,149
def get_tag_html(tag_id): tag_data = get_lazy_tag_data(tag_id) tag = tag_data[] args = tag_data[] kwargs = tag_data[] lib, tag_name = get_lib_and_tag_name(tag) args_str = if args: for arg in args: if isinstance(arg, six.string_types): args_str += " ...
Returns the Django HTML to load the tag library and render the tag. Args: tag_id (str): The tag id for the to return the HTML for.
17,150
def rekey(self, uid=None, offset=None, **kwargs): if uid is not None: if not isinstance(uid, six.string_types): raise TypeError("The unique identifier must be a string.") if offset is not None: if not isinstance(o...
Rekey an existing key. Args: uid (string): The unique ID of the symmetric key to rekey. Optional, defaults to None. offset (int): The time delta, in seconds, between the new key's initialization date and activation date. Optional, defaults ...
17,151
def flatten_multi_dim(sequence): for x in sequence: if (isinstance(x, collections.Iterable) and not isinstance(x, six.string_types)): for y in flatten_multi_dim(x): yield y else: yield x
Flatten a multi-dimensional array-like to a single dimensional sequence (as a generator).
17,152
def add_template_global(self, f, name=None): self.jinja_env.globals[name or f.__name__] = f
Register a custom template global function. Works exactly like the :meth:`template_global` decorator. .. versionadded:: 0.10 :param name: the optional name of the global function, otherwise the function name will be used.
17,153
def best_match_from_list(item,options,fuzzy=90,fname_match=True,fuzzy_fragment=None,guess=False): matches = matches_from_list(item,options,fuzzy,fname_match,fuzzy_fragment,guess) if len(matches)>0: return matches[0] return None
Returns the best match from :meth:`matches_from_list` or ``None`` if no good matches
17,154
def driver_send(command,hostname=None,wait=0.2): cmd = [] if hostname: cmd += [,hostname] if isinstance(command,basestring): command = [command] cmd += [[,x] for x in command] + [] o = nl.run(cmd,quiet=None,stderr=None) if wait!=None: time.sleep(wait)
Send a command (or ``list`` of commands) to AFNI at ``hostname`` (defaults to local host) Requires plugouts enabled (open afni with ``-yesplugouts`` or set ``AFNI_YESPLUGOUTS = YES`` in ``.afnirc``) If ``wait`` is not ``None``, will automatically sleep ``wait`` seconds after sending the command (to make sure it...
17,155
def apparent_dip_correction(axes): a1 = axes[0].copy() a1[-1] = 0 cosa = angle(axes[0],a1,cos=True) _ = 1-cosa**2 if _ > 1e-12: sina = N.sqrt(_) if cosa < 0: sina *= -1 R= N.array([[cosa,sina],[-sina,cosa]]) else: R = N....
Produces a two-dimensional rotation matrix that rotates a projected dataset to correct for apparent dip
17,156
def select_distinct_field(col, field_or_fields, filters=None): fields = _preprocess_field_or_fields(field_or_fields) if filters is None: filters = dict() if len(fields) == 1: key = fields[0] data = list(col.find(filters).distinct(key)) return data else: pip...
Select distinct value or combination of values of single or multiple fields. :params fields: str or list of str. :return data: list of list. **中文文档** 选择多列中出现过的所有可能的排列组合。
17,157
def encode_grib2_data(self): lscale = 1e6 grib_id_start = [7, 0, 14, 14, 2] gdsinfo = np.array([0, np.product(self.data.shape[-2:]), 0, 0, 30], dtype=np.int32) lon_0 = self.proj_dict["lon_0"] sw_lon = self.grid_dict["sw_lon"] if lon_0 < 0: lon_0 += 36...
Encodes member percentile data to GRIB2 format. Returns: Series of GRIB2 messages
17,158
def getWorkerInfo(dataTask): workertime = [] workertasks = [] for fichier, vals in dataTask.items(): if hasattr(vals, ): totaltime = sum([a[] for a in vals.values()]) totaltasks = sum([1 for a in vals.values()]) workertime.append(tot...
Returns the total execution time and task quantity by worker
17,159
def _create_page(cls, page, lang, auto_title, cms_app=None, parent=None, namespace=None, site=None, set_home=False): from cms.api import create_page, create_title from cms.utils.conf import get_templates default_template = get_templates()[0][0] if page is N...
Create a single page or titles :param page: Page instance :param lang: language code :param auto_title: title text for the newly created title :param cms_app: Apphook Class to be attached to the page :param parent: parent page (None when creating the home page) :param na...
17,160
def randtld(self): self.tlds = tuple(tlds.tlds) if not self.tlds else self.tlds return self.random.choice(self.tlds)
-> a random #str tld via :mod:tlds
17,161
def join_state(self, state, history_index, concurrency_history_item): state.join() if state.backward_execution: self.backward_execution = True state.state_execution_status = StateExecutionStatus.INACTIVE if not self.backward_execution: state.con...
a utility function to join a state :param state: the state to join :param history_index: the index of the execution history stack in the concurrency history item for the given state :param concurrency_history_item: the concurrency history item that stores the exe...
17,162
def s3_etag(url: str) -> Optional[str]: s3_resource = boto3.resource("s3") bucket_name, s3_path = split_s3_path(url) s3_object = s3_resource.Object(bucket_name, s3_path) return s3_object.e_tag
Check ETag on S3 object.
17,163
def _deregister(self, session): if session in self: self._sessions.pop(self._get_session_key(session), None)
Deregister a session.
17,164
def update_agent_state(): configure_service() status = if get_service_status(db.Service.SCHEDULE) == db.ServiceStatus.STOPPED: status = elif get_service_status(db.Service.CAPTURE) == db.ServiceStatus.BUSY: status = elif get_service_status(db.Service.INGEST) == db.Servic...
Update the current agent state in opencast.
17,165
def GetVersion(): with open(os.path.join(, )) as versions_file: source = versions_file.read() return re.search((.*?)\, source).group(1)
Gets the version from googleads/common.py. We can't import this directly because new users would get ImportErrors on our third party dependencies. Returns: The version of the library.
17,166
def DVSFile(ID, season, cadence=): if cadence == : strcadence = else: strcadence = return \ % (ID, season, EVEREST_MAJOR_MINOR, strcadence)
Returns the name of the DVS PDF for a given target. :param ID: The target ID :param int season: The target season number :param str cadence: The cadence type. Default `lc`
17,167
def n_to_one(num_inputs, num_streams, bits_per_axis, weight_per_axis): num_bits = num_streams*bits_per_axis encoder_params = { "dimensions" : num_streams, "max_values" : [[0.,1.]]*num_streams, "bits_per_axis" : [bits_per_axis]*num_streams, "weight_per_axis...
Creating inputs of the form: ``( x, y, ..., y )'' |---------| n Here n = num_streams -1. To be more precise, for each component we allocate a fixed number of units `bits_per_axis` and encode each component with a scalar encoder. This is a toy exampl...
17,168
def compile_link_import_strings(codes, build_dir=None, **kwargs): build_dir = build_dir or tempfile.mkdtemp() if not os.path.isdir(build_dir): raise OSError("Non-existent directory: ", build_dir) source_files = [] if kwargs.get(, False) is True: import logging logging.basic...
Creates a temporary directory and dumps, compiles and links provided source code. Parameters ---------- codes: iterable of name/source pair tuples build_dir: string (default: None) path to cache_dir. None implies use a temporary directory. **kwargs: keyword arguments passed onto...
17,169
def find_end(self, text, start_token, end_token, ignore_end_token=None): if not text.startswith(start_token): raise MAVParseError("invalid token start") offset = len(start_token) nesting = 1 while nesting > 0: idx1 = text[offset:].find(start_token) ...
find the of a token. Returns the offset in the string immediately after the matching end_token
17,170
def convert(self, txn): ofxid = self.mk_ofxid(txn.id) metadata = {} posting_metadata = {"ofxid": ofxid} if isinstance(txn, OfxTransaction): posting = Posting(self.name, Amount(txn.amount, self.currency), m...
Convert an OFX Transaction to a posting
17,171
def constant(X, n, mu, hyper_deriv=None): if (n == 0).all(): if hyper_deriv is not None: return scipy.ones(X.shape[0]) else: return mu * scipy.ones(X.shape[0]) else: return scipy.zeros(X.shape[0])
Function implementing a constant mean suitable for use with :py:class:`MeanFunction`.
17,172
def addpackage(sys_sitedir, pthfile, known_dirs): with open(join(sys_sitedir, pthfile)) as f: for n, line in enumerate(f): if line.startswith(" continue line = line.rstrip() if line: if line.startswith(("import ", "import\t")): ...
Wrapper for site.addpackage Try and work out which directories are added by the .pth and add them to the known_dirs set :param sys_sitedir: system site-packages directory :param pthfile: path file to add :param known_dirs: set of known directories
17,173
def closed(self, reason): self.logger.debug(.format(self.item_list)) output_strings = json.dumps(self.item_list, ensure_ascii=False) with open(self.output_file, ) as fh: fh.write(output_strings)
异步爬取全部结束后,执行此关闭方法,对 ``item_list`` 中的数据进行 **JSON** 序列化,并输出到指定文件中,传递给 :meth:`.ZhihuDaily.crawl` :param obj reason: 爬虫关闭原因
17,174
def close(self, reply_code=0, reply_text=, method_sig=(0, 0)): if not self.is_open: return args = AMQPWriter() args.write_short(reply_code) args.write_shortstr(reply_text) args.write_short(method_sig[0]) args.write_short(method_sig[1]) ...
request a channel close This method indicates that the sender wants to close the channel. This may be due to internal conditions (e.g. a forced shut-down) or due to an error handling a specific method, i.e. an exception. When a close is due to an exception, the sender provides ...
17,175
def set(self, image_file, source=None): image_file.set_size() self._set(image_file.key, image_file) if source is not None: if not self.get(source): raise ThumbnailError( % source.name) ...
Updates store for the `image_file`. Makes sure the `image_file` has a size set.
17,176
def pem_as_string(cert): if hasattr(cert, ): return cert cert = cert.encode() if isinstance(cert, unicode) else cert if re.match(_PEM_RE, cert): return True return False
Only return False if the certificate is a file path. Otherwise it is a file object or raw string and will need to be fed to the file open context.
17,177
def commit_on_success(using=None): def entering(using): enter_transaction_management(using=using) def exiting(exc_value, using): try: if exc_value is not None: if is_dirty(using=using): rollback(using=using) else: ...
This decorator activates commit on response. This way, if the view function runs successfully, a commit is made; if the viewfunc produces an exception, a rollback is made. This is one of the most common ways to do transaction control in Web apps.
17,178
def quick_add(self, api_token, text, **kwargs): params = { : api_token, : text } return self._post(, params, **kwargs)
Add a task using the Todoist 'Quick Add Task' syntax. :param api_token: The user's login api_token. :type api_token: str :param text: The text of the task that is parsed. A project name starts with the `#` character, a label starts with a `@` and an assignee starts with ...
17,179
def target_to_ipv6_short(target): splitted = target.split() if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET6, splitted[0]) end_value = int(splitted[1], 16) except (socket.error, ValueError): return None start_value = int(binascii....
Attempt to return a IPv6 short-range list from a target string.
17,180
def add_synonym(self, syn): n = self.node(syn.class_id) if not in n: n[] = {} meta = n[] if not in meta: meta[] = [] meta[].append(syn.as_dict())
Adds a synonym for a node
17,181
def update_channel(self, channel): data = {: channel} return super(ApiInterfaceRequest, self).put(, data)
Method to update a channel. :param channel: List containing channel's desired to be created on database. :return: Id.
17,182
def CreateWeightTableLDAS(in_ldas_nc, in_nc_lon_var, in_nc_lat_var, in_catchment_shapefile, river_id, in_connectivity_file, out_weight_table, ...
Create Weight Table for NLDAS, GLDAS grids as well as for 2D Joules, or LIS Grids Parameters ---------- in_ldas_nc: str Path to the land surface model NetCDF grid. in_nc_lon_var: str The variable name in the NetCDF file for the longitude. in_nc_lat_var: str The variable ...
17,183
def from_miss(self, **kwargs): raise type(self).Missing(type(self)(**kwargs).key())
Called to initialize an instance when it is not found in the cache. For example, if your CacheModel should pull data from the database to populate the cache, ... def from_miss(self, username): user = User.objects.get(username=username) self.emai...
17,184
def get_target_list(self, scan_id): target_list = [] for target, _, _ in self.scans_table[scan_id][]: target_list.append(target) return target_list
Get a scan's target list.
17,185
def items(self): l = list() for attr, value in get_all_attributes(self.__class__): value = getattr(self, attr) if not isinstance(value, Constant): l.append((attr, value)) return list(sort...
non-class attributes ordered by alphabetical order. :: >>> class MyClass(Constant): ... a = 1 # non-class attributre ... b = 2 # non-class attributre ... ... class C(Constant): ... pass ... ... ...
17,186
async def ack(self): state = self._state if state.is_bot: raise ClientException() return await state.http.ack_message(self.channel.id, self.id)
|coro| Marks this message as read. The user must not be a bot user. Raises ------- HTTPException Acking failed. ClientException You must not be a bot user.
17,187
def polytropic_exponent(k, n=None, eta_p=None): r if n is None and eta_p: return k*eta_p/(1.0 - k*(1.0 - eta_p)) elif eta_p is None and n: return n*(k - 1.0)/(k*(n - 1.0)) else: raise Exception()
r'''Calculates one of: * Polytropic exponent from polytropic efficiency * Polytropic efficiency from the polytropic exponent .. math:: n = \frac{k\eta_p}{1 - k(1-\eta_p)} .. math:: \eta_p = \frac{\left(\frac{n}{n-1}\right)}{\left(\frac{k}{k-1} \right)} = \frac{n(k-...
17,188
def _set_view(self): if self.logarithmic: view_class = HorizontalLogView else: view_class = HorizontalView self.view = view_class( self.width - self.margin_box.x, self.height - self.margin_box.y, self._box )
Assign a horizontal view to current graph
17,189
def get_feat_segments(F, bound_idxs): assert len(bound_idxs) > 0, "Boundaries canre not out of bounds assert bound_idxs[0] >= 0 and bound_idxs[-1] < F.shape[0], \ "Boundaries are not correct for the given feature dimensions." feat_segments = [] for i in range(len(bound_idxs) - 1)...
Returns a set of segments defined by the bound_idxs. Parameters ---------- F: np.ndarray Matrix containing the features, one feature vector per row. bound_idxs: np.ndarray Array with boundary indeces. Returns ------- feat_segments: list List of segments, one for eac...
17,190
def close(self, error=None): if self.state is ConnectionStates.DISCONNECTED: return with self._lock: if self.state is ConnectionStates.DISCONNECTED: return log.info(, self, error or ) self._update_reconnect_backoff() se...
Close socket and fail all in-flight-requests. Arguments: error (Exception, optional): pending in-flight-requests will be failed with this exception. Default: kafka.errors.KafkaConnectionError.
17,191
def submit_export(cls, file, volume, location, properties=None, overwrite=False, copy_only=False, api=None): data = {} params = {} volume = Transform.to_volume(volume) file = Transform.to_file(file) destination = { : volume, ...
Submit new export job. :param file: File to be exported. :param volume: Volume identifier. :param location: Volume location. :param properties: Properties dictionary. :param overwrite: If true it will overwrite file if exists :param copy_only: If true files are kept on Se...
17,192
def lookup_rdap(self, inc_raw=False, retry_count=3, depth=0, excluded_entities=None, bootstrap=False, rate_limit_timeout=120, asn_alts=None, extra_org_map=None, inc_nir=True, nir_field_list=None, asn_methods=None, get_asn_description=True):...
The function for retrieving and parsing whois information for an IP address via HTTP (RDAP). **This is now the recommended method, as RDAP contains much better information to parse.** Args: inc_raw (:obj:`bool`): Whether to include the raw whois results in t...
17,193
def update_readme(self, template_readme: Template): readme = os.path.join(self.cached_repo, "README.md") if os.path.exists(readme): os.remove(readme) links = {model_type: {} for model_type in self.models.keys()} for model_type, model_uuids in self.models.items(): ...
Generate the new README file locally.
17,194
def eval(self, expr): self.expr = expr return self._eval(ast.parse(expr.strip()).body[0].value)
Evaluates an expression :param expr: Expression to evaluate :return: Result of expression
17,195
def sort(self, **parameters): self._sort_by_sortedset = None is_sortedset = False if parameters.get(): if parameters.get(): raise ValueError("You canby_score_instanceTo sort by sorted set, you must pass a SortedSetFied (attached to a model) or a string repres...
Enhance the default sort method to accept a new parameter "by_score", to use instead of "by" if you want to sort by the score of a sorted set. You must pass to "by_sort" the key of a redis sorted set (or a sortedSetField attached to an instance)
17,196
def replace(self, source, dest): for i, broker in enumerate(self.replicas): if broker == source: self.replicas[i] = dest return
Replace source broker with destination broker in replica set if found.
17,197
def _read_config(self): if not self._file_path: return None elif self._file_path.startswith(): return self._read_s3_config() elif self._file_path.startswith() or \ self._file_path.startswith(): return self._read_remote_config() ...
Read the configuration from the various places it may be read from. :rtype: str :raises: ValueError
17,198
def _validate_ding0_grid_import(mv_grid, ding0_mv_grid, lv_grid_mapping): _validate_ding0_mv_grid_import(mv_grid, ding0_mv_grid) _validate_ding0_lv_grid_import(mv_grid.lv_grids, ding0_mv_grid, lv_grid_mapping) _validate_load_generation(mv_grid, ding0...
Cross-check imported data with original data source Parameters ---------- mv_grid: MVGrid eDisGo MV grid instance ding0_mv_grid: MVGridDing0 Ding0 MV grid instance lv_grid_mapping: dict Translates Ding0 LV grids to associated, newly created eDisGo LV grids
17,199
def pull_logs(self, project_name, logstore_name, shard_id, cursor, count=None, end_cursor=None, compress=None): headers = {} if compress is None or compress: if lz4: headers[] = else: headers[] = else: head...
batch pull log data from log service Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type logstore_name: string :param logstore_name: the logstore name :type shard_id: int :param sh...