content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def links_at_node(shape): """Get link ids for each node. Parameters ---------- shape : tuple of int Shape of grid of nodes. Returns ------- (N, 4) ndarray of int Array of link ids. Examples -------- >>> from landlab.grid.structured_quad.links import links_at_no...
0f354530d5c6b415c886df25e1b15ba2477de8c9
3,656,900
def manage_addFancyContent(self, id, REQUEST=None): """Add the fancy fancy content.""" id = self._setObject(id, FancyContent(id)) return ''
47efd8df7d0ccc12894729d142a09a8a53562ff5
3,656,901
def convert_sentences(sentences, tokenizer): """ Truncate each sentence to 512 bpes in order to fit on BERT and convert it to bpes. :param tokenizer: The BERT tokenizer we used in order convert each sentence to ids. :param sentences: The tokenized sentences of the summary we are processing. :return:...
48cde2cba0af288bff9f49cb2ffc66dd22cfd952
3,656,902
from typing import Union from typing import Tuple def imscale(image: Imagelike, scale: Union[float, Tuple[float, float]], **kwargs) -> np.ndarray: """Scale the given image. The result will be a new image scaled by the specified scale. """ global _resizer if _resizer is None: _...
1c0949b445620febe1482ea4d32ae2dd4ac44e04
3,656,903
from typing import Union def parse_tooltip(spell: Union[ChampionSpell, SummonerSpell], tooltip: str) -> str: """ Improved tooltip parser based on the built-in Cassiopeia `Spell.__replace_variables` """ for dto in spell._data.values(): try: costs_burn = dto.costBurn eff...
ed729e7ce47b393d64c9f83d6bc8cb8337dee0f7
3,656,904
def _packages_info() -> dict: """Return a dict with installed packages version""" return Dependencies.installed_packages()
a4095968c7553aad017e97ab88322c616586961f
3,656,905
import warnings import os import gzip import pickle def _save_mnist_recreation_indices(): """Code to find MNIST train, validation and test indices for recreation of MNIST MAF dataset. Note this should not be called directly. This is only here for reproducibility.""" warnings.warn('This function shoul...
ff4956a22067fab3ef539c2460c6b7f779447714
3,656,906
def _first(root: TreeNode) -> TreeNode: """Return a first in "inorder" traversal order of the `root` subtree Args: root (TreeNode): root of subtree Returns: TreeNode: first node in subtree """ if root.left is None: return root return _first(root.left)
6464b7b920b32d3e3fd309eb1a7de26bd21a5710
3,656,907
def get_library_version() -> str: """ Returns the version of minecraft-launcher-lib """ return __version__
aaa0703835cb00370bf30e96f2988f4c2e16bb51
3,656,908
import os import tarfile def download_voc_pascal(data_dir='../data'): """Download the Pascal VOC2012 Dataset.""" voc_dir = os.path.join(data_dir, 'VOCdevkit/VOC2012') url = "http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar" sha1 = '4e443f8a2eca6b1dac8a6c57641b67dd40621a49' ...
04d14ac2d5260f2f05ac6223e6efcd2fa0940287
3,656,909
def load_image(image): """reshape and convert image to fit the model""" img = cv2.imread(image) # Load images img = cv2.resize(img, (257, 257), interpolation=cv2.INTER_LINEAR) # resize img = (np.float32(img) - 127.5) / 127.5 # change image to float and normalize img = img.reshape((1, 257, 25...
642f1da152b7e852e46c57d4c2608e469ba7bddb
3,656,910
def hist_trigger_time_diff(df_dev): """ plots """ df = devices_trigger_time_diff(df_dev.copy()) fig = go.Figure() trace = go.Histogram(x=np.log(df['row_duration'].dt.total_seconds()/60), nbinsx=200, ) fig.add_trace(trace) return fig
43ae70a2ff9a6b7f9927d91c88c2d540f7b8ca24
3,656,911
def verify_spec(spec_utid, proxy_utid): """ For a specific unit test id (utid) compares the spec with the proxy """ results='' for key in spec_utid: results += '%s: spec=%s, proxy=%s (%s) *** ' % (key,spec_utid[key],proxy_utid[key],(spec_utid.get(key)==proxy_utid.get(key))) return results
b9854e23f0d88ed4f9abcc0c16236a2d543b9eb0
3,656,912
def lammps_created_gsd(job): """Check if the mdtraj has converted the production to a gsd trajectory for the job.""" return job.isfile("trajectory-npt.gsd")
a66c899a20e9602098150f46067d5505572232c2
3,656,913
from datetime import datetime def neo4j_data_age(data, max_data_age=None): """ Checks the noclook_last_seen property against datetime.datetime.now() and if the difference is greater than max_data_age (hours) (django_settings.NEO4J_MAX_DATA_AGE will be used if max_data_age is not specified) and the...
77f703f972b7b67ec5de48c9f8a0aceef3cd0646
3,656,914
import optparse def ProfileOptions(parser): """Build option group for profiling chrome. Args: parser: OptionParser object for parsing the command-line. Returns: Option group that contains profiling chrome options. """ profile_options = optparse.OptionGroup(parser, 'Profile Chrome Options') brows...
57b41cf7a629b566aec995be2d6181357000fc1c
3,656,915
def _clean_unicode(value): """Return the value as a unicode.""" if isinstance(value, str): return value.decode('utf-8') else: return unicode(value)
be04bf30cecd7f25d0c39c05f6d5e6d995438c0b
3,656,916
def deslugify_province(prov): """ Province slug to name, i.e. dashes to spaces and title case. KZN is a special case. """ if prov == 'kwazulu-natal': return 'KwaZulu-Natal' return prov.replace('-', ' ').title()
8e88ea7325c3b911495780b4437bc02784fbad82
3,656,917
def color_debug(): """ Color for info """ return read_config_color("COLOR", "debug", "grey")
87eb9e867c34149b605ade2152dec0f9bf74e6c4
3,656,918
def replace_sym(data: str) -> str: """ Converts currency strings such as ``£5.00`` to ``5.00 GBP`` - or ``10 kr`` to ``10 SEK`` """ origdata = data data = data.strip() for s, r in settings.CUR_SYMBOLS.items(): if data.startswith(s) or data.endswith(s): log.debug(f"Replacing s...
75cad28158839618195f7c5b7eefeece9a59e001
3,656,919
import re def parse_vectors(vectors): """ Basic cleanup of vector or vectors Strip out V from V#s. Similar to parse tables, this by no means guarantees a valid entry, just helps with some standard input formats Parameters ---------- vectors : list of str or str A string or list of st...
d2161e45bae51db21d7668ea6008ddb9ada16c4e
3,656,920
def sort_slopes(sds): """Sort slopes from bottom to top then right to left""" sds = np.array(sds) scores = sds[:, 0, 1] + sds[:, 1, 1] * 1e6 inds = np.argsort(scores) return sds[inds]
3bb62bf3be98176ae096bfe5f55b203173c3a425
3,656,921
import os import json def _get_mock_dataset(root_dir, base_dir_name): """ root_dir: directory to the mocked dataset """ base_dir = os.path.join(root_dir, base_dir_name) os.makedirs(base_dir, exist_ok=True) if base_dir_name == SQuAD1.__name__: file_names = ("train-v1.1.json", "dev-v1.1...
a34432f044c17d2ebb35445a1c1a081114a57058
3,656,922
def serialize_skycoord(o): """ Serializes an :obj:`astropy.coordinates.SkyCoord`, for JSONification. Args: o (:obj:`astropy.coordinates.SkyCoord`): :obj:`SkyCoord` to be serialized. Returns: A dictionary that can be passed to :obj:`json.dumps`. """ representation = o.representa...
52830d9243cac36573c358f1579987eb43435892
3,656,923
def redis_sentinel(create_sentinel, sentinel, loop): """Returns Redis Sentinel client instance.""" redis_sentinel = loop.run_until_complete( create_sentinel([sentinel.tcp_address], timeout=2, loop=loop)) assert loop.run_until_complete(redis_sentinel.ping()) == b'PONG' return redis_sentinel
3b779c9ef73e3bc5949afadbace34a9dcca1273a
3,656,924
from typing import Tuple from typing import Dict def compute_features( seq_path: str, map_features_utils_instance: MapFeaturesUtils, social_features_utils_instance: SocialFeaturesUtils, ) -> Tuple[np.ndarray, Dict[str, np.ndarray]]: """Compute social and map features for the sequence. ...
bd8414b81bc3b1856773767d4f8db8897436ddf3
3,656,925
def summarizeTitlesByLength(titlesAlignments, limit=None): """ Sort match titles by sequence length. @param titlesAlignments: A L{dark.titles.TitlesAlignments} instance. @param limit: An C{int} limit on the number of results to show. @return: An C{IPython.display.HTML} instance with match titles so...
31f9a358032018b51910148dfaa82d4deb08191f
3,656,926
def _diff_tail(msg): """`msg` is an arbitrary length difference "path", which could be coming from any part of the mapping hierarchy and ending in any kind of selector tree. The last item is always the change message: add, replace, delete <blah>. The next to last should always be a selector key of s...
224a4ca5f73b1f147c27599b62f0540480e40a0d
3,656,927
def select_standard_name(session, cluster, importance_table_name): """ Use cluster members for a WHERE ... IN (...) query Use SQLAlchemy to handle the escaping """ stmt = session.query('name from %s' % importance_table_name) \ .filter(column('name').in_(list(cluster))) \ .order_by('"...
173113f8abf6b675fefe7279cfa1e28579747085
3,656,928
def calculate_depth(experiment): """ Calculate the minor, major, total depth Args: experiment (remixt.Experiment): experiment object Returns: pandas.DataFrame: read depth table with columns, 'major', 'minor', 'total', 'length' """ data = remixt.analysis.experiment.create_segment_...
d4db665eff37f6590a2362af8896db25b8ae758b
3,656,929
import random def checkerboard(key, nsq, size, dtype=np.float32): """Create a checkerboard background image with random colors. NOTE: only supports a single value for nsq (number squares). Args: key: JAX PRNGkey. nsq (int): number of squares per side of the checkerboard. size (int): size of one si...
4f6428450a05fcb92ba05e22e336d887860fb143
3,656,930
import torch def choice(x, a): """Generate a random sample from an array of given size.""" if torch.is_tensor(x): return x[torch.randint(len(x), (a,))] return x
af21321bcd12fe5f1a5eb59b8f0db14096899b5d
3,656,931
def correct_gene_names(df): """ Fix datetime entries in Gene names """ update_symbols = [] for i, gs in enumerate(df.Gene_Symbol): if (not (isinstance(gs, str))) or (':' in gs): update_symbols.append(mapping.get_name_from_uniprot(df.Uniprot_Id.iloc[i])) else: upda...
5ca1aa1da60f238f9c377640b9f1a350658ea9d0
3,656,932
def process_repl_args(args): """ Process PANDA replay-related arguments. """ assert False, 'Not implemented yet.' cmd = [] cmd.extend(['-display', 'none']) return cmd # p_test "${panda_rr}-rr-snp" f "trace memory snapshot" # p_test "${panda_rr}-rr-nondet.log" f "trace nondet log" # -...
660495454f3b04f76d9aa0447262cb3a8c06b543
3,656,933
def choose(n, k): """ A fast way to calculate binomial coefficients by Andrew Dalke (contrib). """ if 0 <= k <= n: ntok = 1 ktok = 1 for t in range(1, min(k, n - k) + 1): # changed from xrange ntok *= n ktok *= t n -= 1 return ntok // ...
22c8639b3e110673164faa1ea84d669d5f8816d4
3,656,934
import pickle def _get_ReaLiSe_dataset(which="15"): """ For its """ print("Loading ReaLiSe Dataset !") print("Hint: The Data You loading now is the preprocessed sighan from ReaLise, ") ddp_exec("os.system('date')") path = "../SE_tmp_back/milestone/ReaLiSe/data/" train_dataset = pickl...
418f443fa3e2094b5288bcaf3490780632b2922c
3,656,935
def generate_check_phrase() -> bytes: """ Generate check-phrase for connecting of auxiliary socket. :return: some array of ATOM_LENGTH bytes. """ return get_random_bytes(ATOM_LENGTH)
9bcd270bd1f9c3a7943d4910c065cc9fdee02141
3,656,936
import pickle def load_pickle(filename: str): """ Load a file from disk. Parameters ---------- filename: str Name of the file that is loaded. Returns ------- """ return pickle.load(open(filename, 'rb'))
cae6710ba18664f244c55525c14a6bda0bea314d
3,656,937
import os def find_pssm_missing_proteins(fasta_dict, pssm_dir): """find_pssm_missing_proteins function finds the missing pssm files of the proteins in fasta file. Args: fasta_dict (dict): This is a dict of fasta file. The keys of fasta_dict are protein ids and values are protein sequences. ...
d3ab3011216329ba7dc9a6d7449d930ea3e536c7
3,656,938
import os def _format_echo(text): """Compose system echo command outputs text""" quote = '' if os.name == 'nt' else '"' return 'echo {}{}{}'.format(quote, text, quote)
65dde7b473b618a957c3eddd4bb205df5d9cb674
3,656,939
def crop_to_reference(dataset: xr.Dataset, ref_dataset: xr.Dataset) -> xr.Dataset: """ Crops horizontal coordinates to match reference dataset """ if "longitude" not in dataset.coords.keys(): raise ValueError("Longitude is not a coordinate of dataset.") if "longitude" not in ref_dataset.coords...
c915ec99dca5cd33531c049447e23e380590b1af
3,656,940
def parse_line(description, inline_comments=_INLINE_COMMENT_PREFIXES): """ Parse a line and correctly add the description(s) to a collection """ # manually strip out the comments # py2 cannot ignore comments on a continuation line # https://stackoverflow.com/q/9110428/1177288 # # PY3 ca...
6fc58aef5b103ce429ed82378bce81a4550abb0f
3,656,941
def target_frame(): """Input frame.""" return 'IAU_ENCELADUS'
8c57ab924a7b4471ac2f549493ebc176e853c652
3,656,942
def cards(cs): """Parse cards""" cs = cs.split(' ') result = np.zeros([len(valueL), len(colorL)], int) for c in cs: result[np.where(valueL == c[0])[0][0], np.where(colorL == c[1])[0][0]] = 1 return result
9db7aa3ae9b42fb7b3fcd67371bca02b455fd8e4
3,656,943
def _get_max_diag_idx(m, n_A, n_B, diags, start, percentage): """ Determine the diag index for when the desired percentage of distances is computed Parameters ---------- m : int Window size n_A : int The length of the time series or sequence for which to compute the matrix ...
b6f86ee110ae4fa16638f86f2dcf324e7ebfb674
3,656,944
def get_argument_values(arg_defs, arg_asts, variables): """Prepares an object map of argument values given a list of argument definitions and list of argument AST nodes.""" if arg_asts: arg_ast_map = {arg.name.value: arg for arg in arg_asts} else: arg_ast_map = {} result = {} f...
0bad38e7155d04ac297e2112b8f9b70e5fcc18a0
3,656,945
def get_identifier(positioner_id, command_id, uid=0, response_code=0): """Returns a 29 bits identifier with the correct format. The CAN identifier format for the positioners uses an extended frame with 29-bit encoding so that the 11 higher bits correspond to the positioner ID, the 8 middle bits are the...
57a1ce7004186e8c1c88c06665311e71010705c4
3,656,946
def standardized(array): """Normalize the values in an array. Arguments: array (np.ndarray): Array of values to normalize. Returns: array with zero mean and unit standard deviation. """ return (array - array.mean()) / max(1e-4, array.std())
1764dfd1e4e173d2ca081edeb8b7165a79d63b7d
3,656,947
import json def newaddress(fn,passphrase,addr_type=0): """ getnetaddress """ wallet = Wallet(fn).fromFile(passphrase) # Address Types # addr_type == 0, deposit # addr_type == 1, change # addr_type == 2, staking # addr_type == 3, Dealer # Address types aren't programmatically important, but help to organize ...
8afca8b83ea8464d3aeb02f5d2e406d2f5bebc53
3,656,948
import logging def index(args): """Handles the index step of the program.""" if not args.index: # build index logging.info(" Building index...") index_list = generate_index(args.input_dir) if not index_list: # list is empty logging.error(" Empty index. Exiting...") ...
5e8e37d387612eb81984c7bff48e747780475f78
3,656,949
import cv2 import torch def setup_harness(bsize=16, workers=0): """ CommandLine: python ~/code/netharn/netharn/examples/yolo_voc.py setup_harness Example: >>> # DISABLE_DOCTSET >>> harn = setup_harness() >>> harn.initialize() """ xpu = nh.XPU.cast('argv') nic...
7ea7841646e4be1f4d776e78fa4e8a7d5e1117c3
3,656,950
def _output_object_or_file_map_configurator(prerequisites, args): """Adds the output file map or single object file to the command line.""" return _output_or_file_map( output_file_map = prerequisites.output_file_map, outputs = prerequisites.object_files, args = args, )
7d362be5d6478764810ae3a9013ce1cb807efde3
3,656,951
def get_file_name(): """This function asl the user for file and returns it""" f_name = input('Input your file name: ') return f_name
5d3e524ebe423410f721afb070bfba9d804ed19f
3,656,952
import six import subprocess def GetMinikubeVersion(): """Returns the current version of minikube.""" return six.ensure_text(subprocess.check_output([_FindMinikube(), 'version']))
bee4129bb9d63aa1aad39451290df136977027be
3,656,953
import itertools def minimum_distance(geo1, geo2): """ get the minimum distance between atoms in geo1 and those in geo2 """ xyzs1 = coordinates(geo1) xyzs2 = coordinates(geo2) return min(cart.vec.distance(xyz1, xyz2) for xyz1, xyz2 in itertools.product(xyzs1, xyzs2))
ce6493d7e12bd3f48db209a01fe85eb4305835d0
3,656,954
def prepare(): """ Get the list of filtered tweets by target entity where each item contains the tweet with its original attributes when downloaded from Twitter :return: """ path = '../../Data.json' List = loadData(path) # load data tweets = [List[i]['text'] for i in range(len(List))] ...
0707993267bd6e76d432b08e947582f8a151f591
3,656,955
from typing import Dict from typing import List import os import sys import re def get_console_script_specs(console: Dict[str, str]) -> List[str]: """ Given the mapping from entrypoint name to callable, return the relevant console script specs. """ # Don't mutate caller's version console = con...
80d4c71f87ff1af9762c2a8a0bdf99c1efb8a3d7
3,656,956
import requests def deletecall(bam_url,api_call,call_parameters,delete_entity,header): """API request to delete and return values""" call_url = "http://"+bam_url+"/Services/REST/v1/"+api_call+"?" print("You are requesting to delete:") print(delete_entity) answer = input("Do you want to proceed (y ...
f6cffd225b9dd8d4d387b472d5ef522e2a48d738
3,656,957
def haDecFromAzAlt (azAlt, lat): """Converts alt/az position to ha/dec position. Inputs: - azAlt (az, alt) (deg) - lat latitude (degrees); >0 is north of the equator, <0 is south Returns a tuple containing: - haDec (HA, Dec) (deg), a tuple; HA is i...
9387d6771dd3fd4754a874141679902954adbecf
3,656,958
def get_description(expression, options=None): """Generates a human readable string for the Cron Expression Args: expression: The cron expression string options: Options to control the output description Returns: The cron expression description """ descripter = ExpressionDes...
b52bb4bda67074e5b9270f33f68892e371234dc4
3,656,959
import os def check_for_firefox(): """ Determine if Firefox is available. """ if os.path.exists('/Applications/Firefox.app/Contents/MacOS/firefox'): return True for exe in ('firefox',): if find_executable(exe): return True return False
cf193934b6adafd2bfba44f06848f9d9ca6bbda0
3,656,960
def midpoint(close, length=None, offset=None, **kwargs): """Indicator: Midpoint""" # Validate arguments close = verify_series(close) length = int(length) if length and length > 0 else 1 min_periods = int(kwargs['min_periods']) if 'min_periods' in kwargs and kwargs['min_periods'] is not None else len...
3b14546715bec61dfd73a70d4a83042366c1ef08
3,656,961
from ..distributions.baseclass import Dist import numpy def quad_fejer(order, domain=(0, 1), growth=False, segments=1): """ Generate the quadrature abscissas and weights in Fejer quadrature. Args: order (int, numpy.ndarray): Quadrature order. domain (chaospy.distributions.base...
ec2472e134a2adab5cfa42703fdaafde844aee79
3,656,962
from pathlib import Path def probe(app: FastFlixApp, file: Path) -> Box: """ Run FFprobe on a file """ command = [ f"{app.fastflix.config.ffprobe}", "-v", "quiet", "-loglevel", "panic", "-print_format", "json", "-show_format", "-show_stre...
055ac6003642bc78d1fcabbbb89765d1cacb3d80
3,656,963
def is_standard_time_series(time_series, window=180): """ Check the length of time_series. If window = 180, then the length of time_series should be 903. The mean value of last window should be larger than 0. :param time_series: the time series to check, like [data_c, data_b, data_a] :type time_ser...
7fb3212c69efb076dbab9555cf1eab9698475f9b
3,656,964
def get_comment_type(token, comment_syntax): """ SQLエンジン関連コメントTypeを返す """ if is_block_comment(token): return comment_syntax.get_block_comment_type(token) elif is_line_comment(token): return comment_syntax.get_line_comment_type(token)
0ddd68b4cd12909c5689f5620b785ccb8a45cbeb
3,656,965
from typing import Any from typing import Dict def edit(project: Any, params: Dict[str, str]) -> Dict[str, str]: """ Add a new method to a Python class in its given module. TODO: See why an <EOF> char is added along with the new method """ eng = project.context().pathExpressionEngine() res = ...
3d5b0778d8c74ced8fb360e47c40648c17629748
3,656,966
def get_country_code(country_name): """ Return the Pygal 2-digit country code for the given country.""" for code, name in COUNTRIES.items(): if name == country_name: return code # If the country wasn't found, return None. return None
485684fe01ade5e2ad558523ca839a468c083686
3,656,967
def get_divmod(up, down, minute=False, limit=2): """ 获取商 :param up: 被除数 :param down: 除数 :param minute: 换算成分钟单位 :param limit: 保留小数的位数 :return: 商 """ if up == 0: return 0 if down == 0: return 0 if minute: return round(up/down/60.0, limit) return roun...
253304cde82fd4a3aa70737f4caabb20b5166349
3,656,968
def find_kernel_base(): """Find the kernel base.""" return idaapi.get_fileregion_ea(0)
20315c1fecc8d2a4ecf7301ccedeca84d4027285
3,656,969
def get_padding(x, padding_value=0, dtype=tf.float32): """Return float tensor representing the padding values in x. Args: x: int tensor with any shape padding_value: int value that dtype: type of the output Returns: float tensor with same shape as x containing values 0 or 1. ...
d11650796b980a53a5790588ac123c5323b867bd
3,656,970
import typing def canonical_symplectic_form_inverse (darboux_coordinates_shape:typing.Tuple[int,...], *, dtype:typing.Any) -> np.ndarray: """ Returns the inverse of canonical_symplectic_form(dtype=dtype). See documentation for that function for more. In particular, the inverse of the canonical symplectic...
4ef3c820c7919fcd1bb7fda3fdf2482f3cd70c03
3,656,971
def update_with_error(a, b, path=None): """Merges `b` into `a` like dict.update; however, raises KeyError if values of a key shared by `a` and `b` conflict. Adapted from: https://stackoverflow.com/a/7205107 """ if path is None: path = [] for key in b: if key in a: i...
201650bba4fcae21d353f88ff22a9559aea61ff4
3,656,972
import re def tokenize(sent): """Return the tokens of a sentence including punctuation. >>> tokenize("Bob dropped the apple. Where is the apple?") ["Bob", "dropped", "the", "apple", ".", "Where", "is", "the", "apple", "?"] """ return [x.strip() for x in re.split(r"(\W+)?", sent) if x and x.strip(...
09456d2ae7d590ba8d6373a27993a52c0693027b
3,656,973
def tree_unflatten(flat, tree, copy_from_tree=None): """Unflatten a list into a tree given the tree shape as second argument. Args: flat: a flat list of elements to be assembled into a tree. tree: a tree with the structure we want to have in the new tree. copy_from_tree: optional list of elements that ...
711bc67a20835091360d0fbc64e0a8842eec53ba
3,656,974
def ByteOffsetToCodepointOffset( line_value, byte_offset ): """The API calls for byte offsets into the UTF-8 encoded version of the buffer. However, ycmd internally uses unicode strings. This means that when we need to walk 'characters' within the buffer, such as when checking for semantic triggers and similar,...
0a826157c43cb73a5dff31c20c906144b4a0eaa6
3,656,975
def get_authed_tweepy(access_token, token_secret): """Returns an authed instance of the twitter api wrapper tweepy for a given user.""" social_app_twitter = get_object_or_404(SocialApp, provider='twitter') auth = tweepy.OAuthHandler(social_app_twitter.client_id, social_app_twitter.secret) auth.set_acce...
33bbf0cabdf2bbd3fc543efc4d921119d29c7729
3,656,976
def suffix_for_status(status): """Return ``title`` suffix for given status""" suffix = STATUS_SUFFIXES.get(status) if not suffix: return '' return ' {}'.format(suffix)
a908d28c6e461dcc8277784e82e383642b5ecfa3
3,656,977
import json def login(): """ login an existing user """ try: username = json.loads(request.data.decode())['username'].replace(" ", "") password = json.loads(request.data.decode())['password'].replace(" ", "") user = User(username, "", "") user = user.exists() i...
8e09725c37ac897efefd3cd546ce929cdf799716
3,656,978
def soma_radius(morph): """Get the radius of a morphology's soma.""" return morph.soma.radius
2f9991a2f9240965bdb69a1a14814ed99bf60f86
3,656,979
async def async_get_authorization_server(hass: HomeAssistant) -> AuthorizationServer: """Return authorization server.""" return AuthorizationServer( authorize_url=AUTHORIZATION_ENDPOINT, token_url=TOKEN_ENDPOINT, )
99d7c0d25168d07d0d27ee95e6ee0b59cb6d48c0
3,656,980
from typing import Optional def check_proposal_functions( model: Model, state: Optional[flow.SamplingState] = None, observed: Optional[dict] = None, ) -> bool: """ Check for the non-default proposal generation functions Parameters ---------- model : pymc4.Model Model to sample posteri...
3d0d14f800f3d499de0c823dd2df8b852573c56f
3,656,981
def smaller_n(n1, n2): """ Compare two N_Numbers and returns smaller one. """ p1, s1 = n1 p2, s2 = n2 p1l = len(str(p1)) + s1 p2l = len(str(p2)) + s2 if p1l < p2l: return n1 elif p1l > p2l: return n2 p1 = p1.ljust(36, '9') p2 = p2.ljust(36, '9') if p1 <= p2: ...
1f5922b74bdb8e5ee4dba7a85a9a70efdb024c59
3,656,982
def sortDict(dictionary: dict): """Lambdas made some cringe and stupid thing some times, so this dirty thing was developed""" sortedDictionary = {} keys = list(dictionary.keys()) keys.sort() for key in keys: sortedDictionary[key] = dictionary[key] return sortedDictionary
ed61adf95f2b8c1c4414f97d84b8863596681478
3,656,983
def elina_linexpr0_alloc(lin_discr, size): """ Allocate a linear expressions with coefficients by default of type ElinaScalar and c_double. If sparse representation, corresponding new dimensions are initialized with ELINA_DIM_MAX. Parameters ---------- lin_discr : c_uint Enum of typ...
56bbaa01ba3b9bbe657240abdf8fb92daa527f29
3,656,984
def FrameTag_get_tag(): """FrameTag_get_tag() -> std::string""" return _RMF.FrameTag_get_tag()
21392f22a0b67f86c5a3842ab6befc4b1e3938c6
3,656,985
def noise4(x: float, y: float, z: float, w: float) -> float: """ Generate 4D OpenSimplex noise from X,Y,Z,W coordinates. """ return _default.noise4(x, y, z, w)
75b5911e9b8b4a08abba9540992e812d2a1dee83
3,656,986
def damerau_levenshtein_distance(word1: str, word2: str) -> int: """Calculates the distance between two words.""" inf = len(word1) + len(word2) table = [[inf for _ in range(len(word1) + 2)] for _ in range(len(word2) + 2)] for i in range(1, len(word1) + 2): table[1][i] = i - 1 for i in range...
7b75bb94fe66897c1807ac185d8602ea2b3ebd67
3,656,987
from typing import Any def ga_validator(value: Any) -> str | int: """Validate that value is parsable as GroupAddress or InternalGroupAddress.""" if isinstance(value, (str, int)): try: parse_device_group_address(value) return value except CouldNotParseAddress: ...
84845c9dbf5db041e243bf462dec4533ff7e0e3e
3,656,988
import time import re from datetime import datetime def getTime(sim): """ Get the network time @param sim: the SIM serial handle """ sim.write(b'AT+CCLK?\n') line = sim.readline() res = None while not line.endswith(b'OK\r\n'): time.sleep(0.5) matcher = re.match(br'^\+C...
77c889a41b214046a5965126927ca7e7ee043129
3,656,989
import makehuman def defaultTargetLicense(): """ Default license for targets, shared for all targets that do not specify their own custom license, which is useful for saving storage space as this license is globally referenced by and applies to the majority of targets. """ return makehuman.get...
a638129f1674b14fbf0d72e5323c1725f6fb5035
3,656,990
import json def get_repo_info(main_path): """ Get the info of repo. Args: main_path: the file store location. Return: A json object. """ with open(main_path + '/repo_info.json') as read_file: repo_info = json.load(read_file) return repo_info
f4a538819add0a102f6cbe50be70f2c9a0f969b6
3,656,991
import yaml def parse_settings(settings_file: str) -> dict: """ The function parses settings file into dict Parameters ---------- settings_file : str File with the model settings, must be in yaml. Returns ------- ydict : dict Parsed settings used for m...
1aec2a8be51376209db81d60115814ddefca7ea6
3,656,992
def get_mac_address(path): """ input: path to the file with the location of the mac address output: A string containing a mac address Possible exceptions: FileNotFoundError - when the file is not found PermissionError - in the absence of access rights to the file TypeError - If t...
814a530b63896103adcb8fbc84d17939644b9bbe
3,656,993
def jwt_get_username_from_payload_handler(payload): """ Override this function if username is formatted differently in payload """ return payload.get('name')
92d60ce714632571346e93459729dcf1d764617b
3,656,994
import shlex def grr_uname(line): """Returns certain system infornamtion. Args: line: A string representing arguments passed to the magic command. Returns: String representing some system information. Raises: NoClientSelectedError: Client is not selected to perform this operation. """ args ...
5e671fcffe415397edc3b7c6011cc4e21b72cb5a
3,656,995
import requests import warnings def stock_szse_summary(date: str = "20200619") -> pd.DataFrame: """ 深证证券交易所-总貌-证券类别统计 http://www.szse.cn/market/overview/index.html :param date: 最近结束交易日 :type date: str :return: 证券类别统计 :rtype: pandas.DataFrame """ url = "http://www.szse.cn/api/report...
6544b0d78baa76858c13a001287b35d2a0faf7ba
3,656,996
def find_all_movies_shows(pms): # pragma: no cover """ Helper of get all the shows on a server. Args: func (callable): Run this function in a threadpool. Returns: List """ all_shows = [] for section in pms.library.sections(): if section.TYPE in ('movie', 'show'):...
ca4a8a5f4b2c1632ea6e427c748ef790c896b3ba
3,656,997
def parse_vars(vars): """ Transform a list of NAME=value environment variables into a dict """ retval = {} for var in vars: key, value = var.split("=", 1) retval[key] = value return retval
e2c6ae05cdf0151caaf8589eb7d7df90dcdd99a1
3,656,998
from typing import List import collections def find_dup_items(values: List) -> List: """Find duplicate items in a list Arguments: values {List} -- A list of items Returns: List -- A list of duplicated items """ dup = [t for t, c in collections.Counter(values).items() if c > 1] ...
3a84c2f3b723bed9b7a82dc5f0cfd81d99c2bf48
3,656,999