content
stringlengths
22
815k
id
int64
0
4.91M
def subtract(value, *args, **kwargs): """ Return the difference between ``value`` and a :class:`relativedelta`. :param value: initial date or datetime. :param args: positional args to pass directly to :class:`relativedelta`. :param kwargs: keyword args to pass directly to :class:`relativedelta`. ...
14,200
def plot_coastline( axes, bathymetry, coords='grid', isobath=0, xslice=None, yslice=None, color='black', server='local', zorder=2, ): """Plot the coastline contour line from bathymetry on the axes. The bathymetry data may be specified either as a file path/name, or as a ...
14,201
def validate_offset(parameter, argument): """ For a given offset parameter, check if its argument is valid. If not, then raise `ValueError`. Examples -------- >>> validate_offset(parameter='last', argument='3d') >>> validate_offset(parameter='last', argument='XYZ') Traceback (most rec...
14,202
def dump_model(object_to_dump, output_path, flags): """Pickle the object and save to the output_path. Args: object_to_dump: Python object to be pickled output_path: (string) output path which can be Google Cloud Storage Returns: None """ with open('model.pkl', 'wb') as mod...
14,203
def test_ckeditor_file_upload_image_orphan(admin_api_client_logged_in): """ CKEditor file upload should create files protected by sendfile. The user can upload files when still being in the process of creating the Hearing, so the section id is not known yet. """ ckeditor_params = '?CKEditor=id_s...
14,204
def get_clang_format_from_cache_and_extract(url, tarball_ext): """Get clang-format from mongodb's cache and extract the tarball """ dest_dir = tempfile.gettempdir() temp_tar_file = os.path.join(dest_dir, "temp.tar" + tarball_ext) # Download from file print("Downloading clang-format %s from ...
14,205
def validate_manifest(integration: Integration): """Validate manifest.""" try: MANIFEST_SCHEMA(integration.manifest) except vol.Invalid as err: integration.add_error( "manifest", "Invalid manifest: {}".format(humanize_error(integration.manifest, err)), ) ...
14,206
def gen_files(): """Return a generator of dir names reading in tempfile tempfile has this format: challenge<int>/file_or_dir<str>,is_dir<bool> 03/rss.xml,False 03/tags.html,False ... 03/mridubhatnagar,True 03/aleksandarknezevic,True -> use last column to fi...
14,207
def multi_build(request, recipes_fixture): """ Builds the "one", "two", and "three" recipes. """ if request.param: docker_builder = docker_utils.RecipeBuilder(use_host_conda_bld=True) mulled_test = True else: docker_builder = None mulled_test = False build.build_r...
14,208
def p_unary_expr(t): """ unary_expr : MINUS expr """ t[0] = FuncCall(t[1],[t[2]])
14,209
def systemd_daemon(agent_name, action=None): """Manage systemd daemon for agent. Args: agent_name: Name of agent action: Action to occur Returns: None """ # Initialize key variables executable = '/bin/systemctl' options = ['start', 'stop', 'restart'] fixed_acti...
14,210
def safelog(func): """Version of prism.log that has prism as an optional dependency. This prevents the sql database, which may not be available, from becoming a strict dependency.""" @wraps(func) def inner(self, update, context): try: self.bot.cores["prism"].log_user(update.effective...
14,211
def test_invalid_edge_color(): """Test providing an invalid edge color raises an exception""" np.random.seed(0) shape = (10, 2, 2) data = np.random.random(shape) data[:, 0, :] = 20 * data[:, 0, :] layer = Vectors(data) with pytest.raises(ValueError): layer.edge_color = 5
14,212
def draw(args): """ Draw a GraphML with the tribe draw method. """ G = nx.read_graphml(args.graphml[0]) draw_social_network(G, args.write) return ""
14,213
def extract_stem_voc(x): """extract word from predefined vocbulary with stemming and lemmatization Args: x ([string]): [a sentence] Returns: [list]: [word after stemming and lemmatization] """ stem = PorterStemmer() # wnl = WordNetLemmatizer() all_words = set(words.word...
14,214
def plot_without_vis_spec( conditions_df: Union[str, pd.DataFrame], grouping_list: Optional[List[IdsList]] = None, group_by: str = 'observable', measurements_df: Optional[Union[str, pd.DataFrame]] = None, simulations_df: Optional[Union[str, pd.DataFrame]] = None, plotted_...
14,215
def _get_culled_faces(face_verts: torch.Tensor, frustum: ClipFrustum) -> torch.Tensor: """ Helper function used to find all the faces in Meshes which are fully outside the view frustum. A face is culled if all 3 vertices are outside the same axis of the view frustum. Args: face_verts: An (F...
14,216
def _build_pep8_output(result): """ Build the PEP8 output based on flake8 results. Results from both tools conform to the following format: <filename>:<line number>:<column number>: <issue code> <issue desc> with some issues providing more details in the description within parentheses. ...
14,217
def form_value(request, entity, attribute): """ Return value from request params or the given entity. :param request: Pyramid request. :param entity: Instance to get attribute from if it isn't found in the request params. :param str attribute: Name of attribute to search for in the request ...
14,218
def run(session): """Run inside host app.""" try: # Show the UI session.seqRenameUI.show() except: # Create the UI session.seqRenameUI = SequenceRenameApp(parent=UI._main_window()) session.seqRenameUI.show()
14,219
def process_batch_data(batch_words, batch_tags=None): """ Padding batched dataset. Args: batch_words: Words in a batch. batch_tags: Punctuations in a batch. Returns: Words and punctuations after padding. """ b_words, b_words_len = pad_sequences(batch_words) if batch_tags is N...
14,220
def mock_update_actions_interface( mock_root_fs_interface: MagicMock, mock_partition_manager_invalid_switch: MagicMock ) -> MagicMock: """Mock UpdateActionsInterface""" updater = Updater( root_FS_intf=mock_root_fs_interface, part_mngr=mock_partition_manager_invalid_switch, ) mock = M...
14,221
def grb2nc(glob_str, in_dir='./', out_dir='./'): """ Creates netCDF files from grib files. :param glob_str: (str) - the naming pattern of the files :param in_dir: (str) - directory of input files :param out_dir: (str) - directory of output files :return fo_names: (list) - list of netCDF files' ...
14,222
def test_MSIDset(): """ Read all available MSIDs into a single MSIDset. Use the empirically determined lengths as regression tests. """ msids = [hdr3['msid'] for hdr3 in aca_hdr3.HDR3_DEF.values() if 'value' in hdr3] msids = sorted(msids) # Read all MSIDs as a set dat = aca_hdr3.MSIDse...
14,223
def check_that_all_fields_and_groups_invisible(sdk_client: ADCMClient, path, app): """Prepare cluster from `path` and check that all fields and groups invisible.""" _, config = prepare_cluster_and_get_config(sdk_client, path, app) fields = config.get_field_groups() for field in fields: assert ...
14,224
def emit(path_local, path_s3, time, poisson=0.0, ls=None, z_line=None, actin_permissiveness=None, comment = None, write = True, **kwargs): """Produce a structured JSON file that will be consumed to create a run Import emit into an interactive workspace and populate a directory with run configurations ...
14,225
def adjust_learning_rate( optimizer: torch.optim, base_lr: float, iteration: int, warm_iter: int, max_iter: int, ) -> float: """ warmup + cosine lr decay """ start_lr = base_lr / 10 if iteration <= warm_iter: lr = start_lr + (base_lr - start_lr) * iteration / warm_iter else: ...
14,226
def load_data(region): """ Function to read in data according to region Args: region (str): valid values are US, JP and EU Returns: pd.DataFrame containing factors returns """ # region='US' reg_mapper = {'US': 'USA', 'JP': 'JPN', 'EU': 'Europe'} if region not in reg_map...
14,227
def convert(source, destination, worksheet_order=None, style=None, ignore_extra_sheets=True): """ Convert among Excel (.xlsx), comma separated (.csv), and tab separated formats (.tsv) Args: source (:obj:`str`): path to source file destination (:obj:`str`): path to save converted file wo...
14,228
def load_data(filename: str): """ Load house prices dataset and preprocess data. Parameters ---------- filename: str Path to house prices dataset Returns ------- Design matrix and response vector (prices) - either as a single DataFrame or a Tuple[DataFrame, Series] """ ...
14,229
def face_at_link(shape, actives=None, inactive_link_index=BAD_INDEX_VALUE): """Array of faces associated with links. Returns an array that maps link ids to face ids. For inactive links, which do not have associated faces, set their ids to *inactive_link_index*. Use the *actives* keyword to specify an a...
14,230
def snrcat(spec,plugmap): """This function calculates the S/N for each fiber. Parameters ---------- spec : SpecFrame object The SpecFrame object that constrains the 1D extracted spectra. plugmap : numpy structured array The plugmap information for each fiber including which...
14,231
def progress_bar( iterations: Any, prefix: str = "", size: int = 60, file: Any = sys.stdout ) -> None: """ A function to display the progress bar related to a process. :param iterations: :param prefix: :param size: :param file: :return: """ count = len(iterations) ...
14,232
def test_parsed_dbase(): """ Test that parsed_based still matches what is returned by rhessi. """ filename, _ = urlretrieve( "https://hesperia.gsfc.nasa.gov/hessidata/dbase/hsi_obssumm_filedb_200311.txt") dbase = sunpy.instr.rhessi.parse_observing_summary_dbase_file(filename) rows = {} ...
14,233
def forward(S, A, O, obs): """Calculates the forward probability matrix F. This is a matrix where each (i, j) entry represents P(o_1, o_2, ... o_j, X_t = i| A, O). In other words, each (i, j) entry is the probability that the observed sequence is o_1, ... o_j and that at position j we are in hidden st...
14,234
def dl_progress(num_blocks, block_size, total_size): """Show a decent download progress indication.""" progress = num_blocks * block_size * 100 / total_size if num_blocks != 0: sys.stdout.write(4 * '\b') sys.stdout.write('{0:3d}%'.format((progress)))
14,235
def sample(): """Sample database commands."""
14,236
def calculate_state(position, dt): """ Sometimes, a data file will include position only. In those cases, the velocity must be calculated before the regression is run. If the position is | position_11 position_21 | | position_12 position_22 | | ....................... | ...
14,237
def QuitChrome(chrome_path): """ Tries to quit chrome in a safe way. If there is still an open instance after a timeout delay, the process is killed the hard way. Args: chrome_path: The path to chrome.exe. """ if not CloseWindows(chrome_path): # TODO(robertshield): Investigate w...
14,238
def create_tables(conn, create_table_sql): """ create a table from the create_table_sql statement :param conn: Connection object :param create_table_sql: a CREATE TABLE statement :return: """ try: c = conn.cursor() c.execute(create_table_sql) conn.commit() except Exce...
14,239
def get_server(name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetServerResult: """ Use this data source to retrieve an auth server from Okta. ## Example Usage ```python import pulumi import pulumi_okta as okta example = okta.auth.get_se...
14,240
def estimate_aps_user_defined(ml, X_c = None, X_d = None, data = None, C: Sequence = None, D: Sequence = None, L: Dict[int, Set] = None, S: int = 100, delta: float = 0.8, seed: int = None, pandas: bool = False, pandas_cols: Sequence = None, keep_order: bool = ...
14,241
def shared_vinchain_instance(): """ This method will initialize ``SharedInstance.instance`` and return it. The purpose of this method is to have offer single default vinchainio instance that can be reused by multiple classes. """ if not SharedInstance.instance: clear_cache() ...
14,242
def export_viewpoint_to_nw(view_point: ViewPoint) -> Element: """ Represents current view point as a NavisWorks view point XML structure :param view_point: ViewPoint instance that should be represented in XML :return: XML Element instance with inserted view point """ path_to_viewpoint_template...
14,243
def generateMfccFeatures(filepath): """ :param filepath: :return: """ y, sr = librosa.load(filepath) mfcc_features = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=40) return mfcc_features
14,244
def homography_crop_resize(org_img_size, crop_y, resize_img_size): """ compute the homography matrix transform original image to cropped and resized image :param org_img_size: [org_h, org_w] :param crop_y: :param resize_img_size: [resize_h, resize_w] :return: """ # transform ...
14,245
def writeSetFLFinnisSinclair( nrho, drho, nr, dr, eampots, pairpots, out = sys.stdout, comments = ["", "", ""], cutoff = None): """Creates Finnis-Sinclar EAM potential in the DYNAMO ``setfl`` format. The format should be used with the ``LAMMPS`` `eam/fs pair_style <http://lammps.sandia.gov/doc/pair_ea...
14,246
def AddtoVtuField(vtu, add, fieldName, scale = None): """ Add a field from a vtu onto the corresponding field in an input vtu """ if optimise.DebuggingEnabled(): assert(VtuMatchLocations(vtu, add)) if scale is None: vtu.AddFieldToField(fieldName, add.GetField(fieldName)) else: vtu.AddField...
14,247
def generate_offsets(minRadius : int = 0, maxRadius : int = 3_750_000): """Generate x and z coordinates in concentric circles around the origin Uses Bresenham's Circle Drawing Algorithm """ def yield_points(x, y): yield x, y yield x, -y yield -x, -y ...
14,248
def extract_project_info(req_soup, full_name=False): """Extract the relevant project info from a request. Arguments: req_soup (BS4 soup object): The soup of the request. full_name (boolean): Whether or not to capture the entire project name or just the last h...
14,249
def histogram(ax, data, **kwargs): """smp_base.plot.histogram Plot the histogram """ assert len(data.shape) > 0, 'Data has bad shape = %s' % (data.shape, ) _loglevel = loglevel_debug + 0 # logger.log(_loglevel, " plot.histogram histo kwargs", kwargs) # init local kwargs kwa...
14,250
def test_measure_6(base_settings): """No. 6 tests collection for Measure. Test File: measure-composite-example.json """ filename = base_settings["unittest_data_dir"] / "measure-composite-example.json" inst = measure.Measure.parse_file( filename, content_type="application/json", encoding="utf...
14,251
def get_underlying_asset_price(token_symbol: str) -> Optional[Price]: """Gets the underlying asset price for token symbol, if any This function is neither in inquirer.py or chain/ethereum/defi.py due to recursive import problems """ price = None if token_symbol == 'yaLINK': price = Inq...
14,252
def do_call_async( fn_name, *args, return_type=None, post_process=None ) -> asyncio.Future: """Perform an asynchronous library function call.""" lib_fn = getattr(get_library(), fn_name) loop = asyncio.get_event_loop() fut = loop.create_future() cf_args = [None, c_int64, c_int64] if return_ty...
14,253
def prefer_static_value(x): """Return static value of tensor `x` if available, else `x`. Args: x: `Tensor` (already converted). Returns: Numpy array (if static value is obtainable), else `Tensor`. """ static_x = tensor_util.constant_value(x) if static_x is not None: return static_x return x
14,254
def copy_parameter_value(value, shared_types=None, memo=None): """ Returns a copy of **value** used as the value or spec of a Parameter, with exceptions. For example, we assume that if we have a Component in an iterable, it is meant to be a pointer rather than something used...
14,255
def center(win): """ centers a tkinter window :param win: the main window or Toplevel window to center """ win.update_idletasks() width = win.winfo_width() frm_width = win.winfo_rootx() - win.winfo_x() win_width = width + 2 * frm_width height = win.winfo_height() titlebar_height ...
14,256
def test_get_window(): """ Test rebootmgr.get_window without parameters """ window = "Maintenance window is set to *-*-* 03:30:00, lasting 01h30m." salt_mock = { "cmd.run_all": MagicMock(return_value={"stdout": window, "retcode": 0}) } with patch.dict(rebootmgr.__salt__, salt_mock): ...
14,257
def procmap(method, item_list): """ Like :py:func:`map`, but where the method being applied has no return value. In other words, the procedure is called on every item in the list sequentially, but since each call has no return value, the call to :func:`procmap` also has no return value. :param ...
14,258
def test_convert_dict_to_list(): """Should convert dict to list.""" listdict = { "0": "apple", "1": "banana", "2": "orange", } expected = [ "apple", "banana", "orange", ] assert loader._convert_dict_to_list(listdict) == expected
14,259
def ajax_login_required(function): """ Decorator for views that checks that the user is logged in, resulting in a 403 Unauthorized response if not. """ @wraps(function, assigned=available_attrs(function)) def wrapped_function(request, *args, **kwargs): if request.user.is_authenticated: ...
14,260
def compile_str_from_parsed(parsed): """The (quasi-)inverse of string.Formatter.parse. Args: parsed: iterator of (literal_text, field_name, format_spec, conversion) tuples, as yield by string.Formatter.parse Returns: A format string that would produce such a parsed input. >>> ...
14,261
def __ixor__(self: array, other: array, /) -> array: """ Note: __ixor__ is a method of the array object. """ pass
14,262
def calculate_class_weight(labels): """Calculates the inverse of the class cardinalities and normalizes the weights such that the minimum is equal to 1. Args: labels: List of integers representing class labels Returns: Numpy array with weight for each class """ labels =...
14,263
def kill_processes(procs, kill_children=True): """Kill a list of processes and optionally it's children.""" for proc in procs: LOGGER.debug("Starting kill of parent process %d", proc.pid) kill_process(proc, kill_children=kill_children) ret = proc.wait() LOGGER.debug("Finished kil...
14,264
def gather_from_workers(who_has, deserialize=True, rpc=rpc, close=True, permissive=False): """ Gather data directly from peers Parameters ---------- who_has: dict Dict mapping keys to sets of workers that may have that key Returns dict mapping key to value See ...
14,265
def run(flock, previous_flock, amaze, template_triangles, amendments): """ Detects collisions and calculates required amendments that allow boid to avoid collisions. For each boid it first checks if boid collides with the wall by rotating on the same spot. If it is, boid is moved out...
14,266
def CosEnv(length,rft=(0.005),fs=(44100)): """ rft : Rise and fall time [s] length : Total length of window [s] fs : Sampling freq [Hz] """ rfsamp = int(np.round(rft * fs)) windowsamp = int(np.round(length * fs)) flatsamp = windowsamp - (2 * rfsamp) time_index = np.arange(0, 1,...
14,267
def generate_client_credentials(cluster_name, public_key, verify_code): """Generate the client credentials""" prompts = [] prompts += expect('Enter a name for this cluster:', cluster_name) prompts += expect("Input the server's public key:", public_key) prompts += expect("Input the server verify cod...
14,268
def load_deck_obj(deckFile, deckObj): """ reset the deckObj, and load in the lines from deckFile. """ deckObj = [] # open up the deck file, and start adding lines to the deckObj with open(deckFile, 'r') as deckItem: for deckLine in deckItem: # print([deckLine]) deckObj += [deckLine] #...
14,269
def flatten(nested_list): """ Args: nested_list (list): list of lists Returns: list: flat list Example: >>> import ubelt as ub >>> nested_list = [['a', 'b'], ['c', 'd']] >>> list(ub.flatten(nested_list)) ['a', 'b', 'c', 'd'] """ return it.chain.f...
14,270
def fetch_reply(query, session_id): """ main function to fetch reply for chatbot and return a reply dict with reply 'type' and 'data' """ response = apiai_response(query, session_id) intent, params = parse_response(response) reply = {} if intent == None: reply['type'] = 'none' reply['data'] = "I didn't u...
14,271
def test_DataFrameProfile_invalid(): """DataFrame profile should not accept invalid data types""" invalid_types = [ TEST_CAT_SERIES, TEST_NUM_SERIES, "data", 34, 34.5, {"data": "dictionary"}, [["col_name", 1], ["col_name2", 2]], (("col_name", 3), (...
14,272
def create_SpatialReference(sr): """ creates an arcpy.spatial reference object """ return arcpy.SpatialReference(sr)
14,273
def main(): """ main solver function """ graph = defaultdict(list) with open("passage_pathing.txt", encoding="utf-8") as file: lines = file.readlines() nodes = set() for line in lines: line = line.strip() start, end = line.split("-") nodes....
14,274
def check_in_image(paste_image_location, paste_image_size, canvas_image_size): """Checks whether the location for the pasted image is within the canvas. Args: paste_image_location: a namedtuple of utils.XY, with 'x' and 'y' coordinates of the center of the image we want to paste. paste_image_si...
14,275
def test_add_auth_blank_user(mechfile_one_entry_with_auth_and_mech_use): """Test add_auth.""" inst = mech.mech_instance.MechInstance('first', mechfile_one_entry_with_auth_and_mech_use) inst.user = '' inst.password = 'vagrant' inst.vmx = '/tmp/first/some.vmx' with raises(SystemExit, match=r"Need ...
14,276
def get_gpu(os: str, line: List, value: str, key: str): """ Append the GPU info from the given neofetch line to the GPU list Parameters ---------- os : OS type line : List Component line value : str Neofetch extracted line key : str Component key """ ...
14,277
def withSEVCHK(fcn): """decorator to raise a ChannelAccessException if the wrapped ca function does not return status = dbr.ECA_NORMAL. This handles the common case of running :func:`PySEVCHK` for a function whose return value is from a corresponding libca function and whose return value should be ...
14,278
def test_add_with_formatting(): """Use formatting expressions.""" context = Context({ 'arbset': {1, 2}, 'addthis': 3, 'add': { 'set': PyString('arbset'), 'addMe': '{addthis}' }}) add.run_step(context) context['add']['addMe'] = 4 add.run_step...
14,279
def convert_ts_to_date(ts): """ Converts a timestamp to a date object """ # TODO: is this function necessary? return datetime.fromtimestamp(ts)
14,280
def add_message(request, kind, message): """ Put message into session """ messages = request.session.get('messages', []) messages.append((kind, message)) request.session['messages'] = messages
14,281
def available_methods(): """Get all available importance scores """ from . import ism, gradient, referencebased int_modules = [ism, gradient, referencebased] available_methods = {} for m in int_modules: available_methods = merge_dicts(available_methods, m.METHODS) return available_m...
14,282
def clip(*args, **kwargs): """ This command is used to create, edit and query character clips. Flags: - absolute : abs (bool) [create] This flag is now deprecated. Use aa/allAbsolute, ar/allRelative, ra/rotationsAbsolute, or da/defaultAbsolute instead. ...
14,283
def PDeselSN (inSC, SNTab, isuba, fgid, ants, timerange, err): """ Deselect entries in an SN table Routine to deselect records in an SN table if they match a given subarray, have a selected FQ id, appear on a list of antennas and are in a given timerange. inSC = Selfcal object SNTab = ...
14,284
def p_cmdexpr_table(p): """cmdexpr : TABLE arglist | TABLE MACRO"""
14,285
def templates(): """ .. versionadded:: 2015.5.0 List the available LXC template scripts installed on the minion CLI Examples: .. code-block:: bash salt myminion lxc.templates """ try: template_scripts = os.listdir("/usr/share/lxc/templates") except OSError: re...
14,286
def reg_planes_to_img(imgs, path=None, ax=None): """Export registered image single planes to a single figure. Simplified export tool taking a single plane from each registered image type, overlaying in a single figure, and exporting to file. Args: imgs (List[:obj:`np.ndarray`]): Sequen...
14,287
def is_sketch_list_empty(): """Check to see if any sketches""" return len(_CVB_SKETCH_LIST) == 0
14,288
def pb22(): """ Problem 22 : Names scores. We first open the file, suppress the useless ", put everything into lowercase, and split to get a list. We use merge sort to sort the list by alphabetical order (see utils.merge_sort), and then : - for each word in the list - for each character in t...
14,289
def resize(im, target_size, max_size, stride=0, interpolation = cv2.INTER_LINEAR): """ only resize input image to target size and return scale :param im: BGR image input by opencv :param target_size: one dimensional size (the short side) :param max_size: one dimensional max size (the long side)...
14,290
def _add_qc( samples: List[Sample], namespace: str, overwrite_multiqc: bool ) -> Tuple[str, str]: """ Populates s.qc_values for each Sample object. Returns paths to MultiQC html and json files. """ multiqc_html_path = join( f'gs://cpg-{NAGIM_PROJ_ID}-{namespace}-web/qc/multiqc.html' ...
14,291
def oscillAnglesOfHKLs(hkls, chi, rMat_c, bMat, wavelength, vInv=None, beamVec=bVec_ref, etaVec=eta_ref): """ Takes a list of unit reciprocal lattice vectors in crystal frame to the specified detector-relative frame, subject to the conditions: 1) the reciprocal lattice vector mus...
14,292
def srfFaultSurfaceExtract(SRFfile): """ Generate fault surface from SRF file convention Following the Graves' SRF convention used in BBP and CyberShake """ lines = open( SRFfile, 'r' ).readlines() Nseg = int(lines[1].strip().split()[1]) # loop over segments to get (Nrow,Ncol) of ...
14,293
def disconnectHandler(crash=True): """ Handles disconnect Writes a crash log if the crash parameter is True """ executeHandlers("evt02") if crash: crashLog("main.disconnect") logger.critical("disconnecting from the server") try: Component.disconnect() except AttributeError: pass global ALIVE ALIVE = Fa...
14,294
def _to_response( uploaded_protocol: UploadedProtocol, ) -> route_models.ProtocolResponseAttributes: """Create ProtocolResponse from an UploadedProtocol""" meta = uploaded_protocol.data analysis_result = uploaded_protocol.data.analysis_result return route_models.ProtocolResponseAttributes( i...
14,295
def has_valid_chars(token: str) -> bool: """ decides whether this token consists of a reasonable character mix. :param token: the token to inspect :return: True, iff the character mix is considered "reasonable" """ hits = 0 # everything that is not alphanum or '-' or '.' limit = int(l...
14,296
def sqlalchemy_engine(args, url): """engine constructor""" environ['PATH'] = args.ora_path # we have to point to oracle client directory url = f'oracle://{args.user}:{pswd(args.host, args.user)}@{args.host}/{args.sid}' logging.info(url) return create_engine(url)
14,297
def cpu_count(): """ Returns the default number of slave processes to be spawned. """ num = os.getenv("OMP_NUM_THREADS") if num is None: num = os.getenv("PBS_NUM_PPN") try: return int(num) except: return multiprocessing.cpu_count()
14,298
def shortcut_layer(name: str, shortcut, inputs): """ Creates the typical residual block architecture. Residual blocks are useful for training very deep convolutional neural networks because they act as gradient 'highways' that enable the gradient to flow back into the first few initial convolution...
14,299