content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def Get_Histogram_key(qubitOperator): """ Function to obtain histogram key string for Cirq Simulator. e.g. PauliWord = QubitOperator('X0 Z2 Y3', 0.5j) returning: histogram_string = '0,2,3' Args: qubitOperator (openfermion.ops._qubit_operator.QubitOperator): QubitOper...
f574f7b3f6c43de7b3121d4e49240a84a4bcfdfc
8,627
def get_organizations(): """ Queries API for a list of all basketball organizations registered with Basketbal Vlaanderen. :return: list of basketball organizations :rtype: [Organization] """ organizations = [] for organization_data in get_list(): organizations.append(Organizatio...
bcf29925465cde99399214cbe44648bbfd136e1b
8,628
def logout(): """Logout.""" logout_user() flash('您已成功登出', 'info') return redirect(url_for('public.home'))
e816d67e4084bad0549d0b932ec806de55cfc41d
8,629
def get_column_labels(): """ This function generates a list of column names for the extracted features that are returned by the get_features function. """ # list the names of the extracted features feature_labels = ["amplitude_envelope", "root_mean_square_energy", ...
c140ced9c4344bd7a4029d331d50ebe0750fac0a
8,630
def corr_finder(X, threshold): """ For each variable, find the independent variables that are equal to or more highly correlated than the threshold with the curraent variable Parameters ---------- X : pandas Dataframe Contains only independent variables and desired index threshold:...
3b32a3eacb721ff09f6b5614c0ada82df814d5fa
8,631
def magic_file(filename): """ Returns tuple of (num_of_matches, array_of_matches) arranged highest confidence match first. :param filename: path to file :return: list of possible matches, highest confidence first """ head, foot = _file_details(filename) if not head: raise ValueError...
3fc625006c5589b14c73fff501d48a523d1bce5b
8,632
def plot_sentiment( df: pd.DataFrame, title: str = None, height: int = 300, label_col: str = "label" ) -> Figure: """ Plot the predicted sentiment of the sentences. Args: df (pd.DataFrame): Dataframe with the outputs of a sentiment analysis model. title (str): Ti...
bf5f7f65fa4cbee6b0abfc77d1f47b6f175ed8f9
8,633
def subf(pattern, format, string, count=0, flags=0): # noqa A002 """Apply `sub` with format style replace.""" is_replace = _is_replace(format) is_string = isinstance(format, (_util.string_type, _util.binary_type)) if is_replace and not format.use_format: raise ValueError("Compiled replace is n...
7ef105eeafb5ab4e6c3405206d850520d3489314
8,634
def independent_connections(fn): """Target must support simultaneous, independent database connections.""" # This is also true of some configurations of UnixODBC and probably win32 # ODBC as well. return _chain_decorators_on( fn, no_support('sqlite', 'Independent connections disabled wh...
cf11838e5b32cc2a6c165fda38baf4d680beda4a
8,635
def Route(template, handler): """Make a Route whose placeholders accept only allowable map IDs or labels.""" return webapp2.Route(template.replace('>', r':[\w-]+>'), handler)
2ec563ed4db815ee98d050e8e9a672a7a53ca010
8,636
def values_iterator(dictionary): """Add support for python2 or 3 dictionary iterators.""" try: v = dictionary.itervalues() # python 2 except: v = dictionary.values() # python 3 return v
e4fef48fd1b2a9189d81465fec259efe102c5b75
8,637
def _standardize_bicluster(bicluster): """Standardize a bicluster by subtracting the mean and dividing by standard deviation. Ref.: Pontes, B., Girldez, R., & Aguilar-Ruiz, J. S. (2015). Quality measures for gene expression biclusters. PloS one, 10(3), e0115497. Note that UniBic synthetic data ...
371adc72f64bec4039e0fab65e8acb77e37063d8
8,638
def get_deployment_polarion_id(): """ Determine the polarion_id of the deployment or upgrade Returns: str: polarion_id of the deployment or upgrade """ polarion_config = config.REPORTING.get('polarion') if polarion_config: if config.UPGRADE.get('upgrade'): if config...
475689b0adac68fdaf60d77af88f5b6c3e229003
8,639
import io import traceback def mail_on_fail(func: callable): """Send an email when something fails. Use this as a decorator.""" @wraps(func) def _wrap(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: # Handle recursive error handling. ...
6672ec78551f26e875002b24ef21f331ab171540
8,641
def base_conv(num, base): """Write a Python program to converting an Integer to a string in any base""" _list = [] if num//base == 0: return str(num%base) else: return (base_conv(num//base, base) + str(num%base))
9fcc28ccfe8ba80d974cc4012aad456bfb8c9544
8,642
def handle_log(request): """ Handle streaming logs to a client """ params = request.match_info log_dir = py.path.local('data').join( params['project_slug'], params['job_slug'], ) # Handle .log ext for DockCI legacy data log_path_bare = log_dir.join(params['stage_slug']) log...
4d5b4bd14ff759cd62b72224c0a2d1c99b7dc786
8,643
def get_scheme(patterns, config): """Returns the encoding scheme specified by the given config object Args: patterns (list(list)): List of input patterns config (dict): The config object """ assert(type(patterns) == list and len(patterns) > 0) assert(type(config) == dict) min_ma...
de9cc88bed0446854903832fb7bc64c24cc37144
8,644
def open_signatures_window(*args): """ open_signatures_window() -> TWidget * Open the signatures window ( 'ui_open_builtin' ). @return: pointer to resulting window """ return _ida_kernwin.open_signatures_window(*args)
e699df0192755b28d3c1c324c485ca4486cab98e
8,645
def get_subscription_id(_ctx=ctx): """ Gets the subscription ID from either the node or the provider context """ return get_credentials(_ctx=_ctx).subscription_id
23af53f6f807e14ad629e60ea79e21e8ed3eeef5
8,646
def origin_trial_function_call(feature_name, execution_context=None): """Returns a function call to determine if an origin trial is enabled.""" return 'RuntimeEnabledFeatures::{feature_name}Enabled({context})'.format( feature_name=feature_name, context=execution_context if execution_cont...
201dbe8449373dbad0144633350d3e6adbb58b80
8,647
def get_bit(byteval, index) -> bool: """retrieve bit value from byte at provided index""" return (byteval & (1 << index)) != 0
1fe020449ae2ae2513073835db6f75b24e558fdb
8,648
def upsert_target(data, analyst): """ Add/update target information. :param data: The target information. :type data: dict :param analyst: The user adding the target. :type analyst: str :returns: dict with keys "success" (boolean) and "message" (str) """ if 'email_address' not in d...
4baa064c52bbeacdc18323196c1762cabd9607aa
8,649
import torch def batch_data(data, batch_size): """ data is a dict := {'x': [numpy array], 'y': [numpy array]} (on one client) returns x, y, which are both numpy array of length: batch_size """ data_x = data["x"] data_y = data["y"] # randomly shuffle data np.random.seed(100) rng_st...
58cfde03668dd61e23bdb8b96527ae17176c4872
8,650
def simplify_board_name(board_name: str) -> str: """Removes the following from board names: - `x86-`, e.g. `x86-mario` - `_he`, e.g. `x86-alex_he` - `&` - e.g. `falco & falco_II` - ',' - e.g. `hoho, but substitute a dp to vga chip` (why) Args: board_name: the board name to simplify ...
bd6a9756aa6e6725b9727825f52ba544e2e4a97d
8,652
def delete_news_site(user_id, news_name): """ Delete subscription to user list Params: - user_id: The user email - news_name: The name of news provider Return: void """ user_info = get_user_by_email(user_id) user_info = user_info.to_dict() list_news = user_info['news_sites'] ...
02f4ea485b2822c1a614e39dae3ef3aa924596b0
8,654
from datetime import datetime def get_time_str(dt: datetime.datetime = None, tz_default=LocalTimeZone): """ @param dt 为None时,返回当前时间 @param tz_default dt无时区信息时的默认时区 """ if not dt: dt = datetime.datetime.now() dt = convert_zone(dt, tz_default=tz_default) time_str = dt.isoformat().spl...
41f9f1465fe88e35450569995a14dfce6ebc9bc5
8,655
def plotLikesTablePair( likesTableFNs, plotFile, nonNormedStats = (), includeSpecialBins = True, getio = None ): """Visually plot a likes table. """ if getio: return dict( depends_on = likesTableFNs, creates ...
6671877a21749747ce45a020d7a87eec86280d8c
8,656
def del_api_msg(): """ @api {post} /v1/interfaceapimsg/del InterfaceApiImsg_删除接口信息 @apiName interfaceApiImsgDel @apiGroup Interface @apiDescription 删除接口信息 @apiParam {int} apiMsgId 接口信息id @apiParamExample {json} Request-Example: { "apiMsgId": 1, } @apiSuccessExample {json}...
fabd5a2fc257219e2568991f9520587d4053c909
8,658
def find_nearest(array, value): """ Find nearest value of interest in array (used for frequencies, no double value issues) Parameters ---------- array: array Give the array in which you want to find index of value nearest-by value: int or float The value of interest Return ...
e96a87b5b857a8cafbc0c6371b395040dde48e8d
8,659
def get_book(isbn): """ Retrieve a specific book record by it's ISBN --------------------------------------------- Endpoints: GET /books/isbn GET /books/isbn?act=(borrow|handback) @QueryParams: act: (optional) specific action on book Possible values: borrow, handback ...
fd1471234f6c73062569fea0ae489da3dc9af8ac
8,661
def toint16(i): """ Convert a number to a hexadecimal string of length 2 """ return f'{i:02x}'
3effd2b3f011a962beac19682ad29e930eb0f057
8,662
def is_phone(text): """ 验证字符串是否是固定电话 :param text: 需要检查的字符串 :return: 符合返回True,不符合返回False """ return check_string(text, '\(?0\d{2,3}[) -]?\d{7,8}$')
a90e8d28737b94f02381ed6e959e0a155628eaae
8,663
def get_loc(frameInfo, bbox_type): """Return GeoJSON bbox.""" bbox = np.array(frameInfo.getBBox()).astype(np.float) print("get_loc bbox: %s" %bbox) if bbox_type == "refbbox": bbox = np.array(frameInfo.getReferenceBBox()).astype(np.float) coords = [ [ bbox[0,1], bbox[0,0] ], ...
a95a9eb6ae9e33b5d69451fb1b34e19c7b0be8d3
8,664
def load_df(input_path, fname, ext): """Read chain as Pandas DataFrame""" fname = os.path.join(input_path, fname + ext) print 'loading %s' % fname assert(os.path.isabs(fname)) X = pd.DataFrame.from_csv(fname) return X
be4c0d82bdb8881d3ad555b215469df7e8daaefe
8,665
from typing import Set def _load_order_component(comp_name: str, load_order: OrderedSet, loading: Set) -> OrderedSet: """Recursive function to get load order of components. Async friendly. """ component = get_component(comp_name) # If None it does not exist, error alrea...
c9d2adc8dbcf392e3d904b1e5f9d47f623e5646e
8,666
def clean_english_str_tf(input_str): """Clean English string with tensorflow oprations.""" # pylint: disable=anomalous-backslash-in-string string = tf.regex_replace(input_str, r"[^A-Za-z0-9(),!?\'\`<>/]", " ") string = tf.regex_replace(string, "\'s", " \'s") string = tf.regex_replace(string, "\'ve", " \'ve") ...
6439f708dea8566d5706968811aed7478b1c107c
8,667
def _square_eqt(x, y, x0, y0, angle): """simple equation for a square. this returns: max(np.dstack([abs(x0 - x), abs(y0 -y)]), 2). this should then be compared to the "radius" of the square (half the width) the equation comes from this post: http://polymathprogrammer.com/2010/03/01/answered-can-yo...
4000bf329399dfc8b842c2a496cdea193dd47fc6
8,668
def multinomial(x, num_samples=1, replacement=False, name=None): """ This OP returns a Tensor filled with random values sampled from a Multinomical distribution. The input ``x`` is a tensor with probabilities for generating the random number. Each element in ``x`` should be larger or equal to 0, but not...
6412cf815aaf8b9175946c501beacb716deb0c5c
8,669
def run_experiment( max_epochs, log=None, evaluate=True, projection=True, save_directory=".", save_file=None, save_interval=1, **configuration, ): """Runs the Proof of Constraint experiment with the given configuration :param max_epochs: number of epochs to run the experiment ...
7ebfc72dc3ebe7047e708ffa0903f24de67d8134
8,670
from typing import List from typing import Callable def compose_decorators(decorators: List[Callable]) -> Callable: """Compose multiple decorators into one. Helper function for combining multiple instrumentation decorators into one. :param list(Callable) decorators: A list of instrumentation decorators ...
14d8ecbf5af598419906ba9776bb40be6271279f
8,671
import torch def xyz_to_polar(sphere_points): """ (B,3,N) -> theta, phi (B,2,N), r (B) x = r*cos(theta)*sin(phi) y = r*sin(theta)*sin(phi) z = r*cos(phi) """ r = torch.sqrt(torch.sum(sphere_points*sphere_points, dim=1)) theta = torch.atan2(sphere_points[:,1,:], sphere_points[:,0,:]) ...
3332240df5230d801800ab3601873d26872326fc
8,672
def get_cpu_cores(): """获取每个cpu核的信息 Returns: 统计成功返回是一个元组: 第一个元素是一个列表存放每个cpu核的信息 第二个元素是列表长度, 也就是计算机中cpu核心的总个数 若统计出来为空, 则返回None """ cpu_cores = [] with open('/proc/cpuinfo') as f: for line in f: info = line.strip() if info.starts...
ad66faac3a956b1922173263415890bc543e0bba
8,673
from typing import Union from typing import Tuple def itk_resample(image: sitk.Image, spacing: Union[float, Tuple[float, float, float]], *, interpolation: str = "nearest", pad_value: int) -> sitk.Image: """ resample sitk image given spacing, pad value and interpolation. Args: ima...
37636c42e3f28c09dc0d3ef511c483eec0d3b3e2
8,674
def gen_anchor_targets( anchors, image, bboxes, labels, num_classes, negative_overlap=0.4, positive_overlap=0.5 ): """ Generate anchor targets for bbox detection. @author: Eli This is a version of anchor_targets_bbox that takes tensors for images, bboxes, and labels to play...
6ac0b5602a6d3aa2d1905da09f457ca44193b02c
8,675
def parameters_to_weights(parameters: Parameters) -> Weights: """Convert parameters object to NumPy weights.""" return [bytes_to_ndarray(tensor) for tensor in parameters.tensors]
e235fee46ad9ffcc31eea86f2491a9ac305d3ac5
8,676
from multiprocessing import Pool def get_iou(data_list, class_num, save_path=None): """ Args: data_list: a list, its elements [gt, output] class_num: the number of label """ ConfM = ConfusionMatrix(class_num) f = ConfM.generateM pool = Pool() m_list = pool.map(f, data_list) ...
cce5b270a34700eed592e9a47d0c56a8b43027ff
8,677
def bridge_forward_delay(brname): """Read a bridge device's forward delay timer. :returns ``int``: Bridge forward delay timer. :raises: OSError, IOError (ENOENT) if the device doesn't exist. """ return int(_get_dev_attr(brname, 'bridge/forward_delay'))
ba164ba85f1e1e3c5f82e28f38413cb8ca9e5090
8,679
def RF(X, y, X_ind, y_ind, is_reg=False): """Cross Validation and independent set test for Random Forest model Arguments: X (ndarray): Feature data of training and validation set for cross-validation. m X n matrix, m is the No. of samples, n is the No. of fetures y (ndarray...
c8ab9aa7cf6bbe159be172cdea82bc970b896914
8,680
import struct def keystring2list(s): """convert a string of keys to a list of keys.""" if len(s) == 0: return [] keys = [] i = 0 while i < len(s): keylength = struct.unpack(data.MESSAGE_KEY_LENGTH_FORMAT, s[i:i + data.MESSAGE_KEY_LENGTH_SIZE])[0] i += data.MESSAGE_KEY_LENGT...
b580d4062be1f5e99f5264aeb5c0a7e4cb70bbd2
8,681
def binary_fmt(num, suffix='B'): """A binary pretty-printer.""" if num == 0.0: return '0 %s' % suffix for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return '%.3g %s%s' % (num, unit, suffix) num /= 1024.0 return '%.3g %s%s' % (num, 'Yi', suffix)
70ae3ee429dd80e8d9cb3a1a3c6eeba09f7ea77a
8,682
def transformMatrices( translation = (0,0,0), center = (0,0,0), rotation = (0,1,0,0), scale = (1,1,1), scaleOrientation = (0,1,0,0), parentMatrix = None, ): """Calculate both forward and backward matrices for these parameters""" T,T1 = transMatrix( translatio...
0d1ae564b0e27000ce1c8d0a3e5aa04ec02fa19f
8,683
async def get_region(country=None, id=None): """ `linode_region` provides details about a specific Linode region. """ __args__ = dict() __args__['country'] = country __args__['id'] = id __ret__ = await pulumi.runtime.invoke('linode:index/getRegion:getRegion', __args__) return GetRegion...
09bd2e83496b6a38d477a24e3bc70a72a8bea8a7
8,684
def entry_type(entry, default): """Return the type of and entry""" if entry.attribute is None: return default return entry.attribute.get('entry_type', default)
04825e225e86bbb98808d0d18633032c022e4870
8,685
def build_expression(backend, arrays, expr): """Build an expression, based on ``expr`` and initial arrays ``arrays``, that evaluates using backend ``backend``. """ return CONVERT_BACKENDS[backend](arrays, expr)
da10481741b2dae18e47a7b203dc548cc6d78a0e
8,686
from mlalchemy.parser import parse_query as mlalchemy_parse_query from typing import OrderedDict def parse_query(qd, session, config): """Parses the given query dictionary to produce a BaseQuery object.""" defaults = { "limit": config["default_limit"], "backref_limit": config["default_backref...
17001d60365451375939fd902a6720b4d5889a7c
8,688
from typing import Dict def get_covid19_us_bears( url_root=CSV_URL_ROOT, file_prefix=CSV_FILE_PREFIX, file_suffix=CSV_FILE_SUFFIX, encoding=CSV_ENCODING) -> Dict[Dict[Bears]]: """Converts USAFACTS confirmed and deaths CSV files to state and county `Bears` to a dictionary of dictionaries. Args: ...
2cdc1b3112cde9d589388666484cf17a0f6055af
8,689
from typing import Optional from typing import Union from typing import Tuple import json def jsonify_promise( future_obj: Input[Jsonable], indent: Input[Optional[Union[int, str]]]=None, separators: Input[Optional[Tuple[str, str]]]=None ) -> Output[str]: """Convert a Promise object to a Promis...
bc0769d6897c771c4a04b76ace11b90c13bde844
8,690
def randnums(start, stop, n_samples): """ Helper function to select real samples and generate fake samples """ ix = [] for i in range(n_samples): ix.append(randint(start, stop)) ix = np.array(ix) return ix
da2e06527e56e9a971a904fee176428bef2b536a
8,691
def shift_1_spectra(spectra, shift): """ This method find the relative position of the FFT of the two spectras \ in order to later k-linearize. Args: :param spectra1: OCT spectra of first mirror. :type spectra1: list Return: :rname: Zspace: - pi to pi linear vector space ...
b76616a064da9eefb9199088ffba50950c9f160a
8,692
import pandas import types def hpat_pandas_series_div(self, other, level=None, fill_value=None, axis=0): """ Pandas Series method :meth:`pandas.Series.div` and :meth:`pandas.Series.truediv` implementation. .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_serie...
25fdfed169738ee0a7d1faabba7b52217736cbe9
8,693
def alias(self, arg): """ set the new alias to magic *alias alias1 string* alias1 is added into magic command """ if arg == '' or arg.lower() == 'help': return dbhelp(self, 'alias') name, fstring = arg.split(" ", 1) print "new alias: %s <%s>" % (DBPRINT.msg_green(name), fstring) ...
aaf4c3d72b740888b2282258b6138c80827e8665
8,694
def _transform_cat_options(metadata: dict) -> pd.DataFrame: """Transform category options metadata into a formatted DataFrame.""" df = pd.DataFrame.from_dict(metadata.get("categoryOptions")) df = df[["id", "code", "shortName", "name"]] df.columns = ["co_uid", "co_code", "co_shortname", "co_name"] re...
b1e9ac9ac578c8c0253ee7a0ece58a090d134385
8,695
def idaview(request, idadb, idadf): """ IdaDataFrame fixture to be used for the whole testing session. Open a view based on idadf fixture. """ def fin(): try: idadb.drop_view("TEST_VIEW_ibmdbpy") idadb.commit() except: pass request.addfinalizer...
6540f4e844b8709b4b8338b15aa913e3ed67d4da
8,696
def heuristical_lengths(items): """ heuristical_lengths tries to deriver the lengths of the content of items. It always returns a list. a) If typeof(items) is a string, it'll return [len(items)] b) If typeof(items) is a dict, it'll return [len(items)] c) If typeof(items) is either list or tuple,...
94a0759bcdc2e57431e8524f164a51f2091b6e61
8,698
def next(space, w_arr): """ Advance the internal array pointer of an array """ length = w_arr.arraylen() current_idx = w_arr.current_idx + 1 if current_idx >= length: w_arr.current_idx = length return space.w_False w_arr.current_idx = current_idx return w_arr._current(space)
668fec305ed6bbe05895f317e284c7d2e4f83189
8,700
def geocoordinatess_id_get(id, username=None): # noqa: E501 """Get a single GeoCoordinates by its id Gets the details of a given GeoCoordinates (more information in https://w3id.org/okn/o/sdm#GeoCoordinates) # noqa: E501 :param id: The ID of the GeoCoordinates to be retrieved :type id: str :param...
3ac772eab95915ac0030187f22da74f9965f6dfc
8,701
def check_callable(target, label=None): """Checks target is callable and then returns it.""" if not callable(target): raise TypeError('Expected {} callable, found non-callable {}.'.format( '{} to be'.format(label) if label is not None else 'a', type_string(type(target)))) return target
a22006b72e04adb47eeef0ee418301cecdbfde0b
8,702
import re def convert_dictionary_values(d, map={}): """convert string values in a dictionary to numeric types. Arguments d : dict The dictionary to convert map : dict If map contains 'default', a default conversion is enforced. For example, to force int for every column but colum...
4ecbd8ddd53324c3a83ce6b5bbe3ef0e5a86bc1e
8,703
def GetLimitPB(user, action_type): """Return the apporiate action limit PB part of the given User PB.""" if action_type == PROJECT_CREATION: if not user.project_creation_limit: user.project_creation_limit = user_pb2.ActionLimit() return user.project_creation_limit elif action_type == ISSUE_COMMENT: ...
91f9289d3be149112d08409b1cf1e2c8e68a9668
8,704
def best_int_dtype(data): """get bit depth required to best represent float data as int""" d, r = divmod(np.log2(data.ptp()), 8) d = max(d, 1) i = (2 ** (int(np.log2(d)) + bool(r))) return np.dtype('i%d' % i)
c8d54b10ba67a83250312668f7cd09b99e47bf56
8,705
def gen_decorate_name(*args): """ gen_decorate_name(name, mangle, cc, type) -> bool Generic function for 'decorate_name()' (may be used in IDP modules) @param name (C++: const char *) @param mangle (C++: bool) @param cc (C++: cm_t) @param type (C++: const tinfo_t *) """ return _ida_typeinf.g...
963f6bfc5ca30a7552f881d8c9f030c0c1653fce
8,706
def main(self, count=10): """ kosmos -p 'j.servers.myjobs.test("start")' """ self.reset() def wait_1sec(): gevent.sleep(1) return "OK" ids = [] for x in range(count): job_sch = self.schedule(wait_1sec) ids.append(job_sch.id) self._workers_gipc_nr_max =...
0634f76d33d6b32150f367d6c598f5c520991ef3
8,707
import requests def get_asc() -> pd.DataFrame: """Get Yahoo Finance small cap stocks with earnings growth rates better than 25%. [Source: Yahoo Finance] Returns ------- pd.DataFrame Most aggressive small cap stocks """ url = "https://finance.yahoo.com/screener/predefined/aggressive_sm...
7d7d9810782950434a0752c97984f20df74a3366
8,708
def getEnabled(chat_id): """Gets the status of a conversation""" status = EnableStatus.get_by_id(str(chat_id)) if status: return status.enabled return False
24d7ca4f197f6e4dc4c9c54e59824ff4fc89114e
8,709
def create_app(config=DevelopConfig): """App factory.""" app = Flask( __name__.split('.')[0], static_url_path='/static', static_folder=f'{config.PROJECT_PATH}/src/static' ) app.url_map.strict_slashes = False app.config.from_object(config) register_extensions(app) regi...
0154d3ebb00ae869c2f1bb2a2392e2bde74e36b4
8,710
def merge_inputs_for_create(task_create_func): """Merge all inputs for start operation into one dict""" # Needed to wrap the wrapper because I was seeing issues with # "RuntimeError: No context set in current execution thread" def wrapper(**kwargs): # NOTE: ctx.node.properties is an ImmutablePr...
119ab1b40ba84959b960295b35e668de7296929f
8,711
def embedding_lookup(params, ids): """Wrapper around ``tf.nn.embedding_lookup``. This converts gradients of the embedding variable to tensors which allows to use of optimizers that don't support sparse gradients (e.g. Adafactor). Args: params: The embedding tensor. ids: The ids to lookup in :obj:`para...
774595aaf119ab93928095f397bc4ff7f5ebad53
8,712
from re import T def value_as_unit(value: T | None, unit: Unit = None) -> T | Quantity[T] | None: """Return value as specified unit or sensor fault if value is none.""" if value is None: return None if unit is None: return value return value * unit
3f96d837a40894d589fbae3f40ca6adf220a9d56
8,713
import numpy def get_static_spatial_noise_image(image) : """ The first step is to sum all of the odd-numbered images (sumODD image) and separately sum all of the even-numbered images (sumEVEN image). The difference between the sum of the odd images and the sum of the even images (DIFF = su...
511275fefc2368c6d3976ea420e11fcf1a913f8c
8,714
def get_movie_title(movie_id): """ Takes in an ID, returns a title """ movie_id = int(movie_id)-1 return items.iloc[movie_id]['TITLE']
e3e0694eb35923ce3a6f528a4b9ac622044b9159
8,717
import logging def get_logger(): """ Return a logger object """ logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) handler = logging.StreamHandler() handler.setLevel(logging.INFO) formatter = logging.Formatter("%(asctime)s - %(message)s") handler.setFormatter(form...
a23531364d947a83ace175ba02212ff57ba7e0ea
8,718
def enough_gap_since_last_obs(df, current_state, obs_log): """ Determine if a sufficient time has passed since the last observation in this subprogram (in any filter): """ now = current_state['current_time'].mjd # don't mess up with the upstream data structure df = df.copy() grp = df....
3a58a7d03074eec6458b4a10addc40953d01da8b
8,719
def find_nearest_feature_to_attribute(sentence, features, attribute): """ Parameters ---------- sentence: str, One sentence from the info text of a mushroom species features: list of strs List of possible features as in dataset_categories.features_list attribute: str, Mushroom featur...
6877ec945870cce9a0873a713830fa5f830408fc
8,720
from datetime import datetime def lists(): """ 库存列表 :return: """ template_name = 'inventory/lists.html' # 文档信息 document_info = DOCUMENT_INFO.copy() document_info['TITLE'] = _('inventory lists') # 搜索条件 form = InventorySearchForm(request.form) form.warehouse_id.choices = get...
25c561167cc34eba5bd8bf8123007961d28165e3
8,721
def open_1d_txt(filename, xaxcol=0, datacol=1, errorcol=2, text_reader='simple', format=None, **kwargs): """ Attempt to read a 1D spectrum from a text file assuming wavelength as the first column, data as the second, and (optionally) error as the third. Reading can be done either with a...
133361ba2ba75a1f13f8768c6130601db3d870ec
8,722
def clean_record(raw_string: str) -> str: """ Removes all unnecessary signs from a raw_string and returns it :param raw_string: folder or file name to manage :return: clean value """ for sign in ("'", '(', ')', '"'): raw_string = raw_string.replace(sign, '') return raw_string.replace...
ea484934dc10da879ede883287fc1d650cda74b8
8,723
import pandas as pd import numpy as np def df_of_tables_for_dd_ids(dd_ids, sqlite_tables, sql_con): """ :param list dd_ids: list of Deep Dive IDs to retrieve :param list sqlite_tables: list of SQLite tables to join :param sqlalchemy.create_engine sql_con: Connection to SQLite (can be \ omitted) ...
282d3e9bda8e38687660c21323f8bb3ea40abbd2
8,724
from typing import Union def get_group_type(group: Union[hou.EdgeGroup, hou.PointGroup, hou.PrimGroup]) -> int: """Get an HDK compatible group type value. :param group: The group to get the group type for. :return: An HDK group type value. """ try: return _GROUP_TYPE_MAP[type(group)] ...
e8b708911760c99c6e3c23d39b4fc4d205380bac
8,725
def mp2d_driver(jobrec, verbose=1): """Drive the jobrec@i (input) -> mp2drec@i -> mp2drec@io -> jobrec@io (returned) process.""" return module_driver( jobrec=jobrec, module_label='mp2d', plant=mp2d_plant, harvest=mp2d_harvest, verbose=verbose)
efa3cf31714719f87c239dbd6cdd1aad80982647
8,726
def query_user_list(): """ Retrieve list of users on user watch list. """ conn = connect.connect() cur = conn.cursor() cur.execute("SELECT * FROM watched_users") watched_users = cur.fetchall() return watched_users
2de40bc963503e4c87d7bc15409bf4803c5c87a6
8,727
def service_stop_list(service_id, direction): """ Queries all patterns for a service and creates list of stops sorted topologically. :param service_id: Service ID. :param direction: Groups journey patterns by direction - False for outbound and True for inbound. """ graph, di...
c2eaf08853469597a83647a3e1ec5fc6a7b02ced
8,728
def convert_coord(value): """将GPS值转换为度分秒形式 Args: value(str): GPS读取的经度或纬度 Returns: list: 度分秒列表 """ v1, v2 = value.split('.') v2_dec = Decimal(f'0.{v2}') * 60 # + Decimal(random.random()) return [v1[:-2], v1[-2:], v2_dec.to_eng_string()]
4269e9d9b58e3d7ce42c82cd0299abac6c740499
8,729
import torch def _interpolate_zbuf( pix_to_face: torch.Tensor, barycentric_coords: torch.Tensor, meshes ) -> torch.Tensor: """ A helper function to calculate the z buffer for each pixel in the rasterized output. Args: pix_to_face: LongTensor of shape (N, H, W, K) specifying the indices ...
b54d6c44fd23f842b13cb7ac1984f77c7a6a31a4
8,730
from typing import Sequence def pp_chain(chain: Sequence[Subtree]) -> str: """Pretty-print a chain """ return ' '.join( s.label if isinstance(s, ParentedTree) else str(s) for s in chain )
372488b64c86c2af459d67e5ddde0a77fa26fb5c
8,731
def ptr_ty(ty : 'LLVMType') -> 'LLVMPointerType': """``ty*``, i.e. a pointer to a value of type ``ty``.""" return LLVMPointerType(ty)
79c7d304c4cd20937abe982311b2ff6ff17a01f9
8,732
def series_spline(self): """Fill NaNs using a spline interpolation.""" inds, values = np.arange(len(self)), self.values invalid = isnull(values) valid = -invalid firstIndex = valid.argmax() valid = valid[firstIndex:] invalid = invalid[firstIndex:] inds = inds[firstIndex:] result ...
1fbbf66efc7e6c73bdcc3c63aab83237e434aa79
8,733
def label(job_name, p5_connection=None): """ Syntax: Job <name> label Description: Returns the (human readable) job label. The following labels are returned: Archive, Backup, Synchronize and System. A Job label can be used in conjunction with the Job describe command to better display the jo...
ec58cbb085cb06f5ad8f2c2d04ee6cd9d3638984
8,734
import math def rating(pairing, previous): """The lower the rating value is the better""" current = set(chain.from_iterable(pair[1] for pair in pairing)) overlaps = current & set(previous) if overlaps: return sum(math.pow(0.97, previous[overlap] / 86400) for overlap in overlaps) return 0.0
af86bf1c1bbe036e20e3a1e7bcff0dec09d382cf
8,735
from typing import Optional from typing import Dict def copy_multipart_passthrough(src_blob: AnyBlob, dst_blob: CloudBlob, compute_checksums: bool=False) -> Optional[Dict[str, str]]: """ Copy from `src_blob` to `dst_blob`, passing data through the ...
ba37598a55e00252f879e66c1438681f0033de34
8,736
import csv def read_manifest_from_csv(filename): """ Read the ballot manifest into a list in the format ['batch id : number of ballots'] from CSV file named filename """ manifest = [] with open(filename, newline='') as csvfile: reader = csv.reader(csvfile, delimiter = ",") for ...
b04b6a1b20512c27bb83a7631346bc6553fdc251
8,737