content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def BondConst_get_decorator_type_name(): """BondConst_get_decorator_type_name() -> std::string""" return _RMF.BondConst_get_decorator_type_name()
a416e6d8f105146a7e1a13cc69822081b4aac46f
63,800
def _discover(disp,ns,jid,node=None,fb2b=0,fb2a=1): """ Try to obtain info from the remote object. If remote object doesn't support disco fall back to browse (if fb2b is true) and if it doesnt support browse (or fb2b is not true) fall back to agents protocol (if gb2a is true). Returns obtained info. Used interna...
d74270d7619a6c61580316af091ed0c362dfb43f
63,801
def cross_validation(x, y, k_indices, get_weights, compute_loss): """Return train and test loss of the average cross validation""" # split data in k fold k_fold = len(k_indices) # define lists to store the loss of training data and test data losses_tr = [] losses_te = [] for k in ...
6d614f3276fa2e441bdd944c00dc098e3f4bf9d0
63,802
def resize_lazy(image, width=None, height=None, crop=False, force=False, namespace="resized", storage=default_storage, as_url=False): """ Returns the name of the resized file. Returns the url if as_url is True """ # First normalize params to determine which file to get ...
ee8b010dfe9ae8b945f57de6356a5acaf89bb4bd
63,803
def receive_hook(): """Receive a webhook and handle it Webhooks can be received from GitHub or fro BitBucket. This endpoint examines the request headers and decides if the data should be processed as a GitHub or as a BitBucket event. If the data is valid, a webhook can end if a project creation, a sca...
edb1617414792504ee14fd0613588ac483fa9506
63,804
def get_parent_doc(__type: type, /) -> str | None: """Get the nearest parent documentation using the given :py:class:`type`'s mro. :return The closest docstring for an object's class, None if not found. """ doc = None for parent in __type.__mro__: doc = parent.__doc__ if doc: ...
efe61d30a82e08ccdf5411ffc9feb4252fdb53e2
63,805
def infection_rate_asymptomatic_20x60(): """ Real Name: b'infection rate asymptomatic 20x60' Original Eqn: b'contact infectivity asymptomatic 20x60*(social distancing policy SWITCH self 60*social distancing policy 60\\\\ +(1-social distancing policy SWITCH self 60))*Infected asymptomatic 20x60*Susceptible 6...
c6128f114a107036c94600b712705da8b2dc20e9
63,806
from datetime import datetime def now(): """Return an aware datetime.datetime now.""" # timeit shows that datetime.now(tz=utc) is 24% slower return datetime.utcnow().replace(tzinfo=utc)
a34162f227b75cce06ae915febb41fc20a6a6ec1
63,807
def hashbytes(arg, how='sha256'): """ Compute a binary hash value for the indicated value expression. Parameters ---------- arg : binary or string value expression how : {'md5', 'sha1', 'sha256', 'sha512'}, default 'sha256' Hash algorithm to use Returns ------- hash_value : b...
7251f402a0e8cda130ecec409a63e74de861a715
63,808
def drop_multiple_col(col_names_list, df): """AIM -> Drop multiple columns based on their column names. INPUT -> List of column names, df. OUTPUT -> updated df with dropped columns""" df.drop(col_names_list, axis=1, inplace=True) return df
991144349d383b79e1510fa5c106226254f8329b
63,809
from sys import path import json import bisect def return_descriptions(valid_dict: list) -> tuple: """ This constructs the file path to ``descriptions.json`` and then uses the ``valid_dict`` to match the scores from ``valid_dict`` and classify them as high or low and return the relevant descriptions. """ ...
6f8a97119f741319abe82d463327b9dc5c7b8efe
63,810
def getCuttoffsFromJson(json_data): """Get HF and MP2 cutoffs from json file.""" cutoff_dims = json_data["keywords"]["frag"].get("dimer_cutoff", 10000) / angstrom2bohr cutoff_trims = json_data["keywords"]["frag"].get("trimer_cutoff", 10000) / angstrom2bohr cutoff_tets = json_data["keywords"]["frag"].ge...
4143496b0349855e2e644cc30e8242c3aab9a3c5
63,811
def make_parameter_histogram(data_info, report_info): """ Create a histogram for parameters in the query results :param data_info: Query result for data :param report_info: Query result for reports :return: histogram data """ histograms = { field_name: get_histogram_points( ...
6718b5d85936b5dcea0a2a0c2ab7b99d9fdd2061
63,812
def point3d(p): """Converts list of np array to fusion360 point3d object Parameters ---------- p : List or np array of shape (3) Returns ------- adsk.core.Point3D """ return adsk.core.Point3D.create(p[0], p[1], p[2])
e45963be6c847992dccc3a9190247c8f625a18ab
63,813
def replstring(string, i, j, repl): """ Replace everything in string between and including indices i and j with repl >>> replstring("abc", 0, 0, "c") 'cbc' >>> replstring("abc def LOL jkl", 8, 10, "ghi") 'abc def ghi jkl' """ # Convert to list since strings are immutable strlist = li...
97eee8912a6c8fd9e29a5784af1f3853b714cf0b
63,814
def deeplink_url_patterns( prefix='', url_base_pattern=r'^init/%s/$', login_init_func=login_init, ): """ Returns new deeplink URLs based on 'links' from settings.SAML2IDP_REMOTES. Parameters: - url_base_pattern - Specify this if you need non-standard deeplink URLs. NOTE: This wil...
20fed762cb22f904c2d2088ad18d763b5bab5e7a
63,815
def _parse_line(line): """ Do a regex search against all defined regexes and return the key and match result of the first matching regex """ for key, rx in rx_dict.items(): match = rx.search(line) if match: return key, match # if there are no matches return None...
a313743f179291fe95cb1a8fe64e0a18d631df72
63,816
def get_key_padding_mask(padded_input, pad_idx): """Creates a binary mask to prevent attention to padded locations. Arguments ---------- padded_input: int Padded input. pad_idx: idx for padding element. Example ------- >>> a = torch.LongTensor([[1,1,0], [2,3,0], [4,5,0]...
ffbcb4de13b1be6a35944f79b1daf6d51d5cbec8
63,817
def DSQuery(dstype, objectname, attribute=None, node='.'): """DirectoryServices query. Args: dstype: The type of objects to query. user, group. objectname: the object to query. attribute: the optional attribute to query. node: the node to query. Returns: If an attribute is specified, the valu...
7a458b5b51ca929a7e3d9e604f19cf426ff60716
63,818
import os import shutil def delete_directory(dirpath): """Delete a directory""" errors = [] if not os.path.isdir(dirpath): errors.append('Directory does not exist') else: try: shutil.rmtree(dirpath, ignore_errors=False) except PermissionError: errors.app...
d76fb2e29585cf6f27c3afa79fa2362e2056c15a
63,819
def one_hot_encode(labels): """ Take as input a list of labels (strings) and encode them using one_hot_encoding scheme, i.e. assuming there are 3 activities: A, B in the LABELS_NAMES array, if the input is [A, B] then return [[1, 0, 0].[0, 1, 0]]. If the label does not exist then raise a NameError. ...
b789e646e89a363169a5d9e8f6dc288f412fcd2d
63,820
def run_stdout( cmd, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=None, env=None, clean_env=False, template=None, rstrip=True, umask=None, output_encoding=None, output_loglevel="debug", log_callback=None, hide_output=Fals...
c756d2e0e82b79caac9951699a58968626829713
63,821
def _get_next_id() -> str: """Return the next id based on the last saved it.""" return str(int(_get_last_id()) + 1)
46294953b9ebac71c340b43f202475f6f38a4bec
63,822
def zpl_parse(filename): """ Convert a ZPL file back to an image. """ # pylint: disable=too-many-locals,too-many-statements if not filename: raise ValueError("No filename given, or empty") source = sys.stdin if filename == '-' else open(filename) data = source.read() # Find s...
a4cbf87bbff20abb375c75be7e1f4b2d8e302f95
63,823
def server_error(request, template_name='500.html'): """ 500 error handler. Template: `500.html` """ t = loader.get_template(template_name) rendered = t.render({'media_url': settings.MEDIA_URL,}, request) return HttpResponseServerError(rendered)
303bae0a95290f75ca669fa83cdf5e5f7f71d911
63,824
def known_good_image( docker_registry_secure: DockerRegistrySecure, request ) -> TypingKnownGoodImage: """Provides 'known good' metadata for a local image that can be modified.""" image_name = ImageName.parse(request.param["image"]) image_name.endpoint = docker_registry_secure.endpoint request.param...
89353f7e74c89a0ef6ad33bcd6651ece5700495d
63,825
from yaml import YAMLError import sys def parse_yaml(location): """ Parse a yaml file :param location: The location of the yaml file to parse :return: The contents of the yaml file """ yaml = YAML(typ="rt") with open(location, 'r') as stream: try: parsed_yaml = yaml.lo...
8bbf6a33a92d48374de9aa39f5dc9214aa2a5527
63,826
def cli(ctx, workflow_id): """Delete a workflow identified by `workflow_id`. Output: A message about the deletion .. warning:: Deleting a workflow is irreversible - all workflow data will be permanently deleted. """ return ctx.gi.workflows.delete_workflow(workflow_id)
9ee3aa82a9577f9b20574f821f4a9e226665740d
63,827
import os import scipy def _load_from_matlab_file(dataset_path, shape_idx): """Load demonstrations from Matlab files.""" file_name = sorted(os.listdir(dataset_path))[shape_idx] return (scipy.io.loadmat(dataset_path + file_name)["demos"][0], file_name[:-4])
3e8d80ac7f19d66be075ce58011aacde10e1c285
63,828
def sen_diff(x): """Sen's difference operator. Paramaters ---------- x : array_like Observations taken at a fixed frequency. Returns ------- Sen difference """ #x = x[~np.isnan(x)] n = len(x) N = int(n*(n-1)/2) # number of slope estimates s = np.zeros(N) i = ...
9ac8f462dc04b72f8990269b5868f14e21306e25
63,829
def connect_room(room_name, vc_room, force=False, room_verbose_name=None): """Connects a room given its name with a given vc_room. If a `RavemException` is raised it is important to verify the `reason` attribute of the exception. If the room is already connected to the given VC room, the `reason` will ...
9aad4b0b60bbadf47c9734d1316d679a97de9fd5
63,830
import functools def compute_module_criticality( objective_fn, module_variables_init, module_variables_final, num_samples_per_iteration=10, alpha_grid_size=10, sigma_grid_size=10, sigma_ratio=1.0, loss_threshold_condition=relative_error_condition, normalize_error=False, ): """Com...
724fd13e56f6a86cddec19707237154eeff84e61
63,831
import warnings def deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emmitted when the function is used.""" def newFunc(*args, **kwargs): warnings.warn("Call to deprecated function %s." % func.__name__, ...
c2f533022c77b3c86f3b028a82c7d3b3770e7273
63,832
def remove_stop_words(speech_edit): """Remove stop words from string and return string.""" stop_words = set(stopwords.words('english')) speech_edit_no_stop = '' for word in nltk.word_tokenize(speech_edit): if word.lower() not in stop_words: speech_edit_no_stop += word + ' ' ret...
a9ef3e1fd15fcfb49c27a3d8642eba568203bb0f
63,833
def validate_seq(seq): """Check the sequence to make sure it is a valid DNA string""" tmpseq = seq.upper() for nuc in tmpseq: if nuc not in DNA_Nucleotides: return False return True
0e9e5e2e59f6c1ed79d7bc80f4c8f4d375ee904b
63,834
def longest_increasing_subseq_length(xs): """Return the length of the longest increasing subsequence of xs. >>> longest_increasing_subseq_length(range(3)) 3 >>> longest_increasing_subseq_length([3, 1, 2, 0]) 2 """ return 1 + maximum((pile for x, pile in patience_sort(xs)), -1)
c2f7db601f23e35a037f587a3fad4a9c75d535e1
63,835
def load_embed_from_text(emb_file, token_dim): """ :return: embed: numpy, vocab2id: dic """ print('==> loading embed from txt') embed = [] vocab2id = {} word_id = 0 embed.append([0.0] * token_dim) with open(emb_file, 'r') as fr: print('embedding info: ', fr.readline()) ...
27000433da66cbc51dfb6638d92ce4db4464be6b
63,836
def drsclient(drs_client): """ Mock drsclient """ return drs_client
3aaf02188dc2193271a7999a4b3c763a6c3e435f
63,837
def clean_markup(markup, keep_links=False, ignore_headers=True): """ Clean Wikimarkup to produce plaintext. :param keep_links: Set to True to keep internal and external links :param ignore_headers: if set to True, the output list will not contain headers, only Returns a list of paragraphs (un...
dc271406d180c6b493d6324d443f1a3edbdcd22f
63,838
def _prune_traverse_using_omitted_locations(match_traversal, omitted_locations, complex_optional_roots, location_to_optional_roots): """Return a prefix of the given traverse, excluding any blocks after an omitted optional. Given a subset (omitted_locations) of complex_optional_roots, return a new match traversal ...
f59bc17c425f387bccf54a59a7d9c985f6e3412f
63,839
import importlib import os def load_module(path_): """ Loads module from Path object. Returns the module """ module = importlib.machinery.SourceFileLoader( path_.stem, os.fspath(path_.resolve()) ) return module.load_module()
89fee0ce648b77436b80ad2d3f02be4fcd5f0f8b
63,840
def stop_preview(con_handle: ConnectionHandler) -> str: """Interface to stop preview mode. Args: con_handle: A unique identifier per mainframe connection. Returns: An String value representing request status. """ response_json = con_handle.send_request_wait_response("StopPreview",...
d1675ebc5bf659653c636a55d782b7b7c3984cf0
63,841
import os def main(datasets, evaluate=False, store=True, verbose=False, **kwargs): """ It runs the pipeline for each dataset, collects predicted pairs and computes evaluation scores based on all of them. :param datasets: list, of int with the ids of the datasets :param evaluate: boolean, if evalu...
7ff55b78661271d057acc658492c7c39b259a97e
63,842
import math def _BucketInterpolate(last_percentage, target, next_percentage, bucket_min, bucket_max): """Estimate a minimum which should have the target % of samples below it. We do linear interpolation only if last_percentage and next_percentage are adjacent, and hence we are in a linea...
5183f20c9510cfb6d2642b5820f36f5b490c425e
63,843
def int2bit(x, w=20): """ Generates a binary representation of an integer number (as a tuple) >>> bits = int2bit(10, w=4) >>> bits (1, 0, 1, 0) >>> bit2int( bits ) 10 """ bits = [ ] while x: bits.append(x%2) x /= 2 # a bit of padding bits = bits ...
b65cd8f7c6232896eb2aef9f9d69b6ac4fd97bc6
63,844
from typing import Optional from typing import Type from typing import Sequence from typing import Any from typing import Callable from typing import Dict from typing import Union def parse_type(bridge: 'phpbridge.PHPBridge', spec: str, cls: Optional[Type] = None, bases: O...
62a804b3a983c3712d0ddc742f2a81278bed953b
63,845
def test_taumodel_tage(values=10**np.linspace(np.log10(0.11), 1, 9), tau=1.0, sf_slope=0.0, sfh=1): """Test (delayed-) tau models """ pname = 'tage' sps.params['sfh'] = sfh mysps.sfh_type = sfhtype[sfh] mysps.configure() sfig, saxes = pl.subplots(2, 1, figsize=(11, 8.5...
03c0cc274d678c39b5fe47fd0591d15bfd076c8f
63,846
def _certificate_fingerprint(identity): """Extracts a fingerprint given identity in a mobileprovision file.""" _, fingerprint, _ = execute.execute_and_filter_output([ "openssl", "x509", "-sha1", "-inform", "DER", "-noout", "-fingerprint", ], inputstr=identity, raise_on_fa...
12051667a36166819b3f444c8a5fee43b46b1d95
63,847
def potsdam_palette(): """Potsdam palette for external use.""" return [[255, 255, 255], [0, 0, 255], [0, 255, 255], [0, 255, 0], [255, 255, 0], [255, 0, 0]]
a2410ed1fb32909130a26d2cfe9e86e78c3a57f1
63,848
def alt(left: BaseParser, right: BaseParser) -> Alternate: """Create an Alternate parser""" return Alternate(left, right)
72447988038b156057ff4425cb393d1d57c535c9
63,849
def course_detail(request, username, course_key): """ Return a single course identified by `course_key`. The course must be visible to the user identified by `username` and the logged-in user should have permission to view courses available to that user. Arguments: request (HTTPRequest...
f8d328a14575e707252cbe2cfc12b449996db7bc
63,850
def combine_bam(in_files, out_file, config): """Parallel target to combine multiple BAM files. """ runner = broad.runner_from_path("picard", config) runner.run_fn("picard_merge", in_files, out_file) for in_file in in_files: save_diskspace(in_file, "Merged into {0}".format(out_file), config) ...
d68afdfa63d2695463dee990918f723b9a00dc41
63,851
import requests def test_user_token(test_auth_user): """ Create a new test user and get a login key """ # create custom token token = auth.create_custom_token(test_auth_user.uid).decode() # get ID token - Python Firebase Auth library doesn't have this function *shrug* url = f"https://identitytoo...
2820317156473ff44caab2c5a5482c3dbeec8da0
63,852
def get_full_path(path): """Return the positions along a path. Appends the points in the correct order to be able to build a path.""" p_list = [] curp = None for i in range(len(path) - 1): p = get_path(path[i], path[i + 1]) if curp is None: curp = p if (np.sum((p[0] -...
87b8e0a675075dca436942b22053a3d85292dd6f
63,853
import os def native_modules(target): """Find stdlib modules already implemented in java.""" modules = [] for folder in ['common', target]: basedir = os.path.join(REPO_ROOT, 'python', folder, 'python') for name in os.listdir(basedir): module_name, ext = os.path.splitext(name) ...
1e6506fb2aa05562d49df74a05b1302c242e464a
63,854
def getRenderer(ren_type='geo'): """ Choose renderer type geo: phong-shading denspose: densepose IUV normal: normal map torch3d: via pytorch3d TODO """ if ren_type=='geo': renderer = meshRenderer.meshRenderer() renderer.setRenderMode('geo') elif ren_type=='n...
8d053fd4a48a376b2f077bd8333344e313d97867
63,855
import json def GetSwarmingTaskRequest(task_id, http_client): """Returns an instance of SwarmingTaskRequest representing the given task.""" swarming_server_host = waterfall_config.GetSwarmingSettings().get( 'server_host') url = ('https://%s/_ah/api/swarming/v1/task/%s/request') % ( swarming_server_h...
9e22169d3059724dc9750a7b05abc9c2b4027dbd
63,856
import traceback import json def select(request): """ [メソッド概要] メニューグループ:メニューのプルダウンリスト作成処理 """ logger.logic_log('LOSI00001', 'None', request=request) msg = '' try: ita_driver_id = request.POST.get('ita_driver_id', None) version = request.POST.get('version', None) ...
9723572452d87ba147960220f65fbbbe42d75591
63,857
def str_to_hex(value: str) -> str: """Convert a string to a variable-length ASCII hex string.""" return "".join([f"{ord(x):02X}" for x in value])
f604a8bedcb00efd448eab2a831dd8373b328c2d
63,858
import logging import webbrowser def oauth_login(consumer_key: str, consumer_secret: str): """Authenticate with Twitter via OAuth. :param consumer_key: the consumer API key :param consumer_secret: the consumer API secret key """ logger = logging.getLogger(__name__) logger.info("Authenticati...
bd66c4acf023f2a873d680cc38777da8c3b902c8
63,859
import httpx def get_manga(website: str) -> bool: """ API Manga website scraper checker. """ check = True try: httpx.get(f"{API_URL}/manga?q={website}").json() # if len(res["chapters"]) < 1: # check = False except Exception: # there was a problem with the ...
8246325da103704dfb42849a5692b7f119c6d499
63,860
def to_tuple(x): """Converts lists to tuples. For example:: >>> from networkx.utils import to_tuple >>> a_list = [1, 2, [1, 4]] >>> to_tuple(a_list) (1, 2, (1, 4)) """ if not isinstance(x, (tuple, list)): return x return tuple(map(to_tuple, x))
29586512b336ae5079e991bb13c1ac904e5eefe9
63,861
def isallowed(context, operation, resource, authority=None): """ Useful when you want to store ACL result in a variable to be tested with other parameters. For example : {% isallowed "my_operation" my_resource as can_do_operation %} {% if my_resource.some_boolean or can_do_operation %} Display ...
760b3162a87db09b68aaae9fda894565d0ee784d
63,862
def mean_residue_ellipticity(phi, n, c, l): """ Calculate mean residue ellipticity (millideg cm2 / decimol) from ellipticity (mdeg) Args: phi (float): a ellipticity (milli deg) n (int): the number of residues c (float): the molar concentration of the polymer (mol/L) l (f...
a51a90e3a12b921b2e12fb75160929d60652dcca
63,863
import re from typing import Counter def __chemical_elements(chemical): """Decomposes a chemical to it's elements. Parameters ---------- chemical : string The molecular formula of the given chemical compound given as a string. Returns ------- dict Dictionary of the chemic...
8297aa4997b6f708e7e5c2b2e181f85531a4f146
63,864
def load_user_credentials(path): """ Gets user account credentials from JSON file at ``path``. Parameters ---------- path : str Path to credentials JSON file. Returns ------- google.auth.credentials.Credentials Raises ------ pydata_google_auth.exceptions.PyDataCre...
5f7bfd7f8e168658a94bf132b7dcf5f95c27e2b9
63,865
def generate_user(): """ Returns a randomly generate dictionary representing a user, where each user is described by a user agent string, an ID, a latlng, an IP, an age_bracket, whether they've oped into marketing and the :return: """ user = {} user['lat'] = "" user['lng'] = "" w...
e27e0897de5f3ec1880de20594e1d932bbb1bbd9
63,866
def sector(request,sectorid=1): """ view for homepage """ sector = Sector.objects.get(id=sectorid) ord_by = request.GET.get('order_by','grade') prob_list = BaseProblem.objects.filter(sector=sector,approved=True,exists=True).order_by(ord_by) arlist = Area.objects.all() if hasattr(request....
2b36e0f0a129e36cb3cb671838caae3f27ddd97b
63,867
from typing import cast from typing import Dict from typing import Any import json def route_get_context(): """ Main handler for values saved in the integration context """ params = demisto.params() app_id = params.get('app_id') app_secret = params.get('app_secret') if app_secret: ...
36dcc763b8e2dfcc538edaf08520bfd22784676d
63,868
def simple_ipv4ip_packet(pktlen=300, eth_dst='00:01:02:03:04:05', eth_src='00:06:07:08:09:0a', dl_vlan_enable=False, vlan_vid=0, vlan_pcp=0, dl_vlan_cfi=0, ...
944e3e6dca5bd7c8adad30205f0f759cb12f9f8c
63,869
def get_all_ec2_instances_list(): """ :return: list of all ec2 instances connected to account """ print("++ get_all_ec2_instances_list") all_instance_ids = [] ec2 = boto3.client('ec2') paginator = ec2.get_paginator('describe_instances') for page in paginator.paginate(): for res in p...
be1e1e6d75727cdc0d281b66f2bfea98f55df326
63,870
def get_modified_remote_data_command(client, args): """ Gets the modified remote incident IDs. Args: client: The client object. args: last_update: the last time we retrieved modified incidents. Returns: GetModifiedRemoteDataResponse object, which contains a list of t...
1617644bbca81821e6b3f38a24719a9fb24c8807
63,871
def column_into_set(dataframe, column): """ Return normal set from given dataframe's column Parameters ---------- dataframe : pyspark.sql.dataframe.DataFrame Spark dataframe column : str Column in dataframe Returns ------- set_ : {} """ if not isinstance(dat...
99e248b130662dbb3042d315e073c40a8c36756b
63,872
from operator import index def route_dict(): """ 路由字典 key 是路由(路由就是 path) value 是路由处理函数(就是响应) """ d = { '/': index, '/static': static, } return d
1b4c7e45ed11a77f4336f107d0046952e85e4e18
63,873
def cells_data_delete(context, cell_id, data): """Delete the existing key (variable) from cells data.""" session = get_session() with session.begin(): query = model_query(context, models.Cell, session=session, project_only=True) query = query.filter_by(id=cell_id)...
be1c9cba4b94420d7c7b426e9f63e643bf4e2d62
63,874
def increase_patch_version(old_version): """ :param old_version: 2.0.1 :return: 2.0.2.dev """ return "{}.{}.{}.dev".format( old_version.major, old_version.minor, old_version.micro + 1 )
313adf2a3e862e123c79b16a437a7a9018f8203a
63,875
import subprocess import coverage import coverage import pylint def main(): """main()""" try: args = sys.argv[1:] except: args = [] env = '&d3b2mg6&=twp3q*!n9f!1#(zp($j34m5ds=e7v2@+t7m&3z4o' SECRET_KEY = os.environ.get('SECRET_KEY', None) if SECRET_KEY != env: print('c...
e393a7a9b3f07d4ac6b208ee202ec208d54c8eca
63,876
def wiki_delete(request, pro_id, wiki_id): """ 删除文件 """ wiki_obj = models.Wiki.objects.filter(id=wiki_id).delete() url = reverse('app01:wiki', kwargs={'pro_id': pro_id}) return redirect(url)
282011dec63ad1be12d4f24c32aa4073629c230d
63,877
def get_ip_address(): """ :return: """ localIP = Get_local_ip() return localIP
cc419035383914af3fb224495f42bf42930b8170
63,878
def build_dataset(filename, sequence_length, alphabet_size, max_lines=-1): """Loads a text file, and turns each line into an encoded sequence.""" with open(filename) as f: content = f.readlines() content = content[:max_lines] content = [line for line in content if len(line) > 2] # Remove blank...
9549d17e1878dd3ec135fbbf667953df7e41f10a
63,879
def login(x): # type: () -> Response """ Load the login page or redirect to the welcome page if already logged in. If the user hasn't logged in yet, load the login page for them to log in, but if the user has already logged in, redirect straight to the welcome page. :return: the login ...
ceb8f98ff75ba8dfc17a7f8364525b4f3b577ce5
63,880
def get_cluster_indices(labels, cluster=-1): """ labels : DBSCAN.labels_ object (numpy array) cluster : int cluster label whose in dices are desired. cluster=-1 default automatically selects outliers. """ indices = [] for i,j in enumerate(labels): if j == cluster: ...
bdcb3b90cdb81d4b9d4c4f4ca274049074330f7f
63,881
import os def read_strategy_map(): """ Read in the strategy map from strategy/strategy_map.json. :returns: (succ, msg) -- succ = strategy_map if valid strategy map, False otherwise -- with msg containing the error found. """ strategy_map = os.path.join(os.path.dirname(os.path.realpath(__...
ec1c19d0852fd9ccd0e764c72c023b5cea9064a0
63,882
import pathlib def electricity_planning_areas(pudl_settings): """Electric Planning Area geometries from HIFLD.""" gdb_path = pathlib.Path( pudl_settings["data_dir"], "local/hifld/electric_planning_areas.gdb" ) gdf = ( geopandas.read_file(gdb_path) .assign( ...
c4b359d082966369ec0c800242fd00a661f96c1f
63,883
def calculate_flicker_amplitude(data:np.ndarray) -> float: """ Computes the flicker amplitude after Bastien et al. (2013) :param data: data consisting of the full lightcurve :return: flicker amplitude """ flicker_time = get_flicker_time(data) t_step = get_time_step(data) elements = data[...
323143f8065ba96aa1d25b04eff13144d19ba864
63,884
from pathlib import Path def parse_master(data_dir_path=None): """A top-level function for getting and parsing the exomol.all master file. Parameters ---------- data_dir_path : Path or str, optional Path to the exomol data directory, containing all the directories belonging to all...
94d79ea7152a95eb651f6f56b0f0dc0c67c8dfc4
63,885
def process_text(text: str) -> str: """ Removes stop words, punctuation, pronouns and empty tokens Args: text (str): contents of a file/sentence/paragraph etc as a string Returns: String of tokens with stop words, punctuation, pronouns and empty tokens removed """ doc = nlp_lg(...
c33b9b9172d32c37fab07e9e5faa404ae68d5526
63,886
import re def convert(input): """Find all defines in the compiler generated assembly and convert them to #define pragmas""" asm_define_re = re.compile(r'">>(\w+) (?:\$|#)([-0-9]+) (?:\$|#)(0|1)<<"') asm_defines = asm_define_re.findall(input) if not asm_defines: raise RuntimeError("Failed to find any asm ...
ad67532f8497f09655a09598d7babbfa89808b12
63,887
def db_save_poster(code: str, name: str, preview: str, json: str): """ 保存海报 :param code: :param name: :param preview: :param json: :return: """ with conn() as con: c = con.cursor() params = [code, name, preview, json, now_str(), int(C.STATUS_NORMAL)] c.execute...
72f4874885c3e1b8500fe5002959ee1c063739d9
63,888
def get_roles_with_access_content(obj, request=None): """ Return the roles that has access to the content that are global roles""" if obj is None: return [] roles = cached_roles(obj, "guillotina.AccessContent", "o") result = [] all_roles = role.global_roles() + role.local_roles() for r i...
3bbf803ebc40077c9d8403bda49e5ebef6867ac4
63,889
def send_survey(report, project, email, sender="genomics_support@scilifelab.se", smtphost=None, smtpport=None, dryrun=False): """Send the survey to the supplied email address """ text = generate_email(email, report._meta.salt, project) try: msg = MIMEText(text, 'html') msg['To'] = ",...
0a5a74d453e4c1c238ff472ca8929a81ee5adc4e
63,890
from typing import List from typing import Tuple import random def generate_round_robin_matches(bots: List[str]) -> List[Tuple[str, str]]: """ Returns a list of pairs of bots that should play against each other for a round robin. """ # This makes the list of matches consistent over multiple calls. E.g...
1d29e36613210d8d1198fe5943c035c0e435b8dc
63,891
def gsl_blas_sdot(*args, **kwargs): """gsl_blas_sdot(gsl_vector_float X, gsl_vector_float Y, float result) -> int""" return _gslwrap.gsl_blas_sdot(*args, **kwargs)
d3f5fa80e04d2f8ee511a3a960a1c3bce448c415
63,892
def binary_search(array, item): """Return the index of item in sorted array or None if item is not found. Runtime Analysis: On each iteration or recursive step through this function, half of the list elements are eliminated from consideration. On the best case, the item is found exactly...
b622232e61500a8609ef1abdd54bdf9eb475c5ee
63,893
def filter_shots_from_range( shots=None, start_frame=None, end_frame=None, sequence_time=False): """ Filter shots if their range contains any frame in the given one. :param list[str] shots: Maya shot nodes. Use all shot if None. :param float start_frame: :param float end_frame: :param bo...
4355bee4dc7f91cdd4f156259cff2511564d389f
63,894
import random def navigable_small_world_graph(n, p=1, q=1, r=2, dim=2, seed=None): """Return a navigable small-world graph. A navigable small-world graph is a directed grid with additional long-range connections that are chosen randomly. [...] we begin with a set of nodes [...] that are identified...
1bd91d12264c8f0ee63cee55e0f0d0830ffe1354
63,895
import math def csr_to_2d_sell(n_row, rowptr, colidx, val, slice_height): """ Convert CSR format to Sliced ELLPACK format. The colidx and val will be stored as 2d array. Parameters ---------- n_row : int Number of rows rowptr : ndarrays Row pointer of CSR format colidx...
0b1c52bc2d73b13a05595e512558e2c8a0b38013
63,896
def sample_n_trajectories(env, policy, n_trajectories, max_episode_length): """Sample n trajectories using the given policy. Parameters ---------- env: A WhyNot gym environment. policy: An instance of Policy. n_trajectories: Number of trajectories. max_episode_length: Cap on max length for ...
56c9764a3bb7014d430b36070b09866d98028265
63,897
def bin2dec(string_num): """Turn binary into decimal.""" return str(int(string_num, 2))
5c8ba774f1a749947e64a00c86e6cb4054b44d97
63,898
def get_aws_client(config): """Returns an S3 service. Args: config (dict): The configuration object. Returns: obj: The correctly configured client service. """ log.debug('Initializing S3 client.') client = boto3.client('s3', region_name=config['aws_region_name'], aws...
181a66aaa8353eca0e379efe43a6a7b529bdd3be
63,899