content
stringlengths
22
815k
id
int64
0
4.91M
def get_parent_directory(path): """ Get parent directory of the path """ return os.path.abspath(os.path.join(path, os.pardir))
5,346,000
def generate_fig_univariate_categorical( df_all: pd.DataFrame, col: str, hue: str, nb_cat_max: int = 7, ) -> plt.Figure: """ Returns a matplotlib figure containing the distribution of a categorical feature. If the feature is categorical and contains too many categories, the smallest categories are grouped into a new 'Other' category so that the graph remains readable. Parameters ---------- df_all : pd.DataFrame The input dataframe that contains the column of interest col : str The column of interest hue : str The column used to distinguish the values (ex. 'train' and 'test') nb_cat_max : int The number max of categories to be displayed. If the number of categories is greater than nb_cat_max then groups smallest categories into a new 'Other' category Returns ------- matplotlib.pyplot.Figure """ df_cat = df_all.groupby([col, hue]).agg({col: 'count'})\ .rename(columns={col: "count"}).reset_index() df_cat['Percent'] = df_cat['count'] * 100 / df_cat.groupby(hue)['count'].transform('sum') if pd.api.types.is_numeric_dtype(df_cat[col].dtype): df_cat = df_cat.sort_values(col, ascending=True) df_cat[col] = df_cat[col].astype(str) nb_cat = df_cat.groupby([col]).agg({'count': 'sum'}).reset_index()[col].nunique() if nb_cat > nb_cat_max: df_cat = _merge_small_categories(df_cat=df_cat, col=col, hue=hue, nb_cat_max=nb_cat_max) fig, ax = plt.subplots(figsize=(7, 4)) sns.barplot(data=df_cat, x='Percent', y=col, hue=hue, palette=dict_color_palette, ax=ax) for p in ax.patches: ax.annotate("{:.1f}%".format(np.nan_to_num(p.get_width(), nan=0)), xy=(p.get_width(), p.get_y() + p.get_height() / 2), xytext=(5, 0), textcoords='offset points', ha="left", va="center") # Shrink current axis by 20% box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) # Put a legend to the right of the current axis ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) # Removes plot borders ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) new_labels = [truncate_str(i.get_text(), maxlen=45) for i in ax.yaxis.get_ticklabels()] ax.yaxis.set_ticklabels(new_labels) return fig
5,346,001
def pt_sharp(x, Ps, Ts, window_half, method='diff'): """ Calculate the sharpness of extrema Parameters ---------- x : array-like 1d voltage time series Ps : array-like 1d time points of oscillatory peaks Ts : array-like 1d time points of oscillatory troughs window_half : int Number of samples in each direction around extrema to use for sharpness estimation Returns ------- Psharps : array-like 1d sharpness of peaks Tsharps : array-like 1d sharpness of troughs """ # Assure input has the same number of peaks and troughs if len(Ts) != len(Ps): raise ValueError('Length of peaks and troughs arrays must be equal') # Calculate the sharpness of each peak P = len(Ps) Psharps = np.zeros(P) for e in range(P): if method == 'deriv': Edata = x[Ps[e]-window_half: Ps[e]+window_half+1] Psharps[e] = np.mean(np.abs(np.diff(Edata))) elif method == 'diff': Psharps[e] = np.mean((x[Ps[e]]-x[Ps[e]-window_half],x[Ps[e]]-x[Ps[e]+window_half])) T = len(Ts) Tsharps = np.zeros(T) for e in range(T): if method == 'deriv': Edata = x[Ts[e]-window_half: Ts[e]+window_half+1] Tsharps[e] = np.mean(np.abs(np.diff(Edata))) elif method == 'diff': Tsharps[e] = np.mean((x[Ts[e]-window_half]-x[Ts[e]],x[Ts[e]+window_half]-x[Ts[e]])) return Psharps, Tsharps
5,346,002
def associate_by_email(strategy, details, user=None, *args, **kwargs): """Deny duplicate email addresses for new users except in specific cases If the incoming email is associated with existing user, authentication is denied. Exceptions are: * the existing user does not have associated social login * the incoming email belongs to a trusted domain * the duplicate email address check has been disabled in the settings In the first two cases, the incoming social login is associated with the existing user. In the third case a separate new user is created. """ logger.debug(f"starting association by email; user:{user}; details:{details}") if user: return if settings.ALLOW_DUPLICATE_EMAILS: return email = details.get('email') if not email: return backend = kwargs['backend'] User = get_user_model() # noqa existing_users = User.objects.filter(email__iexact=email).order_by('-date_joined') if not existing_users: return logger.debug(f"found existing users with email '{email}': {existing_users}") user = existing_users[0] trusted_email_domains = backend.setting('TRUSTED_EMAIL_DOMAINS', []) explicitly_trusted = False if trusted_email_domains: email_domain = email.split('@')[1] if email_domain in trusted_email_domains or trusted_email_domains == '*': explicitly_trusted = True social_set = user.social_auth.all() # If the account doesn't have any social logins yet, or if we # explicitly trust the social media provider, allow the signup. if explicitly_trusted or not social_set: return { 'user': user, } logger.debug(f"'{email}' already in use by existing user and email domain not trusted") providers = [a.provider for a in social_set] strategy.request.other_logins = LoginMethod.objects.filter(provider_id__in=providers) error_view = AuthenticationErrorView(request=strategy.request) return error_view.get(strategy.request)
5,346,003
async def test_service_setup(hass): """Verify service setup works.""" assert deconz.services.DECONZ_SERVICES not in hass.data with patch( "homeassistant.core.ServiceRegistry.async_register", return_value=Mock(True) ) as async_register: await deconz.services.async_setup_services(hass) assert hass.data[deconz.services.DECONZ_SERVICES] is True assert async_register.call_count == 2
5,346,004
def test_service(host): """ Check if database service is started and enabled """ service = '' if host.system_info.distribution in ('debian', 'ubuntu'): service = 'postgresql' assert host.service(service).is_enabled # Systemctl not available with Docker images if 'docker' != host.backend.NAME: assert host.service(service).is_running
5,346,005
def convert_date(string, report_date, bad_dates_rep, bad_dates_for): """ Converts date string in format dd/mm/yyyy to format dd-Mmm-yyyy """ x = string.split('/') try: date = datetime.datetime(int(x[2]),int(x[1]),int(x[0])) date_str = date.strftime("%Y-%m-%d") return(date_str) # Print out cases that do not match input date convention except (IndexError, ValueError) as errors: bad_dates_rep.append(report_date) bad_dates_for.append(string) return(string) pass
5,346,006
def render_raw(request, paste, data): """Renders RAW content.""" return HttpResponse(paste.content, content_type="text/plain")
5,346,007
def node_avg(): """get the avg of the node stats""" node_raw = ["average", 0, 0, 0] for node in node_stats(): node_raw[1] += float(node[1]) node_raw[2] += float(node[2]) node_raw[3] += float(node[3]) num = len(node_stats()) node_avg = ["average", "{:.2f}".format(node_raw[1]/num), "{:.2f}".format(node_raw[2]/num), "{:.2f}".format(node_raw[3]/num)] return node_avg
5,346,008
def decrypt_vault_password(key: bytes, password: Union[str, bytes]) -> Union[str, bool]: """Decrypt and return the given vault password. :param key: The key to be used during the decryption :param password: The password to decrypt """ if isinstance(password, str): password = password.encode("utf-8") f = Fernet(key) try: return f.decrypt(password).decode() except InvalidToken: return False
5,346,009
def readData(op,filetype,config): """ Reads data from Hive or CSV """ try: if filetype=='csv': print('csv') csvU=optimusCsvUtils(config) hr=datetime.now().hour today=str(datetime.now().date()) path=os.path.join(config['data']['DIR'],'performance_{}_hr_{}.csv'.format(today,hr)) print(path) df=csvU.readData(op,path=path) elif filetype=='hive': print(HQL) hive=optimusHiveUtils(config) df=hive.readData(op,HQL) elif filetype=='jdbc': print(HQL) jdbc=optimusJDBC(config) df=jdbc.readData(op,HQL) elif filetype=='parquet': parqU=optimusParquetUtils(config) path=os.path.join(config['data']['DIR'],'performance_{}_hr_{}.csv'.format(today,hr)) df=parqU.readData(op,path=path) df=parqU.readData(op) return df except Exception as e: logger.critical('Exception occured during Reading the data - {}'.format(e)) raise Exception('Exception occured during Reading the data - {}'.format(e))
5,346,010
def get_gv_rng_if_none(rng: Optional[rnd.Generator]) -> rnd.Generator: """get gym-gridverse module rng if input is None""" return get_gv_rng() if rng is None else rng
5,346,011
def fill_name(f): """ Attempts to generate an unique id and a parent from a BioPython SeqRecord. Mutates the feature dictionary passed in as parameter. """ global UNIQUE # Get the type ftype = f['type'] # Get gene name gene_name = first(f, "gene") # Will attempt to fill in the uid from attributes. uid = '' # Deal with known types. if ftype == 'gene': name = gene_name or first(f, "locus_tag") uid = name elif ftype == 'CDS': count = get_next_count(ftype=ftype, label=gene_name) prot = first(f, "protein_id") or f"{gene_name}-CDS-{count}" uid = f"{prot}" name = prot elif ftype == 'mRNA': count = get_next_count(ftype=ftype, label=gene_name) uid = first(f, "transcript_id") or f"{gene_name}-mRNA-{count}" name = uid elif ftype == "exon": name = gene_name else: name = first(f, "organism") or first(f, "transcript_id") or None uid = first(f, "transcript_id") # Set the unique identifier. f['id'] = uid or f"{ftype}-{next(COUNTER)}" # Set the feature name. f['name'] = name or ftype return f
5,346,012
def run_single_softmax_experiment(beta, alpha): """Run experiment with agent using softmax update rule.""" print('Running a contextual bandit experiment') cb = ContextualBandit() ca = ContextualAgent(cb, beta=beta, alpha=alpha) trials = 360 for _ in range(trials): ca.run() df = DataFrame(ca.log, columns=('context', 'action', 'reward', 'Q(c,23)', 'Q(c,14)', 'Q(c,8)', 'Q(c,3)')) # fn = 'softmax_experiment.csv' # df.to_csv(fn, index=False) # print('Sequence written in', fn) # globals().update(locals()) # return df
5,346,013
def test_meta_schedule_local_multiple_runs(): """Test meta schedule local runner for multiple runs""" # Build the module mods = [ MatmulModule, MatmulReluModule, BatchMatmulModule, ] builder = LocalBuilder() builder_inputs = [BuilderInput(mod, Target("llvm")) for mod in mods] builder_results = builder.build(builder_inputs) for builder_result in builder_results: assert builder_result.artifact_path is not None assert builder_result.error_msg is None args_infos = [ [ TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), ], [ TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), ], [ TensorInfo("float32", [16, MATMUL_M, MATMUL_M]), TensorInfo("float32", [16, MATMUL_M, MATMUL_M]), TensorInfo("float32", [16, MATMUL_M, MATMUL_M]), ], ] runner_inputs = [ RunnerInput(builder_results[i].artifact_path, "llvm", args_infos[i]) for i in range(len(mods)) ] evaluator_config = EvaluatorConfig( number=1, repeat=1, min_repeat_ms=0, enable_cpu_cache_flush=False, ) runner = LocalRunner(timeout_sec=100, evaluator_config=evaluator_config) # Run the module runner_futures = runner.run(runner_inputs) runner_results = [runner_future.result() for runner_future in runner_futures] for runner_result in runner_results: assert runner_result.error_msg is None for result in runner_result.run_secs: if isinstance(result, FloatImm): result = result.value assert isinstance(result, float) assert result >= 0.0 for builder_result in builder_results: _clean_build(builder_result.artifact_path)
5,346,014
def available(name): """ Returns ``True`` if the specified service is available, otherwise returns ``False``. We look up the name with the svcs command to get back the FMRI This allows users to use simpler service names CLI Example: .. code-block:: bash salt '*' service.available net-snmp """ cmd = "/usr/bin/svcs -H -o FMRI {0}".format(name) name = __salt__["cmd.run"](cmd, python_shell=False) return name in get_all()
5,346,015
def coincidence_rate(text): """ Return the coincidence rate of the given text Args: text (string): the text to get measured Returns: the coincidence rate """ ko = 0 # measure the frequency of each letter in the cipher text for letter in _VOCAB: count = text.count(letter) ko = ko + (count * (count - 1)) return ko / (len(text) * (len(text) - 1))
5,346,016
def convert_bytes_to_ints(in_bytes, num): """Convert a byte array into an integer array. The number of bytes forming an integer is defined by num :param in_bytes: the input bytes :param num: the number of bytes per int :return the integer array""" dt = numpy.dtype('>i' + str(num)) return numpy.frombuffer(in_bytes, dt)
5,346,017
def test_es_connection(es): """Tests health and presence of connection to elasticsearch.""" try: health = es.cluster.health() except elasticsearch.exceptions.ConnectionError: current_app.logger.error( "Elasticsearch does not seem to be running on " f"{current_app.config['SEARCH_CONF']['url']}. Please start " "it, for example with: sudo service elasticsearch restart" ) current_app.logger.error( "You can disable Elasticsearch by modifying the `enabled` variable " f"in {str(Path(current_app.config['INTERNAL_DIR']) / 'config.yml')}" ) sys.exit(1) if health["status"] not in ("yellow", "green"): current_app.logger.warning( "Elasticsearch reports that it is not working " "properly. Search might not work. You can disable " "Elasticsearch by setting ELASTICSEARCH_ENABLED to 0." )
5,346,018
def search_spec(spec, search_key, recurse_key): """ Recursively scans spec structure and returns a list of values keyed with 'search_key' or and empty list. Assumes values are either list or str. """ value = [] if search_key in spec and spec[search_key]: if isinstance(spec[search_key], str): value.append(spec[search_key]) else: value += spec[search_key] if recurse_key in spec and spec[recurse_key]: for child_spec in spec[recurse_key]: value += search_spec(child_spec, search_key, recurse_key) return sorted(value)
5,346,019
def before_class(home=None, **kwargs): """Like @test but indicates this should run before other class methods. All of the arguments sent to @test work with this decorator as well. """ kwargs.update({'run_before_class':True}) return test(home=home, **kwargs)
5,346,020
async def setuExecutor(bot: Bot, event: MessageEvent, state: T_State) -> None: """获取response""" keyword: str = state['keyword'] member_id: int = event.sender.user_id if cd.check(member_id) is False: resp = SetuResp(code=-3, msg='技能冷却中') else: resp = await SetuResp.get(keyword) state['setu_resp'] = resp
5,346,021
def get_airports(force_download=False): """ Gets or downloads the airports.csv in ~/.config/mss and returns all airports within """ global _airports, _airports_mtime file_exists = os.path.exists(os.path.join(MSS_CONFIG_PATH, "airports.csv")) if _airports and file_exists and os.path.getmtime(os.path.join(MSS_CONFIG_PATH, "airports.csv")) == _airports_mtime: return _airports is_outdated = file_exists \ and (time.time() - os.path.getmtime(os.path.join(MSS_CONFIG_PATH, "airports.csv"))) > 60 * 60 * 24 * 30 if (force_download or is_outdated or not file_exists) \ and QtWidgets.QMessageBox.question(None, "Allow download", f"You selected airports to be " f"{'drawn' if not force_download else 'downloaded (~10 MB)'}." + ("\nThe airports file first needs to be downloaded or updated (~10 MB)." if not force_download else "") + "\nIs now a good time?", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) \ == QtWidgets.QMessageBox.Yes: download_progress(os.path.join(MSS_CONFIG_PATH, "airports.csv"), "https://ourairports.com/data/airports.csv") if os.path.exists(os.path.join(MSS_CONFIG_PATH, "airports.csv")): with open(os.path.join(MSS_CONFIG_PATH, "airports.csv"), "r", encoding="utf8") as file: _airports_mtime = os.path.getmtime(os.path.join(MSS_CONFIG_PATH, "airports.csv")) return list(csv.DictReader(file, delimiter=",")) else: return []
5,346,022
def hellinger_distance_poisson_variants(a_means, b_means, n_samples, sample_distances): """ a - The coverage vec for a variant over n_samples b - The coverage vec for a variant over n_samples returns average hellinger distance of multiple poisson distributions """ # generate distirbutions for each sample # and calculate divergence between them # Get the means for each contig h_geom_mean = [] both_present = [] for i in range(0, n_samples): # Use this indexing method as zip does not seem to work so well in njit # Add tiny value to each to avoid division by zero a_mean = a_means[i] + 1e-6 b_mean = b_means[i] + 1e-6 if a_mean > 1e-6 and b_mean > 1e-6: both_present.append(i) if a_mean > 1e-6 or b_mean > 1e-6: # First component of hellinger distance h1 = math.exp(-0.5 * ((np.sqrt(a_mean) - np.sqrt(b_mean))**2)) h_geom_mean.append(1 - h1) if len(h_geom_mean) >= 1: # convert to log space to avoid overflow errors d = np.log(np.array(h_geom_mean)) # return the geometric mean d = np.exp(d.sum() / len(d)) geom_sim = geom_sim_calc(both_present, sample_distances) d = d ** (1/geom_sim) else: d = 1 return d
5,346,023
def min_threshold(x, thresh, fallback): """Returns x or `fallback` if it doesn't meet the threshold. Note, if you want to turn a hyper "off" below, set it to "outside the threshold", rather than 0. """ return x if (x and x > thresh) else fallback
5,346,024
def get_command(command, meta): """Construct the command.""" bits = [] # command to run bits.append(command) # connection params bits.extend(connect_bits(meta)) # database name if command == 'mysqladmin': # these commands shouldn't take a database name return bits if command == 'pg_restore': bits.append('--dbname') if command == 'mysql': bits.append('--database') bits.append(meta['path'][1:]) return bits
5,346,025
def main(): # pragma: no cover """Executes model.""" import sys try: infile = sys.argv[1] except IndexError: print("Must include input file name on command line") sys.exit(1) em = BasicDdSt.from_file(infile) em.run()
5,346,026
def get_common_count(list1, list2): """ Get count of common between two lists :param list1: list :param list2: list :return: number """ return len(list(set(list1).intersection(list2)))
5,346,027
def text_present(nbwidget, text="Test"): """Check if a text is present in the notebook.""" if WEBENGINE: def callback(data): global html html = data nbwidget.dom.toHtml(callback) try: return text in html except NameError: return False else: return text in nbwidget.dom.toHtml()
5,346,028
def multiFilm(layers, det, e0=20.0, withPoisson=True, nTraj=defaultNumTraj, dose=defaultDose, sf=defaultCharFluor, bf=defaultBremFluor, xtraParams=defaultXtraParams): """multiFilm(layers, det, e0=20.0, withPoisson=True, nTraj=defaultNumTraj, dose=defaultDose, sf=defaultCharFluor, bf=defaultBremFluor, xtraParams={}): Monte Carlo simulate a spectrum from a multilayer thin film. Layers is a iterable list of \ [material,thickness]. Note the materials must have associated densities.""" tmp = u"MC simulation of a multilayer film [%s] at %0.1f keV%s%s" % (",".join("%0.0f nm of %s" % (1.0e9 * layer[1], layer[0]) for layer in layers), e0, (" + CSF" if sf else ""), (" + BSF" if bf else "")) return base(det, e0, withPoisson, nTraj, dose, sf, bf, tmp, buildFilm, {"Layers": layers }, xtraParams)
5,346,029
def basis_lattice(lattice: str) -> np.ndarray: """ Description ----------- Return a matrix whose column space is the three lattice vector m = | a_1 b_1 c_1 | | a_2 b_2 c_2 | | a_3 b_3 c_3 | the covariances (a|b|c_i) are in the crystal frame Parameters ---------- lattice: str lattice name Returns ------- np.ndarray column space matrix """ pass
5,346,030
def main(url: str, **options) -> None: """ Displays information on a Github repository. URL_OR_REPO_PATH must be either some form of Github Url or path starting with username and repo such as `user/repo/whatever`. """ if options["set_token"]: set_token(url) token = get_token() owner, repo = get_url_info(url) query_variables = { "owner": owner, "repo": repo, "branch": f"{options['branch'] if options['branch'] else 'HEAD'}" } if options["file_tree"]: depth = "" for i in range(options["depth"] - 1): depth = f"... on Tree {{ entries {{ name type object {{... on Blob {{ byteSize }} {depth} }} }} }}" query_variables["path"] = f"{options['branch'] if options['branch'] else 'HEAD'}:{options['path']}" error, data, _ = get_data(FILE_QUERY_1 + depth + FILE_QUERY_2, token, query_variables) if error: print(data) return if not data["object"]: print("No files available") return entries = data["object"]["entries"] branch_name = data["defaultBranchRef"]["name"] entries = sort_entries(entries) path = ( f"/{owner}" f"/{repo}" f"/tree" f"/{options['branch'] if options['branch'] else branch_name}" f"/{options['path']}" ) if options["path"] else f"/{owner}/{repo}" root = populate_tree( f"[blue link https://github.com{path}]{path}[/]", entries, options["collapse"] ) for pre, fill, node in RenderTree(root, style=ContRoundStyle()): tree = "%s%s" % (pre, node.name) print(tree) elif options["lang"]: error, data, rate_limit = get_data(LANG_QUERY, token, query_variables) if error: print(data) return data = data["languages"] if not data["edges"]: print("Languages not available") return total_size = data["totalSize"] total_count = data["totalCount"] grid = Table( show_header=False, header_style=None, box=ROUNDED_BORDER, title=f'[green]{owner}/{repo}[/] - Ratelimit: [blue]{rate_limit}[/]' ) langs = [] matrix = [] for lang in data["edges"]: langs.append( f"[{lang['node']['color'] if lang['node']['color'] else '#FFFFFF'}]" f"{lang['node']['name']}[/] - " f"{Number(round(100 * lang['size'] / total_size, 2))}%" ) start = 0 end = 3 for i in range(total_count // 3 + 1): matrix.append(langs[start:end]) start += 3 end += 3 for row in matrix: grid.add_row(*row) print(grid) else: error, data, rate_limit = get_data(INFO_QUERY, token, query_variables) if error: print(data) return grid = Table( show_header=False, header_style=None, box=ROUNDED_BORDER, title=f'[green]{owner}/{repo}[/] - Ratelimit: [blue]{rate_limit}[/]' ) latestRelease = data["latestRelease"] or { "url": "", "name": "None" } licenseInfo = data["licenseInfo"] or { "url": "", "spdxId": "None" } if data['languages']['nodes']: language = data['languages']['nodes'][0]['name'] else: language = "Not available" disk_usage = data["diskUsage"] or 0 if data["object"]: commit_count = data['object']['history']['totalCount'] else: commit_count = "Not available" if options["long"]: grid.add_row( f"Owner - {Link(f'https://github.com/{owner}', owner)} ", f"Created at - {Date(data['createdAt'])} ", f"Is archived - {Bool(data['isArchived'])} " ) grid.add_row( f"URL - {Link(data['url'], 'Link')} ", f"Updated at - {Date(data['updatedAt'])} ", f"Is disabled - {Bool(data['isDisabled'])} " ) grid.add_row( f"License - {Link(licenseInfo['url'], licenseInfo['spdxId'])} ", f"Pushed at - {Date(data['pushedAt'])} ", f"Is fork - {Bool(data['isFork'])} " ) grid.add_row( f"Latest Release - {Link(latestRelease['url'], latestRelease['name'])} ", f"Disk usage - {Size(disk_usage * 1024)} ", f"Is in org. - {Bool(data['isInOrganization'])} " ) grid.add_row( f"Forks - {Number(data['forkCount'])} ", f"Watchers - {Number(data['watchers']['totalCount'])} ", f"Is locked - {Bool(data['isLocked'])} " ) grid.add_row( f"Star count - {Number(data['stargazerCount'])} ", f"Open Issues - {Number(data['openIssues']['totalCount'])} ", f"Is mirror - {Bool(data['isMirror'])} " ) grid.add_row( f"Commit count - {Number(commit_count)} ", f"Closed Issues - {Number(data['issues']['totalCount'] - data['openIssues']['totalCount'])}", f"Is private - {Bool(data['isPrivate'])} " ) grid.add_row( f"Open p.r. - {Number(data['open_pr']['totalCount'])} ", f"Closed p.r. - {Number(data['closed_pr']['totalCount'])} ", f"Merged p.r. - {Number(data['merged_pr']['totalCount'])} ", ) else: grid.add_row( f"Owner - {Link(f'https://github.com/{owner}', owner)} ", f"Disk usage - {Size(disk_usage * 1024)} ", f"Created at - {Date(data['createdAt'])} ", ) grid.add_row( f"URL - {Link(data['url'], 'Link')} ", f"Stars - {Number(data['stargazerCount'])} ", f"Updated at - {Date(data['updatedAt'])} ", ) grid.add_row( f"License - {Link(licenseInfo['url'], licenseInfo['spdxId'])} ", f"Forks - {Number(data['forkCount'])} ", f"Pushed at - {Date(data['pushedAt'])} ", ) grid.add_row( f"Language - [green]{language}[/] ", f"Watchers - {Number(data['watchers']['totalCount'])} ", f"Open issues - {Number(data['openIssues']['totalCount'])} " ) print(grid)
5,346,031
def value_iteration(R, P, gamma, epsilon=1e-6): """ Value iteration for discounted problems. Parameters ---------- R : numpy.ndarray array of shape (S, A) contaning the rewards, where S is the number of states and A is the number of actions P : numpy.ndarray array of shape (S, A, S) such that P[s,a,ns] is the probability of arriving at ns by taking action a in state s. gamma : double discount factor epsilon : double precision Returns -------- tuple (Q, V, n_it) containing the epsilon-optimal Q and V functions, of shapes (S, A) and (S,), respectively, and n_it, the number of iterations """ S, A = R.shape Q = np.zeros((S, A)) Q_aux = np.full((S, A), np.inf) n_it = 0 while np.abs(Q - Q_aux).max() > epsilon: Q_aux = Q Q = bellman_operator(Q, R, P, gamma) n_it += 1 V = np.zeros(S) # numba does not support np.max(Q, axis=1) for ss in range(S): V[ss] = Q[ss, :].max() return Q, V, n_it
5,346,032
def write_quadruple(f, ent, rel, tim, q, S, P, O, T): """Write a quadruple to a file.""" f.write( str(ent[q[S]]) + "\t" + str(rel[q[P]]) + "\t" + str(ent[q[O]]) + "\t" + str(tim[q[T]]) + "\n" )
5,346,033
def mock_api_response(response_config={}): """Create a mock response from the Github API.""" headers = { 'ETag': 'W/"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"', 'Cache-Control': 'public, max-age=60, s-maxage=60', 'Content-Type': 'application/json; charset=utf-8' } api_response = MagicMock(spec=Response) api_response.content_type = 'application/json' for k, v in response_config.iteritems(): if k == 'headers': headers.update(v) setattr(api_response, k, v) # Request headers are case insensitive dicts, # so we need to turn our mock headers into one. api_response.headers = CaseInsensitiveDict(headers) return api_response
5,346,034
def shouty(src, dest): """ Takes a string and makes it SHOUTY. """ dest.write(src.read().upper())
5,346,035
def files_with_extension(path: str,extension: str): """ Gives a list of the files in the given directory that have the given extension Parameters ---------- path: str The full path to the folder where the files are stored extension: str The extension of the files Returns ------- List[str] A list containing the files """ from os import listdir return [f for f in listdir(path) if f.endswith(extension)]
5,346,036
def get_inputs_repl_cluster_or_vol(): """ This input is for clusters that have replication """ parser = argparse.ArgumentParser() parser.add_argument('-m', type=str, required=True, metavar='mvip', help='MVIP/node name or IP') parser.add_argument('-u', type=str, required=True, metavar='user', help='username to connect with') parser.add_argument('-p', type=str, required=False, metavar='user_pass', help='password for user') parser.add_argument('-o', type=str, required=False, metavar='check_opt', choices=['cluster', 'volume'], help='option for cluster or volume') args = parser.parse_args() mvip = args.m user = args.u check_opt = args.o if not args.p: user_pass = getpass("Enter password for user {} " "on cluster {}: ".format(user, mvip)) else: user_pass = args.p return mvip, user, user_pass, check_opt
5,346,037
def write_cases_to_latex(cases: dict, output_file: Path): """ Write a formatted conditionally colored table to a file """ for case in cases.values(): case.calculate_metric_terms() case_keys = list(cases.keys()) n_cases = len(cases) make_colorbar( cell_clip=5.0, label="$d_j$", output_path=output_file.parent / "colorbar.png" ) with open(output_file, "w") as f: # Header f.write(f"\\begin{{tabular}}{{ll{n_cases * 'cc'}}}\n") f.write(f"\\toprule\n") case_header = " & ".join( [ f"\\multicolumn{{2}}{{c}}{{{process_case_key(case_key)}}}" for case_key in case_keys ] ) f.write(f" & & {case_header} \\\\ \n") case_header = " & ".join(n_cases * ["$d_j$ & $S$"]) f.write(f"Diagnostic & observable & {case_header} \\\\ \n") f.write(f"\\midrule\n") # Write the results in for diagnostic, diagnostic_styled in diagnostics_latex.items(): # Assume that all cases have the same hierarchies, so take # the first value hierarchies = cases[case_keys[0]].hierarchy[diagnostic] n_observables = len(hierarchies) f.write( f"\\multirow{{{n_observables + 1}}}{{*}}{{\\makecell{{{diagnostic_styled}}}}}\n" ) d = np.nan * np.ones((n_observables, n_cases)) S = np.nan * np.ones((n_observables, n_cases)) H = np.nan * np.ones(n_observables) i = -1 for observable, observable_styled in observable_latex.items(): if observable in hierarchies.keys(): i += 1 H[i] = 1.0 / hierarchies[observable] f.write(f"& {observable_styled:40} & ") for j, case in enumerate(cases.values()): d[i, j] = case.distance[diagnostic][observable] write_number_w_color(d[i, j], file=f, cell_clip=5.0) f.write(" & ") S[i, j] = case.sensitivity[diagnostic][observable] write_number_w_color(S[i, j], file=f) if not j == n_cases - 1: # Don't write an alignment character for the last entry on a line f.write(" & ") f.write("\\\\\n") f.write(f"\\cline{{2-{2 * n_cases + 2}}}\n") Q = np.nansum(H[:, np.newaxis] * S, axis=0) chi = ( np.nansum(H[:, np.newaxis] * S * level_of_agreement_function(d), axis=0) / Q ) # Write diagnostic chi and Q diagnostic_summary = ( "$\\left(\\chi; Q\\right)$\\textsubscript" + f"{{{diagnostic}}}" ) f.write(f"& {diagnostic_summary:40} & ") for j in range(n_cases): f.write( "\\multicolumn{{2}}{{c}}{{$ \\textbf{{({chi:.2}; \\ {Q:.3})}} $ }}".format( chi=chi[j], Q=Q[j] ) ) if not j == n_cases - 1: # Don't write an alignment character for the last entry on a line f.write(" & ") f.write("\\\\\n") f.write("\\midrule\n") # Write the overall agreement f.write(f"Overall\n& {chi_latex + '; $Q$':40} & ") for j, case in enumerate(cases.values()): chi, Q = case.compute_chi() f.write( "\\multicolumn{{2}}{{c}}{{$ \\textbf{{({chi:.2}; \\ {Q:.3})}} $ }}".format( chi=chi, Q=Q ) ) if not j == n_cases - 1: # Don't write an alignment character for the last entry on a line f.write(" & ") else: f.write("\\\\\n") # Footer f.write("\\bottomrule\n") f.write("\\end{tabular}")
5,346,038
def load_jsonl(file_path): """ Load file.jsonl .""" data_list = [] with open(file_path, mode='r', encoding='utf-8') as fi: for idx, line in enumerate(tqdm(fi)): jsonl = json.loads(line) data_list.append(jsonl) return data_list
5,346,039
def aurora_forecast(): """ Get the latest Aurora Forecast from http://swpc.noaa.gov. Returns ------- img : numpy array The pixels of the image in a numpy array. img_proj : cartopy CRS The rectangular coordinate system of the image. img_extent : tuple of floats The extent of the image ``(x0, y0, x1, y1)`` referenced in the ``img_proj`` coordinate system. origin : str The origin of the image to be passed through to matplotlib's imshow. dt : datetime Time of forecast validity. """ # GitHub gist to download the example data from #url = ('https://gist.githubusercontent.com/belteshassar/' # 'c7ea9e02a3e3934a9ddc/raw/aurora-nowcast-map.txt') # To plot the current forecast instead, uncomment the following line url = 'http://services.swpc.noaa.gov/text/aurora-nowcast-map.txt' response_text = StringIO(urlopen(url).read().decode('utf-8')) img = np.loadtxt(response_text) # Read forecast date and time response_text.seek(0) for line in response_text: if line.startswith('Product Valid At:', 2): dt = datetime.strptime(line[-17:-1], '%Y-%m-%d %H:%M') img_proj = ccrs.PlateCarree() img_extent = (-180, 180, -90, 90) return img, img_proj, img_extent, 'lower', dt
5,346,040
def get_number_trips(grouped_counts): """ Gets the frequency of number of trips the customers make Args: grouped_counts (Pandas.DataFrame): The grouped dataframe returned from a get_trips method call Returns: Pandas.DataFrame: the dataframe containing the frequencies for each number of trips """ return frequency(grouped_counts.groupby('cust_id').count(), 0)
5,346,041
def process_text(text, max_features=200, stopwords=None): """Splits a long text into words, eliminates the stopwords and returns (words, counts) which is necessary for make_wordcloud(). Parameters ---------- text : string The text to be processed. max_features : number (default=200) The maximum number of words. stopwords : set of strings The words that will be eliminated. Notes ----- There are better ways to do word tokenization, but I don't want to include all those things. """ if stopwords is None: stopwords = STOPWORDS d = {} flags = re.UNICODE if type(text) is unicode else 0 for word in re.findall(r"\w[\w']*", text, flags=flags): if word.isdigit(): continue word_lower = word.lower() if word_lower in stopwords: continue # Look in lowercase dict. if word_lower in d: d2 = d[word_lower] else: d2 = {} d[word_lower] = d2 # Look in any case dict. d2[word] = d2.get(word, 0) + 1 d3 = {} for d2 in d.values(): # Get the most popular case. first = max(d2.iteritems(), key=item1)[0] d3[first] = sum(d2.values()) # merge plurals into the singular count (simple cases only) for key in d3.keys(): if key.endswith('s'): key_singular = key[:-1] if key_singular in d3: val_plural = d3[key] val_singular = d3[key_singular] d3[key_singular] = val_singular + val_plural del d3[key] words = sorted(d3.iteritems(), key=item1, reverse=True) words = words[:max_features] maximum = float(max(d3.values())) for i, (word, count) in enumerate(words): words[i] = word, count/maximum return words
5,346,042
def update_graph_map(n): """Update the graph rail network mapbox map. Returns: go.Figure: Scattermapbox of rail network graph """ return get_graph_map()
5,346,043
def get_party_leads_sql_string_for_state(party_id, state_id): """ :type party_id: integer """ str = """ select lr.candidate_id, c.fullname as winning_candidate, lr.constituency_id, cons.name as constituency, lr.party_id, lr.max_votes, (lr.max_votes-sr.votes) as lead, sr.candidate_id, loosing_candidate.fullname as runner_up, loosing_party.name as runner_up_party, sr.party_id, ltr.party_id from latest_results lr inner join latest_runners_up as sr on sr.constituency_id = lr.constituency_id inner join candidate c on c.id = lr.candidate_id inner join constituency cons on cons.id = lr.constituency_id inner join party loosing_party on loosing_party.id = sr.party_id inner join candidate loosing_candidate on loosing_candidate.id = sr.candidate_id inner join last_time_winners ltr on ltr.constituency_id=lr.constituency_id where lr.party_id = %s and cons.state_id = %s and lr.status = 'COUNTING' order by lead DESC""" % (party_id, state_id) return str;
5,346,044
def test_read_crux(real_crux_txt): """Test that we parse crux files correctly""" psms = crema.read_crux(real_crux_txt) assert isinstance(psms.data, pd.DataFrame) assert psms.data.shape == (21818, 11) assert list(psms.spectra.columns) == ["scan", "spectrum precursor m/z"] scores = { "refactored xcorr", "combined p-value", "exact p-value", "sp score", "delta_cn", "delta_lcn", "res-ev p-value", } assert set(psms.score_columns) == scores assert psms.scores.shape == (21818, len(scores)) assert psms.targets.shape == (21818,) assert psms.targets.sum() == 10909 assert (~psms.targets).sum() == 10909
5,346,045
def test_hash(): """ """
5,346,046
def opcode_J(renderer, line_cap): """Set line cap style (see p. 216)""" renderer.gs.line_cap = line_cap
5,346,047
def dt_dataset(): """ command line parameter checking filter for dataset files plausibility only. >>> old_state = test_config.setup() >>> cmdline.dataset("foo.nothing") Traceback (most recent call last): ... ValueError: Parameter 'foo.nothing' does not appear to be a dataset filename. >>> cmdline.dataset("data/j8bt05njq_raw.fits") 'data/j8bt05njq_raw.fits' >>> test_config.cleanup(old_state) """
5,346,048
def _check_nonint(logfile): """Do not allow opening of files through file descriptors""" if isinstance(logfile, int): raise TypeError('Integer logfiles not allowed')
5,346,049
def add_stored_files(srr_file, store_files, in_folder="", save_paths=False, usenet=False): """Add one or more files to a SRR reconstruction file. srr_file: the srr file to add files to store_files: a list of files to store in the srr first file will be at the top Wildcards are accepted for paths and file names. in_folder: root folder for relative paths to store necessary when save_paths is True #or paths are relative to in_folder in store_files save_paths: if the path relative to in_folder must be stored with the file name usenet: Don't try to add dupes and keep working quietly Will skip files that cannot be read when usenet=True. TODO: try to process the list like for usenet instead of failing completely? Raises ArchiveNotFoundError, DupeFileName, NotSrrFile, AttributeError """ if not isinstance(store_files, (list, tuple)): # we need a list store_files = [store_files] # Make it more likely to find duplicates store_files = list(map(os.path.normpath, store_files)) rr = RarReader(srr_file) # ArchiveNotFoundError if rr.file_type() != RarReader.SRR: raise NotSrrFile("Not an SRR file.") if _DEBUG: print("Checking for dupes before adding files.") for block in rr.read_all(): if block.rawtype == BlockType.SrrStoredFile: existing = block.os_file_name() if existing in store_files: msg = "There already is a file with the same name stored." _fire(MsgCode.DUPE, message=msg) if usenet: # don't try to add dupes and keep working quietly store_files.remove(existing) else: raise DupeFileName(msg) # create a temporarily file tmpfd, tmpname = mkstemp(prefix="srr_", suffix=".tmp", dir=os.path.dirname(srr_file)) tmpfile = os.fdopen(tmpfd, "wb") in_folder = in_folder if in_folder else os.path.dirname(srr_file) location = False # whether we've added the files or not if _DEBUG: print("Reading blocks for adding files.") try: for block in rr.read_all(): # add the files before the srr rar blocks if block.rawtype == BlockType.SrrRarFile and not location: location = True if not usenet: amount_added = 0 for f in _search(store_files, in_folder): _store(f, tmpfile, save_paths, in_folder) amount_added += 1 if not amount_added: _fire(MsgCode.NO_FILES, message="No files found to add.") else: #TODO: make it nicer for f in store_files: _store_fh(f, tmpfile) tmpfile.write(block.block_bytes()) # we need to copy the contents from blocks too if block.rawtype == BlockType.SrrStoredFile: tmpfile.write(block.srr_data()) # XXX: will this always work correct? if not location: # music video SRR file: add to end if not usenet: amount_added = 0 for f in _search(store_files, in_folder): _store(f, tmpfile, save_paths, in_folder) amount_added += 1 if not amount_added: _fire(MsgCode.NO_FILES, message="No files found to add.") else: #TODO: make it nicer for f in store_files: _store_fh(f, tmpfile) except: tmpfile.close() os.unlink(tmpname) raise else: tmpfile.close() # if not location: # # Bad SRR file or RAR file given. # os.remove(tmpname) # raise NotSrrFile("No SrrRarFile blocks detected. -> Not SRR. " # "Zero files added.") # original srr file is replaced by the temp file os.remove(srr_file) os.rename(tmpname, srr_file)
5,346,050
def goods_images(goods_url): """ 获得商品晒图 Parameters: goods_url - str 商品链接 Returns: image_urls - list 图片链接 """ image_urls = [] productId = goods_url.split('/')[-1].split('.')[0] # 评论url comment_url = 'https://sclub.jd.com/comment/productPageComments.action' comment_params = {'productId':productId, 'score':'0', 'sortType':'5', 'page':'0', 'pageSize':'10', 'isShadowSku':'0', 'fold':'1'} comment_headers = {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36', 'Referer':goods_url, 'Host': 'sclub.jd.com'} comment_req = requests.get(url=comment_url, params=comment_params, headers=comment_headers, verify=False) html = json.loads(comment_req.text) # 获得晒图个数 imageListCount = html['imageListCount'] # 计算晒图页数,向上取整 pages = math.ceil(imageListCount / 10) for page in range(1, pages+1): # 获取晒图图片url club_url = 'https://club.jd.com/discussion/getProductPageImageCommentList.action' now = time.time() now_str = str(now).split('.') now = now_str[0] + now_str[-1][:3] club_params = {'productId':productId, 'isShadowSku':'0', 'page':page, 'pageSize':'10', '_':now} club_headers = comment_headers club_req = requests.get(url=club_url, params=club_params, headers=club_headers, verify=False) html = json.loads(club_req.text) for img in html['imgComments']['imgList']: image_urls.append(img['imageUrl']) # 去重 image_urls = list(set(image_urls)) # 链接合成 image_urls = list(map(lambda x: 'http:'+x, image_urls)) return image_urls
5,346,051
def delete_index_list(base_list, index_list): """ 根据index_list删除base_list中指定元素 :param base_list: :param index_list: :return: """ if base_list and index_list: return [base_list[i] for i in range(len(base_list)) if (i not in index_list)]
5,346,052
def generate_mutated_template(template, outfile, changes_file, header, seedval=None): """Generate a mutated template and writes fasta and changes file""" if seedval: np.random.seed(seedval) seed(seedval) else: np.random.seed() seed() mutated_template, changes = mutate_template(template) write_fasta(outfile, mutated_template, header) write_changes(changes_file, changes) return
5,346,053
def not_found(): """Page not found.""" return make_response( render_template("404.html"), 404 )
5,346,054
def _traverseAgg(e, visitor=lambda n, v: None): """ Traverse a parse-tree, visit each node if visit functions return a value, replace current node """ res = [] if isinstance(e, (list, ParseResults, tuple)): res = [_traverseAgg(x, visitor) for x in e] elif isinstance(e, CompValue): for k, val in e.iteritems(): if val != None: res.append(_traverseAgg(val, visitor)) return visitor(e, res)
5,346,055
def roll(image, delta): """Roll an image sideways (A more detailed explanation goes here.) """ xsize, ysize = image.size delta = delta % xsize if delta == 0: print("the delta was 0!") return image part1 = image.crop((0, 0, delta, ysize)) part2 = image.crop((delta, 0, xsize, ysize)) image.paste(part2, (0, 0, xsize-delta, ysize)) image.paste(part1, (xsize-delta, 0, xsize, ysize)) return image
5,346,056
def make_long_format(path_list, args): """Output list of strings in informative line-by-line format like ls -l Args: path_list (list of (str, zipfile.Zipinfo)): tuples, one per file component of zipfile, with relative file path and zipinfo args (argparse.Namespace): user arguments to script, esp. switches Returns: list of str: list of lines to be printed out one at a time """ path_str_list = [] if args.human_readable: # by design of human-readable formatting max_size_str_len = 4 else: # find longest length of size str to determine width of string field max_size_str_len = 0 for path in path_list: # find longest size string of all paths in pathlist size_str_len = len(format_file_size(path[1].file_size, args)) if size_str_len > max_size_str_len: max_size_str_len = size_str_len for path in path_list: # extra_data = path[1].extra # os_creator = path[1].create_system # 3-unix if path[1].is_dir(): dir_str = "d" else: dir_str = "-" perm_octal = get_zip_perms(path[1]) perm_str = perm_octal2str(perm_octal) + " " size_str = format_file_size(path[1].file_size, args, max_size_str_len) size_str += " " date_str = get_zip_mtime(path[1]) path_str = color_classify(path, args) path_str_list.append(dir_str + perm_str + size_str + date_str + path_str) return path_str_list
5,346,057
def is_name_a_title(name, content): """Determine whether the name property represents an explicit title. Typically when parsing an h-entry, we check whether p-name == e-content (value). If they are non-equal, then p-name likely represents a title. However, occasionally we come across an h-entry that does not provide an explicit p-name. In this case, the name is automatically generated by converting the entire h-entry content to plain text. This definitely does not represent a title, and looks very bad when displayed as such. To handle this case, we broaden the equality check to see if content is a subset of name. We also strip out non-alphanumeric characters just to make the check a little more forgiving. :param str name: the p-name property that may represent a title :param str content: the plain-text version of an e-content property :return: True if the name likely represents a separate, explicit title """ def normalize(s): if not isinstance(s, string_type): s = s.decode('utf-8') s = unicodedata.normalize('NFKD', s) s = s.lower() s = re.sub('[^a-z0-9]', '', s) return s if not content: return True if not name: return False return normalize(content) not in normalize(name)
5,346,058
def insertTweet(details, insertDuplicates=True): """ Adds tweet to database @param details {Dict} contains tweet details @param insertDuplicates {Boolean} optional, if true it will insert even if already exists """ try: if not insertDuplicates: tweet_results = get_tweet_by_id(details['itemid']) if tweet_results != None: logger.info(tweet_results) return False tweet = Tweet( twitter_handle=details['handle'], tweet_time=datetime.datetime.utcfromtimestamp(details['time']), tweet_text=details['text'], data_type=details['type'], data_id=details['itemid'], retweets=details['retweets'], favorites=details['favorites'], status=1 ) session.add(tweet) session.commit() addTweetToHandler(tweet,details['handle']) return True except Exception as e: traceback.print_exc() traceback.print_stack() print("ERROR OCCURED WHEN INSERTING TWEET") print(e) session.rollback() return False
5,346,059
def dump_yaml(file_path, data): """Dump data to a file. :param file_path: File path to dump data to :type file_path: String :param data: Dictionary|List data to dump :type data: Dictionary|List """ with open(os.path.abspath(os.path.expanduser(file_path)), "w") as f: yaml.safe_dump(data, f, default_flow_style=False) return file_path
5,346,060
def pull_apk(package=None, regex=None, devices=None, local_dir=None, force=False): """ Downloads the package apk. If regex matches multiple packages and force is True, each package apk will be downloaded. Args: package: package name as string. regex: string. devices: list of device serials. local_dir: local directory as string. force: boolean. """ _ensure_package_or_regex_given(package, regex) if devices is None: devices = attached_devices() if local_dir is None: local_dir = os.getcwd() if package is not None: for device in devices: _pull_apk(package, device, local_dir) else: _package_iter(regex, devices, _pull_apk, force, local_dir)
5,346,061
def return_embeddings(embedding: str, vocabulary_size: int, embedding_dim: int, worddicts: OrderedDict) -> np.ndarray: """Create array of word embeddings.""" word_embeddings = np.zeros((vocabulary_size, dim_word)) with open(embedding, 'r') as f: for line in f: words=line.split() word = words[0] vector = words[1:] len_vec = len(vector) if(len_vec>300): diff = len_vec-300 word = word.join(vector[:diff]) vector = vector[diff:] if word in worddicts and worddicts[word] < vocabulary_size: vector = [float(x) for x in vector] word_embeddings[worddicts[word], :] = vector[0:300] return word_embeddings
5,346,062
def symLink(twist, dist, angle, offset): """ Transform matrix of this link with DH parameters. (Use symbols) """ twist = twist * sympy.pi / 180 T1 = sympy.Matrix([ [1, 0, 0, dist], [0, sympy.cos(twist), -sympy.sin(twist), 0], [0, sympy.sin(twist), sympy.cos(twist), 0], [0, 0, 0, 1]]) # T1[sympy.abs(T1) < 1e-3] = 0 T2 = sympy.Matrix([ [sympy.cos(angle), -sympy.sin(angle), 0, 0], [sympy.sin(angle), sympy.cos(angle), 0, 0], [0, 0, 1, offset], [0, 0, 0, 1]]) return T1 * T2
5,346,063
async def _parse_action_body(service: UpnpServerService, request: aiohttp.web.Request) -> Tuple[str, Dict[str, Any]]: """Parse action body.""" # Parse call. soap = request.headers.get("SOAPAction", "").strip('"') try: _, action_name = soap.split("#") data = await request.text() root_el: ET.Element = DET.fromstring(data) body_els: Sequence[ET.Element] = root_el.find("s:Body", NAMESPACES) rpc_el = body_els[0] except Exception as exc: raise aiohttp.web.HTTPBadRequest(reason="InvalidSoap") from exc if action_name not in service.actions: raise aiohttp.web.HTTPBadRequest(reason="InvalidAction") kwargs: Dict[str, Any] = {} action = service.action(action_name) for arg in rpc_el: action_arg = action.argument(arg.tag, direction="in") if action_arg is None: raise aiohttp.web.HTTPBadRequest(reason="InvalidArg") state_var = action_arg.related_state_variable kwargs[arg.tag] = state_var.coerce_python(arg.text) return action_name, kwargs
5,346,064
def get_tc_json(): """Get the json for this testcase.""" try: with open(GLOBAL_INPUT_JSON_PATH) as json_file: tc = json.load(json_file) except Exception: return_error('Could not custom_validator_input.json') return tc
5,346,065
def dualgauss(x, x1, x2, w1, w2, a1, a2, c=0): """ Sum of two Gaussian distributions. For curve fitting. Parameters ---------- x: np.array Axis x1: float Center of 1st Gaussian curve x2: float Center of 2nd Gaussian curve w1: float Width of 1st Gaussian curve w2: float Width of 2nd Gaussian curve a1: float Amplitude of 1st Gaussian curve a2: float Amplitude of 2nd Gaussian curve c: float, optional Offset, defaults to 0 """ return a1*np.exp(-0.5*((x-x1)/w1)**2)+a2*np.exp(-0.5*((x-x2)/w2)**2) + c
5,346,066
def pdg_format3( value , error1 , error2 , error3 , latex = False , mode = 'total' ) : """Round value/error accoridng to PDG prescription and format it for print @see http://pdg.lbl.gov/2010/reviews/rpp2010-rev-rpp-intro.pdf @see section 5.3 of doi:10.1088/0954-3899/33/1/001 Quote: The basic rule states that - if the three highest order digits of the error lie between 100 and 354, we round to two significant digits. - If they lie between 355 and 949, we round to one significant digit. - Finally, if they lie between 950 and 999, we round up to 1000 and keep two significant digits. In all cases, the central value is given with a precision that matches that of the error. >>> value, error1, error2 = ... >>> print ' Rounded value/error is %s ' % pdg_format2 ( value , error1 , error2 , True ) """ error = ref_error ( mode , error1 , error2 , error3 ) val , err , q , ecase = pdg_round__ ( value , error ) if ecase <= 0 or ( not isfinite ( error1 ) ) or ( not isfinite ( error2 ) ) or ( not isfinite ( error3 ) ) : if not isfinite ( val ) : return ( '%+g \\pm %-g \\pm %-g \\pm %-g ' % ( val , error1 , error2 , error3 ) ) if latex else \ ( '%+g +/- %-g +/- %-g +/- %-g' % ( val , error1 , error2 , error3 ) ) else : qv , bv = _frexp10_ ( val ) if 0 != bv : scale = 1.0 / 10**bv if latex : return '(%+.2f \\pm %-s \\pm %-s)\\times 10^{%d}' % ( qv , error1 * scale , error2 * scale , error3 * scale , bv ) else : return ' %+.2f +/- %-s +/ %-s +/- %-s )*10^{%d} ' % ( qv , error1 * scale , error2 * scale , error3 * scale , bv ) else : if latex : return ' %+.2f \\pm %-s \\pm %-s \\pm %-s ' % ( qv , error1 , error2 , error3 ) else : return ' %+.2f +/- %-s +/- %-s +/- %-s ' % ( qv , error1 , error2 , error3 ) qe , be = _frexp10_ ( error ) a , b = divmod ( be , 3 ) if 1 == ecase : err1 = round_N ( error1 , 2 ) if isclose ( error1 , error , 1.e-2 ) else err err2 = round_N ( error2 , 2 ) if isclose ( error2 , error , 1.e-2 ) else err err3 = round_N ( error3 , 2 ) if isclose ( error3 , error , 1.e-2 ) else err if 0 == b : nd = 1 elif 1 == b : nd = 3 a += 1 elif 2 == b : a += 1 nd = 2 elif 2 == ecase : err1 = round_N ( error1 , 1 ) if isclose ( error1 , error , 1.e-2 ) else err err2 = round_N ( error2 , 1 ) if isclose ( error2 , error , 1.e-2 ) else err err3 = round_N ( error3 , 1 ) if isclose ( error3 , error , 1.e-2 ) else err if 0 == b : nd = 0 if 2 == a % 3 : nd = 3 a = a + 1 elif 1 == b : nd = 2 a += 1 elif 2 == b : nd = 1 a += 1 elif 3 == ecase : err1 = round_N ( error1 , 2 ) if isclose ( error1 , error , 1.e-2 ) else err err2 = round_N ( error2 , 2 ) if isclose ( error2 , error , 1.e-2 ) else err err3 = round_N ( error3 , 2 ) if isclose ( error3 , error , 1.e-2 ) else err if 0 == b : nd = 0 if 2 == a % 3 : nd = 3 a = a + 1 elif 1 == b : nd = 2 a += 1 elif 2 == b : nd = 1 a += 1 if 0 == a : if latex: fmt = '(%%+.%df \\pm %%.%df \\pm %%.%df \\pm %%.%df)' % ( nd , nd , nd , nd ) else : fmt = ' %%+.%df +/- %%.%df +/- %%.%df +/- %%.%df ' % ( nd , nd , nd . nd ) return fmt % ( val , err ) if latex: fmt = '(%%+.%df \\pm %%.%df \\pm %%.%df \\pm %%.%df)\\times 10^{%%d}' % ( nd , nd , nd , nd ) else : fmt = '(%%+.%df +/- %%.%df +/- %%.%df +/- %%.%df)*10^{%%d}' % ( nd , nd , nd , nd ) scale = 1.0/10**(3*a) return fmt % ( val * scale , err1 * scale , err2 * scale , err3 * scale , 3 * a )
5,346,067
def getChinaHoliday(t): """找出距离输入日期最近的中国节日,输出距离的天数""" date_time = datetime.datetime.strptime(t, '%d %B %Y') y = date_time.year # 中国阳历节日 sh = [ (y, 1, 1), # 元旦 (y, 4, 5), # 清明 (y, 5, 1), # 五一劳动节 (y, 10, 1) # 国庆节 ] # 中国阴历节日 lh = [ (y, 1, 1), # 大年初一(春节) (y, 5, 5), # 端午节 (y, 8, 15) # 中秋节 ] res = 365 for h in sh: hd = datetime.datetime(h[0], h[1], h[2], 0, 0, 0) ds = (date_time-hd).days if abs(ds) < res: # 距离输入的日期最近的阳历节日 res = abs(ds) for h in lh: ld = lunardate.LunarDate(h[0], h[1], h[2], 0).toSolarDate() hd = datetime.datetime(ld.year, ld.month, ld.day, 0, 0, 0) ds = (date_time-hd).days if abs(ds) < res: # 距离输入的日期最近的阴历节日 res = abs(ds) # print t,res return res pass
5,346,068
def parse_mimetype(mimetype): """Parses a MIME type into its components. :param str mimetype: MIME type :returns: 4 element tuple for MIME type, subtype, suffix and parameters :rtype: tuple Example: >>> parse_mimetype('text/html; charset=utf-8') ('text', 'html', '', {'charset': 'utf-8'}) """ if not mimetype: return '', '', '', {} parts = mimetype.split(';') params = [] for item in parts[1:]: if not item: continue key, value = item.split('=', 1) if '=' in item else (item, '') params.append((key.lower().strip(), value.strip(' "'))) params = dict(params) fulltype = parts[0].strip().lower() if fulltype == '*': fulltype = '*/*' mtype, stype = fulltype.split('/', 1) \ if '/' in fulltype else (fulltype, '') stype, suffix = stype.split('+', 1) if '+' in stype else (stype, '') return mtype, stype, suffix, params
5,346,069
def terraform_state_bucket(config): """Get the bucket name to be used for the remote Terraform state Args: config (dict): The loaded config from the 'conf/' directory Returns: string: The bucket name to be used for the remote Terraform state """ # If a bucket name is specified for the remote Terraform state, we can assume the bucket # should NOT be created default_name = DEFAULT_TERRAFORM_STATE_BUCKET_SUFFIX.format( config['global']['account']['prefix'] ) if 'terraform' not in config['global']: return default_name, True # Use the default name and create the bucket bucket_name = config['global']['terraform'].get( 'bucket_name', default_name ) return bucket_name, bucket_name == default_name
5,346,070
def get_binary_matrix(gene_expr, libraries): """ Get binary matrix with genes as rows and pathways as columns. If a gene is found in a given pathway, it is given a value of 1. Else, 0. Only the list of genes in common between that found in the gene set libraries and the current dataset are used. """ function_to_genes = {} set_genes = set() for lib in libraries: f2g, genes = gene_set_dictionaries(lib) function_to_genes.update(f2g) set_genes = set_genes | set(genes) common_genes = list(set_genes & set(gene_expr)) binary_matrix = gs_binary_matrix(function_to_genes, set_genes).loc[common_genes] return binary_matrix
5,346,071
def _delete_policy(policy_name): """ deletes a policy :param str policy_name: the policy name """ url = urljoin(_base_url, 'policies/{vhost}/{name}'.format(vhost=quote(VHOST), name=quote(policy_name))) response = requests.delete(url) if not response.ok: error = "Can't delete policy. error: {}".format(response.content) logging.error(error) raise Exception(error)
5,346,072
def get_tip_downvotes(tips_id): """ GET function for retrieving all User objects that have downvoted a tip """ tip = Tips.objects.get(id=tips_id) tips_downvotes = (tip.to_mongo())["downvotes"] tips_downvotes_list = [ User.objects.get(id=str(user)).to_mongo() for user in tips_downvotes ] response = {"users": tips_downvotes_list} return create_response(data=response)
5,346,073
def count_str_in_read(read_data, string, id_map): """ Count occuerances of a string in a read. """ x = np.zeros(len(read_data)) y = np.zeros_like(x) c = np.zeros_like(x) for i, doc in enumerate(read_data): x[i], y[i] = id_map[doc["barcode"]] c[i] = doc["Read"].count(string)
5,346,074
def get_placements( big_graph: nx.Graph, small_graph: nx.Graph, max_placements=100_000 ) -> List[Dict]: """Get 'placements' mapping small_graph nodes onto those of `big_graph`. This function considers monomorphisms with a restriction: we restrict only to unique set of `big_graph` qubits. Some monomorphisms may be basically the same mapping just rotated/flipped which we purposefully exclude. This could exclude meaningful differences like using the same qubits but having the edges assigned differently, but it prevents the number of placements from blowing up. Args: big_graph: The parent, super-graph. We often consider the case where this is a nx.Graph representation of a Device whose nodes are `cirq.Qid`s like `GridQubit`s. small_graph: The subgraph. We often consider the case where this is a NamedTopology graph. max_placements: Raise a value error if there are more than this many placement possibilities. It is possible to use `big_graph`, `small_graph` combinations that result in an intractable number of placements. Raises: ValueError: if the number of placements exceeds `max_placements`. Returns: A list of placement dictionaries. Each dictionary maps the nodes in `small_graph` to nodes in `big_graph` with a monomorphic relationship. That's to say: if an edge exists in `small_graph` between two nodes, it will exist in `big_graph` between the mapped nodes. """ matcher = nx.algorithms.isomorphism.GraphMatcher(big_graph, small_graph) # de-duplicate rotations, see docstring. dedupe = {} for big_to_small_map in matcher.subgraph_monomorphisms_iter(): dedupe[frozenset(big_to_small_map.keys())] = big_to_small_map if len(dedupe) > max_placements: # coverage: ignore raise ValueError( f"We found more than {max_placements} placements. Please use a " f"more constraining `big_graph` or a more constrained `small_graph`." ) small_to_bigs = [] for big in sorted(dedupe.keys()): big_to_small_map = dedupe[big] small_to_big_map = {v: k for k, v in big_to_small_map.items()} small_to_bigs.append(small_to_big_map) return small_to_bigs
5,346,075
def normalise(hists, integration_range=None, norm_scale=1.): """ Wrapper for normalisation of histograms to a given scale in a given interval :param hists: histograms :type hists: list of dictionary of histograms :param integration_range: range in which integration should be performed (default fill range) :type integration_range: list (default: None) :param norm_scale: normalisation scale (default 1.) :type norm_scale: float :return: nothing :rtype: None """ if integration_range is None: integration_range = [-1, -1] if type(hists) == dict: for h in list(hists.keys()): hists[h] = normalise_hist(hists[h], integration_range, norm_scale) elif type(hists) == list: for h in hists: h = normalise_hist(h, integration_range, norm_scale) else: hists = normalise_hist(hists, integration_range, norm_scale)
5,346,076
def make_static_server_url_stop(root, host=HOST, port=PORT): """start a tornado static file server""" server_args = [ "python", str(PA11Y / "serve.py"), f"--host={host}", f"--port={port}", f"--path={root}", ] url = f"http://{host}:{port}/" def stop(): server.terminate() server.wait() server = subprocess.Popen(server_args) return server, url, stop
5,346,077
def request_url(url): """ get the resource associated with a url. """ try: # -- todo; eliminate pesky assignment so can be put into chain of Ok then's. user_agent = 'Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31' response = requests.get( urllib.parse.unquote(url), headers = { 'User-agent': user_agent, 'Connection': 'close' }, timeout = 30) return Ok(response) except http.client.BadStatusLine as err: return Err({ 'message': "%s returned an unrecognised status." % (url, ), 'code': 404 }) except requests.exceptions.ConnectionError as err: return Err({ 'message': "%s refused the connection." % (url, ), 'code': 404 }) except requests.exceptions.Timeout as err: return Err({ 'message': "%s timed out." % (url, ), 'code': 404 }) except Exception as err: return Err(err)
5,346,078
def makecall(call, stdout=None, stderr=None, stdin=None): """Simplifies running system calls using the subprocess module. stdout and sterr are written to files automatically. """ # streams are ignored if stdout == None and stderr == None and stdin == None: subprocess.call(call) elif stdout != None: with open(stdout, 'w') as outfl: if stderr != None: with open(stderr, 'w') as errfl: # stderr is written to a new file if stdin == None: subprocess.call(call, stdout=outfl, stderr=errfl) # receives a stream from stdin and writes stdin and # stdout are written to files else: with open(stdin, 'r') as inFl: subprocess.call(call, stdin=inFl, stdout=outfl, stderr=errfl) elif stderr == None: # stdout is written to a file if stdin == None: subprocess.call(call, stdout=outfl) # receives a stream from stdin and writes stdout to a # new file else: with open(stdin, 'r') as inFl: subprocess.call(call, stdin=inFl, stdout=outfl) elif stderr != None and stdout == None: with open(stderr, 'w') as errfl: # stderr is written to a file if stdin == None: subprocess.call(call, stderr=errfl) else: # receives a stream from stdin and writes stdout to a # new file with open(stdin, 'r') as inFl: subprocess.call(call, stdin=inFl, stderr=errfl) # receives a stream from stdin elif stdin != None and stderr == None and stdout == None: with open(stdin, 'r') as inFl: subprocess.call(call, stdin=inFl)
5,346,079
def _filter_baseanalysis_kwargs(function, kwargs): """ create two dictionaries with kwargs separated for function and AnalysisBase Parameters ---------- function : callable function to be called kwargs : dict keyword argument dictionary Returns ------- base_args : dict dictionary of AnalysisBase kwargs kwargs : dict kwargs without AnalysisBase kwargs Raises ------ ValueError : if ``function`` has the same kwargs as ``BaseAnalysis`` """ base_argspec = inspect.getargspec(AnalysisBase.__init__) n_base_defaults = len(base_argspec.defaults) base_kwargs = {name: val for name, val in zip(base_argspec.args[-n_base_defaults:], base_argspec.defaults)} argspec = inspect.getargspec(function) for base_kw in six.iterkeys(base_kwargs): if base_kw in argspec.args: raise ValueError( "argument name '{}' clashes with AnalysisBase argument." "Now allowed are: {}".format(base_kw, list(base_kwargs.keys()))) base_args = {} for argname, default in six.iteritems(base_kwargs): base_args[argname] = kwargs.pop(argname, default) return base_args, kwargs
5,346,080
def torch_to_flax(torch_params, get_flax_keys): """Convert PyTorch parameters to nested dictionaries""" def add_to_params(params_dict, nested_keys, param, is_conv=False): if len(nested_keys) == 1: key, = nested_keys params_dict[key] = np.transpose(param, (2, 3, 1, 0)) if is_conv else np.transpose(param) else: assert len(nested_keys) > 1 first_key = nested_keys[0] if first_key not in params_dict: params_dict[first_key] = {} add_to_params(params_dict[first_key], nested_keys[1:], param, ('conv' in first_key and \ nested_keys[-1] != 'bias')) def add_to_state(state_dict, keys, param): key_str = '' for k in keys[:-1]: key_str += f"/{k}" if key_str not in state_dict: state_dict[key_str] = {} state_dict[key_str][keys[-1]] = param flax_params, flax_state = {}, {} for key, tensor in torch_params.items(): if flax_keys[-1] is None: continue flax_keys = get_flax_keys(key.split('.')) if flax_keys[-1] == 'mean' or flax_keys[-1] == 'var': add_to_state(flax_state, flax_keys, tensor.detach().numpy()) else: add_to_params(flax_params, flax_keys, tensor.detach().numpy()) return flax_params, flax_state
5,346,081
def subset_shape( ds: Union[xarray.DataArray, xarray.Dataset], shape: Union[str, Path, gpd.GeoDataFrame], raster_crs: Optional[Union[str, int]] = None, shape_crs: Optional[Union[str, int]] = None, buffer: Optional[Union[int, float]] = None, start_date: Optional[str] = None, end_date: Optional[str] = None, first_level: Optional[Union[float, int]] = None, last_level: Optional[Union[float, int]] = None, ) -> Union[xarray.DataArray, xarray.Dataset]: """Subset a DataArray or Dataset spatially (and temporally) using a vector shape and date selection. Return a subset of a DataArray or Dataset for grid points falling within the area of a Polygon and/or MultiPolygon shape, or grid points along the path of a LineString and/or MultiLineString. If the shape consists of several disjoint polygons, the output is cut to the smallest bbox including all polygons. Parameters ---------- ds : Union[xarray.DataArray, xarray.Dataset] Input values. shape : Union[str, Path, gpd.GeoDataFrame] Path to shape file, or directly a geodataframe. Supports formats compatible with geopandas. raster_crs : Optional[Union[str, int]] EPSG number or PROJ4 string. shape_crs : Optional[Union[str, int]] EPSG number or PROJ4 string. buffer : Optional[Union[int, float]] Buffer the shape in order to select a larger region stemming from it. Units are based on the shape degrees/metres. start_date : Optional[str] Start date of the subset. Date string format -- can be year ("%Y"), year-month ("%Y-%m") or year-month-day("%Y-%m-%d"). Defaults to first day of input data-array. end_date : Optional[str] End date of the subset. Date string format -- can be year ("%Y"), year-month ("%Y-%m") or year-month-day("%Y-%m-%d"). Defaults to last day of input data-array. first_level : Optional[Union[int, float]] First level of the subset. Can be either an integer or float. Defaults to first level of input data-array. last_level : Optional[Union[int, float]] Last level of the subset. Can be either an integer or float. Defaults to last level of input data-array. Returns ------- Union[xarray.DataArray, xarray.Dataset] A subset of `ds` Notes ----- If no CRS is found in the shape provided (e.g. RFC-7946 GeoJSON, https://en.wikipedia.org/wiki/GeoJSON), assumes a decimal degree datum (CRS84). Be advised that EPSG:4326 and OGC:CRS84 are not identical as axis order of lat and long differs between the two (for more information, see: https://github.com/OSGeo/gdal/issues/2035). Examples -------- >>> import xarray as xr # doctest: +SKIP >>> from clisops.core.subset import subset_shape # doctest: +SKIP >>> pr = xr.open_dataset(path_to_pr_file).pr # doctest: +SKIP ... # Subset data array by shape >>> prSub = subset_shape(pr, shape=path_to_shape_file) # doctest: +SKIP ... # Subset data array by shape and single year >>> prSub = subset_shape(pr, shape=path_to_shape_file, start_date='1990-01-01', end_date='1990-12-31') # doctest: +SKIP ... # Subset multiple variables in a single dataset >>> ds = xr.open_mfdataset([path_to_tasmin_file, path_to_tasmax_file]) # doctest: +SKIP >>> dsSub = subset_shape(ds, shape=path_to_shape_file) # doctest: +SKIP """ wgs84 = CRS(4326) # PROJ4 definition for WGS84 with longitudes ranged between -180/+180. wgs84_wrapped = CRS.from_string( "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs lon_wrap=180" ) if isinstance(ds, xarray.DataArray): ds_copy = ds._to_temp_dataset() else: ds_copy = ds.copy() if isinstance(shape, gpd.GeoDataFrame): poly = shape.copy() else: poly = gpd.GeoDataFrame.from_file(shape) if buffer is not None: poly.geometry = poly.buffer(buffer) # Get the shape's bounding box. minx, miny, maxx, maxy = poly.total_bounds lon_bnds = (minx, maxx) lat_bnds = (miny, maxy) # If polygon doesn't cross prime meridian, subset bbox first to reduce processing time # Only case not implemented is when lon_bnds cross the 0 deg meridian but dataset grid has all positive lons try: ds_copy = subset_bbox(ds_copy, lon_bnds=lon_bnds, lat_bnds=lat_bnds) except ValueError as e: raise ValueError( "No grid cell centroids found within provided polygon bounding box. " 'Try using the "buffer" option to create an expanded area.' ) from e except NotImplementedError: pass lon = get_lon(ds_copy) lat = get_lat(ds_copy) if start_date or end_date: ds_copy = subset_time(ds_copy, start_date=start_date, end_date=end_date) if first_level or last_level: ds_copy = subset_level(ds_copy, first_level=first_level, last_level=last_level) # Determine whether CRS types are the same between shape and raster if shape_crs is not None: try: shape_crs = CRS.from_user_input(shape_crs) except ValueError: raise else: try: shape_crs = CRS(poly.crs) except CRSError: poly.crs = wgs84 shape_crs = wgs84 wrap_lons = False if raster_crs is not None: try: raster_crs = CRS.from_user_input(raster_crs) except ValueError: raise else: if np.min(lat_bnds) < -90 or np.max(lat_bnds) > 90: raise ValueError("Latitudes exceed domain of WGS84 coordinate system.") if np.min(lon_bnds) < -180 or np.max(lon_bnds) > 180: raise ValueError("Longitudes exceed domain of WGS84 coordinate system.") try: # Extract CF-compliant CRS_WKT from crs variable. raster_crs = CRS.from_cf(ds_copy.crs.attrs) except AttributeError as e: # This is guessing that lons are wrapped around at 180+ but without much information, this might not be true if np.min(lon) >= -180 and np.max(lon) <= 180: raster_crs = wgs84 elif np.min(lon) >= 0 and np.max(lon) <= 360: wrap_lons = True raster_crs = wgs84_wrapped else: raise CRSError( "Raster CRS is not known and does not resemble WGS84." ) from e _check_crs_compatibility(shape_crs=shape_crs, raster_crs=raster_crs) mask_2d = create_mask(x_dim=lon, y_dim=lat, poly=poly, wrap_lons=wrap_lons).clip( 1, 1 ) # 1 on the shapes, NaN elsewhere. # We simply want to remove the 0s from the zeroth shape, for our outer mask trick below. if np.all(mask_2d.isnull()): raise ValueError( f"No grid cell centroids found within provided polygon bounds ({poly.bounds}). " 'Try using the "buffer" option to create an expanded areas or verify polygon.' ) sp_dims = set(mask_2d.dims) # Spatial dimensions # Find the outer mask. When subsetting unconnected shapes, # we dont want to drop the inner NaN regions, it may cause problems downstream. inner_mask = xarray.full_like(mask_2d, True, dtype=bool) for dim in sp_dims: # For each dimension, propagate shape indexes in either directions # Then sum on the other dimension. You get a step function going from 0 to X. # The non-zero part that left and right have in common is the "inner" zone. left = mask_2d.bfill(dim).sum(sp_dims - {dim}) right = mask_2d.ffill(dim).sum(sp_dims - {dim}) # True in the inner zone, False in the outer inner_mask = inner_mask & (left != 0) & (right != 0) # inner_mask including the shapes inner_mask = mask_2d.notnull() | inner_mask # loop through variables for v in ds_copy.data_vars: if set.issubset(sp_dims, set(ds_copy[v].dims)): # 1st mask values outside shape, then drop values outside inner_mask ds_copy[v] = ds_copy[v].where(mask_2d.notnull()) # Remove grid points outside the inner mask # Then extract the coords. # Using a where(inner_mask) on ds_copy triggers warnings with dask, sel seems safer. mask_2d = mask_2d.where(inner_mask, drop=True) for dim in sp_dims: ds_copy = ds_copy.sel({dim: mask_2d[dim]}) # Add a CRS definition using CF conventions and as a global attribute in CRS_WKT for reference purposes ds_copy.attrs["crs"] = raster_crs.to_string() ds_copy["crs"] = 1 ds_copy["crs"].attrs.update(raster_crs.to_cf()) for v in ds_copy.variables: if {lat.name, lon.name}.issubset(set(ds_copy[v].dims)): ds_copy[v].attrs["grid_mapping"] = "crs" if isinstance(ds, xarray.DataArray): return ds._from_temp_dataset(ds_copy) return ds_copy
5,346,082
def plot_record_static( record, save=True, scale=1000, select_kw={}, x_prop='wavenumber', **kwargs ): """Figure of Static data from a record. High level function. record: Record to get data from save: Boolean, Save figure scale: Scale y axis. select_kw: dict passed to select method Returns fig and ax. """ fig, ax = plt.subplots(num='{}_static'.format(record.name)) fig.clf() select_kw.setdefault('delay_mean', True) select_kw.setdefault('frame_med', True) select_kw.setdefault('prop', 'unpumped') data = record.select(**select_kw) plot_spec(record.select(x_prop), scale*data, **kwargs) plt.title("{}".format(record.lname)) fname = 'figures/{}_static.pdf'.format(record.name) print(fname) if save: plt.savefig(fname) print("saved") return fig, ax
5,346,083
def logmelspectrogram(wave: np.ndarray, conf: ConfMelspec) -> np.ndarray: """Convert a waveform to a scaled mel-frequency log-amplitude spectrogram. Args: wave::ndarray[Time,] - waveform conf - Configuration Returns::(Time, Mel_freq) - mel-frequency log(Bel)-amplitude spectrogram """ # mel-frequency linear-amplitude spectrogram :: [Freq=n_mels, T_mel] mel_freq_amp_spec = librosa.feature.melspectrogram( y=wave, sr=conf.sampling_rate, n_fft=conf.n_fft, hop_length=conf.hop_length, n_mels=conf.n_mels, fmin=conf.fmin, fmax=conf.fmax, # norm=, power=1, pad_mode="reflect", ) # [-inf, `min_db`, `ref_db`, +inf] dB(ref=1,power) => [`min_db_rel`/20, `min_db_rel`/20, 0, +inf] min_db = conf.ref_db + conf.min_db_rel ref, amin = db_to_linear(conf.ref_db), db_to_linear(min_db) # `power_to_db` hack for linear-amplitude spec to log-amplitude spec conversion mel_freq_log_amp_spec = librosa.power_to_db(mel_freq_amp_spec, ref=ref, amin=amin, top_db=None) mel_freq_log_amp_spec_bel = mel_freq_log_amp_spec/10. mel_freq_log_amp_spec_bel = mel_freq_log_amp_spec_bel.T return mel_freq_log_amp_spec_bel
5,346,084
def isNumber(self, s): """ :type s: str :rtype: bool """ #define a DFA state = [{}, {'blank': 1, 'sign': 2, 'digit':3, '.':4}, {'digit':3, '.':4}, {'digit':3, '.':5, 'e':6, 'blank':9}, {'digit':5}, {'digit':5, 'e':6, 'blank':9}, {'sign':7, 'digit':8}, {'digit':8}, {'digit':8, 'blank':9}, {'blank':9}]
5,346,085
def get_trainer_config(env_config, train_policies, num_workers=9, framework="tf2"): """Build configuration for 1 run.""" # trainer config config = { "env": env_name, "env_config": env_config, "num_workers": num_workers, # "multiagent": {"policy_mapping_fn": lambda x: x, "policies": policies, # "policies_to_train": train_policies}, "framework": framework, "train_batch_size": 512, 'batch_mode': 'truncate_episodes', "callbacks": TraceMallocCallback, "lr": 0.0, "num_gpus": 1, } return config
5,346,086
def SamAng(Tth,Gangls,Sangl,IFCoup): """Compute sample orientation angles vs laboratory coord. system :param Tth: Signed theta :param Gangls: Sample goniometer angles phi,chi,omega,azmuth :param Sangl: Sample angle zeros om-0, chi-0, phi-0 :param IFCoup: True if omega & 2-theta coupled in CW scan :returns: psi,gam: Sample odf angles dPSdA,dGMdA: Angle zero derivatives """ if IFCoup: GSomeg = sind(Gangls[2]+Tth) GComeg = cosd(Gangls[2]+Tth) else: GSomeg = sind(Gangls[2]) GComeg = cosd(Gangls[2]) GSTth = sind(Tth) GCTth = cosd(Tth) GSazm = sind(Gangls[3]) GCazm = cosd(Gangls[3]) GSchi = sind(Gangls[1]) GCchi = cosd(Gangls[1]) GSphi = sind(Gangls[0]+Sangl[2]) GCphi = cosd(Gangls[0]+Sangl[2]) SSomeg = sind(Sangl[0]) SComeg = cosd(Sangl[0]) SSchi = sind(Sangl[1]) SCchi = cosd(Sangl[1]) AT = -GSTth*GComeg+GCTth*GCazm*GSomeg BT = GSTth*GSomeg+GCTth*GCazm*GComeg CT = -GCTth*GSazm*GSchi DT = -GCTth*GSazm*GCchi BC1 = -AT*GSphi+(CT+BT*GCchi)*GCphi BC2 = DT-BT*GSchi BC3 = AT*GCphi+(CT+BT*GCchi)*GSphi BC = BC1*SComeg*SCchi+BC2*SComeg*SSchi-BC3*SSomeg psi = acosd(BC) BD = 1.0-BC**2 C = np.where(BD>1.e-6,rpd/np.sqrt(BD),0.) dPSdA = [-C*(-BC1*SSomeg*SCchi-BC2*SSomeg*SSchi-BC3*SComeg), -C*(-BC1*SComeg*SSchi+BC2*SComeg*SCchi), -C*(-BC1*SSomeg-BC3*SComeg*SCchi)] BA = -BC1*SSchi+BC2*SCchi BB = BC1*SSomeg*SCchi+BC2*SSomeg*SSchi+BC3*SComeg gam = atan2d(BB,BA) BD = (BA**2+BB**2)/rpd dBAdO = 0 dBAdC = -BC1*SCchi-BC2*SSchi dBAdF = BC3*SSchi dBBdO = BC1*SComeg*SCchi+BC2*SComeg*SSchi-BC3*SSomeg dBBdC = -BC1*SSomeg*SSchi+BC2*SSomeg*SCchi dBBdF = BC1*SComeg-BC3*SSomeg*SCchi dGMdA = np.where(BD > 1.e-6,[(BA*dBBdO-BB*dBAdO)/BD,(BA*dBBdC-BB*dBAdC)/BD, \ (BA*dBBdF-BB*dBAdF)/BD],[np.zeros_like(BD),np.zeros_like(BD),np.zeros_like(BD)]) return psi,gam,dPSdA,dGMdA
5,346,087
def debye_C_V(T,thetaD,natoms): """ Returns the heat capacity at constant volume, C_V, of the Debeye model at a given temperature, T, in meV/atom/K. """ C_V = 4*debye_func(thetaD/T)-3*(thetaD/T)/(sp.exp(thetaD/T)-1.) C_V = 3*natoms*BOLTZCONST*C_V return C_V
5,346,088
def setup(clip=True, flip=True): """ Project specific data import and setup function :param clip: bool - use clipping :param flip: bool - use flipping :return: data as pandas dataframe, List[LAICPMSData obj] """ # calibration # Zn: y = 0.0395 kcps/(µg/g)* x + 1.308 kcps # use inverse calibration function to get conc from counts; transformation m = 1/m and b = -1 * b/m calibration_functions = { 'Zn:64': lambda x: 1/0.0395 * x - 1.308/0.0395, } # data files filenames = ["../data/LA_Data_C1SA1.csv", "../data/LA_Data_C2SA1.csv", "../data/LA_Data_C3SA1.csv", "../data/LA_Data_C4SA1.csv", "../data/LA_Data_C1SB1.csv", "../data/LA_Data_C2SB1.csv", "../data/LA_Data_C3SB1.csv", "../data/LA_Data_C4SB1.csv", "../data/LA_Data_C1SC1.csv", "../data/LA_Data_C2SC1.csv", "../data/LA_Data_C3SC1.csv", "../data/LA_Data_C4SC1.csv"] # short sample names smpl_names = ["A_1", "A_2", "A_3", "A_4", "B_1", "B_2", "B_3", "B_4", "C_1", "C_2", "C_3", "C_4"] # list on how to flip the data to get matching orientations, h = horizontally, v = vertically if flip: flip_list = [ 'h', 'v', 'h', 'h', 'h', 'h', 'v', 'v', 'v', 'h', 'h', 'h' ] else: flip_list = ['no' for i in range(0, len(filenames))] # clip data to windows of defined size # main reason is comparability & tissue folds if clip: #100 px x 150 px clip_list = [ (70,170,30,180), (70,170,30,180), (50,150,30,180), (60,160,50,200), (30,130,30,180), (40,140,30,180), (40,140,30,180), (40,140,30,180), (60,160,20,170), (60,160,20,170), (60,160,20,170), (60,160,20,170), ] else: clip_list = [None for i in range(0, len(filenames))] ms_data = [] data = [] # here the data gets processed into LAICPMSData objects - one per file # data contains all Zn:64 data - masked/segmented based on P:31 content for smpl, filename, clip, flip in zip(smpl_names, filenames, clip_list, flip_list): curr_ms_data = LAICPMSData(filename=filename, clip_data_around_center=clip, flip=flip, pixel_dimensions=(15,15)) # only assign directly if you know what you are doing! curr_ms_data._calibration_functions = calibration_functions ms_data.append(curr_ms_data) data.append(curr_ms_data.get_masked_data(element_list=['Zn:64'], discriminator='P:31', only_on_tissue=True)) data[-1]['sample'] = [smpl for i in range(0, len(data[-1]))] return pd.concat(data, ignore_index=True), ms_data
5,346,089
def go_test_macro(name, **kwargs): """See go/core.rst#go_test for full documentation.""" _cgo(name, kwargs) go_test(name = name, **kwargs)
5,346,090
def _verify_all_conflicts(buffer_pool_allocations): """Helper to verify liveness conflicts""" for buffer_info, pool_allocation in buffer_pool_allocations.items(): _verify_conflicts(buffer_info, pool_allocation, buffer_pool_allocations)
5,346,091
def choi_to_kraus(q_oper): """ Takes a Choi matrix and returns a list of Kraus operators. TODO: Create a new class structure for quantum channels, perhaps as a strict sub-class of Qobj. """ vals, vecs = eig(q_oper.data.todense()) vecs = list(map(array, zip(*vecs))) return list(map(lambda x: Qobj(inpt=x), [sqrt(vals[j]) * vec2mat(vecs[j]) for j in range(len(vals))]))
5,346,092
async def my_edit(event): """定义编辑文件操作""" logger.info(f'即将执行{event.raw_text}命令') msg_text = event.raw_text.split(' ') SENDER = event.sender_id path = JD_DIR page = 0 if isinstance(msg_text, list) and len(msg_text) == 2: text = msg_text[-1] else: text = None logger.info(f'命令参数值为:{text}') if text and os.path.isfile(text): try: with open(text, 'r', encoding='utf-8') as f: lines = f.readlines() filelist = split_list(lines, 15) path = text except Exception as e: await jdbot.send_message(chat_id, f'something wrong,I\'m sorry\n{str(e)}') elif text and os.path.isdir(text): path = text filelist = None elif text: await jdbot.send_message(chat_id, 'please marksure it\'s a dir or a file') filelist = None else: filelist = None async with jdbot.conversation(SENDER, timeout=120) as conv: msg = await conv.send_message('正在查询,请稍后') while path: path, msg, page, filelist = await edit_file(conv, SENDER, path, msg, page, filelist)
5,346,093
def plot_df_color_per_unit(data, variables, labels, size=(16, 9), labelsize=17, option='Time', name=None): """ """ plt.clf() input_dim = len(variables) # cols = min(np.floor(input_dim ** 0.5).astype(int), 4) # rows = (np.ceil(input_dim / cols)).astype(int) cols = 4 rows = 1 gs = gridspec.GridSpec(rows, cols) leg = [] # fig = plt.figure(figsize=(size, max(size, rows * 2))) fig = plt.figure(figsize=size) color_dic_unit = {'Unit 1': 'C0', 'Unit 2': 'C1', 'Unit 3': 'C2', 'Unit 4': 'C3', 'Unit 5': 'C4', 'Unit 6': 'C5', 'Unit 7': 'C6', 'Unit 8': 'C7', 'Unit 9': 'C8', 'Unit 10': 'C9', 'Unit 11': 'C10', 'Unit 12': 'C11', 'Unit 13': 'C12', 'Unit 14': 'C13', 'Unit 15': 'C14', 'Unit 16': 'C15', 'Unit 17': 'C16', 'Unit 18': 'C17', 'Unit 19': 'C18', 'Unit 20': 'C19'} unit_sel = np.unique(data['unit']) for n in range(input_dim): ax = fig.add_subplot(gs[n]) for j in unit_sel: data_unit = data.loc[data['unit'] == j] if option == 'cycle': time_s = data.loc[data['unit'] == j, 'cycle'] label_x = 'Time [cycle]' else: time_s = np.arange(len(data_unit)) label_x = 'Time [s]' ax.plot(time_s, data_unit[variables[n]], '-o', color=color_dic_unit['Unit ' + str(int(j))], alpha=0.7, markersize=5) ax.tick_params(axis='x', labelsize=labelsize) ax.tick_params(axis='y', labelsize=labelsize) leg.append('Unit ' + str(int(j))) plt.ylabel(labels[n], fontsize=labelsize) plt.xlabel(label_x, fontsize=labelsize) ax.get_xaxis().set_major_formatter( mpl.ticker.FuncFormatter(lambda x, p: format(int(x), ','))) if n == 0: ax.get_yaxis().set_major_formatter( mpl.ticker.FuncFormatter(lambda x, p: format(int(x), ','))) plt.legend(leg, loc='best', fontsize=labelsize - 2) # lower left plt.tight_layout() if name is not None: plt.savefig(name, format='png', dpi=300) plt.show() plt.close()
5,346,094
def extract_file_type(file_location:str) -> str: """ A function to return the type of file -> file_location: str = location of a file in string... ex : "C:\\abc\\abc\\file.xyz" ---- => str: string of the file type, ex : "xyz" """ if not isinstance(file_location,str): raise TypeError("file_location must be a string") try: return file_location.rsplit(".", 1)[1] except IndexError: raise ValueError(f"Invalid File Location : '{file_location}'")
5,346,095
def add_sphinx_context_data(sender, data, build_env, **kwargs): # pylint: disable=unused-argument """ Provides additional data to the sphinx context. Data are injected in the provided context :param sender: sender class :param data: sphinx context :param build_env: BuildEnvironment instance :return: None """ from readthedocs.docsitalia.utils import get_subprojects subprojects = get_subprojects(build_env.project.pk) data['subprojects'] = subprojects publisher_project = build_env.project.publisherproject_set.first() data['publisher_project'] = publisher_project if publisher_project: publisher = publisher_project.publisher data['publisher'] = publisher metadata = publisher.metadata.get('publisher', {}) data['publisher_logo'] = metadata.get('logo_url') else: data['publisher'] = None data['publisher_logo'] = None if build_env.project.tagged_items.exists(): data['tags'] = sorted([t.tag.name for t in build_env.project.tagged_items.all()])
5,346,096
def dualMove(d1, d2, st1, st2, sp1, sp2, ac1, ac2, di1, di2, c1, c2): """ Move 2 steppers at the same time Parameters ---------- d1 : AMIS30543 AMIS30543 Driver d2 : AMIS30543 AMIS30543 Driver st1 : int Steps for motor 1 st2 : int Steps for motor 2 sp1 : int Speed for motor 1 sp2 : int Speed for motor 2 ac1 : int Acceleration for motor 1 ac2 : int Acceleration for motor 2 di1 : boolean direction of motor 1 di2 : boolean direction of motor 2 c1 : int Current for motor 1 c2 : int Current for motor 2 """ d1.setDirection(di1) d1.setDirection(di2) if not baton.locked(): _thread.start_new_thread(secondMove, (d1, st1, sp1, ac1, di1, c1)) d2.moveStepsAcc(st2, sp2, ac2, di2, c2) # make sure that the other thread has finished before moving on. while baton.locked(): time.sleep_us(1) time.sleep_ms(1)
5,346,097
def re_subm(pat, repl, string): """ Like re.sub, but returns the replacement _and_ the match object. >>> t, m = re_subm('g(oo+)fball', r'f\\1lish', 'goooooofball') >>> t 'foooooolish' >>> m.groups() ('oooooo',) """ class re_subm_proxy: def __init__(self): self.match = None def __call__(self, match): self.match = match return '' compiled_pat = re_compile(pat) proxy = re_subm_proxy() compiled_pat.sub(proxy.__call__, string) return compiled_pat.sub(repl, string), proxy.match
5,346,098
def search_view(request): """Get user's saved keywords from the database if they exist and render search page.""" if request.method == 'GET': try: query = request.dbsession.query(Keyword) user_keywords = query.filter(Association.user_id == request.authenticated_userid, Association.keyword_id == Keyword.keyword) except KeyError: return HTTPFound # except DBAPIError: # raise DBAPIError(DB_ERR_MSG, content_type='text/plain', status=500) keywords = [keyword.keyword for keyword in user_keywords] if len(keywords) < 1: return{'message': 'You do not have any keywords saved. Add one!'} return{'keywords': user_keywords}
5,346,099