Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
341,500
def handle(self, *args, **options): LOGGER.info() role = options[] if role == ENTERPRISE_ADMIN_ROLE: self._assign_enterprise_role_to_users(self._get_enterprise_admin_users_batch, options) elif role == ENTERPRISE_OPERATOR_ROLE: s...
Entry point for managment command execution.
341,501
def proj_to_cartopy(proj): import cartopy.crs as ccrs try: from osgeo import osr has_gdal = True except ImportError: has_gdal = False proj = check_crs(proj) if proj.is_latlong(): return ccrs.PlateCarree() srs = proj.srs if has_gdal: s...
Converts a pyproj.Proj to a cartopy.crs.Projection (Code copied from https://github.com/fmaussion/salem) Parameters ---------- proj: pyproj.Proj the projection to convert Returns ------- a cartopy.crs.Projection object
341,502
def _comparator_lt(filter_value, tested_value): if is_string(filter_value): value_type = type(tested_value) try: filter_value = value_type(filter_value) except (TypeError, ValueError): if value_type is int: try: ...
Tests if the filter value is strictly greater than the tested value tested_value < filter_value
341,503
def _bin_to_dec(ip, check=True): if check and not is_bin(ip): raise ValueError( % ip) if isinstance(ip, int): ip = str(ip) return int(str(ip), 2)
Binary to decimal conversion.
341,504
def traptransit_MCMC(ts,fs,dfs=1e-5,nwalkers=200,nburn=300,niter=1000, threads=1,p0=[0.1,0.1,3,0],return_sampler=False, maxslope=MAXSLOPE): model = TraptransitModel(ts,fs,dfs,maxslope=maxslope) sampler = emcee.EnsembleSampler(nwalkers,4,model,threads=threads) T...
Fit trapezoidal model to provided ts, fs, [dfs] using MCMC. Standard emcee usage.
341,505
def _get_syslog_format(event_type): syslog_format_template = get_template() fmt = syslog_format_template.render( event_type=event_type, host=dbconfig.get(, default=) ) return json.dumps(json.loads(fmt))
Take an event type argument and return a python logging format In order to properly format the syslog messages to current standard, load the template and perform necessary replacements and return the string. Args: event_type (str): Event type name Returns: `str`
341,506
def group_by(self, property): self.__prepare() group_data = {} for data in self._json_data: if data[property] not in group_data: group_data[data[property]] = [] group_data[data[property]].append(data) self._json_data = group_data ...
Getting the grouped result by the given property :@param property :@type property: string :@return self
341,507
def format_content_type_object(repo, content_type, uuid): try: storage_manager = StorageManager(repo) model_class = load_model_class(repo, content_type) return dict(storage_manager.get(model_class, uuid)) except GitCommandError: raise NotFound()
Return a content object from a repository for a given content_type and uuid :param Repo repo: The git repository. :param str content_type: The content type to list :returns: dict
341,508
def patch_namespace(self, name, body, **kwargs): kwargs[] = True if kwargs.get(): return self.patch_namespace_with_http_info(name, body, **kwargs) else: (data) = self.patch_namespace_with_http_info(name, body, **kwargs) return data
partially update the specified Namespace This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespace(name, body, async_req=True) >>> result = thread.get() :param async_req bool ...
341,509
def add_items(self, items, index_items): count_templates = 0 count_items = 0 generated_items = [] for item in items: if item.is_tpl(): self.add_template(item) count_templates = count_templates + 1 else: new_...
Add items to template if is template, else add in item list :param items: items list to add :type items: alignak.objects.item.Items :param index_items: Flag indicating if the items should be indexed on the fly. :type index_items: bool :return: None
341,510
def dlogpdf_dlink_dvar(self, link_f, y, Y_metadata=None): c = np.zeros_like(y) if Y_metadata is not None and in Y_metadata.keys(): c = Y_metadata[] val = np.log(y) - link_f val_scaled = val/np.sqrt(self.variance) val_scaled2 = val/self.variance a = ...
:param link_f: latent variables link(f) :type link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: Y_metadata not used in gaussian :returns: derivative of log likelihood evaluated at points link(f) w.r.t variance parameter :rtype: Nx1 array
341,511
def record_to_objects(self): from ambry.orm.exc import NotFoundError fr = self.record contents = fr.unpacked_contents if not contents: return non_empty_rows = drop_empty(contents) s = self._dataset._database.s...
Create config records to match the file metadata
341,512
def RunJob(self, job): if not job.leased_until: raise LockError("CronJob must be leased for Run() to be called.") if job.leased_until < rdfvalue.RDFDatetime.Now(): raise LockError("CronJob lease expired for %s." % job.cron_job_id) logging.info("Starting cron job: %s", job.cron_job_id) ...
Does the actual work of the Cron, if the job is due to run. Args: job: The cronjob rdfvalue that should be run. Must be leased. Returns: A boolean indicating if this cron job was started or not. False may be returned when the threadpool is already full. Raises: LockError: if the o...
341,513
def pymmh3_hash64(key: Union[bytes, bytearray], seed: int = 0, x64arch: bool = True) -> Tuple[int, int]: hash_128 = pymmh3_hash128(key, seed, x64arch) unsigned_val1 = hash_128 & 0xFFFFFFFFFFFFFFFF if unsigned_val1 & 0x8000000000000000 == 0: signed_val1 = ...
Implements 64bit murmur3 hash, as per ``pymmh3``. Returns a tuple. Args: key: data to hash seed: seed x64arch: is a 64-bit architecture available? Returns: tuple: tuple of integers, ``(signed_val1, signed_val2)``
341,514
def split_Text( text, file_name, verbose = True ): if verbose: print(+file_name+, end="" ) start = timer() text = text.tokenize_sentences() all_sentences = len(text[SENTENCES]) end = timer() if verbose: print(+format_time( end-start )+, end="" ) if all_sentences > max...
Tokenizes the *text* (from *file_name*) into sentences, and if the number of sentences exceeds *max_sentences*, splits the text into smaller texts. Returns a list containing the original text (if no splitting was required), or a list containing results of the splitting (smaller texts);
341,515
def on_step_begin(self, step, logs={}): for callback in self.callbacks: if callable(getattr(callback, , None)): callback.on_step_begin(step, logs=logs) else: callback.on_batch_begin(step, logs=logs)
Called at beginning of each step for each callback in callbackList
341,516
def augment_model_meta(model, db_alias, model_meta, column_name_filters=None, count=0, verbosity=0): if settings.DEBUG and verbosity > 2: print % model column_name_filters = util.listify(column_name_filters) queryset = djdb.get_queryset(model) if db_alias: queryset = queryset.usi...
Fields are keyed by their db_column name rather than field name (like model_meta)
341,517
def pipeRecvConsole(self): try: while True: console_msg = self.parent_pipe_recv_console.recv() if console_msg is not None: self.console.writeln(console_msg) time.sleep(0.1) except EOFError: pass
watch for piped data from save dialog
341,518
def select(data, trial=None, invert=False, **axes_to_select): if trial is not None and not isinstance(trial, Iterable): raise TypeError() for axis_to_select, values_to_select in axes_to_select.items(): if (not isinstance(values_to_select, Iterable) or isinstance(values_to_select...
Define the selection of trials, using ranges or actual values. Parameters ---------- data : instance of Data data to select from. trial : list of int or ndarray (dtype='i'), optional index of trials of interest **axes_to_select, optional Values need to be tuple or list. If t...
341,519
def _build_field_type_map(base_class): mapping = {} for cls in _get_recursive_subclasses(base_class): if cls.field_type: if isinstance(cls.field_type, tuple): for field_type in cls.field_type: mapping[field_type] = cls elif isinstance(cls...
Create mapping from all $type values to their respective Field classes
341,520
def get_word_break_property(value, is_bytes=False): obj = unidata.ascii_word_break if is_bytes else unidata.unicode_word_break if value.startswith(): negated = value[1:] value = + unidata.unicode_alias[].get(negated, negated) else: value = unidata.unicode_alias[].get(value, v...
Get `WORD BREAK` property.
341,521
def validate(self, table: pd.DataFrame, failed_only=False) -> pd.DataFrame: raise NotImplementedError("This method must be defined for each subclass.")
Return a dataframe of validation results for the appropriate series vs the vector of validators. Args: table (pd.DataFrame): A dataframe on which to apply validation logic. failed_only (bool): If ``True``: return only the indexes that failed to validate.
341,522
def _normalise_key_values(filter_obj, attr_map=None): new_filter = {} for key, constraints in filter_obj.items(): aliased_key = key if attr_map is not None: aliased_key = attr_map.get(key) if aliased_key is None: raise CloudValueError( ...
Converts nested dictionary filters into django-style key value pairs Map filter operators and aliases to operator-land Additionally, perform replacements according to attribute map Automatically assumes __eq if not explicitly defined
341,523
def get_package(self, name) -> : name, cls_name = parse_package_string(name) try: return self.package_map[name] except KeyError: raise EffectError("No package registered".format(name))
Get a package by python path. Can also contain path to an effect. Args: name (str): Path to effect package or effect Returns: The requested EffectPackage Raises: EffectError when no package is found
341,524
async def create_websocket_client(sock: anyio.abc.SocketStream, addr, path: str, headers: Optional[List] = None, subprotocols: Optional[List[str]] = None): ws = Websocket() ...
A more low-level form of create_websocket_client. You are responsible for closing this websocket.
341,525
def draw_on_image(self, image, color=(0, 255, 0), alpha=1.0, size=1, copy=True, raise_if_out_of_image=False, thickness=None): if thickness is not None: ia.warn_deprecated( "Usage of argument in BoundingBox.draw_on_image() " "is deprecat...
Draw the bounding box on an image. Parameters ---------- image : (H,W,C) ndarray(uint8) The image onto which to draw the bounding box. color : iterable of int, optional The color to use, corresponding to the channel layout of the image. Usually RGB. alp...
341,526
def chunks(seq, size=None, dfmt="f", byte_order=None, padval=0.): if size is None: size = chunks.size chunk = array.array(dfmt, xrange(size)) idx = 0 for el in seq: chunk[idx] = el idx += 1 if idx == size: yield chunk.tostring() idx = 0 if idx != 0: for idx in xrange(idx, ...
Chunk generator based on the array module (Python standard library). See chunk.struct for more help. This strategy uses array.array (random access by indexing management) instead of struct.Struct and blocks/deque (circular queue appending) from the chunks.struct strategy. Hint ---- Try each one to find th...
341,527
def mse(test, ref, mask=None): test, ref, mask = _preprocess_input(test, ref, mask) if mask is not None: test = mask * test ref = mask * ref return np.mean(np.square(test - ref))
Mean Squared Error (MSE) Calculate the MSE between a test image and a reference image. Parameters ---------- ref : np.ndarray the reference image test : np.ndarray the tested image mask : np.ndarray, optional the mask for the ROI Notes ----- Compute the met...
341,528
def attrs(self, attribute_name): desc = u.format(attribute_name) return self.map(lambda el: el.get_attribute(attribute_name), desc).results
Retrieve HTML attribute values from the elements matched by the query. Example usage: .. code:: python # Assume that the query matches html elements: # <div class="foo"> and <div class="bar"> >> q.attrs('class') ['foo', 'bar'] Args: ...
341,529
def download_files(files): for (url, file) in files: print("Downloading %s as %s" % (url, file)) data = download_url(url) if data is None: continue try: open(file, mode=).write(data) except Exception as e: print("Failed to save to %s :...
download an array of files
341,530
def register_widget(self, place=None, type=None, widget=None, filter=None, **kwargs): re mutually exclusive). :returns: created or given widget object :rtype: object register_widget takes either place and type or widget' ) widget = widget o...
Create (see :meth:`create_widget`) or use provided widget and register it. This method provides this dual behavior in order to simplify widget creation-registration on an functional single step without sacrifycing the reusability of a object-oriented approach. :param place: whe...
341,531
def add_elevations(self, gpx, only_missing=False, smooth=False, gpx_smooth_no=0): if only_missing: original_elevations = list(map(lambda point: point.elevation, gpx.walk(only_points=True))) if smooth: self._add_sampled_elevations(gpx) else: for point...
only_missing -- if True only points without elevation will get a SRTM value smooth -- if True interpolate between points if gpx_smooth_no > 0 -- execute gpx.smooth(vertical=True)
341,532
def calc_et0_wet0_v1(self): con = self.parameters.control.fastaccess inp = self.sequences.inputs.fastaccess flu = self.sequences.fluxes.fastaccess log = self.sequences.logs.fastaccess for k in range(con.nhru): flu.et0[k] = (con.wfet0[k]*con.ke[k]*inp.pet + (1.-con....
Correct the given reference evapotranspiration and update the corresponding log sequence. Required control parameters: |NHRU| |KE| |WfET0| Required input sequence: |PET| Calculated flux sequence: |ET0| Updated log sequence: |WET0| Basic equations: :...
341,533
def detect_chip(port=DEFAULT_PORT, baud=ESP_ROM_BAUD, connect_mode=, trace_enabled=False): detect_port = ESPLoader(port, baud, trace_enabled=trace_enabled) detect_port.connect(connect_mode) try: print(, end=) sys.stdout.flush() date_reg = detect_port....
Use serial access to detect the chip type. We use the UART's datecode register for this, it's mapped at the same address on ESP8266 & ESP32 so we can use one memory read and compare to the datecode register for each chip type. This routine automatically performs ESPLoader.conne...
341,534
def _api_all_limits(self): response.content_type = try: limits = json.dumps(self.stats.getAllLimitsAsDict()) except Exception as e: abort(404, "Cannot get limits (%s)" % (str(e))) return limits
Glances API RESTful implementation. Return the JSON representation of all the plugins limits HTTP/200 if OK HTTP/400 if plugin is not found HTTP/404 if others error
341,535
def _done_handler(self, task): try: task.result() except asyncio.CancelledError: pass except Exception as err: try: if self._sm_enabled: self._xmlstream.abort() else: ...
Called when the main task (:meth:`_run`, :attr:`_task`) returns.
341,536
def extract_job_build_url(url_string): global g_failed_test_info_dict global g_jenkins_url global g_view_name tempString = url_string.strip().split() if len(tempString) < 6: print "Illegal URL resource address.\n" sys.exit(1) g_failed_test_info_dict["1.jobName...
From user input, grab the jenkins job name and saved it in g_failed_test_info_dict. In addition, it will grab the jenkins url and the view name into g_jenkins_url, and g_view_name. Parameters ---------- url_string : str contains information on the jenkins job whose console output we are in...
341,537
def step(self, action): total_reward = 0.0 done = None for i in range(self._skip): obs, reward, done, info = self.env.step(action) if i == self._skip - 2: self._obs_buffer[0] = obs if i == self._skip - 1: self._obs_buffer[1] = obs total_reward += reward if ...
Repeat action, sum reward, and max over last observations.
341,538
def update_cnt(uid, post_data): entry = TabPost.update( cnt_html=tools.markdown2html(post_data[]), user_name=post_data[], cnt_md=tornado.escape.xhtml_escape(post_data[].strip()), time_update=tools.timestamp() ).where(TabPost.uid == uid) e...
update content.
341,539
def clone(cls, repo_url, dest, binary=): cmd = [binary, , repo_url, dest] process, out = cls._invoke(cmd) cls._check_result(cmd, process.returncode) return cls(binary=binary, worktree=dest)
Clone the repo at repo_url into dest. :param string binary: The path to the git binary to use, 'git' by default. :returns: an instance of this class representing the cloned repo. :rtype: Git
341,540
def split_first(s, delims): min_idx = None min_delim = None for d in delims: idx = s.find(d) if idx < 0: continue if min_idx is None or idx < min_idx: min_idx = idx min_delim = d if min_idx is None or min_idx < 0: return s, , Non...
Given a string and an iterable of delimiters, split on the first found delimiter. Return two split parts and the matched delimiter. If not found, then the first part is the full input string. Example:: >>> split_first('foo/bar?baz', '?/=') ('foo', 'bar?baz', '/') >>> split_first('...
341,541
def insert(collection_name, docs, check_keys, safe, last_error_args, continue_on_error, opts): options = 0 if continue_on_error: options += 1 data = struct.pack("<i", options) data += bson._make_c_string(collection_name) encoded = [bson.BSON.encode(doc, check_keys, opts) for ...
Get an **insert** message.
341,542
def calculate_hash_of_dir(directory, file_list=None): md5_hash = md5() if not os.path.exists(directory): return -1 try: for subdir, dirs, files in os.walk(directory): for _file in files: file_path = os.path.join(subdir, _file) if file_list is...
Calculate hash of directory.
341,543
def add_set(self): self.__label_counter += 1 new_label = self.__label_counter self.__forest[new_label] = -1 self.__set_counter += 1 return new_label
Adds a new set to the forest. Returns a label by which the new set can be referenced
341,544
def _reduce_boolean_pair(self, config_dict, key1, key2): if key1 in config_dict and key2 in config_dict \ and config_dict[key1] == config_dict[key2]: msg = \ \ \ % (key1, key2, config_dict[key1]) raise BooleansT...
Ensure only one key with a boolean value is present in dict. :param config_dict: dict -- dictionary of config or kwargs :param key1: string -- first key name :param key2: string -- second key name :raises: BooleansToReduceHaveSameValue
341,545
def capture(context, callable_, *args, **kwargs): if not compat.callable(callable_): raise exceptions.RuntimeException( "capture() function expects a callable as " "its argument (i.e. capture(func, *args, **kwargs))" ) context...
Execute the given template def, capturing the output into a buffer. See the example in :ref:`namespaces_python_modules`.
341,546
def init_logging(settings): lg_format = lg_dateformat = logging.basicConfig(format=lg_format, datefmt=lg_dateformat) log = get_logger() handler = logging.handlers.WatchedFileHandler( filename=settings[] \ if in settings.keys() else No...
Set up logger
341,547
def set_global_log_level(level): for logger in _loggers: logger._set_log_level(level) global _log_level _log_level = level
Set the global log level on all loggers instantiated by txaio.
341,548
def get_output_files(self): output_files = list(self.__output_files) if isinstance(self.job(), CondorDAGJob): output_files = output_files + self.job().get_output_files() return output_files
Return list of output files for this DAG node and its job.
341,549
def upload(self, num_iid, properties, session, id=None, image=None, position=None): request = TOPRequest() request[] = num_iid request[] = properties if id!=None: request[] = id if position!=None: request[] = position if image!=None: ...
taobao.item.propimg.upload 添加或修改属性图片 添加一张商品属性图片到num_iid指定的商品中 传入的num_iid所对应的商品必须属于当前会话的用户 图片的属性必须要是颜色的属性,这个在前台显示的时候需要和sku进行关联的 商品属性图片只有享有服务的卖家(如:淘宝大卖家、订购了淘宝多图服务的卖家)才能上传 商品属性图片有数量和大小上的限制,最多不能超过24张(每个颜色属性都有一张)。
341,550
def decorate_callable(self, callable_): @wraps(callable_) def decorated(*args, **kwargs): timeout = kwargs.get() return self.call_in_ioloop(callable_, args, kwargs, timeout) decorated.__doc__ = .join(( , textwrap.dedent(decorated.__doc__...
Decorate a callable to use call_in_ioloop
341,551
def cancelar_ultima_venda(self, chave_cfe, dados_cancelamento): cfe_canc = dados_cancelamento \ if isinstance(dados_cancelamento, basestring) \ else dados_cancelamento.documento() return self.invocar__CancelarUltimaVenda( self.gerar_numero_sessao...
Função ``CancelarUltimaVenda`` conforme ER SAT, item 6.1.4. Envia o CF-e de cancelamento para o equipamento SAT, que o enviará para autorização e cancelamento do CF-e pela SEFAZ. :param chave_cfe: String contendo a chave do CF-e a ser cancelado, prefixada com o literal ``CFe``. ...
341,552
def execute_all(self): for workflow_id in self.workflows: if self.workflows[workflow_id].online: for interval in self.workflows[workflow_id].requested_intervals: logging.info("Executing workflow {} over interval {}".format(workflow_id, interval)) ...
Execute all workflows
341,553
def convert_for_mw(s, locale, update=None): ch = [] rules = [] ruledict = update.copy() if update else {} nested = 0 block = for frag in RE_langconv.split(s): if frag == : nested += 1 block += frag elif frag == : if not nested: ...
Recognizes MediaWiki's human conversion format. Use locale='zh' for no conversion. Reference: (all tests passed) https://zh.wikipedia.org/wiki/Help:高级字词转换语法 https://www.mediawiki.org/wiki/Writing_systems/Syntax >>> print(convert_for_mw('在现代,机械计算-{}-机的应用已经完全被电子计算-{}-机所取代', 'zh-hk')) 在現代,機械計算機的應...
341,554
def login_user(self, request): user = auth.authenticate(identity=self.identity, provider=self.provider) if user and settings.ACTIVATION_REQUIRED and not user.is_active: messages.add_message(request, messages.ERROR, lang.NOT_ACTIVATED) return redirect(settings.AC...
Try to login user by net identity. Do nothing in case of failure.
341,555
def read_uint16(self, little_endian=True): if little_endian: endian = "<" else: endian = ">" return self.unpack( % endian, 2)
Read 2 byte as an unsigned integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int:
341,556
def generate_guids(root): from hashlib import md5 needs_id = { : , : , : , } for (key,value) in needs_id.items(): node_list = root.getElementsByTagName(key) attribute = value for node in node_list: ...
generates globally unique identifiers for parts of the xml which need them. Component tags have a special requirement. Their UUID is only allowed to change if the list of their contained resources has changed. This allows for clean removal and proper updates. To handle this requirement, the uuid i...
341,557
def log_finished(self): delta = time.perf_counter() - self.start_time logger.log("Finished after ", logger.magenta(time_to_text(delta)))
Log that this task is done.
341,558
def mouseDragEvent(self, ev, axis=None): if self._customMouse and ev.button() == QtCore.Qt.RightButton: ev.accept() if ev.isFinish(): pos = ev.pos() self.rbScaleBox.hide() ax = Q...
Customized mouse dragging, where the right drag is bounding box zoom :param ev: event object containing drag state info :type ev: :py:class:`MouseDragEvent<pyqtgraph:pyqtgraph.GraphicsScene.mouseEvents.MouseDragEvent>`
341,559
def json_integrity_multilevel(d1, d2): keys = [x for x in d2] for key in keys: d1_keys = set(d1.keys()) d2_keys = set(d2.keys()) intersect_keys = d1_keys.intersection(d2_keys) added = d1_keys - d2_keys removed = d2_keys - d1_keys modified = {o : (d1[o], d2[o]...
still under development
341,560
def assertFileSizeAlmostEqual( self, filename, size, places=None, msg=None, delta=None): fsize = self._get_file_size(filename) self.assertAlmostEqual( fsize, size, places=places, msg=msg, delta=delta)
Fail if ``filename`` does not have the given ``size`` as determined by their difference rounded to the given number of decimal ``places`` (default 7) and comparing to zero, or if their difference is greater than a given ``delta``. Parameters ---------- filename : str, by...
341,561
def sendMessage(self, to, message, extra={}): to = to if isinstance(to, list) else [to] to = [str(num) for num in to] data = {: to, : message} data = self.merge(data, {: 7, : 1}, extra) content = self.parseRest(self.request(, data, {}, )); result = [] ...
If the 'to' parameter is a single entry, we will parse it into a list. We will merge default values into the request data and the extra parameters provided by the user.
341,562
def done(item, done_type=None, max_tries=None, ttl=None): if done_type is None or done_type == _c.FSQ_SUCCESS: return success(item) return fail(item, fail_type=done_type, max_tries=max_tries, ttl=ttl)
Wrapper for any type of finish, successful, permanant failure or temporary failure
341,563
def changeable(self, request): s instance set ' return self.apply_changeable(self.get_queryset(), request) if self.check_changeable(self.model, request) is not False else self.get_queryset().none()
Checks the both, check_changeable and apply_changeable, against the owned model and it's instance set
341,564
def set_exception(self, exception): assert isinstance(exception, Exception), \ "%r should be an Exception" % exception self._exception = exception self._state = self.FINISHED
Sets the result of the future as being the given exception. Should only be used by Task and unit tests.
341,565
def compare_filesystems(fs0, fs1, concurrent=False): if concurrent: future0 = concurrent_hash_filesystem(fs0) future1 = concurrent_hash_filesystem(fs1) files0 = future0.result() files1 = future1.result() else: files0 = hash_filesystem(fs0) files1 = hash_file...
Compares the two given filesystems. fs0 and fs1 are two mounted GuestFS instances containing the two disks to be compared. If the concurrent flag is True, two processes will be used speeding up the comparison on multiple CPUs. Returns a dictionary containing files created, removed and modified. ...
341,566
def _remove_localizers_by_orientation(dicoms): orientations = [] sorted_dicoms = {} for dicom_header in dicoms: image_orient1 = numpy.array(dicom_header.ImageOrientationPatient)[0:3] image_orient2 = numpy.array(dicom_header.ImageOrientationPatient)[3:6] image_orien...
Removing localizers based on the orientation. This is needed as in some cases with ct data there are some localizer/projection type images that cannot be distiguished by the dicom headers. This is why we kick out all orientations that do not have more than 4 files 4 is the limit anyway for converting to nif...
341,567
def passes_filter(self, user): cls = type(self.condition) qs = cls.objects.filter(pk=self.condition.id) return self.condition in self.pre_filter(qs, user)
Returns true if the condition passes the filter
341,568
def update_session(fname=None): if fname is None: fname = conf.session try: s = six.moves.cPickle.load(gzip.open(fname, "rb")) except IOError: s = six.moves.cPickle.load(open(fname, "rb")) scapy_session = six.moves.builtins.__dict__["scapy_session"] scapy_session.update(...
Update current Scapy session from the file specified in the fname arg. params: - fname: file to load the scapy session from
341,569
def discands(record): import pyfits pyraf.iraf.images() pyraf.iraf.images.tv() display = pyraf.iraf.images.tv.display width=128 cands = record[] exps= record[] comments= record[] headers={} for exp in exps: f = pyfits.open(exp+".fits") heade...
Display the candidates contained in a candidate record list
341,570
def _delete_forever_keys(self): for segment in self._tags.get_namespace().split(): segment = self._forever_key(segment) self._delete_forever_values(segment) self._store.connection().delete(segment)
Delete all of the items that were stored forever.
341,571
def get_name_history_page(name, page, hostport=None, proxy=None): assert hostport or proxy, if proxy is None: proxy = connect_hostport(hostport) name_required = [, , , ] subdomain_required = [] required = None if check_subdomain(name): log.debug(.format(name)) requ...
Get a page of the name's history Returns {'status': True, 'history': ..., 'indexing': ..., 'lastblock': ...} on success Returns {'error': ...} on error
341,572
def search_star_cluster(cluster): base_url = "http://star-api.herokuapp.com/api/v1/open_cluster/" if not isinstance(cluster, str): raise ValueError("The cluster arg you provided is not the type of str") else: base_url += cluster return dispatch_http_get(base_url)
It is also possible to query the star clusters by label, here is an example of querying for the star cluster labeled Berkeley 59 http://star-api.herokuapp.com/api/v1/open_cluster/Berkeley 59
341,573
def consume(self, f): @self.hub.spawn def _(): for item in self: try: f(item) except vanilla.exception.Halt: self.close() break
Creates a sink which consumes all values for this Recver. *f* is a callable which takes a single argument. All values sent on this Recver's Sender will be passed to *f* for processing. Unlike *map* however consume terminates this chain:: sender, recver = h.pipe @recver....
341,574
def compute_verdict(self, results): if results[] in self.reject_classes: threshold = self.reject_classes[results[]] if float(results[]) >= threshold: logger.debug( .format(self.id, results)) ...
Match results to the configured reject, quarantine and accept classes, and return a verdict based on that. The verdict classes are matched in the order: reject_classes, quarantine_classes, accept_classes. This means that you can configure different verdicts for different confidence resu...
341,575
def reload_modules(self): old_modules = set(self.loaded_modules) for module in self.loaded_modules.itervalues(): module.stop(reloading=True) self.loaded_modules = {} self.module_ordering = [] try: modules_to_load = sorted(self.config.items("modu...
(Re)load all of the configured modules. 1. Calls stop(reloading=True) on each loaded module 2. Clears .loaded_modules and .module_ordering 3. Loads each module specified in the config 4. Calls start() on each loaded module, with reloading set depending on whether the module w...
341,576
def __package_dependencies(dist_dir, additional_reqs, silent): logging.info() libs_dir = os.path.join(dist_dir, ) if not os.path.isdir(libs_dir): os.mkdir(libs_dir) req_txt = os.path.join(os.path.dirname(os.path.abspath(__file__)), ) with open(req_txt, ) as req: requiremen...
Installs the app's dependencies from pip and packages them (as zip), to be submitted to spark. Parameters ---------- dist_dir (str): Path to directory where the packaged libs shall be located additional_reqs (str): Path to a requirements.txt, containing any of the app's additional requirements ...
341,577
def set_or_reset_runtime_param(self, key, value): if self._runtime.has_option(, key): self._runtime = self._new_parser() if value is None: return settings._runtime.set(, key.replace(, ), six.text_type(value))
Maintains the context of the runtime settings for invoking a command. This should be called by a click.option callback, and only called once for each setting for each command invocation. If the setting exists, it follows that the runtime settings are stale, so the entire runtim...
341,578
def _read_bin(self, stream, byte_order): try: return _read_array(stream, self.dtype(byte_order), 1)[0] except IndexError: raise StopIteration
Read data from a binary stream. Raise StopIteration if the property could not be read.
341,579
def get_subgraphs_by_citation(graph): rv = defaultdict(graph.fresh_copy) for u, v, key, data in graph.edges(keys=True, data=True): if CITATION not in data: continue dk = data[CITATION][CITATION_TYPE], data[CITATION][CITATION_REFERENCE] rv[dk].add_edge(u, v, key=key, **...
Stratify the graph based on citations. :type graph: pybel.BELGraph :rtype: dict[tuple[str,str],pybel.BELGraph]
341,580
def on_change_specimen_mouse_cursor(self, event): if not self.specimen_EA_xdata or not self.specimen_EA_ydata: return pos = event.GetPosition() width, height = self.canvas2.get_width_height() pos[1] = height - pos[1] xpick_data, ypick_data = pos xdata...
If mouse is over data point making it selectable change the shape of the cursor Parameters ---------- event : the wx Mouseevent for that click
341,581
def list_song_standby(self, song, onlyone=True): def get_score(standby): score = 1 if song.artists_name != standby.artists_name: score -= 0.4 if song.title != standby.title: score -= 0.3 ...
try to list all valid standby Search a song in all providers. The typical usage scenario is when a song is not available in one provider, we can try to acquire it from other providers. Standby choosing strategy: search from all providers, select two song from each provide. Thos...
341,582
def insert_on_duplicate(tablename: str, values: Any = None, inline: bool = False, **kwargs): return InsertOnDuplicate(tablename, values, inline=inline, **kwargs)
Command to produce an :class:`InsertOnDuplicate` object. Args: tablename: name of the table values: values to ``INSERT`` inline: as per http://docs.sqlalchemy.org/en/latest/core/dml.html#sqlalchemy.sql.expression.insert kwargs: additional parameters Returns: ...
341,583
def is_point_in_rect(self, pt_x, pt_y): x_min, x_max, y_min, y_max = self.get_bbox() return x_min <= pt_x <= x_max and y_min <= pt_y <= y_max
Returns True iif point is inside the rectangle (border included) Parameters ---------- * pt_x: Number \tx-value of point * pt_y: Number \ty-value of point
341,584
def __vector_to_string(self, vector): return numpy.array_str(numpy.round(unitvec(vector), decimals=3))
Returns string representation of vector.
341,585
def get_component(self, component_type): matching_components = list(filter(lambda component: isinstance(component, component_type), self._components)) if matc...
Gets component of component_type or returns None
341,586
def display_annotations(self): for item in self.idx_annot: self.scene.removeItem(item) self.idx_annot = [] for item in self.idx_annot_labels: self.scene.removeItem(item) self.idx_annot_labels = [] self.highlight = None window_start = self...
Mark all the bookmarks/events, on top of first plot.
341,587
def _update_belief(self, belief_prop, clique, clique_potential, message=None): old_factor = belief_prop.junction_tree.get_factors(clique) belief_prop.junction_tree.remove_factors(old_factor) if message: if message.scope() and clique_potential.scope(): new_fac...
Method for updating the belief. Parameters: ---------- belief_prop: Belief Propagation Belief Propagation which needs to be updated. in_clique: clique The factor which needs to be updated corresponding to the input clique. out_clique_potential: factor ...
341,588
def _get_valid_stan_args(base_args=None): args = base_args.copy() if base_args is not None else {} args[] = args.get(, 1) args[] = args.get(, False) if args.get() is None or args[] == "sampling": args[] = stan_args_method_t.SAMPLING elif args[] == "optim": args[] ...
Fill in default values for arguments not provided in `base_args`. RStan does this in C++ in stan_args.hpp in the stan_args constructor. It seems easier to deal with here in Python.
341,589
def call(conn=None, call=None, kwargs=None): if call == : raise SaltCloudSystemExit( ) if not in kwargs: raise SaltCloudSystemExit( ) if conn is None: conn = get_conn() func = kwargs.pop() for key, value in kwarg...
Call function from shade. func function to call from shade.openstackcloud library CLI Example .. code-block:: bash salt-cloud -f call myopenstack func=list_images t sujksalt-cloud -f call myopenstack func=create_network name=mysubnet
341,590
def filter_attribute_value_assertions(ava, attribute_restrictions=None): if not attribute_restrictions: return ava for attr, vals in list(ava.items()): _attr = attr.lower() try: _rests = attribute_restrictions[_attr] except KeyError: del ava[attr] ...
Will weed out attribute values and values according to the rules defined in the attribute restrictions. If filtering results in an attribute without values, then the attribute is removed from the assertion. :param ava: The incoming attribute value assertion (dictionary) :param attribute_restriction...
341,591
def build_table(self, data, key_columns=(,), parameter_columns=([, , ], [, , ]), value_columns=None) -> LookupTable: return self._lookup_table_manager.build_table(data, key_columns, parameter_columns, value_col...
Construct a LookupTable from input data. If data is a ``pandas.DataFrame``, an interpolation function of the specified order will be calculated for each permutation of the set of key_columns. The columns in parameter_columns will be used as parameters for the interpolation functions whi...
341,592
def get_writer_position(self, name): cursor = self.cursor cursor.execute( , (name,)) result = cursor.fetchone() return result[0] if result else 0
Get the current writer position
341,593
def value(self): try: data = self.column.get_data(self.datum) if data is None: if callable(self.column.empty_value): data = self.column.empty_value(self.datum) else: data = self.column.empty_value ex...
Returns a formatted version of the data for final output. This takes into consideration the :attr:`~horizon.tables.Column.link`` and :attr:`~horizon.tables.Column.empty_value` attributes.
341,594
def join_phonemes(*args): if len(args) == 1: args = args[0] if len(args) == 2: args += (CODAS[0],) try: onset, nucleus, coda = args except ValueError: raise TypeError() offset = ( (ONSETS.index(onset) * NUM_NUCLEUSES + NUCLEUSES.index(nucleu...
Joins a Hangul letter from Korean phonemes.
341,595
def exact_ratio(x): try: try: return x.numerator, x.denominator except AttributeError: try: return x.as_integer_ratio() except AttributeError: try: return decimal_t...
Convert Real number x exactly to (numerator, denominator) pair. x is expected to be an int, Fraction, Decimal or float.
341,596
def get_real_time_locate(ipAddress, auth, url): real_time_locate_url = "/imcrs/res/access/realtimeLocate?type=2&value=" + str(ipAddress) + "&total=false" f_url = url + real_time_locate_url r = requests.get(f_url, auth=auth, headers=HEADERS) try: if r.status_code == 200: respon...
function takes the ipAddress of a specific host and issues a RESTFUL call to get the device and interface that the target host is currently connected to. Note: Although intended to return a single location, Multiple locations may be returned for a single host due to a partially discovered network or misconfigur...
341,597
def append(self, first, count): self.__range.append(IdRange(first, count))
Add to the set a range of count consecutive ids starting at id first.
341,598
def match_window(in_data, offset): window_start = max(offset - WINDOW_MASK, 0) for n in range(MAX_LEN, THRESHOLD-1, -1): window_end = min(offset + n, len(in_data)) if window_end - offset < THRESHOLD: return None str_to_find = in_data[offset:window_end] ...
Find the longest match for the string starting at offset in the preceeding data
341,599
def sbo_version(self, repo, find): ver = "" if repo == "sbo": ver = "-" + SBoGrep(find).version() return ver
Add version to SBo packages