content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def poppler_page_get_text_layout(page): """ Wrapper of an underlying c-api function not yet exposed by the python-poppler API. Returns a list of text rectangles on the pdf `page` """ n = c_uint(0) rects = CRectangle.ptr() # From python-poppler internals it is known that hash(page) ret...
2c7313004c9a551d943be741c904cadb4593b892
3,653,900
from typing import Optional def get_volume(name: Optional[str] = None, namespace: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetVolumeResult: """ ## Example Usage ```python import pulumi import pulumi_harvester as harvester ub...
528dfb0432b30b40037b86a234e83c8327eb5206
3,653,901
def both_block_num_missing(record): """ Returns true of both block numbers are missing :param record: dict - The record being evaluated :return: bool """ rpt_block_num = record.get("rpt_block_num", "") or "" rpt_sec_block_num = record.get("rpt_sec_block_num", "") or "" # True, if neithe...
63e2fdaef78dbc3c6560a4b015ed022583f30d05
3,653,902
def map_keys(func,dic): """ TODO: Test against all types handle python recursion limit """ return {func(k):map_keys(func,v) if isinstance(v,dict) else v for k,v in dic.items()}
5dc2c292e769037300d6b3f118e887bcb50752ac
3,653,903
def jsonize(v): """ Convert the discount configuration into a state in which it can be stored inside the JSON field. Some information is lost here; f.e. we only store the primary key of model objects, so you have to remember yourself which objects are meant by the primary key values. """ ...
1aa7954c0089726b7707e0180b35a12d679c286b
3,653,904
def clean_kaggle_movies(movies_df): """ Clean the Kaggle movie data with the following steps: 1. Drop duplicate rows 2. Filter out adult videos and drop unnecessary columns 3. Recast columns to appropriate data types Parameters ---------- movies_df : Pandas dataframe Kaggle mov...
05d5a0eb965b26cdc04dcfb9f3a76690d272389c
3,653,905
from typing import List from typing import Dict from typing import Any import torch import pathlib import os def generate_trainer( datafiles: List[str], labelfiles: List[str], class_label: str, batch_size: int, num_workers: int, optim_params: Dict[str, Any]={ 'optimizer': torch.optim.A...
e3448901793e2b58befff751b89edfa968a9e0d1
3,653,906
def make_shift_x0(shift, ndim): """ Returns a callable that calculates a shifted origin for each derivative of an operation derivatives scheme (given by ndim) given a shift object which can be a None, a float or a tuple with shape equal to ndim """ if shift is None: return lambda s, d, i...
e6b01e43c8bf73ba21a9bdfcd27a93db9ccb7478
3,653,907
import os def load_pca_tsne(pca, name, tpmmode=True, logmode=True, exclude=[], cache=True, dir='.'): """ Run t-sne using pca result Parameters ---------- pca : array, shape (n_samples, n_pca) pca matrix. name: str name of pca results Returns ------- tsne : array...
43946e73e367d2d5f0e623dff5f5a8d481917e87
3,653,908
def one_zone_numerical(params, ref_coeff, num_molecules=1e-9): """Returns one zone reactor exit flow.""" time = np.array(params[0], dtype=float) gradient = np.array(params[1], dtype=float) gridpoints = int(params[2]) step_size, area = float(params[3]), float(params[4]) solu = odeint( ...
4eb17f9684d1d12175bf85d15bada4178074de8a
3,653,909
import re def get_all_event_history_links(): """From ufcstat website finds all completed fights and saves the http into the current working directory """ url = "http://www.ufcstats.com/statistics/events/completed?page=all" href_collection = get_all_a_tags(url) #Add all links to list that hav...
ab452c66460f18b5d55ce2be2e22877f07e959d5
3,653,910
import matplotlib import numpy as np import matplotlib.cm as cm import matplotlib.colors as colors def profile_plot(x,z,data,ax,context_label = None,add_labels = False,xlabel = None,xmin = None, xmax=None, max_depth=None): """ UnTRIM-like profile plot of salinity xmin,xmax are the bounds (in km) of the pr...
9758ae430a2d45fd14932b8476648c61120c9749
3,653,911
def plot_book_wordbags(urn, wordbags, window=5000, pr = 100): """Generate a diagram of wordbags in book """ return plot_sammen_vekst(urn, wordbags, window=window, pr=pr)
12a03c70316d3920419f85cd2e4af87c7a16f0f8
3,653,912
def map_line2citem(decompilation_text): """ Map decompilation line numbers to citems. This function allows us to build a relationship between citems in the ctree and specific lines in the hexrays decompilation text. Output: +- line2citem: | a map keyed with line numbers, holdin...
86c8a24f769c7404560bb63c34f2b60ff3a097da
3,653,913
def from_dict(params, filter_func=None, excludes=[], seeds=[], order=2, random_seed=None): """Generates pair-wise cases from given parameter dictionary.""" if random_seed is None or isinstance(random_seed, int): return _from_dict(params, filter_func, excludes, seeds, order, random_seed) ...
d9ecd0528340adbe874afa70d3a9309e53ff87cc
3,653,914
def ensure_min_topology(*args, **kwargs): """ verifies if the current testbed topology satifies the minimum topology required by test script :param spec: needed topology specification :type spec: basestring :return: True if current topology is good enough else False :rtype: bool """ ...
364e7b3c166b725fd73846e1814bd3b7ab92ad96
3,653,915
def encode_mode(mode): """ JJ2 uses numbers instead of strings, but strings are easier for humans to work with CANNOT use spaces here, as list server scripts may not expect spaces in modes in port 10057 response :param mode: Mode number as sent by the client :return: Mode string """ if...
db83c419acb299284b7b5338331efc95051115a5
3,653,916
def split_array(arr, num_of_splits): """split an array into equal pieces""" # TODO Replace this function with gluon.utils.split_data() once targeting MXNet 1.7 size = arr.shape[0] if size < num_of_splits: return [arr[i:i + 1] for i in range(size)] slice_len, rest = divmod(size, num_of_splits...
f8d4812619725940f9e986d238bc4e0f650e8da6
3,653,917
import random def randclust(SC, k): """ cluster using random """ # generate labels. labels = np.array([random.randint(0,k-1) for x in range(SC.shape[1])]) # compute the average. S, cats = avg_cat(labels, SC) # return it. return S, labels, cats
42530495959977c1289fa6bdc2089747a246d210
3,653,918
def get_domains_by_name(kw, c, adgroup=False): """Searches for domains by a text fragment that matches the domain name (not the tld)""" domains = [] existing = set() if adgroup: existing = set(c['adgroups'].find_one({'name': adgroup}, {'sites':1})['sites']) for domain in c['domains'].find({}, {'domain': 1, '...
6ecaf4ccf1ecac806fb621c02282bf46929459ce
3,653,919
def read_bbgt(filename): """ Read ground truth from bbGt file. See Piotr's Toolbox for details """ boxes = [] with open(filename,"r") as f: signature = f.readline() if not signature.startswith("% bbGt version=3"): raise ValueError("Wrong file signature") rects...
25cfe28de9ed67ca0888da5bf27d01a803da8690
3,653,920
def measure(G, wire, get_cb_delay = False, meas_lut_access = False): """Calls HSPICE to obtain the delay of the wire. Parameters ---------- G : nx.MultiDiGraph The routing-resource graph. wire : str Wire type. get_cb_delay : Optional[bool], default = False Determines...
7db83ff5084798100a00d79c4df13a226a2e55a8
3,653,921
def direction_to(front,list_of_others,what="average") : """ Compute the direction vector towards *some other entities*. Parameters ---------- front : :py:class:`front.Front` Front to be used as the origin (starting point) of the direction \ vector list_of_others : list List...
f5757837e0eb71f2c03fda7c1d5b438d5036e8ac
3,653,922
def live_ferc_db(request): """Use the live FERC DB or make a temporary one.""" return request.config.getoption("--live_ferc_db")
f0540c8e3383572c5f686ea89011d9e1ab0bf208
3,653,923
from typing import Optional async def get_eth_hash(timestamp: int) -> Optional[str]: """Fetches next Ethereum blockhash after timestamp from API.""" try: this_block = w3.eth.get_block("latest") except Exception as e: logger.error(f"Unable to retrieve latest block: {e}") return Non...
f7f8cd70857d8bb84261685385f59e7cfd048f4c
3,653,924
import sys def resize_opencv(method, *args, **kwargs): """Direct arguments to one of the resize functions. Parameters ---------- method One among 'crop', 'cover', 'contain', 'width', 'height' or 'thumbnail' image Numpy array size Size object with desired size """ ...
fdbf2e166dd348101c3e39d6edb417112c389aba
3,653,925
import urllib.request, urllib.parse, urllib.error from bs4 import BeautifulSoup import ssl def extract_url_dataset(dataset,msg_flag=False): """ Given a dataset identifier this function extracts the URL for the page where the actual raw data resides. """ # Ignore SSL certificate errors ctx = s...
06ec2dd6bea4c264fe9590663a28c7c92eed6a49
3,653,926
def test_encrypt_and_decrypt_one(benchmark: BenchmarkFixture) -> None: """Benchmark encryption and decryption run together.""" primitives.encrypt = nacl.bindings.crypto_aead_xchacha20poly1305_ietf_encrypt primitives.decrypt = nacl.bindings.crypto_aead_xchacha20poly1305_ietf_decrypt def encrypt_and_decr...
fdd15ca362b983e5f7e28632434c2cbe1ab983ac
3,653,927
def MPI_ITOps(mintime = 5, maxtime = 20, cap = 60): """ Returns a costOfLaborValue object suitable to attach to a sim or other event Time is in hours """ timeDist = LogNormalValue(maxtime, mintime, cap) costDist = LogNormalValue(235, 115, 340) team = costOfLaborValue("IT I&O Team", timeDist,...
829c702d31a585fc18f81eea01c87f32c2458ea6
3,653,928
import json def load_private_wallet(path): """ Load a json file with the given path as a private wallet. """ d = json.load(open(path)) blob = bytes.fromhex(d["key"]) return BLSPrivateHDKey.from_bytes(blob)
9c98be3b3891eaab7b62eba32b426b78ae985880
3,653,929
import json def format_parameters(parameters: str) -> str: """ Receives a key:value string and retuns a dictionary string ({"key":"value"}). In the process strips trailing and leading spaces. :param parameters: The key-value-list :return: """ if not parameters: return '{}' pair...
95f115b9000d495db776798700cfdf35209cfbd4
3,653,930
def downvote_question(current_user, question_id): """Endpoint to downvote a question""" error = "" status = 200 response = {} question = db.get_single_question(question_id) if not question: error = "That question does not exist!" status = 404 elif db.downvote_question(curre...
a7bba2a9608d25b3404f22ca2f283486f205f0ad
3,653,931
def get_new_generation(generation: GEN, patterns: PATTERNS) -> GEN: """Mutate current generation and get the next one.""" new_generation: GEN = dict() plant_ids = generation.keys() min_plant_id = min(plant_ids) max_plant_id = max(plant_ids) for i in range(min_plant_id - 2, max_plant_id + 2): ...
a0908c9c7570814ca86d3b447425e7b75cdbfde2
3,653,932
def ell2tm(latitude, longitude, longitude_CM, ellipsoid = 'GRS80'): """ Convert ellipsoidal coordinates to 3 degree Transversal Mercator projection coordinates Input: latitude: latitude of a point in degrees longitude: longitude of a point in degrees longitude_CM: central meridi...
b6e1361df8b51e188bbc7a49557dbe8f14905df3
3,653,933
def Format_Phone(Phone): """Function to Format a Phone Number into (999)-999 9999)""" Phone = str(Phone) return f"({Phone[0:3]}) {Phone[3:6]}-{Phone[6:10]}"
8e46c35bca9d302d86909457c84785ad5d366c15
3,653,934
from sets import Set def aStarSearch(problem, heuristic=nullHeuristic): """Search the node that has the lowest combined cost and heuristic first.""" "*** YOUR CODE HERE ***" startState = problem.getStartState() if problem.isGoalState(startState): return [] # Each element in the fringe stor...
429c45bff701bbd2bb515be6d8a0f538183941d3
3,653,935
def _stack_add_equal_dataset_attributes(merged_dataset, datasets, a=None): """Helper function for vstack and hstack to find dataset attributes common to a set of datasets, and at them to the output. Note:by default this function does nothing because testing for equality may be messy for certain types; t...
acfeb1e7ca315aa7109731427ce6f058b2fceb6d
3,653,936
def _rstrip_inplace(array): """ Performs an in-place rstrip operation on string arrays. This is necessary since the built-in `np.char.rstrip` in Numpy does not perform an in-place calculation. """ # The following implementation convert the string to unsigned integers of # the right length. ...
f59d6d127d4d3f0725df5eee2e4586ccbea9288b
3,653,937
def compute_fixpoint_0(graph, max_value): """ Computes the fixpoint obtained by the symbolic version of the backward algorithm for safety games. Starts from the antichain of the safe set and works backwards using controllable predecessors. The maximum value for the counters is a parameter to facilitate ...
e2ee9cb00ce6f88e03a080d85a635c208cdd5a35
3,653,938
def extract_unii_other_code(tree): """Extract the codes for other ingredients""" unii_other_xpath = \ '//generalizedMaterialKind/code[@codeSystem="%s"]/@code' % UNII_OTHER_OID return tree.getroot().xpath(unii_other_xpath)
0576dc7537a9212990a72125b8fd406c457efb76
3,653,939
import functools def initfunc(f): """ Decorator for initialization functions that should be run exactly once. """ @functools.wraps(f) def wrapper(*args, **kwargs): if wrapper.initialized: return wrapper.initialized = True return f(*args, **kwargs) wrap...
337ca902fc1fbe138ad5dd4c203a3cac77e89f57
3,653,940
def edit_frame(frame): """edit frame to analyzable frame rgb 2 gray thresh frame color bitwise color Args frame (ndarray): original frame from movie Returns work_frame (ndarray): edited frame """ work_frame = frame work_frame = cv2.cvtColor(work_frame, cv2.COLOR...
b82588fa81093c05e4a683b76aa367ba2be4b2e2
3,653,941
def manchester(bin_string): """ Applies the Manchester technique to a string of bits. :param bin_string: :type bin_string: str :return: :rtype: str """ signal_manager = Signal() for bin_digit in bin_string: if bin_digit == '0': # Generate +- if signal_manager...
e5f58e929db74f0eeb2a003c25c5097f45c74989
3,653,942
from typing import List def load_admin_cells(identifier: str) -> List[MultiPolygon]: """Loads the administrative region cells Data is loaded from :py:const:`ADMIN_GEOJSON_TEMPLATE` ``% identifier``. This is a wrapper function for :py:func:`load_polygons_from_json`. Returns: A list of the adm...
dc2083ca7392da5b2d6509b6dd8f108bd8218726
3,653,943
import inspect def register_writer(format, cls=None): """Return a decorator for a writer function. A decorator factory for writer functions. A writer function should have at least the following signature: ``<class_name_or_generator>_to_<format_name>(obj, fh)``. `fh` is **always** an open filehan...
b8312d987cecfa106c73afb4eca5299637d260f6
3,653,944
import os def get_downloadpath(user_id): """ find the download path """ path = settings.DOCUMENT_PATH + str(user_id) + '/' if not os.path.isdir(path): os.mkdir(path) return path
da3508639cd8740410e5b21df8944a64ade7e50c
3,653,945
import torch def accuracy(output, target, topk=1,axis=1,ignore_index=-100, exclude_mask=False): """Computes the precision@k for the specified values of k prec1, prec5 = accuracy(output.data, target, topk=(1, 5)) """ input_tensor=output.copy().detach() target_tensor=target.copy().detach() num_c...
a35d4bff308862c4c8a83948c619e66299d7887f
3,653,946
def jitter_over_thresh(x: xr.DataArray, thresh: str, upper_bnd: str) -> xr.DataArray: """Replace values greater than threshold by a uniform random noise. Do not confuse with R's jitter, which adds uniform noise instead of replacing values. Parameters ---------- x : xr.DataArray Values. t...
1a508c30aa68c3b8808f3fe0b254ad98621cd245
3,653,947
from .rename_axis import rename_axis_with_level def index_set_names(index, names, level=None, inplace=False): """ Set Index or MultiIndex name. Able to set new names partially and by level. Parameters ---------- names : label or list of label Name(s) to set. level : int, label or...
4ad24ea4c1fd42b1259d43e273c44c4295a9e329
3,653,948
def get_critic(obs_dim: int) -> tf.keras.Model: """Get a critic that returns the expect value for the current state""" observation = tf.keras.Input(shape=(obs_dim,), name='observation') x = layers.Dense(64, activation='tanh')(observation) x = layers.Dense(64, activation='tanh')(x) value = layers.Den...
69082d6260666c733e32093fbc7180726f77acc6
3,653,949
def register_and_login_test_user(c): """ Helper function that makes an HTTP request to register a test user Parameters ---------- c : object Test client object Returns ------- str Access JWT in order to use in subsequent tests """ c.post( "/api/auth/regi...
b76f7f6afa9af453246ae304b1b0504bd68b8919
3,653,950
def get_ssh_challenge_token(account, appid, ip=None, vo='def'): """ Get a challenge token for subsequent SSH public key authentication. The challenge token lifetime is 5 seconds. :param account: Account identifier as a string. :param appid: The application identifier as a string. :param ip: IP...
12da26b4a20e648ca9fc6d325647f42288324b83
3,653,951
def rootpath_capacity_exceeded(rootpath,newSize): """ Return True if rootpath is already allocated to the extent it cannot accomadate newSize, otherwise return False """ vols_in_rootpath = Volume.objects.filter(root_path=rootpath) rootpathallocsum = 0 if vols_in_rootpath.count() > 0: ...
3b8d90f3693ce12de93c967d20c6a7b2ccb7ec38
3,653,952
import requests import json def user_token(user: str) -> str: """ Authorize this request with the GitHub app set by the 'app_id' and 'private_key' environment variables. 1. Get the installation ID for the user that has installed the app 2. Request a new token for that user 3. Return it so it c...
c02fae92505a922f58f231682a009d24ed6432bc
3,653,953
def file_exists(path): """ Return True if the file from the path exists. :param path: A string containing the path to a file. :return: a boolean - True if the file exists, otherwise False """ return isfile(path)
79610224c3e83f6ba4fdeb98b1faaf932c249ff2
3,653,954
from typing import Callable from typing import Dict def _static_to_href(pathto: Callable, favicon: Dict[str, str]) -> Dict[str, str]: """If a ``static-file`` is provided, returns a modified version of the icon attributes replacing ``static-file`` with the correct ``href``. If both ``static-file`` and ``h...
f54e5ced825dc44bfa14a09622c7fa9b179660c5
3,653,955
import torch def concatenate(tensor1, tensor2, axis=0): """ Basically a wrapper for torch.dat, with the exception that the array itself is returned if its None or evaluates to False. :param tensor1: input array or None :type tensor1: mixed :param tensor2: input array :type tensor2: numpy....
24791a201f1ddb64cd2d3f683ecc38471d21697b
3,653,956
def setKey(key, keytype): """ if keytype is valid, save a copy of key accordingly and check if the key is valid """ global _key, _keytype, FREE_API_KEY, PREMIUM_API_KEY keytype = keytype.lower() if keytype in ("f", "fr", "free"): keytype = "free" FREE_API_KEY = key elif keyt...
8baab2972ea5c9fbe33845aaed7c1ab4cc631a2e
3,653,957
import functools import operator def sum_(obj): """Sum the values in the given iterable. Different from the built-in summation function, the summation is based on the first item in the iterable. Or a SymPy integer zero is created when the iterator is empty. """ i = iter(obj) try: ...
70727443ba5a62e5bd91e3c0a60130f6cc0b65e5
3,653,958
def setup_s3_client(job_data): """Creates an S3 client Uses the credentials passed in the event by CodePipeline. These credentials can be used to access the artifact bucket. :param job_data: The job data structure :return: An S3 client with the appropriate credentials """ try: key...
bb51e03de125eeb6ff5e1e6d16b50ba07fdc7c56
3,653,959
import os import shutil import stat def collect_operations(opts): """ Produce a list of operations to take. Each element in the operations list is in the format: (function, (arguments,), 'logging message') """ operations = [] ####################### # Destination directory if o...
85f904d25a1a72fc754e09dbcbcbbed9cee98256
3,653,960
def pad_sequences(sequences, maxlen=None, dtype='int32', padding='pre', truncating='pre', value=0.): """ FROM KERAS Pads each sequence to the same length: the length of the longest sequence. If maxlen is provided, any sequence longer than maxlen is truncated to maxlen. Truncation happens off...
5d4603c5a71f898dc4f501d2424707ea10adbd0e
3,653,961
def basic_pyxll_function_22(x, y, z): """if z return x, else return y""" if z: # we're returning an integer, but the signature # says we're returning a float. # PyXLL will convert the integer to a float for us. return x return y
851b5eef683b0456a0f5bce7f3850698693b067e
3,653,962
def job_hotelling(prob_label, tr, te, r, ni, n): """Hotelling T-squared test""" with util.ContextTimer() as t: htest = tst.HotellingT2Test(alpha=alpha) test_result = htest.perform_test(te) return { 'test_method': htest, 'test_result': test_result, 'time_se...
137a3b4426a01675fe6995408ad71eec34126341
3,653,963
def return_circle_aperature(field, mask_r): """Filter the circle aperature of a light field. Filter the circle aperature of a light field. Parameters ---------- field : Field Input square field. mask_r : float, from 0 to 1 Radius of a circle mask. Returns ...
49ae52bfa639cf8a7b8592caa1dbf8dbdef115f8
3,653,964
import json def user_get(): """ Get information from the database about an user, given his id. If there are field names received in the body, only those will be queried. If no field is provided, every field will be selected. The body should be a JSON object following the schema: { "use...
02b1a1bc1bedc2098bd907098a40fad41c2391d7
3,653,965
def get_data_file_args(args, language): """ For a interface, return the language-specific set of data file arguments Args: args (dict): Dictionary of data file arguments for an interface language (str): Language of the testbench Returns: dict: Language-specific data file argume...
11e30b92316bad9a46b87bd9188f97d5e8860377
3,653,966
def branch_exists(branch): """Return True if the branch exists.""" try: run_git("rev-parse --verify {}".format(branch), quiet=True) return True except ProcessExecutionError: return False
8f08eeb78b322220def2f883e8172ac94df97063
3,653,967
import numpy def spectrum_like_noise(signal: numpy.ndarray, *, sampling_rate=40000, keep_signal_amp_envelope=False, low_pass_cutoff=50, # Hz low_pass_order=6, seed: int = 42...
6e6ced3a5220a9a1d66c83a33a9232d265d18a1a
3,653,968
import re def check_string_capitalised(string): """ Check to see if a string is in all CAPITAL letters. Boolean. """ return bool(re.match('^[A-Z_]+$', string))
f496d79fafae4c89c3686856b42113c4818f7ed8
3,653,969
import torch def sample_zero_entries(edge_index, seed, num_nodes, sample_mult=1.0): """Obtain zero entries from a sparse matrix. Args: edge_index (tensor): (2, N), N is the number of edges. seed (int): to control randomness num_nodes (int): number of nodes in the graph sample_...
211e97fa0a2622d49c50673c0b6255954383f3a0
3,653,970
import textwrap def ped_file_parent_missing(fake_fs): """Return fake file system with PED file""" content = textwrap.dedent( """ # comment FAM II-1\tI-1\t0\t1\t2 FAM I-1 0\t0\t1\t1 """ ).strip() fake_fs.fs.create_file("/test.ped", create_missing_dirs=True, contents=conten...
9df19ab925984236aa581c9b8843591f05d3b7b4
3,653,971
import random import requests def GettingAyah(): """The code used to get an Ayah from the Quran every fixed time""" while True: ayah = random.randint(1, 6237) url = f'http://api.alquran.cloud/v1/ayah/{ayah}' res = requests.get(url) if len(res.json()['data']['text']) <= 280: ...
5739cbd3554b97f01eefef7f59a4087e5497e3e7
3,653,972
def iterdecode(value): """ Decode enumerable from string presentation as a tuple """ if not value: return tuple() result = [] accumulator = u'' escaped = False for c in value: if not escaped: if c == CHAR_ESCAPE: escaped = True ...
d8b03338a4578ee7b37a4f6d31d23463fc0a9b84
3,653,973
def run_resolution_filter(image=None, image_path=None, height=600, width=1000): """ This will take the image which is correctly rotated yolo output. Initially, We are doing for driving licenses only, Will return 1 if the height and width are greater than 700 and 1100 pixels else it will return 10002 :return:...
fde3040dbb29d6c5f7d79237df51f425d2d043b4
3,653,974
import types def text_to_emotion(text): """ テキストから感情を推測して返す Parameters ---------- text : string テキスト Returns ------- {'magnitude','score'} """ client = language.LanguageServiceClient() document = types.Document( content=text, type=enums.Document.Ty...
b3b784fa777146f7f1a361784f848b28651676a4
3,653,975
def process_actions(list_response_json, headers, url, force_reset): """ If a policy does not exist on a given cluster find the right values defined in qos_dict and apply them """ qos_dict = {} # This dictionary sets the tiers and min/max/burst settings qos_dict['tiers'] = {"bronze": [500, 50...
1c3651518c8c0f0f174876afdd0961099b3af342
3,653,976
def validate_ac_power(observation, values): """ Run a number of validation checks on a daily timeseries of AC power. Parameters ---------- observation : solarforecastarbiter.datamodel.Observation Observation object that the data is associated with values : pandas.Series Series of ...
fcc487f61276e319316df3f99559ef935a7f0e7b
3,653,977
import itertools import six def partition(predicate, iterable): """Use `predicate` to partition entries into falsy and truthy ones. Recipe taken from the official documentation. https://docs.python.org/3/library/itertools.html#itertools-recipes """ t1, t2 = itertools.tee(iterable) return ( ...
5777203d9d34a9ffddc565129d8dda3ec91efc8e
3,653,978
def _download(url: str) -> bytes: """Download something from osu!web at `url`, returning the file contents.""" with _login() as sess: resp = sess.get(f"{url}/download", headers={"Referer": url}) if not resp.ok: raise ReplyWith("Sorry, a download failed.") return resp.content
1f7fc60299f066d12438042f43da6b74d1ac0348
3,653,979
def get_node(obj, path): """Retrieve a deep object based on a path. Return either a Wrapped instance if the deep object is not a node, or another type of object.""" subobj = obj indices = [] for item in path: try: subobj = subobj[item] except Exception as e: indic...
f48cb0dc5ae149d0758348725ebc521e7838230f
3,653,980
def without_bond_orders(gra): """ resonance graph with maximum spin (i.e. no pi bonds) """ bnd_keys = list(bond_keys(gra)) # don't set dummy bonds to one! bnd_ord_dct = bond_orders(gra) bnd_vals = [1 if v != 0 else 0 for v in map(bnd_ord_dct.__getitem__, bnd_keys)] bnd_ord_dc...
88b785c802a1d74a12f64a1eab6403429fa00cad
3,653,981
def check_struc(d1, d2, errors=[], level='wf'): """Recursively check struct of dictionary 2 to that of dict 1 Arguments --------- d1 : dict Dictionary with desired structure d2 : dict Dictionary with structre to check errors : list of str, optional Missin...
aa835e7bbd6274e73d0b3d45d1ec4d617af0a167
3,653,982
def indexoflines(LFtop): """ Determining selected line index of Gromacs compatible topology files """ file1 = open(LFtop, "r") readline = file1.readlines() lineindex = ["x", "x", "x"] n = 0 for line in readline: linelist = line.split() if "atomtypes" in linelist: lineindex[0] = n n += 1 elif "molecule...
dd2653c6245d9f7a0fa8647dcc841c51e01f9b2d
3,653,983
def create_mock_github(user='octo-cat', private=False): """Factory for mock GitHub objects. Example: :: >>> github = create_mock_github(user='octocat') >>> github.branches(user='octocat', repo='hello-world') >>> [{u'commit': {u'sha': u'e22d92d5d90bb8f9695e9a5e2e2311a5c1997230', ...
7eaffcc7bc22657eaf3c3e7d41d9492300128a73
3,653,984
import argparse from datetime import datetime from typing import OrderedDict def get_args_string(args: argparse.Namespace) -> str: """ Creates a string summarising the argparse arguments. :param args: parser.parse_args() :return: String of the arguments of the argparse namespace. """ string =...
f1f4de0821d04a21df046bc0dc526b2f9f1135f6
3,653,985
def top_9(limit=21): """Vrni dano število knjig (privzeto 9). Rezultat je seznam, katerega elementi so oblike [knjiga_id, avtor,naslov,slika] """ cur.execute( """SELECT book_id, authors, title, original_publication_year, average_rating,image_url FROM books ORDER BY average_rating DE...
ec87714ea5925c5d4115b0ee091597f7ffb1c323
3,653,986
import torch def spm_dot_torch(X, x, dims_to_omit=None): """ Dot product of a multidimensional array with `x` -- Pytorch version, using Tensor instances @TODO: Instead of a separate function, this should be integrated with spm_dot so that it can either take torch.Tensors or nd.arrays The dimensions in `d...
2dad76db822c24dc740e17b034d74644d0c91e19
3,653,987
def inverseTranslateTaps(lowerTaps, pos): """Method to translate tap integer in range [-lower_taps, raise_taps] to range [0, lowerTaps + raiseTaps] """ # Hmmm... is it this simle? posOut = pos + lowerTaps return posOut
827bdfc51b3581b7b893ff8ff02dd5846ff6cd0f
3,653,988
def GMLstring2points(pointstring): """Convert list of points in string to a list of points. Works for 3D points.""" listPoints = [] #-- List of coordinates coords = pointstring.split() #-- Store the coordinate tuple assert(len(coords) % 3 == 0) for i in range(0, len(coords), 3): list...
e755d344d163bdcdb114d0c9d614a1bbd40be29f
3,653,989
def set_(key, value, service=None, profile=None): # pylint: disable=W0613 """ Set a key/value pair in the etcd service """ client = _get_conn(profile) client.set(key, value) return get(key, service, profile)
c9689c53dc837caf182ac0b5d0e8552888ec70e9
3,653,990
def compute_cw_score_normalized(p, q, edgedict, ndict, params = None): """ Computes the common weighted normalized score between p and q @param p -> A node of the graph @param q -> Another node in the graph @param edgedict -> A dictionary with key `(p, q)` and value `w`. @param ndi...
7769bc21d6a6bf176002ea6f4020cbe78f971b84
3,653,991
def prompt_user_friendly_choice_list(msg, a_list, default=1, help_string=None): """Prompt user to select from a list of possible choices. :param msg:A message displayed to the user before the choice list :type msg: str :param a_list:The list of choices (list of strings or list of dicts with 'name' & 'de...
d2c81b8af3f2de3203dd8cfd11372909e2e9cbe3
3,653,992
import typing import json def fuse(search: typing.Dict, filepath: str): """Build a JSON doc of your pages""" with open(filepath, "w") as jsonfile: return json.dump( [x for x in _build_index(search, id_field="id")], fp=jsonfile, )
542aff31a2861bc8de8a25025582305db0ce2af1
3,653,993
def aggregate_gradients_using_copy_with_device_selection( tower_grads, avail_devices, use_mean=True, check_inf_nan=False): """Aggregate gradients, controlling device for the aggregation. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over towers. The inner li...
24d12a4e3ee63b96dd453bc901a9180ed956003b
3,653,994
def ToOrdinal(value): """ Convert a numerical value into an ordinal number. @param value: the number to be converted """ if value % 100//10 != 1: if value % 10 == 1: ordval = '{}st'.format(value) elif value % 10 == 2: ordval = '{}nd'.format(value) elif...
774bac5fd22714ba3eb4c9dd2b16f4236e2f5e8c
3,653,995
from typing import List def compute_partition(num_list: List[int]): """Compute paritions that add up.""" solutions = [] for bits in helper.bitprod(len(num_list)): iset = [] oset = [] for idx, val in enumerate(bits): (iset.append(num_list[idx]) if val == 0 else ...
408f5f85b1648facdcebfd47f96f53221b54888e
3,653,996
def renumber(conllusent): """Fix non-contiguous IDs because of multiword tokens or removed tokens""" mapping = {line[ID]: n for n, line in enumerate(conllusent, 1)} mapping[0] = 0 for line in conllusent: line[ID] = mapping[line[ID]] line[HEAD] = mapping[line[HEAD]] return conllusent
30f336cd63e7aff9652e6e3d1a35a21dc3379c99
3,653,997
def recall_at(target, scores, k): """Calculation for recall at k.""" if target in scores[:k]: return 1.0 else: return 0.0
0c3f70be3fb4cfde16d5e39b256e565f180d1655
3,653,998
def supports_dynamic_state() -> bool: """Checks if the state can be displayed with widgets. :return: True if widgets available. False otherwise. """ return widgets is not None
bee2f32bb315f086b6bd8b75535eb8fdde36a188
3,653,999