content
stringlengths
22
815k
id
int64
0
4.91M
def run_script(script_path, session, handle_command=None, handle_line=None): """ Run a script file using a valid sqlalchemy session. Based on https://bit.ly/2CToAhY. See also sqlalchemy transaction control: https://bit.ly/2yKso0A :param script_path: The path where the script is located :param sess...
5,343,000
def create_overide_pandas_func( cls, func, verbose, silent, full_signature, copy_ok, calculate_memory ): """ Create overridden pandas method dynamically with additional logging using DataFrameLogger Note: if we extracting _overide_pandas_method outside we need to implement decorator like here ...
5,343,001
def orthogonalize(U, eps=1e-15): """ Orthogonalizes the matrix U (d x n) using Gram-Schmidt Orthogonalization. If the columns of U are linearly dependent with rank(U) = r, the last n-r columns will be 0. Args: U (numpy.array): A d x n matrix with columns that need to be orthogonalized....
5,343,002
def undistort( cam_mat, dist_coeffs, images, res_dirpath): """Saves undistorted images with specified calibration parameters.""" # write the camera matrix imgSize = images[0].shape[:2] h, w = imgSize newcameramtx, roi = cv2.getOptimalNewCameraMatrix( ...
5,343,003
def get_files_under_dir(directory, ext='', case_sensitive=False): """ Perform recursive search in directory to match files with one of the extensions provided :param directory: path to directory you want to perform search in. :param ext: list of extensions of simple extension for files to match ...
5,343,004
def read_ftdc(fn, first_only = False): """ Read an ftdc file. fn may be either a single metrics file, or a directory containing a sequence of metrics files. """ # process dir if os.path.isdir(fn): for f in sorted(os.listdir(fn)): for chunk in read_ftdc(os.path.join(fn, f)):...
5,343,005
def boolean(func): """ Sets 'boolean' attribute (this attribute is used by list_display). """ func.boolean=True return func
5,343,006
def load_output_template_configs(items): """Return list of output template configs from *items*.""" templates = [] for item in items: template = OutputTemplateConfig( id=item["id"], pattern_path=item.get("pattern-path", ""), pattern_base=item.get("pattern-base", ...
5,343,007
def print_http_requests(pcap): """Print out information about each packet in a pcap Args: pcap: dpkt pcap reader object (dpkt.pcap.Reader) """ # For each packet in the pcap process the contents for timestamp, buf in pcap: # Unpack the Ethernet frame (mac src/dst, ethertype) ...
5,343,008
def read_keyword_arguments_section(docstring: Docstring, start_index: int) -> tuple[DocstringSection | None, int]: """ Parse a "Keyword Arguments" section. Arguments: docstring: The docstring to parse start_index: The line number to start at. Returns: A tuple containing a `Sect...
5,343,009
def iter_from_pbf_buffer(buff: IO[bytes]) -> Iterator[dict]: """Yields all items inside a given OSM PBF buffer. """ parser = ParserPbf(buff) yield from parser.parse()
5,343,010
def write_tables(output_dir): """ Write pipeline tables as csv files (in output directory) as specified by output_tables list in settings file. 'output_tables' can specify either a list of output tables to include or to skip if no output_tables list is specified, then no checkpointed tables will be...
5,343,011
def is_builtin(x, drop_callables=True): """Check if an object belongs to the Python standard library. Parameters ---------- drop_callables: bool If True, we won't consider callables (classes/functions) to be builtin. Classes have class `type` and functions have class `builtin_fu...
5,343,012
def random_pair_selection(config_path, data_size=100, save_log="random_sents"): """ randomly choose from parallel data, and save to the save_logs :param config_path: :param data_size: :param save_log: :return: random selected pairs """ ...
5,343,013
def test_deployable(): """ Check that 1) no untracked files are hanging out, 2) no staged but uncommitted updates are outstanding, 3) no unstaged, uncommitted changes are outstanding, 4) the most recent git tag matches HEAD, and 5) the most recent git tag matches the current version. """ pyt...
5,343,014
def profile_nominal(pairs, **options): """Return stats for the nominal field Arguments: :param pairs: list with pairs (row, value) :return: dictionary with stats """ result = OrderedDict() values = [r[1] for r in pairs] c = Counter(values) result['top'], result['freq'] = c.most_comm...
5,343,015
def class_definitions(cursor: Cursor) -> List[Cursor]: """ extracts all class definitions in the file pointed by cursor. (typical mocks.h) Args: cursor: cursor of parsing result of target source code by libclang Returns: a list of cursor, each pointing to a class definition. """ cursors = curs...
5,343,016
def visualize_dataset(dataset_directory=None, mesh_filename_path=None): """ This method loads the mesh file from dataset directory and helps us to visualize it Parameters: dataset_directory (str): root dataset directory mesh_filename_path (str): mesh file name to process Returns: ...
5,343,017
def service_list_by_category_view(request, category): """Shows services for a chosen category. If url doesn't link to existing category, return user to categories list""" template_name = 'services/service-list-by-category.html' if request.method == "POST": contact_form = ContactForm(request.POST...
5,343,018
def unmap_address(library, session): """Unmaps memory space previously mapped by map_address(). :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. """ library.viUnmapAddress(session)
5,343,019
def test_shorter_segments(): """shorter segments than chunks, no tolerance""" document = ("01234 "*4).split() segments = list(segment_fuzzy(document, segment_size=4)) assert segments == [[['0', '1', '2', '3']], [['4'], ['0', '1', '2']], [['3', '4'], ['0', ...
5,343,020
def check_columns(board: list): """ Check column-wise compliance of the board for uniqueness (buildings of unique height) and visibility (top-bottom and vice versa). Same as for horizontal cases, but aggregated in one function for vertical case, i.e. columns. >>> check_columns(['***21**', '412453*', '...
5,343,021
def get_git_tree(pkg, g, top_prd): """ :return: """ global pkg_tree global pkg_id global pkg_list global pkg_matrix pkg_tree = Tree() pkg_id = 0 pkg_list = dict() # pkg_list['root'] = [] if pkg == '': return None if pkg in Config.CACHED_GIT_REPOS: p...
5,343,022
def get_requests_session(): """Return an empty requests session, use the function to reuse HTTP connections""" session = requests.session() session.mount("http://", request_adapter) session.mount("https://", request_adapter) session.verify = bkauth_settings.REQUESTS_VERIFY session.cert = bkauth_...
5,343,023
def edit_role_description(rid, description, analyst): """ Edit the description of a role. :param rid: The ObjectId of the role to alter. :type rid: str :param description: The new description for the Role. :type description: str :param analyst: The user making the change. :type analyst:...
5,343,024
def test_incidents_info_md_with_invalid_keys(mocker): """ Given: - Incidents in campaign context contains some invalid keys (e.g. status), When: - Get value from incident (GetCampaignIncidentsInfo.get_incident_val) Then: - Validate invalid key not in the human readable "...
5,343,025
def have_questions(pair, config, info=None): """ Return True iff both images are annotated with questions. """ qas = info["qas"] c1id = pair[0] if qas[c1id]['qas'] == []: return False c2id = pair[1] if qas[c2id]['qas'] == []: return False return True
5,343,026
def free_strings( allocator, # type: Allocator ranges, # type: List[Tuple] data, # type: Union[bytes, bytearray, memoryview] ): """ Mark as free the space used by the strings delimited by `ranges`, also detect and mark as free zero padding (alignment) between strings. The `ranges` argume...
5,343,027
def get_dist_genomic(genomic_data,var_or_gene): """Get the distribution associated to genomic data for its characteristics Parameters: genomic_data (dict): with UDN ID as key and list with dictionaries as value, dict contaning characteristics of the considered genomic data ...
5,343,028
def get_gmb_dataset_train(max_sentence_len): """ Returns the train portion of the gmb data-set. See TRAIN_TEST_SPLIT param for split ratio. :param max_sentence_len: :return: """ tokenized_padded_tag2idx, tokenized_padded_sentences, sentences = get_gmb_dataset(max_sentence_len) return tokeniz...
5,343,029
def is_answer_reliable(location_id, land_usage, expansion): """ Before submitting to DB, we judge if an answer reliable and set the location done if: 1. The user passes the gold standard test 2. Another user passes the gold standard test, and submitted the same answer as it. Parameters --------...
5,343,030
def _polyfit_coeffs(spec,specerr,scatter,labelA,return_cov=False): """For a given scatter, return the best-fit coefficients""" Y= spec/(specerr**2.+scatter**2.) ATY= numpy.dot(labelA.T,Y) CiA= labelA*numpy.tile(1./(specerr**2.+scatter**2.),(labelA.shape[1],1)).T ATCiA= numpy.dot(labelA.T,CiA) AT...
5,343,031
async def test_device_security_gateway(): """Test device class on a security gateway.""" mock_requests = MagicMock(return_value=Future()) mock_requests.return_value.set_result("") devices = Devices([GATEWAY_USG3], mock_requests) assert len(devices.values()) == 1 gateway = devices[GATEWAY_USG3[...
5,343,032
def generate_diagram(acc, draw_fname): """ :param acc: acc :param draw_file_base: base of the diagram :return: None """ data = pd.DataFrame(acc, columns=['Property Concept', 'Metric', 'Value']) ax = sns.barplot(x="Value", y="Property Concept", hue="Metric", ...
5,343,033
def plot_electoral_position_based_summary_stats( data: Optional[pd.DataFrame] = None, ) -> None: """ Input data should be the "flattened" dataset. """ # Load default data if data is None: data = flatten_access_eval_2021_dataset() # Only work against the post data for summary stats a...
5,343,034
def update_player_shots(settings, game_stats, player, player_shots, shields, invaders, invader_shots): """Update position of player shots, explode shots that reach a certain height and then remove them.""" # Update shot position. player_shots.update() for shot in player_shots: # Color shots above certain positio...
5,343,035
def get_repo_dir(): """Get repository root directory""" root_dir = './' if os.path.isdir(Path(__file__).parent.parent / 'src'): root_dir = f"{str((Path(__file__).parent.parent).resolve())}/" elif os.path.isdir('../src'): root_dir = '../' elif os.path.isdir('./src'): root_dir ...
5,343,036
def colorize(data, colors, display_ranges): """Example: colors = 'white', (0, 1, 0), 'red', 'magenta', 'cyan' display_ranges = np.array([ [100, 3000], [700, 5000], [600, 3000], [600, 4000], [600, 3000], ]) rgb = fig4.colorize(data, colors, display_ranges) ...
5,343,037
def multi_mdf(S, all_drGs, constraints, ratio_constraints=None, net_rxns=[], all_directions=False, x_max=0.01, x_min=0.000001, T=298.15, R=8.31e-3): """Run MDF optimization for all condition combinations ARGUMENTS S : pandas.DataFrame Pandas DataFrame that corresponds t...
5,343,038
def cache_data(datatable, data, **kwargs): """Stores the object list in the cache under the appropriate key.""" cache_key = "%s%s" % (CACHE_PREFIX, datatable.get_cache_key(**kwargs)) log.debug("Setting data to cache at %r: %r", cache_key, data) cache.set(cache_key, data)
5,343,039
def rank_zero_warn(*args, **kwargs) -> None: """Warning only if (sub)process has rank 0.""" global _proc_rank if _proc_rank == 0: warnings.warn(*args, **kwargs)
5,343,040
def test_loop_dist_matrix(X_n120) -> None: """ Tests to ensure the proper results are returned when supplying the appropriate format distance and neighbor matrices. :param X_n120: A pytest Fixture that generates 120 observations. :return: None """ # generate distance and neighbor indices ...
5,343,041
def nufft_adjoint(input, coord, oshape=None, oversamp=1.25, width=4.0, n=128): """Adjoint non-uniform Fast Fourier Transform. Args: input (array): Input Fourier domain array. coord (array): coordinate array of shape (..., ndim). ndim determines the number of dimension to apply nuff...
5,343,042
def get_bustools_version(): """Get the provided Bustools version. This function parses the help text by executing the included Bustools binary. :return: tuple of major, minor, patch versions :rtype: tuple """ p = run_executable([get_bustools_binary_path()], quiet=True, returncode=1) match ...
5,343,043
def main(): """ Args: none Returns: exit code Usage: python -m rununittest """ # Can use unittest or nose; nose here, which allows --with-coverage. import nose return nose.run(argv=[sys.argv[0], "-s", "--with-coverage", "rununittest"])
5,343,044
def request_from_url(url): """Parses a gopher URL and returns the corresponding Request instance.""" pu = urlparse(url, scheme='gopher', allow_fragments=False) t = '1' s = '' if len(pu.path) > 2: t = pu.path[1] s = pu.path[2:] if len(pu.query) > 0: s = s + '?' + pu.query...
5,343,045
def getJsonPath(name, moduleFile): """ 获取JSON配置文件的路径: 1. 优先从当前工作目录查找JSON文件 2. 若无法找到则前往模块所在目录查找 """ currentFolder = os.getcwd() currentJsonPath = os.path.join(currentFolder, name) if os.path.isfile(currentJsonPath): return currentJsonPath else: moduleFolder = os.path.a...
5,343,046
def enable_pause_data_button(n, interval_disabled): """ Enable the play button when data has been loaded and data *is* currently streaming """ if n and n[0] < 1: return True if interval_disabled: return True return False
5,343,047
def convertFiles(directory: str): """Convert files downloaded from Solar Atlas.""" files_list = glob.glob(os.path.join(directory, "*.tif")) if len(files_list) > 0: logging.info("Converting files") if not os.path.exists( os.path.join(os.path.dirname(directory), "converted_files") ...
5,343,048
def dProj(z, dist, input_unit='deg', unit='Mpc'): """ Projected distance, physical or angular, depending on the input units (if input_unit is physical, returns angular, and vice-versa). The units can be 'cm', 'ly' or 'Mpc' (default units='Mpc'). """ if input_unit in ('deg', 'arcmin', 'arcsec'): ...
5,343,049
def savgoldiff(x, dt, params=None, options={}, dxdt_truth=None, tvgamma=1e-2, padding='auto', optimization_method='Nelder-Mead', optimization_options={'maxiter': 10}, metric='rmse'): """ Optimize the parameters for pynumdiff.linear_model.savgoldiff See pynumdiff.optimize.__optimize__ and pynu...
5,343,050
def credentials(scope="module"): """ Note that these credentials match those mentioned in test.htpasswd """ h = Headers() h.add('Authorization', 'Basic ' + base64.b64encode("username:password")) return h
5,343,051
def assign_oe_conformers(oe_mol: "OEMol", conformers: List[unit.Quantity]): """Assign a set of conformers to an OE molecule, overwriting any existing ones.""" from openeye import oechem oe_mol.DeleteConfs() assert len(conformers) > 0, "at least one conformer must be provided/" for conformer i...
5,343,052
def _score_match(matchinfo: bytes, form, query) -> float: """ Score how well the matches form matches the query 0.5: half of the terms match (using normalized forms) 1: all terms match (using normalized forms) 2: all terms are identical 3: all terms are identical, including case """ t...
5,343,053
def _set_bias(clf, X, Y, recall, fpos, tneg): """Choose a bias for a classifier such that the classification rule clf.decision_function(X) - bias >= 0 has a recall of at least `recall`, and (if possible) a false positive rate of at most `fpos` Paramters --------- clf : Classifier ...
5,343,054
def get_additional_params(model_klass: Type['Model']) -> Dict[str, Any]: """ By default, we dont need additional params to FB API requests. But in some instances (i.e. fetching Comments), adding parameters makes fetching data simpler """ assert issubclass(model_klass, abstractcrudobject.AbstractCrud...
5,343,055
def thread_loop(run): """decorator to make the function run in a loop if it is a thread""" def fct(self, *args, **kwargs): if self.use_thread: while True: run(*args, **kwargs) else: run(*args, **kwargs) return fct
5,343,056
def rand_index(pred_cluster: Dict, target_cluster: Dict) -> float: """Use contingency_table to get RI directly RI = Accuracy = (TP+TN)/(TP,TN,FP,FN) Args: pred_cluster: Dict element:cluster_id (cluster_id from 0 to max_size)| predicted clusters target_cluster: Dict element:cluster_id (clust...
5,343,057
def retrieve(lims, csv, acc): """Saves matching account to csv""" account = getAccount(lims,acc) print ("Writing results to {0}".format(csv)) # unicode(, "utf8") with open(csv, 'w') as csv_file: csv_file.write( getAccountCSV(account) )
5,343,058
def _strToDateTimeAndStamp(incoming_v, timezone_required=False): """Test (and convert) datetime and date timestamp values. @param incoming_v: the literal string defined as the date and time @param timezone_required: whether the timezone is required (ie, for date timestamp) or not @return datetime @r...
5,343,059
def get_price_for_market_stateless(result): """Returns the price for the symbols that the API doesnt follow the market state (ETF, Index)""" ## It seems that for ETF symbols it uses REGULAR market fields return { "current": result['regularMarketPrice']['fmt'], "previous": result['regularMark...
5,343,060
def make_sure_not_modified(arg): """ Function checking whether annotation of SomeList is never resized and never modified, useful for debugging. Does nothing when run directly """ return arg
5,343,061
def jump(current_command): """Return Jump Mnemonic of current C-Command""" #jump exists after ; if ; in string. Always the last part of the command if ";" in current_command: command_list = current_command.split(";") return command_list[-1] else: return ""
5,343,062
def get_veterans(uname=None): """ @purpose: Runs SQL commands to querey the database for information on veterans. @args: The username of the veteran. None if the username is not provided. @returns: A list with one or more veterans. """ vet = None if uname: command = "SELECT * FROM v...
5,343,063
def install(): """ Starts the coverage tool if the coverage dir directive is set. """ if os.environ.get('COVERAGE_DIR', None): _install()
5,343,064
def main(): """ Dump info about a given font file. """ # pylint: disable=too-many-locals parser = argparse.ArgumentParser() parser.add_argument('fontfile', help='Path to font file to inspect.') args = parser.parse_args() print(args.fontfile) fname, _, chars = query_font(args.fontfil...
5,343,065
def multiline(xs, ys, c=None, ax=None, **kwargs): """ Plot lines with different colorings Adapted from: https://stackoverflow.com/a/50029441/2565317 Parameters ---------- xs : iterable container of x coordinates ys : iterable container of y coordinates c : iterable container of numbers...
5,343,066
def main(): """PARSE AND VALIDATE INTEGRATION PARAMS.""" command = demisto.command() params = demisto.params() verify_certificate = not params.get('insecure', False) proxy = params.get('proxy', False) api_key = params.get('apikey', {}) demisto.info(f'Command being called is {command}') ...
5,343,067
def mock_movement_handler() -> AsyncMock: """Get an asynchronous mock in the shape of an MovementHandler.""" return AsyncMock(spec=MovementHandler)
5,343,068
def compute( op , x , y ): """Compute the value of expression 'x op y', where -x and y are two integers and op is an operator in '+','-','*','/'""" if (op=='+'): return x+y elif op=='-': return x-y elif op=='*': return x*y elif op=='/': return x/y else: r...
5,343,069
def _add_registration_to_section(reg_json, section): """ Add the Registration object to section. """ registration = Registration(data=reg_json) section.registration = registration section.grade_date = registration.grade_date section.student_grade = registration.grade section.is_auditor =...
5,343,070
def ensure_test_env(outpath=None): """Make an empty .env file for testing purposes.""" if outpath is None: outpath = conf.PROJECT_ROOT / '.env' else: outpath = path(outpath) if not outpath.exists(): # It's fine if it's empty, just make sure it exists local('touch %s' % o...
5,343,071
def list_arg(raw_value): """argparse type for a list of strings""" return str(raw_value).split(',')
5,343,072
def create_tracking(slug, tracking_number): """Create tracking, return tracking ID """ tracking = {'slug': slug, 'tracking_number': tracking_number} result = aftership.tracking.create_tracking(tracking=tracking, timeout=10) return result['tracking']['id']
5,343,073
def get_indentation(line_): """ returns the number of preceding spaces """ return len(line_) - len(line_.lstrip())
5,343,074
def main(): """ Find the 10001th prime main method. :param n: integer n :return: 10001th prime """ primes = {2, } for x in count(3, 2): if prime(x): primes.add(x) if len(primes) >= 10001: break return sorted(primes)[-1]
5,343,075
def findDataById(objectids, level=None, version=None): """Return xml list of urls for each objectid.""" if sciflo.utils.isXml(objectids): et, xmlNs = sciflo.utils.getXmlEtree(objectids) objectids = et.xpath('.//_default:objectid/text()', xmlNs) infoLoL = [] headerLoL = ['objectid', ['ur...
5,343,076
def node_parameter_parser(s): """Expects arguments as (address,range,probability)""" try: vals = s.split(",") address = int(vals[0]) range = float(vals[1]) probability = float(vals[2]) return address, range, probability except: raise argparse.ArgumentTypeError...
5,343,077
def launch(context, service_id, catalog_packages=""): """ Initialize the module. """ return EnvManager(context=context, service_id=service_id, catalog_packages=catalog_packages)
5,343,078
def handle_verification_token(request, token) -> [404, redirect]: """ This is just a reimplementation of what was used previously with OTC https://github.com/EuroPython/epcon/pull/809/files """ token = get_object_or_404(Token, token=token) logout(request) user = token.user user.is_acti...
5,343,079
def multi_perspective_expand_for_2d(in_tensor, weights): """Given a 2d input tensor and weights of the appropriate shape, weight the input tensor by the weights by multiplying them together. """ # Shape: (num_sentence_words, 1, rnn_hidden_dim) in_tensor_expanded = tf.expand_dims(in_tensor, axis=...
5,343,080
def get_temp_url(src, *args): """ Caches `data` in a file of type specified in `mimetype`, to the images/temp folder and returns a link to the data. The generated URL is used only once, after it is accessed, the data is deleted from the machine. Argument: data: `bytes` | `str` - If it's type is ...
5,343,081
def _import(package, plugin): """Import the given plugin file from a package""" importlib.import_module(f"{package}.{plugin}")
5,343,082
def generateBasicAuthHeader(username, password): """ Generates a basic auth header :param username: Username of user :type username: str :param password: Password of user :type password: str :return: Dict containing basic auth header :rtype: dict >>> generateBasicAuthHeader('test',...
5,343,083
def test_string_overuse( assert_errors, assert_error_text, parse_ast_tree, default_options, strings, string_value, ): """Ensures that over-used strings raise violations.""" tree = parse_ast_tree(strings.format(string_value)) visitor = StringOveruseVisitor(default_options, tree=tree)...
5,343,084
def correlation(df, target, limit=0, figsize=None, plot=True): """ Display Pearson correlation coefficient between target and numerical features Return a list with low-correlated features if limit is provided """ numerical = list(df.select_dtypes(include=[np.number])) numerical_f = [n for n i...
5,343,085
def fasta_to_raw_observations(raw_lines): """ Assume that the first line is the header. @param raw_lines: lines of a fasta file with a single sequence @return: a single line string """ lines = list(gen_nonempty_stripped(raw_lines)) if not lines[0].startswith('>'): msg = 'expected the...
5,343,086
def pc_proj(data, pc, k): """ get the eigenvalues of principal component k """ return np.dot(data, pc[k].T) / (np.sqrt(np.sum(data**2, axis=1)) * np.sqrt(np.sum(pc[k]**2)))
5,343,087
def split_data(): """Data spliter for train/val/test sets""" path = "cochrane_collections/cochrane_summary_collection.json" random.seed(13) with open(path, "r", encoding="utf-8") as f: cochrane_dict = json.load(f) cochrane = [q for q in cochrane_dict] random.s...
5,343,088
def compare_time(time_str): """ Compare timestamp at various hours """ t_format = "%Y-%m-%d %H:%M:%S" if datetime.datetime.now() - datetime.timedelta(hours=3) <= \ datetime.datetime.strptime(time_str, t_format): return 3 elif datetime.datetime.now() - datetime.timedelta(hours=6) <= \ ...
5,343,089
def trendline(xd, yd, order=1, c='r', alpha=1, Rval=True): """Make a line of best fit, Set Rval=False to print the R^2 value on the plot""" #Only be sure you are using valid input (not NaN) idx = np.isfinite(xd) & np.isfinite(yd) #Calculate trendline coeffs = np.polyfit(xd[idx], yd[idx...
5,343,090
def groupby(key, seq): """ Group a collection by a key function >>> names = ['Alice', 'Bob', 'Charlie', 'Dan', 'Edith', 'Frank'] >>> groupby(len, names) # doctest: +SKIP {3: ['Bob', 'Dan'], 5: ['Alice', 'Edith', 'Frank'], 7: ['Charlie']} >>> iseven = lambda x: x % 2 == 0 >>> groupby(iseven, [...
5,343,091
def evo(): """Creates a test evolution xarray file.""" nevo = 20 gen_data = {1: np.arange(nevo), 2: np.sin(np.linspace(0, 2*np.pi, nevo)), 3: np.arange(nevo)**2} data = {'X1': np.linspace(0.1, 1.7, nevo)*_unit_conversion['AU'], 'X2': np.deg2rad(np.linspace(6...
5,343,092
def jinja_calc_buffer(fields: List[Any], category: Optional[str] = None) -> int: """calculate buffer for list of fields based on their length""" if category: fields = [f for f in fields if f.category == category] return max(len(f.to_string()) for f in fields)
5,343,093
def get_delete_op(op_name): """ Determine if we are dealing with a deletion operation. Normally we just do the logic in the last return. However, we may want special behavior for some types. :param op_name: ctx.operation.name.split('.')[-1]. :return: bool """ return 'delete' == op_name
5,343,094
def label(img_id): """ GET: return the current label for <img_id> POST: update the current label for <img_id> """ if request.method == 'PUT': #TODO: figure out how to get `request` to properly parse json on PUT req_dict = json.loads(request.data.decode()) with connection.cur...
5,343,095
def random_radec(nsynths, ra_lim=[0, 360], dec_lim=[-90, 90], random_state=None, **kwargs): """ Generate random ra and dec points within a specified range. All angles in degrees. Parameters ---------- nsynths : int Number of random points to generate. ra_lim : list-l...
5,343,096
def test_modules_bump_versions_single_module(self): """Test updating a single module""" # Change the star/align version to an older version main_nf_path = os.path.join(self.nfcore_modules, "modules", "star", "align", "main.nf") with open(main_nf_path, "r") as fh: content = fh.read() new_cont...
5,343,097
def display_alert( alert: Union[Mapping[str, Any], SecurityAlert], show_entities: bool = False ): """ Display a Security Alert. Parameters ---------- alert : Union[Mapping[str, Any], SecurityAlert] The alert to display as Mapping (e.g. pd.Series) or SecurityAlert show_entiti...
5,343,098
def warmUp(): """ Warm up the machine in AppEngine a few minutes before the daily standup """ return "ok"
5,343,099