Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
359,100
def mme_nodes(mme_base_url, token): nodes = [] if not mme_base_url or not token: return nodes url = .join([mme_base_url, ]) nodes = matchmaker_request(url=url, token=token, method=) LOG.info(.format(nodes)) return nodes
Return the available MatchMaker nodes Args: mme_base_url(str): base URL of MME service token(str): MME server authorization token Returns: nodes(list): a list of node disctionaries
359,101
def _to_json(uniq): result_json = {} depth, ipix = utils.uniq2orderipix(uniq) min_depth = np.min(depth[0]) max_depth = np.max(depth[-1]) for d in range(min_depth, max_depth+1): pix_index = np.where(depth == d)[0] if pix_index.size: ...
Serializes a MOC to the JSON format. Parameters ---------- uniq : `~numpy.ndarray` The array of HEALPix cells representing the MOC to serialize. Returns ------- result_json : {str : [int]} A dictionary of HEALPix cell lists indexed by their depth...
359,102
def pad_to_aspect_ratio(self, aspect_ratio, mode="constant", cval=0.0, return_pad_amounts=False): arr_padded, pad_amounts = ia.pad_to_aspect_ratio(self.arr, aspect_ratio=aspect_ratio, mode=mode, cval=cval, return_pad_amounts=True) segmap ...
Pad the segmentation map on its sides so that its matches a target aspect ratio. Depending on which dimension is smaller (height or width), only the corresponding sides (left/right or top/bottom) will be padded. In each case, both of the sides will be padded equally. Parameters ...
359,103
def eight_schools_joint_log_prob( treatment_effects, treatment_stddevs, avg_effect, avg_stddev, school_effects_standard): rv_avg_effect = tfd.Normal(loc=0., scale=10.) rv_avg_stddev = tfd.Normal(loc=5., scale=1.) rv_school_effects_standard = mvn( loc=tf.zeros_like(school_effects_standard), ...
Eight-schools joint log-prob.
359,104
def _float_oper(op1, op2=None): output = [] op = op2 if op2 is not None else op1 indirect = (op[0] == ) if indirect: op = op[1:] if is_float(op): op = float(op) if indirect: op = int(op) & 0xFFFF output.append( % op) output.append()...
Returns pop sequence for floating point operands 1st operand in A DE BC, 2nd operand remains in the stack Unlike 8bit and 16bit version, this does not supports operands inversion. Since many of the instructions are implemented as functions, they must support this. However, if 1st operand is a numb...
359,105
def update_extent(self, extent): if not self._initialized: raise pycdlibexception.PyCdlibInternalError() self.bl_cont_area = extent
Update the extent for this CE record. Parameters: extent - The new extent for this CE record. Returns: Nothing.
359,106
def _load_from_file_object(self, f): subtoken_strings = [] for line in f: s = line.strip() (s.startswith("\"") and s.endswith("\""))): s = s[1:-1] subtoken_strings.append(native_to_unicode(s)) self._init_subtokens_from_list(subtoken_strings) self._init_alphabet_...
Load from a file object. Args: f: File object to load vocabulary from
359,107
def _from_base_type(self, value): if not value: return None try: credentials = client.Credentials.new_from_json(value) except ValueError: credentials = None return credentials
Converts our stored JSON string back to the desired type. Args: value: A value from the datastore to be converted to the desired type. Returns: A deserialized Credentials (or subclass) object, else None if the value can't be parsed.
359,108
def convex_conj(self): conj_exp = conj_exponent(self.pointwise_norm.exponent) return GroupL1Norm(self.domain, exponent=conj_exp)
Convex conjugate functional of IndicatorLpUnitBall. Returns ------- convex_conj : GroupL1Norm The convex conjugate is the the group L1-norm.
359,109
def read(self): logging.debug(.format(x=self)) request_url = self._artifactory.drive + .format(uri=self._uri, x=self) r = self._session.get( request_url, auth=self._auth, ) if 404 == r.status_code or 400 == r.status_code: logging.debug...
Read object from artifactory. Fill object if exist :return: True if object exist, False else
359,110
def _assert_all_loadable_terms_specialized_to(self, domain): for term in self.graph.node: if isinstance(term, LoadableTerm): assert term.domain is domain
Make sure that we've specialized all loadable terms in the graph.
359,111
def calculate(self, **state): T = state[] x = state[] x_total = sum(x.values()) x = {compound: x[compound]/x_total for compound in x.keys()} xg = x.get(, .00) + x.get(, 0.0) xm = x.get(, 0.0) + x.get(, 0.0) + x.get(, 0.0) + \ x.get(, 0.0) ...
Calculate dynamic viscosity at the specified temperature and composition: :param T: [K] temperature :param x: [mole fraction] composition dictionary , e.g. \ {'SiO2': 0.25, 'CaO': 0.25, 'MgO': 0.25, 'FeO': 0.25} :returns: [Pa.s] dynamic viscosity The **state parameter ...
359,112
def get_catalog_hierarchy_design_session(self, proxy): if not self.supports_catalog_hierarchy_design(): raise errors.Unimplemented() return sessions.CatalogHierarchyDesignSession(proxy=proxy, runtime=self._runtime)
Gets the catalog hierarchy design session. arg: proxy (osid.proxy.Proxy): proxy return: (osid.cataloging.CatalogHierarchyDesignSession) - a ``CatalogHierarchyDesignSession`` raise: NullArgument - ``proxy`` is null raise: OperationFailed - unable to complete request ...
359,113
def ip_address(self, container: Container ) -> Union[IPv4Address, IPv6Address]: r = self.__api.get(.format(container.uid)) if r.status_code == 200: return r.json() self.__api.handle_erroneous_response(r)
The IP address used by a given container, or None if no IP address has been assigned to that container.
359,114
def just_load_srno(srno, prm_filename=None): from cellpy import dbreader, filefinder print("just_load_srno: srno: %i" % srno) print("just_load_srno: making class and setting prms") d = CellpyData() print() print("just_load_srno: starting to load reader") ...
Simply load an dataset based on serial number (srno). This convenience function reads a dataset based on a serial number. This serial number (srno) must then be defined in your database. It is mainly used to check that things are set up correctly. Args: prm_filename: name of parameter file (op...
359,115
def force_to_string(unknown): result = if type(unknown) is str: result = unknown if type(unknown) is int: result = str(unknown) if type(unknown) is float: result = str(unknown) if type(unknown) is dict: result = Dict2String(unknown) if type(unknown) is list:...
converts and unknown type to string for display purposes.
359,116
def get_internal_registry_ip(): with conu.backend.origin.backend.OpenshiftBackend() as origin_backend: services = origin_backend.list_services() for service in services: if service.name == : logger.debug("Internal docker-registry IP: %s", ...
Search for `docker-registry` IP :return: str, ip address
359,117
def _comports(): return (pd.DataFrame(list(map(list, serial.tools.list_ports.comports())), columns=[, , ]) .set_index())
Returns ------- pandas.DataFrame Table containing descriptor, and hardware ID of each available COM port, indexed by port (e.g., "COM4").
359,118
def emitDataChanged(self, regItem): leftIndex = self.indexFromItem(regItem, col=0) rightIndex = self.indexFromItem(regItem, col=-1) logger.debug("Data changed: {} ...{}".format(self.data(leftIndex), self.data(rightIndex))) self.dataChanged.emit(leftIndex, rightIndex)
Emits the dataChagned signal for the regItem
359,119
def find_console_handler(logger): for handler in logger.handlers: if (isinstance(handler, logging.StreamHandler) and handler.stream == sys.stderr): return handler
Return a stream handler, if it exists.
359,120
def list_groups(self, scope_descriptor=None, subject_types=None, continuation_token=None): query_parameters = {} if scope_descriptor is not None: query_parameters[] = self._serialize.query(, scope_descriptor, ) if subject_types is not None: subject_types = ",".jo...
ListGroups. [Preview API] Gets a list of all groups in the current scope (usually organization or account). :param str scope_descriptor: Specify a non-default scope (collection, project) to search for groups. :param [str] subject_types: A comma separated list of user subject subtypes to reduce t...
359,121
def get_preferred_submodules(): modules_path = get_conf_path() modules_db = PickleShareDB(modules_path) if in modules_db: return modules_db[] submodules = [] for m in PREFERRED_MODULES: submods = get_submodules(m) submodules += submods ...
Get all submodules of the main scientific modules and others of our interest
359,122
def hashi(self, key, replica=0): dh = self._listbytes(md5(str(key).encode()).digest()) rd = replica * 4 return ( (dh[3 + rd] << 24) | (dh[2 + rd] << 16) | (dh[1 + rd] << 8) | dh[0 + rd])
Returns a ketama compatible hash from the given key.
359,123
def get_by_name(self, name): for p in self.project_list: if p.nme == name: return p return None
returns an object Project which matches name
359,124
def set(self, name, valu): byts = s_msgpack.en(valu) lkey = self.pref + name.encode() self.slab.put(lkey, byts, db=self.db) self.info[name] = valu
Set a name in the SlabDict. Args: name (str): The key name. valu (obj): A msgpack compatible value. Returns: None
359,125
def process_link(self, env, refnode, has_explicit_title, title, target): result = super(DotNetXRefRole, self).process_link(env, refnode, has_explicit_title, title, target) (title,...
This handles some special cases for reference links in .NET First, the standard Sphinx reference syntax of ``:ref:`Title<Link>```, where a reference to ``Link`` is created with title ``Title``, causes problems for the generic .NET syntax of ``:dn:cls:`FooBar<T>```. So, here we assume th...
359,126
def build_eval_session(module_spec, class_count): eval_graph, bottleneck_tensor, resized_input_tensor, wants_quantization = ( create_module_graph(module_spec)) eval_sess = tf.Session(graph=eval_graph) with eval_graph.as_default(): (_, _, bottleneck_input, ground_truth_input, final_tenso...
Builds an restored eval session without train operations for exporting. Args: module_spec: The hub.ModuleSpec for the image module being used. class_count: Number of classes Returns: Eval session containing the restored eval graph. The bottleneck input, ground truth, eval step, and prediction tens...
359,127
def arma2psd(A=None, B=None, rho=1., T=1., NFFT=4096, sides=, norm=False): r if NFFT is None: NFFT = 4096 if A is None and B is None: raise ValueError("Either AR or MA model must be provided") psd = np.zeros(NFFT, dtype=complex) if A is not None: ip = len(A) ...
r"""Computes power spectral density given ARMA values. This function computes the power spectral density values given the ARMA parameters of an ARMA model. It assumes that the driving sequence is a white noise process of zero mean and variance :math:`\rho_w`. The sampling frequency and noise variance a...
359,128
def compute(self, xt1, yt1, xt, yt, theta1t1, theta2t1, theta1, theta2): dx = xt - xt1 dy = yt - yt1 if self.numPoints < self.maxPoints: self.dxValues[self.numPoints,0] = dx self.dxValues[self.numPoints,1] = dy self.thetaValues[self.numPoints,0] = theta1 self.thetaValues[self....
Accumulate the various inputs.
359,129
def set_gid(self): if self.group: gid = getgrnam(self.group).gr_gid try: os.setgid(gid) except Exception: message = ("Unable to switch ownership to {0}:{1}. " + "Did you start the daemon as root?") ...
Change the group of the running process
359,130
def show_fabric_trunk_info_output_show_trunk_list_trunk_list_groups_trunk_list_member_trunk_list_src_interface(self, **kwargs): config = ET.Element("config") show_fabric_trunk_info = ET.Element("show_fabric_trunk_info") config = show_fabric_trunk_info output = ET.SubElement(show...
Auto Generated Code
359,131
def find_saas_endurance_tier_price(package, tier_level): target_capacity = ENDURANCE_TIERS.get(tier_level) for item in package[]: if not in item\ or not in item[]\ or item[][]\ != : continue if int(item[]) != target_capacity: ...
Find the SaaS storage tier level price for the specified tier level :param package: The Storage As A Service product package :param tier_level: The endurance tier for which a price is desired :return: Returns the price for the given tier, or an error if not found
359,132
def samblaster_dedup_sort(data, tx_out_file, tx_sr_file, tx_disc_file): samblaster = config_utils.get_program("samblaster", data["config"]) samtools = config_utils.get_program("samtools", data["config"]) tmp_prefix = "%s-sorttmp" % utils.splitext_plus(tx_out_file)[0] tobam_cmd = ("{samtools} sort {...
Deduplicate and sort with samblaster, produces split read and discordant pair files.
359,133
def show_report(self, session, *levels): if levels: self.make_report(session, *levels) if self.__report: session.write_line(self.to_json(self.__report)) else: session.write_line("No report to show")
Shows the report that has been generated
359,134
def plot_pointings(self, pointings=None): if pointings is None: pointings = self.pointings i = 0 for pointing in pointings: items = [] i = i + 1 label = {} label[] = pointing[][] for ccd in numpy.radians(pointing[...
Plot pointings on canavs
359,135
def nfa_nonemptiness_check(nfa: dict) -> bool: queue = list() visited = set() for state in nfa[]: visited.add(state) queue.append(state) while queue: state = queue.pop(0) visited.add(state) for a in nfa[]: if (state, a) in nfa[]: ...
Checks if the input NFA reads any language other than the empty one, returning True/False. The language L(A) recognized by the automaton A is nonempty iff there are states :math:`s ∈ S_0` and :math:`t ∈ F` such that t is connected to s. Thus, automata nonemptiness is equivalent to graph reachabilit...
359,136
def _get_translation(self, field, code): if not code in self._translation_cache: translations = self.translations.select_related() logger.debug( u, field, code ) try: translation_obj = translations.get(la...
Gets the translation of a specific field for a specific language code. This raises ObjectDoesNotExist if the lookup was unsuccesful. As of today, this stuff is cached. As the cache is rather aggressive it might cause rather strange effects. However, we would see the same effects when an...
359,137
def cdx_resolve_revisits(cdx_iter): originals = {} for cdx in cdx_iter: is_revisit = cdx.is_revisit() digest = cdx.get(DIGEST) original_cdx = None if digest: original_cdx = originals.get(digest) if not original_cdx and not is_revisit: ...
resolve revisits. this filter adds three fields to CDX: ``orig.length``, ``orig.offset``, and ``orig.filename``. for revisit records, these fields have corresponding field values in previous non-revisit (original) CDX record. They are all ``"-"`` for non-revisit records.
359,138
def send(self, wallet, source, destination, amount, work=None, id=None): wallet = self._process_value(wallet, ) source = self._process_value(source, ) destination = self._process_value(destination, ) amount = self._process_value(amount, ) payload = { "walle...
Send **amount** from **source** in **wallet** to **destination** .. enable_control required :param wallet: Wallet of account used to send funds :type wallet: str :param source: Account to send funds from :type source: str :param destination: Account to send funds to ...
359,139
def cdf(self, x_data): if len(self) > 1 and evaluation.get_dependencies(*self): raise StochasticallyDependentError( "Cumulative distribution does not support dependencies.") q_data = self.fwd(x_data) if len(self) > 1: q_data = numpy.prod(q_data, 0...
Cumulative distribution function. Note that chaospy only supports cumulative distribution functions for stochastically independent distributions. Args: x_data (numpy.ndarray): Location for the distribution function. Assumes that ``len(x_data) == len(...
359,140
def get_function_spec(name): if not hasattr(get_function_spec, ): modelfile = os.path.join(, , ) modelfile = os.path.expandvars(modelfile) get_function_spec.fndict = yaml.load(open(modelfile)) if not name in get_function_spec.fndict.keys(): ...
Return a dictionary with the specification of a function: parameter names and defaults (value, bounds, scale, etc.). Returns ------- par_names : list List of parameter names for this function. norm_par : str Name of normalization parameter. default : dict Parameter def...
359,141
def run_fatcat(structure_path_1, structure_path_2, fatcat_sh, outdir=, silent=False, print_cmd=False, force_rerun=False): filename1 = op.splitext(op.basename(structure_path_1))[0] filename2 = op.splitext(op.basename(structure_path_2))[0] if not op.exists(outdir): os.mkdir(outdir) outfile =...
Run FATCAT on two PDB files, and return the path of the XML result file. Args: structure_path_1 (str): Path to PDB file structure_path_2 (str): Path to PDB file fatcat_sh (str): Path to "runFATCAT.sh" executable script outdir (str): Path to where FATCAT XML output files will b...
359,142
def set_state_from_file(self, filename): with self.io(filename, ) as fp: rstate = fp.read_random_state() numpy.random.set_state(rstate) self._sampler.random_state = rstate
Sets the state of the sampler back to the instance saved in a file.
359,143
def distorted_inputs(data_dir, batch_size): filenames = [os.path.join(data_dir, % i) for i in xrange(1, 6)] for f in filenames: if not tf.gfile.Exists(f): raise ValueError( + f) filename_queue = tf.train.string_input_producer(filenames) read_input = read_cifar10(filename_que...
Construct distorted input for CIFAR training using the Reader ops. Args: data_dir: Path to the CIFAR-10 data directory. batch_size: Number of images per batch. Returns: images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size. labels: Labels. 1D tensor of [batch_size] size.
359,144
def cublasStpmv(handle, uplo, trans, diag, n, AP, x, incx): status = _libcublas.cublasStpmv_v2(handle, _CUBLAS_FILL_MODE[uplo], _CUBLAS_OP[trans], _CUBLAS_DIAG[diag], ...
Matrix-vector product for real triangular-packed matrix.
359,145
def Zabransky_cubic_integral_over_T(T, a1, a2, a3, a4): r T = T/100. return R*(T*(T*(T*a4/3 + a3/2) + a2) + a1*log(T))
r'''Calculates the integral of liquid heat capacity over T using the model developed in [1]_. Parameters ---------- T : float Temperature [K] a1-a4 : float Coefficients Returns ------- S : float Difference in entropy from 0 K, [J/mol/K] Notes ----- ...
359,146
def get_bookmark_tags(self, bookmark_id): url = self._generate_url(.format(bookmark_id)) return self.get(url)
Retrieve tags that have been applied to a bookmark. The requested bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to delete.
359,147
def _filter_dict(input_dict, search_key, search_value): output_dict = dict() for key, key_list in six.iteritems(input_dict): key_list_filtered = _filter_list(key_list, search_key, search_value) if key_list_filtered: output_dict[key] = key_list_filtered return output_dict
Filters a dictionary of dictionaries by a key-value pair. :param input_dict: is a dictionary whose values are lists of dictionaries :param search_key: is the key in the leaf dictionaries :param search_values: is the value in the leaf dictionaries :return: filtered dictionary
359,148
def ipi_name_number(name=None): if name is None: name = field = basic.numeric(11) field.setName(name) return field.setResultsName()
IPI Name Number field. An IPI Name Number is composed of eleven digits. So, for example, an IPI Name Number code field can contain 00014107338. :param name: name for the field :return: a parser for the IPI Name Number field
359,149
def stationary_distributions(self, max_iter=200, tol=1e-5): r m = self.moment_sequence() mu_x, mu_y, Sigma_x, Sigma_y = next(m) i = 0 error = tol + 1 while error > tol: if i > max_iter: fail_message = raise ...
r""" Compute the moments of the stationary distributions of :math:`x_t` and :math:`y_t` if possible. Computation is by iteration, starting from the initial conditions self.mu_0 and self.Sigma_0 Parameters ---------- max_iter : scalar(int), optional(default=200) ...
359,150
def lag_matrix(blk, max_lag=None): if max_lag is None: max_lag = len(blk) - 1 elif max_lag >= len(blk): raise ValueError("Block length should be higher than order") return [[sum(blk[n - i] * blk[n - j] for n in xrange(max_lag, len(blk)) ) for i in xrange(max_lag + 1) ] for j in...
Finds the lag matrix for a given 1-D block sequence. Parameters ---------- blk : An iterable with well-defined length. Don't use this function with Stream objects! max_lag : The size of the result, the lags you'd need. Defaults to ``len(blk) - 1``, the maximum lag that doesn't create fully zero...
359,151
def get_queryset(self, request): opts = self.model._meta model_name = ("%s.%s" % (opts.app_label, opts.object_name)).lower() models_all_editable = settings.OWNABLE_MODELS_ALL_EDITABLE models_all_editable = [m.lower() for m in models_all_editable] qs = super(OwnableAdmin,...
Filter the change list by currently logged in user if not a superuser. We also skip filtering if the model for this admin class has been added to the sequence in the setting ``OWNABLE_MODELS_ALL_EDITABLE``, which contains models in the format ``app_label.object_name``, and allows models ...
359,152
def uncertain_inputs_sparse_regression(max_iters=200, optimize=True, plot=True): fig, axes = pb.subplots(1, 2, figsize=(12, 5), sharex=True, sharey=True) S = np.ones((20, 1)) X = np.random.uniform(-3., 3., (20, 1)) Y = np.sin(X) + np.random.randn(20, 1) * 0.05 Z = np.random.uniform(-...
Run a 1D example of a sparse GP regression with uncertain inputs.
359,153
def toc_html(self, depth=6, lowest_level=6): toc = self.toc(depth=depth, lowest_level=lowest_level) if not toc: return def map_toc_list(toc_list): result = if toc_list: result += result += .join( ...
Get TOC of currently fed HTML string in form of HTML string. :param depth: the depth of TOC :param lowest_level: the allowed lowest level of header tag :return: an HTML string
359,154
def PopupGetFile(message, title=None, default_path=, default_extension=, save_as=False, file_types=(("ALL Files", "*"),), no_window=False, size=(None, None), button_color=None, background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False, grab_anywhere...
Display popup with text entry field and browse button. Browse for file :param message: :param default_path: :param default_extension: :param save_as: :param file_types: :param no_window: :param size: :param button_color: :param background_color: :param text_color: :param icon...
359,155
def parseBranches(self, descendants): i, branches = self.parseTopDepth(descendants), [] for descendant in descendants: if self.getHeadingLevel(descendant, self.hierarchy) == i: branches.append({: descendant}) if self.getHeadingLevel(descendant, self.hiera...
Parse top level of latex :param list elements: list of source objects :return: list of filtered TreeOfContents objects >>> toc = TOC.fromLatex(r'\section{h1}\subsection{subh1}\section{h2}\ ... \subsection{subh2}') >>> toc.parseTopDepth(toc.descendants) 1 >>> toc....
359,156
def load_environment_vars(self): for k, v in os.environ.items(): if k.startswith(MACH9_PREFIX): _, config_key = k.split(MACH9_PREFIX, 1) self[config_key] = v
Looks for any MACH9_ prefixed environment variables and applies them to the configuration if present.
359,157
def replace_activities(self): logger.debug() new_stmts = [] def has_agent_activity(stmt): for agent in stmt.agent_list(): if isinstance(agent, Agent) and agent.activity is not None: return True return Fal...
Replace ative flags with Agent states when possible.
359,158
def main(argv=sys.argv): if len(argv) < 2: usage(argv) config_uri = argv[1] setup_logging(config_uri) settings = get_appsettings(config_uri) engine = engine_from_config(settings, "sqlalchemy.") DBSession.configure(bind=engine) Base.metadata.create_all(engine) for i in...
Populate database with 30 users.
359,159
def _get_hidden_forum_ids(self, forums, user): visible_forums = self._get_forums_for_user( user, [, , ], use_tree_hierarchy=True, ) return forums.exclude(id__in=[f.id for f in visible_forums])
Given a set of forums and a user, returns the list of forums that are not visible by this user.
359,160
def query(self, xri, service_types): services = [] canonicalID = None for service_type in service_types: url = self.queryURL(xri, service_type) response = fetchers.fetch(url) if response.status not in (200, 206): ...
Resolve some services for an XRI. Note: I don't implement any service endpoint selection beyond what the resolver I'm querying does, so the Services I return may well include Services that were not of the types you asked for. May raise fetchers.HTTPFetchingError or L{etxrd.XRDSError} i...
359,161
def _handle_changed_fields(self, old_data): for link in self.get_links(is_set=False): fld_id = un_camel_id(link[]) if not old_data or old_data.get(fld_id) != self._data[fld_id]: if self._data[fld_id]: linked_mdl = getattr(se...
Looks for changed relation fields between new and old data (before/after save). Creates back_link references for updated fields. Args: old_data: Object's data before save.
359,162
def sort_by_key(self, keys=None): keys = keys or self.key_on keys = keys if isinstance(keys, (list, tuple)) else [keys] for key in reversed(keys): reverse, key = (True, key[1:]) if key[0] == else (False, key) self.table.sort(key=lambda row: row[key], reverse=rev...
:param keys: list of str to sort by, if name starts with - reverse order :return: None
359,163
def login(session, username, password, class_name=None): logging.debug() try: session.cookies.clear() logging.debug() except KeyError: logging.debug() if class_name is not None: class_url = CLASS_URL.format(class_name=class_name) r = requests.get(class...
Login on coursera.org with the given credentials. This adds the following cookies to the session: sessionid, maestro_login, maestro_login_flag
359,164
def tagged(*tags: Tags) -> Callable: global GREENSIM_TAG_ATTRIBUTE def hook(event: Callable): def wrapper(*args, **kwargs): event(*args, **kwargs) setattr(wrapper, GREENSIM_TAG_ATTRIBUTE, tags) return wrapper return hook
Decorator for adding a label to the process. These labels are applied to any child Processes produced by event
359,165
def calculate_fuzzy_chi(alpha, square_map, right_eigenvectors): A = to_square(alpha, square_map) A = fill_A(A, right_eigenvectors) chi_fuzzy = np.dot(right_eigenvectors, A) mapping = np.argmax(chi_fuzzy, 1) return A, chi_fuzzy, mapping
Calculate the membership matrix (chi) from parameters alpha. Parameters ---------- alpha : ndarray Parameters of objective function (e.g. flattened A) square_map : ndarray Mapping from square indices (i,j) to flat indices (k). right_eigenvectors : ndarray The right eigenvect...
359,166
def on_startup(self): LOGGER.debug("> Calling Component Framework method.".format(self.__class__.__name__)) if self.Autostart_TCP_Server_checkBox.isChecked(): if not self.__tcp_server.online: self.__tcp_server.port = self.Port_spinBox.value() self...
Defines the slot triggered on Framework startup.
359,167
def list_subnets(self, tag_values=None): title = % self.__class__.__name__ input_fields = { : tag_values } for key, value in input_fields.items(): if value: object_title = % (title, key, str(value)) self.fields.va...
a method to discover the list of subnets on AWS EC2 :param tag_values: [optional] list of tag values :return: list of strings with subnet ids
359,168
def new_object(cls, state, type_, symbolic=False, init_object=False): obj_ref = cls(heap_alloc_id=state.memory.get_new_uuid(), type_=type_, symbolic=symbolic) if init_object: l.info(">" * 15 + " Initialize object %r ... " + ">" * 15, obj_ref) ...
Creates a new object reference. :param state: State associated to the object. :param type_: Class of the object. :param init_object: Whether the objects initializer method should be run. :return: Reference to the new object.
359,169
def create(self, subid, params=None): params = update_params(params, {: subid}) return self.request(, params, )
/v1/snapshot/create POST - account Create a snapshot from an existing virtual machine. The virtual machine does not need to be stopped. Link: https://www.vultr.com/api/#snapshot_create
359,170
def effective_sample_size(states, filter_threshold=0., filter_beyond_lag=None, name=None): states_was_list = _is_list_like(states) if not states_was_list: states = [states] filter_beyond_lag = _broadcast_maybelist_arg(states...
Estimate a lower bound on effective sample size for each independent chain. Roughly speaking, "effective sample size" (ESS) is the size of an iid sample with the same variance as `state`. More precisely, given a stationary sequence of possibly correlated random variables `X_1, X_2,...,X_N`, each identically d...
359,171
def load_state(self, state_id, delete=True): return self._store.load_state(f, delete=delete)
Load a state from storage identified by `state_id`. :param state_id: The state reference of what to load :return: The deserialized state :rtype: State
359,172
def mtz2tw(n,c,e,l): model = Model("tsptw - mtz-strong") x,u = {},{} for i in range(1,n+1): u[i] = model.addVar(lb=e[i], ub=l[i], vtype="C", name="u(%s)"%i) for j in range(1,n+1): if i != j: x[i,j] = model.addVar(vtype="B", name="x(%s,%s)"%(i,j)) fo...
mtz: model for the traveling salesman problem with time windows (based on Miller-Tucker-Zemlin's one-index potential formulation, stronger constraints) Parameters: - n: number of nodes - c[i,j]: cost for traversing arc (i,j) - e[i]: earliest date for visiting node i - l[i]: lates...
359,173
def runGenome(bfile, options): outPrefix = options.out + ".genome" if options.sge: plinkCommand = ["plink", "--noweb", "--bfile", bfile, "--freq", "--out", options.out + ".frequency"] runCommand(plinkCommand) nbJob = splitFile(bfil...
Runs the genome command from plink. :param bfile: the input file prefix. :param options: the options. :type bfile: str :type options: argparse.Namespace :returns: the name of the ``genome`` file. Runs Plink with the ``genome`` option. If the user asks for SGE (``options.sge`` is True), a...
359,174
def set_nb_theme(name): from IPython.core.display import HTML styles_dir = os.path.join(package_dir, ) css_path = glob(.format(styles_dir, name))[0] customcss = open(css_path, "r").read() return HTML(.join([, customcss, ]))
Set theme from within notebook
359,175
def run_config(path, source=None, config_name=None, config_data=None, config_data_source=None, script_parameters=None, salt_env=): rbase** ret = compile_config(path=path, source=source, ...
r''' Compile a DSC Configuration in the form of a PowerShell script (.ps1) and apply it. The PowerShell script can be cached from the master using the ``source`` option. If there is more than one config within the PowerShell script, the desired configuration can be applied by passing the name in the ...
359,176
def add_mimetype(mimedb, mimetype, extension): strict = extension in mimedb.types_map[True] mimedb.add_type(mimetype, extension, strict=strict)
Add or replace a mimetype to be used with the given extension.
359,177
def send_message(self, fakeid, content): url = payload = { : fakeid, : 1, : self.__token, : content, : 1, } headers = { : , : .format( fakeid=fakeid, token=self._...
主动发送文本消息 :param fakeid: 用户的 UID (即 fakeid ) :param content: 发送的内容 :raises NeedLoginError: 操作未执行成功, 需要再次尝试登录, 异常内容为服务器返回的错误数据 :raises ValueError: 参数出错, 具体内容有 ``fake id not exist``
359,178
def view_help(self): def format_desc(desc): return "%s (Type: %s, Default: %s)\n%s" % ( desc.name, desc.validator.__name__.replace(, ), desc.default, desc.help or ) def format_namespace(key, desc_list):...
Return a help message describing all the statically configured keys.
359,179
def build_transgenic_lines(self): allen_namespaces = { : , : , : , } for prefix, iri in allen_namespaces.items(): self.g.add_namespace(prefix, iri) for cell_line in self.neuron_data[:]: for tl in cell_line[][]: ...
init class | "transgenic_line_source_name":"stock_number" a Class add superClass | rdfs:subClassOf ilxtr:transgenicLine add *order* | ilxtr:useObjectProperty ilxtr:<order> add name | rdfs:label "name" add def | definition: "description" add transtype | ...
359,180
def decode(self, packet): self.encoded = packet lenLen = 1 while packet[lenLen] & 0x80: lenLen += 1 packet_remaining = packet[lenLen+1:] self.dup = (packet[0] & 0x08) == 0x08 self.qos = (packet[0] & 0x06) >> 1 self.retain = (packet[0] & ...
Decode a PUBLISH control packet.
359,181
def stop(self): if self._progressing: self._progressing = False self._thread.join()
Stop the progress bar.
359,182
def transpose(self): return SuperOp( np.transpose(self._data), input_dims=self.output_dims(), output_dims=self.input_dims())
Return the transpose of the QuantumChannel.
359,183
def stream(self, limit=None, page_size=None): limits = self._version.read_limits(limit, page_size) page = self.page(page_size=limits[], ) return self._version.stream(page, limits[], limits[])
Streams KeyInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. :param int limit: Upper limit for the number of reco...
359,184
def prune_by_ngram_count_per_work(self, minimum=None, maximum=None, label=None): self._logger.info() matches = self._matches keep_ngrams = matches[constants.NGRAM_FIELDNAME].unique() if label is not None: matches = matches[matche...
Removes results rows if the n-gram count for all works bearing that n-gram is outside the range specified by `minimum` and `maximum`. That is, if a single witness of a single work has an n-gram count that falls within the specified range, all result rows for that n-gram are kept...
359,185
def ingest(self): self.log.debug() dictList = self._create_dictionary_of_veron() tableName = self.dbTableName createStatement = % locals() self.add_data_to_database_table( dictList=dictList, createStatement=createStatement ) s...
ingest the veron catalogue into the catalogues database See class docstring for usage.
359,186
def get_authorization_url(self, signin_with_twitter=False, access_type=None): try: if signin_with_twitter: url = self._get_oauth_url() if access_type: logging.warning(WARNING_MESS...
Get the authorization URL to redirect the user
359,187
def make_response(status, headers, payload, environ): return Response(body=payload, status=int(status.split()[0]), headers=headers)
This function generates an appropriate response object for this async mode.
359,188
def BOUND(self): logger.debug() logger.info(, self.client.iface, STATES2NAMES[self.current_state]) self.current_state = STATE_BOUND self.client.lease.info_lease() if self.script is not None: self.script.script_init(self.client.lease, self....
BOUND state.
359,189
def get_reservations(**kwargs): kwargs["scope"] = "extended" url = "/r25ws/servlet/wrd/run/reservations.xml" if len(kwargs): url += "?%s" % urlencode(kwargs) return reservations_from_xml(get_resource(url))
Return a list of reservations matching the passed filter. Supported kwargs are listed at http://knowledge25.collegenet.com/display/WSW/reservations.xml
359,190
def with_options(self, codec_options=None, read_preference=None, write_concern=None, read_concern=None): return Database(self.client, self.__name, codec_options or self.codec_options, read_preference or self.re...
Get a clone of this database changing the specified settings. >>> db1.read_preference Primary() >>> from pymongo import ReadPreference >>> db2 = db1.with_options(read_preference=ReadPreference.SECONDARY) >>> db1.read_preference Primary() >>> db2.rea...
359,191
def parse(self, inputstring, document): link = json.loads(inputstring) env = document.settings.env source_dir = os.path.dirname(env.doc2path(env.docname)) abs_path = os.path.normpath(os.path.join(source_dir, link[])) path = utils.relative_path(None, abs_path) pa...
Parse the nblink file. Adds the linked file as a dependency, read the file, and pass the content to the nbshpinx.NotebookParser.
359,192
def is_parent_of_vault(self, id_, vault_id): if self._catalog_session is not None: return self._catalog_session.is_parent_of_catalog(id_=id_, catalog_id=vault_id) return self._hierarchy_session.is_parent(id_=vault_id, parent_id=id_)
Tests if an ``Id`` is a direct parent of a vault. arg: id (osid.id.Id): an ``Id`` arg: vault_id (osid.id.Id): the ``Id`` of a vault return: (boolean) - ``true`` if this ``id`` is a parent of ``vault_id,`` ``false`` otherwise raise: NotFound - ``vault_id`` is not ...
359,193
def frmnam(frcode, lenout=_default_len_out): frcode = ctypes.c_int(frcode) lenout = ctypes.c_int(lenout) frname = stypes.stringToCharP(lenout) libspice.frmnam_c(frcode, lenout, frname) return stypes.toPythonString(frname)
Retrieve the name of a reference frame associated with a SPICE ID code. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/frmnam_c.html :param frcode: an integer code for a reference frame :type frcode: int :param lenout: Maximum length of output string. :type lenout: int :return: the na...
359,194
def ReadFlagsFromFiles(self, argv, force_gnu=True): rest_of_args = argv new_argv = [] while rest_of_args: current_arg = rest_of_args[0] rest_of_args = rest_of_args[1:] if self.__IsFlagFileDirective(current_arg): if current_arg == or current_arg == : ...
Processes command line args, but also allow args to be read from file. Args: argv: A list of strings, usually sys.argv[1:], which may contain one or more flagfile directives of the form --flagfile="./filename". Note that the name of the program (sys.argv[0]) should be omitted. force_gnu...
359,195
def choices(self): choice_list = getattr( settings, , DEFAULT_MARKUP_CHOICES ) return [(f, self._get_filter_title(f)) for f in choice_list]
Returns the filter list as a tuple. Useful for model choices.
359,196
def authenticate_search_bind(self, username, password): connection = self._make_connection( bind_user=self.config.get(), bind_password=self.config.get(), ) try: connection.bind() log.debug("Successfully bound to LDAP as for search_bind m...
Performs a search bind to authenticate a user. This is required when a the login attribute is not the same as the RDN, since we cannot string together their DN on the fly, instead we have to find it in the LDAP, then attempt to bind with their credentials. Args: user...
359,197
def LogMsg(msg): global headerlogged if headerlogged == 0: print("{0:<8} {1:<90} {2}".format( "Time", "MainThread", "UpdateSNMPObjsThread" )) print("{0:-^120}".format("-")) headerlogged = 1 threadname = threading.currentThread().name funcname = sys._getframe(1).f_code.co_name if funcname == ...
Writes a formatted log message with a timestamp to stdout.
359,198
def _tree_stat(self, mode, infostr, stat): action_str = mode.upper() info_str = infostr if stat == : self.action_st_panel.SetBackgroundColour() else: self.action_st_panel.SetBackgroundColour() self.action_st.SetLabel(action_str) if info_...
update stat regarding to tree generating process, e.g. show_tree()
359,199
def string_get(self, ypos, xpos, length): xpos -= 1 ypos -= 1 cmd = self.exec_command( "Ascii({0},{1},{2})".format(ypos, xpos, length).encode("ascii") ) assert len(cmd.data) == 1, cmd.data return cmd.data[0].decode("ascii")
Get a string of `length` at screen co-ordinates `ypos`/`xpos` Co-ordinates are 1 based, as listed in the status area of the terminal.