Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
387,600
def _get_assessment_taken(self, assessment_taken_id): if assessment_taken_id not in self._assessments_taken: mgr = self._get_provider_manager() lookup_session = mgr.get_assessment_taken_lookup_session(proxy=self._proxy) lookup_session.use_federated_bank_view() ...
Helper method for getting an AssessmentTaken objects given an Id.
387,601
def get_next_first(intersection, intersections, to_end=True): along_edge = None index_first = intersection.index_first s = intersection.s for other_int in intersections: other_s = other_int.s if other_int.index_first == index_first and other_s > s: if along_edge is None ...
Gets the next node along the current (first) edge. .. note:: This is a helper used only by :func:`get_next`, which in turn is only used by :func:`basic_interior_combine`, which itself is only used by :func:`combine_intersections`. Along with :func:`get_next_second`, this function does th...
387,602
def psd(self): if not self._psd: errMsg = "The PSD has not been set in the metricParameters " errMsg += "instance." raise ValueError(errMsg) return self._psd
A pyCBC FrequencySeries holding the appropriate PSD. Return the PSD used in the metric calculation.
387,603
def save_ds9(output, filename): ds9_file = open(filename, ) ds9_file.write(output) ds9_file.close()
Save ds9 region output info filename. Parameters ---------- output : str String containing the full output to be exported as a ds9 region file. filename : str Output file name.
387,604
def to_dict(self): data = {} data["name"] = self.name data["description"] = self.description if self.description and len(self.description) else None data["type"] = self.type if self.type and len(self.type) else None data["allowed_chars"] = self.allowed_chars if...
Transform an attribute to a dict
387,605
def process_blast( blast_dir, org_lengths, fraglengths=None, mode="ANIb", identity=0.3, coverage=0.7, logger=None, ): blastfiles = pyani_files.get_input_files(blast_dir, ".blast_tab") results = ANIResults(list(org_lengths.keys()), mode) for org, length in lis...
Returns a tuple of ANIb results for .blast_tab files in the output dir. - blast_dir - path to the directory containing .blast_tab files - org_lengths - the base count for each input sequence - fraglengths - dictionary of query sequence fragment lengths, only needed for BLASTALL output - mode - pars...
387,606
def get_users(self, fetch=True): return Users(self.resource.users, self.client, populate=fetch)
Return this Applications's users object, populating it if fetch is True.
387,607
def _reset_cache(self, key=None): if getattr(self, , None) is None: return if key is None: self._cache.clear() else: self._cache.pop(key, None)
Reset cached properties. If ``key`` is passed, only clears that key.
387,608
def read(self, ncfile, timegrid_data) -> None: array = query_array(ncfile, self.name) idxs: Tuple[Any] = (slice(None),) subdev2index = self.query_subdevice2index(ncfile) for devicename, seq in self.sequences.items(): if seq.NDIM: if self._timeaxis: ...
Read the data from the given NetCDF file. The argument `timegrid_data` defines the data period of the given NetCDF file. See the general documentation on class |NetCDFVariableFlat| for some examples.
387,609
def resolve_links(self): for resource in self.items_mapped[].values(): for dct in [getattr(resource, , {}), resource.fields]: for k, v in dct.items(): if isinstance(v, ResourceLink): resolved = self._resolve_resource_link(v) ...
Attempt to resolve all internal links (locally). In case the linked resources are found either as members of the array or within the `includes` element, those will be replaced and reference the actual resources. No network calls will be performed.
387,610
def QA_indicator_WR(DataFrame, N, N1): HIGH = DataFrame[] LOW = DataFrame[] CLOSE = DataFrame[] WR1 = 100 * (HHV(HIGH, N) - CLOSE) / (HHV(HIGH, N) - LLV(LOW, N)) WR2 = 100 * (HHV(HIGH, N1) - CLOSE) / (HHV(HIGH, N1) - LLV(LOW, N1)) DICT = {: WR1, : WR2} return pd.DataFrame(DICT)
威廉指标
387,611
def _import_all_modules(): import traceback import os global results globals_, locals_ = globals(), locals() def load_module(modulename, package_module): try: names = [] module = __import__(package_module, globals_, locals_, [modulename]) for name i...
dynamically imports all modules in the package
387,612
def add_console_logger(logger, level=): logger.setLevel(getattr(logging, level.upper())) if not logger.handlers: color = False if curses and sys.stderr.isatty(): try: curses.setupterm() if curses.tigetnum("colors") > 0: ...
增加console作为日志输入.
387,613
def remove(self): lib.gp_camera_folder_remove_dir( self._cam._cam, self.parent.path.encode(), self.name.encode(), self._cam._ctx)
Remove the directory.
387,614
def transform(self, fn, dtype=None, *args, **kwargs): rdd = self._rdd.map(fn) if dtype is None: return self.__class__(rdd, noblock=True, **self.get_params()) if dtype is np.ndarray: return ArrayRDD(rdd, bsize=self.bsize, noblock=True) elif dtype is sp.sp...
Equivalent to map, compatibility purpose only. Column parameter ignored.
387,615
def get_all_sources(self): if self.__all_sources is None: self.__all_sources = OrderedDict() self.walk(self.__add_one) return self.__all_sources
Returns: OrderedDict: all source file names in the hierarchy, paired with the names of their subpages.
387,616
def parse_baxter(reading): initial = medial = final = tone = inienv = True medienv = False finenv = False tonenv = False inichars = "pbmrtdnkgnsyhzljwXHptkRPjyjuww' + medial return initial,medial,final,tone
Parse a Baxter string and render it with all its contents, namely initial, medial, final, and tone.
387,617
def _app_cache_deepcopy(obj): if isinstance(obj, defaultdict): return deepcopy(obj) elif isinstance(obj, dict): return type(obj)((_app_cache_deepcopy(key), _app_cache_deepcopy(val)) for key, val in obj.items()) elif isinstance(obj, list): return list(_app_cache_deepcopy(val) for...
An helper that correctly deepcopy model cache state
387,618
def fence_point_encode(self, target_system, target_component, idx, count, lat, lng): return MAVLink_fence_point_message(target_system, target_component, idx, count, lat, lng)
A fence point. Used to set a point when from GCS -> MAV. Also used to return a point from MAV -> GCS target_system : System ID (uint8_t) target_component : Component ID (uint8_t) idx : point index (first point is...
387,619
def Var(self, mu=None): if mu is None: mu = self.Mean() var = 0.0 for x, p in self.d.iteritems(): var += p * (x - mu) ** 2 return var
Computes the variance of a PMF. Args: mu: the point around which the variance is computed; if omitted, computes the mean Returns: float variance
387,620
def model(self, value): if value == self._defaults[] and in self._values: del self._values[] else: self._values[] = value
The model property. Args: value (string). the property value.
387,621
def migrate(connection, dsn): all_migrations = _get_all_migrations() logger.debug(.format(all_migrations)) for version, modname in all_migrations: if _is_missed(connection, version) and version <= SCHEMA_VERSION: logger.info(.format(version)) module = __import__(modname...
Collects all migrations and applies missed. Args: connection (sqlalchemy connection):
387,622
def _calculate_status(self, target_freshness, freshness):
Calculate the status of a run. :param dict target_freshness: The target freshness dictionary. It must match the freshness spec. :param timedelta freshness: The actual freshness of the data, as calculated from the database's timestamps
387,623
def from_content(cls, content): parsed_content = parse_tibiacom_content(content) tables = cls._parse_tables(parsed_content) filters = tables.get("Highscores Filter") if filters is None: raise InvalidContent("content does is not from the highscores section of Tibia.co...
Creates an instance of the class from the html content of a highscores page. Notes ----- Tibia.com only shows up to 25 entries per page, so in order to obtain the full highscores, all 12 pages must be parsed and merged into one. Parameters ---------- content: :c...
387,624
def carrysave_adder(a, b, c, final_adder=ripple_add): a, b, c = libutils.match_bitwidth(a, b, c) partial_sum = a ^ b ^ c shift_carry = (a | b) & (a | c) & (b | c) return pyrtl.concat(final_adder(partial_sum[1:], shift_carry), partial_sum[0])
Adds three wirevectors up in an efficient manner :param WireVector a, b, c : the three wires to add up :param function final_adder : The adder to use to do the final addition :return: a wirevector with length 2 longer than the largest input
387,625
def __cache(self, file, content, document): self.__files_cache.add_content(**{file: CacheData(content=content, document=document)})
Caches given file. :param file: File to cache. :type file: unicode :param content: File content. :type content: list :param document: File document. :type document: QTextDocument
387,626
def valuefrompostdata(self, postdata): if self.multi: found = False if self.id in postdata: found = True passedvalues = postdata[self.id].split() values = [] for choicekey in [x[0] for x in self.choices]: ...
This parameter method searches the POST data and retrieves the values it needs. It does not set the value yet though, but simply returns it. Needs to be explicitly passed to parameter.set()
387,627
def setup(level=, output=None): output = output or settings.LOG[] level = level.upper() handlers = [ logbook.NullHandler() ] if output == : handlers.append( logbook.StreamHandler(sys.stdout, format_string=settings.LOG[], ...
Hivy formated logger
387,628
def gen_token(cls): token = os.urandom(16) token_time = int(time.time()) return {: token, : token_time}
生成 access_token
387,629
def format_result(result): instance = None error = None if result["instance"] is not None: instance = format_instance(result["instance"]) if result["error"] is not None: error = format_error(result["error"]) result = { "success": result["success"], "plugin": f...
Serialise Result
387,630
def __audioread_load(path, offset, duration, dtype): y = [] with audioread.audio_open(path) as input_file: sr_native = input_file.samplerate n_channels = input_file.channels s_start = int(np.round(sr_native * offset)) * n_channels if duration is None: s_end = ...
Load an audio buffer using audioread. This loads one block at a time, and then concatenates the results.
387,631
def find(cls, key=None, **kwargs): if not key: return super(Asset, cls).find(**kwargs) params = {"asset[key]": key} params.update(kwargs) theme_id = params.get("theme_id") path_prefix = "%s/themes/%s" % (cls.site, theme_id) if theme_id else cls.site ...
Find an asset by key E.g. shopify.Asset.find('layout/theme.liquid', theme_id=99)
387,632
def ip(): ok, err = _hack_ip() if not ok: click.secho(click.style(err, fg=)) sys.exit(1) click.secho(click.style(err, fg=))
Show ip address.
387,633
def _mapped_std_streams(lookup_paths, streams=(, , )): standard_inos = {} for stream in streams: try: stream_stat = os.fstat(getattr(sys, stream).fileno()) key = stream_stat.st_dev, stream_stat.st_ino standard_inos[key] = stream except Exception: ...
Get a mapping of standard streams to given paths.
387,634
def sys_version(version_tuple): old_version = sys.version_info sys.version_info = version_tuple yield sys.version_info = old_version
Set a temporary sys.version_info tuple :param version_tuple: a fake sys.version_info tuple
387,635
def get_content_commit_date(extensions, acceptance_callback=None, root_dir=): logger = logging.getLogger(__name__) def _null_callback(_): return True if acceptance_callback is None: acceptance_callback = _null_callback root_dir = os.path.abspath(r...
Get the datetime for the most recent commit to a project that affected certain types of content. Parameters ---------- extensions : sequence of 'str' Extensions of files to consider in getting the most recent commit date. For example, ``('rst', 'svg', 'png')`` are content extensions ...
387,636
def syllabify(word): compound = bool(re.search(r, word)) syllabify = _syllabify_compound if compound else _syllabify_simplex syllabifications = list(syllabify(word)) for word, rules in rank(syllabifications): word = str(replace_umlauts(word, put_back=True)) rules = rules[1...
Syllabify the given word, whether simplex or complex.
387,637
def list_vnets(access_token, subscription_id): endpoint = .join([get_rm_endpoint(), , subscription_id, , , NETWORK_API]) return do_get(endpoint, access_token)
List the VNETs in a subscription . Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of VNets list with properties.
387,638
def get_hex_color(layer_type): COLORS = [, , , , , , , , , , , , , , , , , , , ] hashed = int(hash(layer_type)) % 5 if "conv" in layer_type.lower(): return COLORS[:5][hashed] if layer_type in lasagne.layers.pool.__all__: return COLORS[5:10...
Determines the hex color for a layer. :parameters: - layer_type : string Class name of the layer :returns: - color : string containing a hex color for filling block.
387,639
def _get_fuzzy_tc_matches(text, full_text, options): print("text: {}, full: {}, options: {}".format(text, full_text, options)) matching_options = _get_fuzzy_matches(full_text, options) input_tokens = full_text.split() initial_tokens = input_tokens.remove(text) ...
Get the options that match the full text, then from each option return only the individual words which have not yet been matched which also match the text being tab-completed.
387,640
def remove(self): try: self.phase = PHASE.REMOVE self.logger.info("Removing environment %s..." % self.namespace) self.instantiate_features() self._specialize() for feature in self.features.run_order: try: se...
remove the environment
387,641
def tai(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0, jd=None): if jd is not None: tai = jd else: tai = julian_date( _to_array(year), _to_array(month), _to_array(day), _to_array(hour), _to_array(minute), _to_ar...
Build a `Time` from a TAI calendar date. Supply the International Atomic Time (TAI) as a proleptic Gregorian calendar date: >>> t = ts.tai(2014, 1, 18, 1, 35, 37.5) >>> t.tai 2456675.56640625 >>> t.tai_calendar() (2014, 1, 18, 1, 35, 37.5)
387,642
def read_composite_array(fname, sep=): r with open(fname) as f: header = next(f) if header.startswith(): attrs = dict(parse_comment(header[1:])) header = next(f) else: attrs = {} transheader = htranslator.read(header.split(sep)) field...
r""" Convert a CSV file with header into an ArrayWrapper object. >>> from openquake.baselib.general import gettemp >>> fname = gettemp('PGA:3,PGV:2,avg:1\n' ... '.1 .2 .3,.4 .5,.6\n') >>> print(read_composite_array(fname).array) # array of shape (1,) [([0.1, 0.2, 0.3], [0.4, 0...
387,643
def add_btn_ok(self,label_ok): self.wbtn_ok = button.Button("btn_ok",self,self.window,self.peng, pos=lambda sw,sh, bw,bh: (sw/2-bw/2,sh/2-bh/2-bh*2), size=[0,0], label=label_ok, borderstyle=self.bor...
Adds an OK button to allow the user to exit the dialog. This widget can be triggered by setting the label ``label_ok`` to a string. This widget will be mostly centered on the screen, but below the main label by the double of its height.
387,644
def convert_csv_with_dialog_paths(csv_file): def convert_line_to_path(line): file, dir = map(lambda x: x.strip(), line.split(",")) return os.path.join(dir, file) return map(convert_line_to_path, csv_file)
Converts CSV file with comma separated paths to filesystem paths. :param csv_file: :return:
387,645
def _parse_scram_response(response): return dict(item.split(b"=", 1) for item in response.split(b","))
Split a scram response into key, value pairs.
387,646
def _format_msg(text, width, indent=0, prefix=""): r text = repr(text).replace("`", "\\`").replace("\\n", " ``\\n`` ") sindent = " " * indent if not prefix else prefix wrapped_text = textwrap.wrap(text, width, subsequent_indent=sindent) return ("\n".join(wrapped_text))[1:-1].rstrip()
r""" Format exception message. Replace newline characters \n with ``\n``, ` with \` and then wrap text as needed
387,647
def insert(self, fields, typecast=False): return self._post(self.url_table, json_data={"fields": fields, "typecast": typecast})
Inserts a record >>> record = {'Name': 'John'} >>> airtable.insert(record) Args: fields(``dict``): Fields to insert. Must be dictionary with Column names as Key. typecast(``boolean``): Automatic data conversion from string values. Retu...
387,648
def from_args(cls, args, project_profile_name=None): cli_vars = parse_cli_vars(getattr(args, , )) threads_override = getattr(args, , None) target_override = getattr(args, , None) raw_profiles = read_profile(args.profiles_dir) profile_name = cls.pick_profile_name(args.pro...
Given the raw profiles as read from disk and the name of the desired profile if specified, return the profile component of the runtime config. :param args argparse.Namespace: The arguments as parsed from the cli. :param project_profile_name Optional[str]: The profile name, if ...
387,649
def start(self): if self._running: raise RuntimeError(.format( self._owner.__class__.__name__)) self._running = True self.queue_command(self._owner.start_event) while self._incoming: self.queue_command(self._incoming.popleft())
Start the component's event loop (thread-safe). After the event loop is started the Qt thread calls the component's :py:meth:`~Component.start_event` method, then calls its :py:meth:`~Component.new_frame_event` and :py:meth:`~Component.new_config_event` methods as required until ...
387,650
def format_command( command_args, command_output, ): text = .format(command_args) if not command_output: text += elif logger.getEffectiveLevel() > logging.DEBUG: text += else: if not command_output.endswith(): command_output += text +...
Format command information for logging.
387,651
def subset(args): p = OptionParser(subset.__doc__) p.add_option("--qchrs", default=None, help="query chrs to extract, comma sep [default: %default]") p.add_option("--schrs", default=None, help="subject chrs to extract, comma sep [default: %default]") p.add_option("--...
%prog subset blastfile qbedfile sbedfile Extract blast hits between given query and subject chrs. If --qchrs or --schrs is not given, then all chrs from q/s genome will be included. However one of --qchrs and --schrs must be specified. Otherwise the script will do nothing.
387,652
def write(self, chunk, offset): return lib.zfile_write(self._as_parameter_, chunk, offset)
Write chunk to file at specified position Return 0 if OK, else -1
387,653
def pywt_wavelet(wavelet): if isinstance(wavelet, pywt.Wavelet): return wavelet else: return pywt.Wavelet(wavelet)
Convert ``wavelet`` to a `pywt.Wavelet` instance.
387,654
def get_stream_url(self, session_id, stream_id=None): url = self.api_url + + self.api_key + + session_id + if stream_id: url = url + + stream_id return url
this method returns the url to get streams information
387,655
def insert(self, index, p_object): validated_value = self.get_validated_object(p_object) if validated_value is not None: self.__modified_data__.insert(index, validated_value)
Insert an element to a list
387,656
def _clone(self, cid): try: iid = self.client.commit( container=cid, conf={ : { : } } )[] except docker.errors.APIError as ex: raise MountError(st...
Create a temporary image snapshot from a given cid. Temporary image snapshots are marked with a sentinel label so that they can be cleaned on unmount.
387,657
def wrap_rtx(packet, payload_type, sequence_number, ssrc): rtx = RtpPacket( payload_type=payload_type, marker=packet.marker, sequence_number=sequence_number, timestamp=packet.timestamp, ssrc=ssrc, payload=pack(, packet.sequence_number) + packet.payload) rtx.c...
Create a retransmission packet from a lost packet.
387,658
def change_type(self, bucket, key, storage_type): resource = entry(bucket, key) return self.__rs_do(, resource, .format(storage_type))
修改文件的存储类型 修改文件的存储类型为普通存储或者是低频存储,参考文档: https://developer.qiniu.com/kodo/api/3710/modify-the-file-type Args: bucket: 待操作资源所在空间 key: 待操作资源文件名 storage_type: 待操作资源存储类型,0为普通存储,1为低频存储
387,659
def receive_external(self, http_verb, host, url, http_headers): if http_verb == : return self.http.get(host + url, headers=http_headers, stream=True) else: raise ValueError("Unsupported http_verb:" + http_verb)
Retrieve a streaming request for a file. :param http_verb: str GET is only supported right now :param host: str host we are requesting the file from :param url: str url to ask the host for :param http_headers: object headers to send with the request :return: requests.Response con...
387,660
def cheat(num): solution = click.style(Problem(num).solution, bold=True) click.confirm("View answer to problem %i?" % num, abort=True) click.echo("The answer to problem {} is {}.".format(num, solution))
View the answer to a problem.
387,661
def write_tsv(self, path): with open(path, ) as ofh: writer = csv.writer( ofh, dialect=, quoting=csv.QUOTE_NONE, lineterminator=os.linesep ) for gs in self._gene_sets.values(): writer.writerow(gs.to_list())
Write the database to a tab-delimited text file. Parameters ---------- path: str The path name of the file. Returns ------- None
387,662
def external_commands(self): res = [] with self.app.external_commands_lock: for cmd in self.app.get_external_commands(): res.append(cmd.serialize()) return res
Get the external commands from the daemon Use a lock for this function to protect :return: serialized external command list :rtype: str
387,663
def linspace2(a, b, n, dtype=None): a = linspace(a, b, n + 1, dtype=dtype)[:-1] if len(a) > 1: diff01 = ((a[1] - a[0]) / 2).astype(a.dtype) a += diff01 return a
similar to numpy.linspace but excluding the boundaries this is the normal numpy.linspace: >>> print linspace(0,1,5) [ 0. 0.25 0.5 0.75 1. ] and this gives excludes the boundaries: >>> print linspace2(0,1,5) [ 0.1 0.3 0.5 0.7 0.9]
387,664
def serialize( self, value, state ): if self._nested is None: state.raise_error(InvalidRootProcessor, .format(self.alias)) if not value and self.required: s...
Serialize the value into a new Element object and return it.
387,665
def clean_axis(axis): axis.get_xaxis().set_ticks([]) axis.get_yaxis().set_ticks([]) for spine in list(axis.spines.values()): spine.set_visible(False)
Remove ticks, tick labels, and frame from axis
387,666
def load_from_stream(self, stream, container, **opts): root = ET.parse(stream).getroot() path = anyconfig.utils.get_path_from_stream(stream) nspaces = _namespaces_from_file(path) return root_to_container(root, container=container, nspaces=nspaces...
:param stream: XML file or file-like object :param container: callble to make a container object :param opts: optional keyword parameters to be sanitized :return: Dict-like object holding config parameters
387,667
def square_distance(a: Square, b: Square) -> int: return max(abs(square_file(a) - square_file(b)), abs(square_rank(a) - square_rank(b)))
Gets the distance (i.e., the number of king steps) from square *a* to *b*.
387,668
def script_current_send(self, seq, force_mavlink1=False): return self.send(self.script_current_encode(seq), force_mavlink1=force_mavlink1)
This message informs about the currently active SCRIPT. seq : Active Sequence (uint16_t)
387,669
def chat_update_message(self, channel, text, timestamp, **params): method = if self._channel_is_name(channel): channel = self.channel_name_to_id(channel) params.update({ : channel, : text, : timestamp, }) retu...
chat.update This method updates a message. Required parameters: `channel`: Channel containing the message to be updated. (e.g: "C1234567890") `text`: New text for the message, using the default formatting rules. (e.g: "Hello world") `timestamp`: Timestamp of the me...
387,670
def _as_rdf_xml(self, ns): self.rdf_identity = self._get_identity(ns) elements = [] elements.append(ET.Element(NS(, ), attrib={NS(, ): self._get_persistent_identitity(ns)})) if self.name is not None: ...
Return identity details for the element as XML nodes
387,671
def dump(self): result = list(self.output_lines()) if self.locked: result.append() if self.choices: for choice in self.choices: result.append( + choice) if self.explanation: result.append( + self.explanation) ...
Serialize a test case to a string.
387,672
def password_hash(password): try: return bcrypt_sha256.encrypt(password) except TypeError: return bcrypt_sha256.encrypt(password.decode())
Hash the password, using bcrypt+sha256. .. versionchanged:: 1.1.0 :param str password: Password in plaintext :return: password hash :rtype: str
387,673
def sill(self): sill = self.nugget for v in self.variograms: sill += v.contribution return sill
get the sill of the GeoStruct Return ------ sill : float the sill of the (nested) GeoStruct, including nugget and contribution from each variogram
387,674
def getByTime(self, startTime=None, endTime=None): collections = self.get_data_collections() if startTime is not None: startTime = float(startTime) if endTime is not None: endTime = float(endTime) if startTime is not None and endTime is not None: ...
:desc: Get all the notes in the given time window :param int startTime: The begining of the window :param int endTime: The end of the window :returns: A list of IDs :ravl: list
387,675
def firsttime(self): self.config.set(, , ) if self.cli_config.getboolean(, , fallback=False): print(PRIVACY_STATEMENT) else: self.cli_config.set_value(, , ask_user_for_telemetry()) self.update()
sets it as already done
387,676
def GetRemainder(self): ret = libxml2mod.xmlTextReaderGetRemainder(self._o) if ret is None:raise treeError() __tmp = inputBuffer(_obj=ret) return __tmp
Method to get the remainder of the buffered XML. this method stops the parser, set its state to End Of File and return the input stream with what is left that the parser did not use. The implementation is not good, the parser certainly procgressed past what's left in reader->inp...
387,677
def get_ticker(self, symbol=None): data = {} tick_path = if symbol is not None: tick_path = data = { : symbol } return self._get(tick_path, False, data=data)
Get symbol tick https://docs.kucoin.com/#get-ticker :param symbol: (optional) Name of symbol e.g. KCS-BTC :type symbol: string .. code:: python all_ticks = client.get_ticker() ticker = client.get_ticker('ETH-BTC') :returns: ApiResponse .. co...
387,678
def _disconnect(self, mqttc, userdata, rc): self.connected = False if rc != 0: LOGGER.info("MQTT Unexpected disconnection. Trying reconnect.") try: self._mqttc.reconnect() except Exception as ex: template = "An exception of typ...
The callback for when a DISCONNECT occurs. :param mqttc: The client instance for this callback :param userdata: The private userdata for the mqtt client. Not used in Polyglot :param rc: Result code of connection, 0 = Graceful, anything else is unclean
387,679
def get_requests(self): requests = self.derived_get_requests() for request in requests: request.url = URLHelper.remove_hash(request.url) return requests
Get all the new requests that were found in the response. Returns: list(:class:`nyawc.http.Request`): A list of new requests that were found.
387,680
def build_request(self, input_data=None, *args, **kwargs): if input_data is not None: self.input_data = input_data if self.input_data is None: raise ValueError() if self.uo is None: raise ValueError() self.request = RequestHolder() se...
Builds request :param input_data: :param args: :param kwargs: :return:
387,681
def chunks(iterable, size): it = iter(iterable) item = list(islice(it, size)) while item: yield item item = list(islice(it, size))
Splits a very large list into evenly sized chunks. Returns an iterator of lists that are no more than the size passed in.
387,682
def spectrum(self, function=, lmax=None, unit=, base=10.): if function.lower() not in (, , , ): raise ValueError( "function must be of type , , , or " ". Provided value was {:s}".format(repr(function)) ) s = _spectrum(self.coeffs, nor...
Return the spectrum as a function of spherical harmonic degree. Usage ----- spectrum, [error_spectrum] = x.spectrum([function, lmax, unit, base]) Returns ------- spectrum : ndarray, shape (lmax+1) 1-D numpy ndarray of the spectrum, where lmax is the maximum ...
387,683
def _clean_up_columns( self): self.log.debug() sqlQueries = [ "update tcs_helper_catalogue_tables_info set old_table_name = table_name where old_table_name is null;", "update tcs_helper_catalogue_tables_info set version_number = where table_name like and v...
clean up columns .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any useful text ...
387,684
def lpc(blk, order=None): if order < 100: return lpc.nautocor(blk, order) try: return lpc.kautocor(blk, order) except ParCorError: return lpc.nautocor(blk, order)
Find the Linear Predictive Coding (LPC) coefficients as a ZFilter object, the analysis whitening filter. This implementation uses the autocorrelation method, using the Levinson-Durbin algorithm or Numpy pseudo-inverse for linear system solving, when needed. Parameters ---------- blk : An iterable with ...
387,685
def upgradeShare1to2(oldShare): "Upgrader from Share version 1 to version 2." sharedInterfaces = [] attrs = set(oldShare.sharedAttributeNames.split(u)) for iface in implementedBy(oldShare.sharedItem.__class__): if set(iface) == attrs or attrs == set(): sharedInterfaces.append(iface) ...
Upgrader from Share version 1 to version 2.
387,686
def setObsoletedBy(self, pid, obsoletedByPid, serialVersion, vendorSpecific=None): response = self.setObsoletedByResponse( pid, obsoletedByPid, serialVersion, vendorSpecific ) return self._read_boolean_response(response)
See Also: setObsoletedByResponse() Args: pid: obsoletedByPid: serialVersion: vendorSpecific: Returns:
387,687
def set_roots(self, uproot_with=None): self.treedir = os.environ.get(, None) if not uproot_with else uproot_with if not self.treedir: treefilepath = os.path.dirname(os.path.abspath(__file__)) if in treefilepath: self.treedir = treefilepath.rspl...
Set the roots of the tree in the os environment Parameters: uproot_with (str): A new TREE_DIR path used to override an existing TREE_DIR environment variable
387,688
def write(self, args): ShellProgressView.done = False message = args.get(, ) percent = args.get(, None) if percent: ShellProgressView.progress_bar = _format_value(message, percent) if int(percent) == 1: ShellProgressView.progress_bar = N...
writes the progres
387,689
def like_shared_file(self, sharekey=None): if not sharekey: raise Exception( "You must specify a sharekey of the file you" "want to .") endpoint = .format(sharekey=sharekey) data = self._make_request("POST", endpoint=endpoint, data=None) ...
'Like' a SharedFile. mlkshk doesn't allow you to unlike a sharedfile, so this is ~~permanent~~. Args: sharekey (str): Sharekey for the file you want to 'like'. Returns: Either a SharedFile on success, or an exception on error.
387,690
def complete_info(self, text, line, begidx, endidx): opts = self.INFO_OPTS if not text: completions = opts else: completions = [f for f in opts if f.startswith(text) ] retu...
completion for info command
387,691
def dlabfs(handle): handle = ctypes.c_int(handle) descr = stypes.SpiceDLADescr() found = ctypes.c_int() libspice.dlabfs_c(handle, ctypes.byref(descr), ctypes.byref(found)) return descr, bool(found.value)
Begin a forward segment search in a DLA file. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dlabfs_c.html :param handle: Handle of open DLA file. :type handle: int :return: Descriptor of next segment in DLA file :rtype: spiceypy.utils.support_types.SpiceDLADescr
387,692
def extended_analog(self, pin, data): task = asyncio.ensure_future(self.core.extended_analog(pin, data)) self.loop.run_until_complete(task)
This method will send an extended-data analog write command to the selected pin.. :param pin: 0 - 127 :param data: 0 - 0-0x4000 (14 bits) :returns: No return value
387,693
def serialize_formula(formula): rPd(NH3)4+3H12N4Pd+3 charge = charge_from_formula(formula) element_dict = nested_formula_parser(formula) base = atoms_to_Hill(element_dict) if charge == 0: pass elif charge > 0: if charge == 1: base += else: base +...
r'''Basic formula serializer to construct a consistently-formatted formula. This is necessary for handling user-supplied formulas, which are not always well formatted. Performs no sanity checking that elements are actually elements. Parameters ---------- formula : str Formula strin...
387,694
def optional(validator): if isinstance(validator, list): return _OptionalValidator(_AndValidator(validator)) return _OptionalValidator(validator)
A validator that makes an attribute optional. An optional attribute is one which can be set to ``None`` in addition to satisfying the requirements of the sub-validator. :param validator: A validator (or a list of validators) that is used for non-``None`` values. :type validator: callable or :c...
387,695
def equivalent(kls, first, second): if first.empty() and second.empty(): return True elif first.vertices.shape[0] != second.vertices.shape[0]: return False elif first.edges.shape[0] != second.edges.shape[0]: return False EPSILON = 1e-7 vertex1, inv1 = np.unique(first.vertice...
Tests that two skeletons are the same in form not merely that their array contents are exactly the same. This test can be made more sophisticated.
387,696
def check_var_units(self, ds): results = [] for variable in self.get_applicable_variables(ds): msgs = [] unit_check = hasattr(ds.variables[variable], ) no_dim_check = (getattr(ds.variables[variable], ) == tuple()) if no_d...
Checks each applicable variable for the units attribute :param netCDF4.Dataset ds: An open netCDF dataset
387,697
def get_histogram_bins(min_, max_, std, count): width = _get_bin_width(std, count) count = int(round((max_ - min_) / width) + 1) if count: bins = [i * width + min_ for i in xrange(1, count + 1)] else: bins = [min_] return bins
Return optimal bins given the input parameters
387,698
def node_validate(node_dict, node_num, cmd_name): req_lu = {"run": ["stopped", "Already Running"], "stop": ["running", "Already Stopped"], "connect": ["running", "Can't Connect, Node Not Running"], "details": [node_dict[node_num].state, ""]} tm = {True: ("Node...
Validate that command can be performed on target node.
387,699
def NRMSE_sliding(data, pred, windowSize): halfWindowSize = int(round(float(windowSize)/2)) window_center = range(halfWindowSize, len(data)-halfWindowSize, int(round(float(halfWindowSize)/5.0))) nrmse = [] for wc in window_center: nrmse.append(NRMSE(data[wc-halfWindowSize:wc+halfWindowSize], ...
Computing NRMSE in a sliding window :param data: :param pred: :param windowSize: :return: (window_center, NRMSE)