content
stringlengths
22
815k
id
int64
0
4.91M
def atom_eq(at1,at2): """ Returns true lits are syntactically equal """ return at1 == at2
5,317,100
def is_valid_month (val): """ Checks whether or not a two-digit string is a valid date month. Args: val (str): The string to check. Returns: bool: True if the string is a valid date month, otherwise false. """ if len(val) == 2 and count_digits(val) == 2: month = int(val) ...
5,317,101
def generate_tclloader_looseends(imgout, platform): """ Handle files that need to be handled. :param imgout: Directory that files are to be copied to. :type imgout: str :param platform: Platform type (i.e. subdirectory of target/product). :type platform: str """ if platform == "bbry_qc...
5,317,102
def test_unicode_auth_ascii(api_type): """Ensure that login without unicode works""" with api_select.api(__file__, api_type, username=username, password=password) as api: api.flow_job() api.job('j11', max_fails=0, expect_invocations=1, invocation_delay=1.0, expect_order=1) with flow.se...
5,317,103
def test_list_g_month_day_min_length_4_nistxml_sv_iv_list_g_month_day_min_length_5_3(mode, save_output, output_format): """ Type list/gMonthDay is restricted by facet minLength with value 10. """ assert_bindings( schema="nistData/list/gMonthDay/Schema+Instance/NISTSchema-SV-IV-list-gMonthDay-min...
5,317,104
def env_repos(action=None): """ Perform an action on each environment repository, specified by action. """ actions = { 'add': _add_repo, 'reset': _reset_repo, 'rm': _rm_repo } def validate_action(input): if input not in actions: raise Exception('Inval...
5,317,105
def get_job_definition_name_by_arn(job_definition_arn): """ Parse Job Definition arn and get name. Args: job_definition_arn: something like arn:aws:batch:<region>:<account-id>:job-definition/<name>:<version> Returns: the job definition name """ pattern = r".*/(.*):(.*)" return re.s...
5,317,106
def get_polyline_length(polyline: np.ndarray) -> float: """Calculate the length of a polyline. Args: polyline: Numpy array of shape (N,2) Returns: The length of the polyline as a scalar """ assert polyline.shape[1] == 2 return float(np.linalg.norm(np.diff(polyline, axis=0), axi...
5,317,107
def GDALReadBlock(dataset, blocno, BSx=-1, BSy=-1, verbose=False): """ GDALReadBlock """ dataset = gdal.Open(dataset, gdal.GA_ReadOnly) if isstring(dataset) else dataset if dataset: band = dataset.GetRasterBand(1) BSx, BSy = (BSx, BSy) if BSx > 0 else band.GetBlockSize() M, ...
5,317,108
def save_to_npy(sFrames, sPath): """ Write np.array to file """ dir_path = "/gdrive/My Drive/Capstone/frames_npy/" # if file exist do not save if not os.path.exists(dir_path): os.makedirs(dir_path, exist_ok = True) # create full path to save frames sPath = os.path.join(dir...
5,317,109
def select_does_not_contain(self, option, id_): """Assert the select does not contain the given option.""" assert option_in_select(world.browser, id_, option) is None, \ "Selector should not have the given option."
5,317,110
def add_update_stock(symbol, is_held): """This function takes a stock symbol as a string, makes a call to yfinance, and gets back the necessary data to add the symbol to the database. `is_held` must also be specified, to mark the is_held flag in the database True/False.""" session = connect_to_sessio...
5,317,111
def k2(Ti, exp=math.exp): """[cm^3 / s]""" return 2.78e-13 * exp(2.07/(Ti/300) - 0.61/(Ti/300)**2)
5,317,112
async def add_source(request): """ API Endpoint to add new datasets to an instance API Params: file: location of the json or hub file filetype: 'hub' if trackhub or 'json' if configuration file Args: request: a sanic request object Returns: success/fail after addi...
5,317,113
def sweepPlotGen(*args): """Call this function to generate the swept process description plots.""" #Generating points nsteps = int(blocksize/(2*boundaryPoints)) usb,diasb,dsb = generateSets(*args) usbEdges = getEdgeBlocks(usb,args[3],args[2]) dialen = int(np.shape(diasb)[1]/2-1) tempDias = t...
5,317,114
def clean_counties_data(): """Clean US Counties data from NY Times Returns: DataFrame -- clean us counties data Updates: database table -- NYTIMES_COUNTIES_TABLEs database view -- COUNTIES_VIEW """ _db = DataBase() data = _db.get_table(US_COUNTIES_TABLE, parse_dates=['d...
5,317,115
def basic_trainer_sub(ckpt_path, save_file): """ This test just makes sure that the BasicTrainer example can be run on a CPU without crashing or raising an error. """ if os.path.isfile(save_file): os.remove(save_file) data = requests.get( "https://archive.org/download/TheLibraryO...
5,317,116
def get_3D_hist(sub_img): """ Take in a sub-image Get 3D histogram of the colors of the image and return it """ M, N = sub_img.shape[:2] t = 4 pixels = sub_img.reshape(M * N, 3) hist_3D, _ = np.histogramdd(pixels, (t, t, t)) return hist_3D
5,317,117
def verify_single_host(host, ip): """ Simple function to verify only a single host returned from query. If no hosts, or multiple hosts are returned, an error message is printed and the program exits. """ if len(host) == 0: print("Error: No host with IP address {} was found".format(ip)) ...
5,317,118
def cache_tree(config_age, location_suffix): """ A decorator for caching pickle files based on the configuration file. It is currently set up to decorate a function that has a single parameter ``site``. The returned function also can be passed keyword arguments to override the ``location_suffix`` a...
5,317,119
def magnitude_prune(masking, mask, weight, name): """Prunes the weights with smallest magnitude. The pruning functions in this sparse learning library work by constructing a binary mask variable "mask" which prevents gradient flow to weights and also sets the weights to zero where the binary mask i...
5,317,120
def delete_post(post_id): """Authenticates and proxies a request to users service to delete a post.""" try: my_user_id = get_user()['user_id'] response = requests.delete(app.config['POSTS_ENDPOINT'] + post_id, data={'author_id': my_user_id}) return resp...
5,317,121
def file_based_convert_examples_to_features_single(examples, label_list, max_seq_length, tokenizer, output_file): """Convert a set of `InputExample`s to a TFRecord file.""" writer = tf.python_io.TFRecordWriter(out...
5,317,122
def less_equal(x, y): """Element-wise truth value of (x <= y). # Arguments x: Tensor or variable. y: Tensor or variable. # Returns A bool tensor. # Raise TypeError: if inputs are not valid. """ scalar = False if isinstance(x, KerasSymbol): x = x.sym...
5,317,123
def p_expr_assign(p): """expr : expr LEFT_ASSIGN expr | expr RIGHT_ASSIGN expr """ p[0] = Assign(p[1], _MakeAtom(p, 2), p[3])
5,317,124
def annual_reports(): """ Return list of all existing annual reports """ database = DataProvider() total = count(database.objects, lambda x: x.with_cafe) * 2 + \ count(database.objects, lambda x: not x.with_cafe) reports_list = list() # calculate count of annual reports items = sorte...
5,317,125
def alpha_036(code, end_date=None, fq="pre"): """ 公式: RANK(SUM(CORR(RANK(VOLUME), RANK(VWAP)), 6), 2) Inputs: code: 股票池 end_date: 查询日期 Outputs: 因子的值 """ end_date = to_date_str(end_date) func_name = sys._getframe().f_code.co_name return JQDataClient.instanc...
5,317,126
def definition_for_include(parsed_include, parent_definition_key): """ Given a parsed <xblock-include /> element as a XBlockInclude tuple, get the definition (OLX file) that it is pointing to. Arguments: parsed_include: An XBlockInclude tuple parent_definition_key: The BundleDefinitionLocator...
5,317,127
def verify_user(uid, token_value): """ Verify the current user's account. Link should have been sent to the user's email. Args: token_value: the verification token value Returns: True if successful verification based on the (uid, token_value) False if token is not valid for...
5,317,128
def reduce_property_booleans(property_results, signature): """Reduces property booleans across examples.""" transposed = zip(*property_results) for property_across_examples in transposed: has_true = any(property_across_examples) has_false = not all(property_across_examples) if has_true and has_false: ...
5,317,129
def cholesky_metric(chol: JAXArray, *, lower: bool = True) -> Metric: """A general metric parameterized by its Cholesky factor The units of the Cholesky factor are length, unlike the dense metric. Therefore, .. code-block:: python cholesky_metric(jnp.diag(ell)) and .. code-block:: p...
5,317,130
def format_roman(value: int) -> str: """Format a number as lowercase Roman numerals.""" assert 0 < value < 4000 result: typing.List[str] = [] index = 0 while value != 0: value, remainder = divmod(value, 10) if remainder == 9: result.insert(0, ROMAN_ONES[index]) ...
5,317,131
def find_top_directory(): """ Find the parent directory of the poky meta-layer :return: the base path """ return os.path.dirname(tinfoil.config_data.getVar("COREBASE", True))
5,317,132
def isint(s): """Does this object represent an integer?""" try: int(s) return True except (ValueError, TypeError): return False
5,317,133
def set_clipboard(data): """Set clipboard to ``data``""" scpt = """ set the clipboard to "{0}" """.format(_applescriptify_str(data)) subprocess.call(['osascript', '-e', scpt])
5,317,134
def embed_vimeo(url): """ Return HTML for embedding Vimeo videos or ``None``, if argument isn't a Vimeo link. The Vimeo ``<iframe>`` is wrapped in a ``<div class="responsive-embed widescreen vimeo">`` element. """ match = VIMEO_RE.search(url) if not match: return None d = ma...
5,317,135
def random_sample(random_state, size=None, chunk_size=None, gpu=None, dtype=None): """ Return random floats in the half-open interval [0.0, 1.0). Results are from the "continuous uniform" distribution over the stated interval. To sample :math:`Unif[a, b), b > a` multiply the output of `random_samp...
5,317,136
def test_news_view(news_client, session, news): """ is shown as the default. """ resp = news_client.get('/news') assert resp.status_code == 200 assert news[0].title.encode('utf8') in resp.data assert news[0].description_html.encode('utf8') in resp.data assert news[1].title.encode('utf8') in ...
5,317,137
def anndata_file(): """Pytest fixture for creation of anndata files.""" def _create_file(nvals): size = 15289 * nvals vals = np.zeros(size, dtype=np.float32) non_zero = size - int(size * 0.92) non_zero = int(np.random.normal(loc=non_zero, scale=10, size=1)) rand = np.rand...
5,317,138
def _heatmap_summary(pvals, coefs, plot_width=1200, plot_height=400): """ Plots heatmap of coefficients colored by pvalues Parameters ---------- pvals : pd.DataFrame Table of pvalues where rows are balances and columns are covariates. coefs : pd.DataFrame Table of coefficien...
5,317,139
def optimize_image(file_path: str) -> None: """convert to jpg, reduce filesize Args: file_path (str): path to image """ # new_path = file_path if not file_path.endswith(".jpg"): new_path = os.path.splitext(file_path)[0] + ".jpg" with Image.open(file_path) as img: im...
5,317,140
def get_warehouse_latest_modified_date(email_on_delay=False): """ Return in minutes how fresh is the data of app_status warehouse model. """ last_completed_app_status_batch = Batch.objects.filter( dag_slug='app_status_batch', completed_on__isnull=False ).order_by('completed_on').last() #...
5,317,141
def main(): """ Main function that calls populate on all the things """ # get set shortnames from input sets = [i.lower() for i in sys.argv[1:]] # populate sets by shortname populate(sets)
5,317,142
def retrieve_contents(repo, commit, path, encoding=None): """Retrieve contents of given file at given revision / tree Parameters ---------- repo : str | git.Repo | pygit2.Repository Pathname to the repository, or either GitPython (git.Repo) or pygit2 (pygit2.Repository) repository objec...
5,317,143
async def async_unload_entry(hass, config_entry): """Handle removal of an entry.""" return True
5,317,144
def render_links(link_dict): """Render links to html Args: link_dict: dict where keys are names, and values are lists (url, text_to_display). For example:: {"column_moistening.mp4": [(url_to_qv, "specific humidity"), ...]} """ return { key: " ".join([_html_l...
5,317,145
def is_valid_json(text: str) -> bool: """Is this text valid JSON? """ try: json.loads(text) return True except json.JSONDecodeError: return False
5,317,146
def peri_saccadic_response(spike_counts, eye_track, motion_threshold=5, window=15): """ Computes the cell average response around saccades. params: - spike_counts: cells activity matrix of shape (t, n_cell) - eye_track: Eye tracking data of shape (t, x_pos, y_pos, ...) - motion_th...
5,317,147
def parameter_file( scene_params: list, light_params: list, camera_params: list, image_params: list, save_path: str, n_variations: int, other_params: namedtuple, ): """ This function stores parameters used for rendering the image set in a json file. """ all_parameters = [] ...
5,317,148
def assign_subpopulation_from_region(pop, region, criteria, verbose=False): """ Compute required consistencies and assign subpopulations to a population of models based on results from a simulation region. Inputs: pop - a PopulationOfModels class region - a list of simulations criteria - has...
5,317,149
def post_error(output_dict): """Celery task that emits invalid login error to user Args: output_dict (dict): Dictionary containing items to emit to user """ from .wsgi_aux import app with app.app_context(): socketio.emit('response_image', output_dict, room=output_dict['room'])
5,317,150
def subscribe_to_collection(user_id, collection_id): """Subscribes a user to a collection. WARNING: Callers of this function should ensure that the user_id and collection_id are valid. Args: user_id: str. The user ID of the new subscriber. collection_id: str. The collection ID. """...
5,317,151
def op_structure(ea, opnum, id, **delta): """Apply the structure identified by `id` to the instruction operand `opnum` at the address `ea`. If the offset `delta` is specified, shift the structure by that amount. """ ea = interface.address.inside(ea) if not database.type.is_code(ea): raise E...
5,317,152
def get_config_path(root: str, idiom: str) -> Path: """Get path to idiom config Arguments: root {str} -- root directory of idiom config idiom {str} -- basename of idiom config Returns: Tuple[Path, Path] -- pathlib.Path to file """ root_path = Path(root) file_name = '{}....
5,317,153
def status(): """ Method to get the list of components available. :return: It yields json string for the list of components. """ data = pgc.get_data("status") return render_template('status.html', data=data)
5,317,154
def dijkstra( graph: LilMatrix, source: Union[int, Iterable[int]] ) -> Tuple[List[int], List[int]]: """Dijkstra Parameters ---------- graph Weighted Graph source (list of) source Returns ------- (cost, prev) Notes ----- Time comple...
5,317,155
def stdev(some_list): """ Calculate the standard deviation of a list. """ m = mean(some_list) var = mean([(v - m)**2 for v in some_list]) return sqrt(var)
5,317,156
def get_hg19_chroms(): """Chromosomes in the human genome Returns: list: list of chromosomes """ return get_hg38_chroms()
5,317,157
def fetch_occurrences(project_read_token, last_id=None, min_id=0): """ Fetch occurrences from a project. This will iterate through all occurrences in descending order by id, starting from `last_id`. last_id: the high id to start from min_id: the low id to not go beyond (not go lower than) """ ...
5,317,158
def track(im0, im1, p0, lk_params_, fb_threshold=-1): """ Main tracking method using sparse optical flow (LK) im0: previous image in gray scale im1: next image lk_params: Lukas Kanade params dict fb_threshold: minimum acceptable backtracking distance """ if p0 is None or not len(p0): ...
5,317,159
def get_kernel(X, Y, type='linear', param=1.0): """Calculates a kernel given the data X and Y (dims x exms)""" _, Xn = X.shape _, Yn = Y.shape kernel = 1.0 if type == 'linear': #print('Calculating linear kernel with size {0}x{1}.'.format(Xn, Yn)) kernel = X.T.dot(Y) if type == ...
5,317,160
def MIDPOINT(ds, count, timeperiod=-2**31): """MidPoint over period""" return call_talib_with_ds(ds, count, talib.MIDPOINT, timeperiod)
5,317,161
def getObjectsByCustomList(conn, customList, objectType = -1, processingFlags = PROCESSING_FLAGS['stamps']): """getObjectsByCustomList. Args: conn: customList: objectType: processingFlags: """ try: cursor = conn.cursor(MySQLdb.cursors.DictCursor) cursor....
5,317,162
def dtype(): """A fixture providing the ExtensionDtype to validate.""" return RaggedDtype()
5,317,163
def quit_handling(): """Quits""" # Confirm to quit if ConfirmDialogBoxConfig.confirm_exit and ( not confirm_dialog( "Quitting", "Are you SURE you want to exit? " "(to prevent this dialog, go to map_maker.py and set confirm_exit to False", ) ): ...
5,317,164
def get_verbs_from_names_functions(names_functions): """ Возвращает список глаголов из списка имён функций @param names_functions: список названий фунций (предполагается что слова в имени функции разделены символом _) @return: генератор """ for name_function in names_functions: for verb ...
5,317,165
def run_propka(args, protein): """Run a PROPKA calculation. Args: args: argparse namespace protein: protein object Returns: 1. DataFrame of assigned pKa values 2. string with filename of PROPKA-created pKa file """ # TODO - eliminate need to write temporary file ...
5,317,166
def geod2cart(rlat, rlon, height): """ Geodetic to Cartesian coordinate conversion Call cart = geod2cart(rlat, rlon, height) Input rlat -- NumPy float array of Geodetic latitudes rlon -- NumPy float array of Geodetic longitudes height -- NumPy float array of heights (m)...
5,317,167
def might_exceed_deadline(deadline=-1): """For hypothesis magic to work properly this must be the topmost decorator on test function""" def _outer_wrapper(func): @wraps(func) def _inner_wrapper(*args, **kwargs): dl = deadline if os.environ.get('PYMOR_ALLOW_DEADLINE_EXCESS...
5,317,168
def check_deluge(): """ Connects to an instance of Deluge and returns a tuple containing the instances status. Returns: (str) an instance of the Status enum value representing the status of the service (str) a short descriptive string representing the status of the service """ heade...
5,317,169
def start(defined = None): """Start new sb_data_gather instance. Depending on the provided argument, this function calls either defined_hard_search() or full_hard_search(). Default is full_hard_search() if no arg is provided. Args: defined -- (string, optional) if provided as "defined", cal...
5,317,170
def copy_permissions(original, duplicate, model, apps): """Copy permissions from original object to it's duplicate.""" UserObjectPermission = apps.get_model("guardian", "UserObjectPermission") GroupObjectPermission = apps.get_model("guardian", "GroupObjectPermission") kwargs = { "permission__co...
5,317,171
def minor_min_width(G): """Computes a lower bound for the treewidth of graph G. Parameters ---------- G : NetworkX graph The graph on which to compute a lower bound on the treewidth. Returns ------- lb : int A lower bound on the treewidth. Examples -------- Thi...
5,317,172
def plot_image_label_prediction(records, model_dir, mode, filename, remap=False): """ :param records: list containing numpy array of image, label and prediction :param model_dir: directory of model where to save images :param mode: str: train or test :param filename: str: filename of image :retu...
5,317,173
def readUptimeSeconds(): """Read and return current host uptime in seconds Returns: the uptime in seconds None on error """ proc_uptime_path = '/proc/uptime' if not os.path.exists(proc_uptime_path): printError('ERROR: unable to find uptime from file {}'.format( ...
5,317,174
async def test_get_async_client_without_ssl(hass): """Test init async client without ssl.""" client.get_async_client(hass, verify_ssl=False) assert isinstance(hass.data[client.DATA_ASYNC_CLIENT_NOVERIFY], httpx.AsyncClient)
5,317,175
def generate_dataset(size=10000, op='sum', n_features=2): """ Generate dataset for NALU toy problem Arguments: size - number of samples to generate op - the operation that the generated data should represent. sum | prod Returns: X - the dataset Y - the dataset labels """ X...
5,317,176
def glob2regexp(glob: str) -> str: """Translates glob pattern into regexp string. """ res = "" escaping = False incurlies = 0 pc = None # Previous char for cc in glob.strip(): if cc == "*": res += ("\\*" if escaping else ".*") escaping = False elif cc...
5,317,177
def distance(array1, array2): """计算两个数组矩阵的欧式距离; axis=0,求每列的 axis=1,求每行的 """ distance = np.sqrt(np.sum(np.power(array1 - array2, 2))) return distance
5,317,178
async def cmd_time(ctx: discord.ext.commands.Context): """ Get PSS stardate, as well as the day and time in Melbourne, Australia. Gives the name of the Australian holiday, if it is a holiday in Australia. Usage: /time Examples: /time - Prints PSS stardate, day & time in Melbourne and publi...
5,317,179
def parallel_map(function, *args, **kwargs): """Wrapper around IPython's map_sync() that defaults to map(). This might use IPython's parallel map_sync(), or the standard map() function if IPython cannot be used. If the 'ask' keyword argument is true, the user will be prompted to start IPython engi...
5,317,180
def init_glorot(shape, name=None): """Glorot & Bengio (AISTATS 2010) init.""" init_range = np.sqrt(6.0/(shape[0]+shape[1])) initial = tf.random_uniform(shape, minval=-init_range, maxval=init_range, dtype=tf.float32) return tf.Variable(initial, name=name)
5,317,181
def securities(identifier=None, query=None, exch_symbol=None): """ Get securities with optional filtering using parameters. Args: identifier: Identifier for the legal entity or a security associated with the company: TICKER SYMBOL | FIGI | OTHER IDENTIFIER query: Search of secur...
5,317,182
def stations_within_radius(stations, centre, r): """The function stations_within_radius returns a list of the stations within a radius r from a centre""" stations_new=[] for s in stations: # distance can be computed using haversine library d=haversine.haversine(s.coord, centre) ...
5,317,183
def main(fleet_endpoint, name, tag, method, instances, unit_file, atomic_handler, chunking, chunking_percent, delay): """Main function""" # Validation if chunking is not None and chunking_percent is not None: raise click.UsageError('Cannot use --chunking and --chunking-percent together.') if c...
5,317,184
def normalize_email(email): """Normalizes the given email address. In the current implementation it is converted to lower case. If the given email is None, an empty string is returned. """ email = email or '' return email.lower()
5,317,185
def _parse_hostname(url, include_port=False): """ Parses the hostname out of a URL.""" if url: parsed_url = urlparse((url)) return parsed_url.netloc if include_port else parsed_url.hostname
5,317,186
def voy(lr_angle): """ Returns y component for reference velocity v_0""" return -np.sin(np.radians(lr_angle))*9+np.cos(np.radians(lr_angle))*(12.+220.)
5,317,187
def importdb(cmdobj, **options): """ 导入morbidmap.txt到数据库 """ if not os.path.exists(options['input']): raise Exception(options['input'] + " not exists") try: register_connection('cmd-import', options['db'], options['host']) # 删除数据库中原有记录 with switch_db(dbmodels.OmimMorb...
5,317,188
def get_l8turbidwater(rho1, rho2, rho3, rho4, rho5, rho6, rho7): """Returns Boolean numpy array that marks shallow, turbid water""" watercond2 = get_l8commonwater(rho1, rho4, rho5, rho6, rho7) watercond2 = np.logical_and(watercond2, rho3 > rho2) return watercond2
5,317,189
def relpath_nt(path, start=os.path.curdir): """Return a relative version of a path""" if not path: raise ValueError("no path specified") start_list = os.path.abspath(start).split(sep) path_list = os.path.abspath(path).split(sep) if start_list[0].lower() != path_list[0].lower(): unc_...
5,317,190
def string_extract_only_alphabets(inputString=""): """ Returns only alphabets from given input string """ return loader.string_extract_only_alphabets(inputString)
5,317,191
def test_is_url(): """test the ability to determine whether a string is a URL""" assert_true(utils.is_url("http://mydomain.com/foo/bar/bat?asdf=1234&qewr=ooo")) assert_true(utils.is_url("http://xkcd.com/1193/")) assert_false(utils.is_url("syn123445")) assert_false(utils.is_url("wasssuuuup???")) ...
5,317,192
def get_trigger(location: Optional[str] = None, project: Optional[str] = None, project_id: Optional[str] = None, trigger_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetTriggerResult: """ Returns information ab...
5,317,193
def dispatch(intent_request): """ Dispatch function In case you want to support multiple intents with a single lambda function """ logger.debug('dispatch userId={}, intentName={}'.format( intent_request['userId'], intent_request['currentIntent']['name'])) intent_name = intent_request['curr...
5,317,194
def selu(x): # https://gist.github.com/naure/78bc7a881a9db17e366093c81425184f """Scaled Exponential Linear Unit. (Klambauer et al., 2017) # Arguments x: A tensor or variable to compute the activation function for. # References - [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706....
5,317,195
def __clsfn_args_kwargs(config, key, base_module=None, args=None, kwargs=None): """ Utility function called by both create_object and create_function. It implements the code that is common to both. """ logger = logging.getLogger('pytorch_lm.utils.config') logger.config('config: {}, key: {}, base...
5,317,196
def update_cluster_settings(test_obj, cluster_id, section, attrs): """Update settings for parameter of the cluster :param test_obj: TestCase object :param cluster_id: Cluster identifier :param section: string :param attrs: dict - settings for the plugin :return: None """ curr_attrs = te...
5,317,197
def parse_read_options(form, prefix=''): """Extract read options from form data. Arguments: form (obj): Form object Keyword Arguments: prefix (str): prefix for the form fields (default: {''}) Returns: (dict): Read options key - value dictionary. """ read_options = { ...
5,317,198
def create_arguement_parser(): """return a arguement parser used in shell""" parser = argparse.ArgumentParser( prog="python run.py", description="A program named PictureToAscii that can make 'Picture To Ascii'", epilog="Written by jskyzero 2016/12/03", formatter_class=argparse.Ar...
5,317,199