content
stringlengths
22
815k
id
int64
0
4.91M
def add_diagdir(parser): """since it's so common to have a diagdir flag for the tooling we've added it here to make it simpler to add""" parser.add_argument( "-d", "--diagdir", dest="diag_dir", default=".", help=" where the diag tarball directory is exported, " ...
5,331,800
def get_project_root() -> Path: """Return the path of the project root folder. Returns: Path: Path to project root """ return Path(__file__).parent
5,331,801
def FTCS(Uo, diffX, diffY=None): """Return the numerical solution of dependent variable in the model eq. This routine uses the explicit Forward Time/Central Space method to obtain the solution of the 1D or 2D diffusion equation. Call signature: FTCS(Uo, diffX, diffY) Parameters ...
5,331,802
def epicyclic_frequency(prof) -> Quantity: """Epicyclic frequency.""" Omega = prof['keplerian_frequency'] R = prof['radius'] return np.sqrt(2 * Omega / R * np.gradient(R ** 2 * Omega, R))
5,331,803
def _filter_subset(systems, test_sets, langpair, origlang, subset=None): """Filter sentences with a given origlang (or subset) according to the raw SGM files.""" if origlang is None and subset is None: return systems if test_sets is None or langpair is None: raise ValueError('Filtering for -...
5,331,804
def get_groups( a_graph, method='component_infomap', return_form='membership'): """ Return the grouping of the provided graph object using the specified method. The grouping is returned as a list of sets each holding all members of a group. Parameters ========== a_graph: :cl...
5,331,805
def positional_rank_queues (service_platform, api_key): """ Get the queues that have positional ranks enabled. References: https://developer.riotgames.com/regional-endpoints.html https://developer.riotgames.com/api-methods/#league-v4/GET_getQueuesWithPositionRanks ...
5,331,806
def maplist(f, xs): """Implement `maplist` in pure Python.""" return list(map(f, xs))
5,331,807
def configure_bgp_l2vpn_neighbor_activate( device, address_family, bgp_as, neighbor_address, address_family_modifier="", community="" ): """ Activate bgp neighbor on bgp router Args: device ('obj') : Device to be configured bgp_as ('...
5,331,808
def sanitize_name_inputs(inputs_data): """ Sanitize value of the keys "name" of the dictionary passed in parameter. Because sometimes output from Galaxy, or even just file name, from user inputs, have spaces. Also, it can contain '/' character and could break the use of os.path function. :param in...
5,331,809
def pull_urls_excel_sheets(workbook): """ Pull URLs from cells in a given ExcelBook object. """ # Got an Excel workbook? if (workbook is None): return [] # Look through each cell. all_cells = excel.pull_cells_workbook(workbook) r = set() for cell in all_cells: # Sk...
5,331,810
def main(): """Main entry point""" parser = argparse.ArgumentParser(prog="glow-tts-export-onnx") parser.add_argument("checkpoint", help="Path to model checkpoint (.pth)") parser.add_argument("output", help="Path to output onnx model") parser.add_argument( "--config", action="append", help="P...
5,331,811
def do_request(base_url, api_path, key, session_id, extra_params=''): """ Voer een aanvraag uit op de KNVB API, bijvoorbeeld /teams; hiermee vraag je alle team-data op """ hashStr = md5.new('{0}#{1}#{2}'.format(key, api_path, se...
5,331,812
def write_code(): """ Code that checks the existing path and snaviewpath in the environmental viriables/PATH """ msg = """\n\n[Code]\n""" msg += """function InstallVC90CRT(): Boolean;\n""" msg += """begin\n""" msg += """ Result := not DirExists('C:\WINDOWS\WinSxS\\x86_Microsoft.VC90...
5,331,813
def get_filenames(filename): """ Return list of unique file references within a passed file. """ try: with open(filename, 'r', encoding='utf8') as file: words = re.split("[\n\\, \-!?;'//]", file.read()) #files = filter(str.endswith(('csv', 'zip')), words) files = set(filter(lambda s: s.end...
5,331,814
def format_filename_gen(prefix, seq_len, tgt_len, bi_data, suffix, src_lang,tgt_lang,uncased=False,): """docs.""" if not uncased: uncased_str = "" else: uncased_str = "uncased." if bi_data: bi_data_str = "bi" else: bi_data_str = "uni" file_name = "{}-{}_{}.seqlen-{}.tg...
5,331,815
def restore_modifiers(obj: Object) -> None: """Restore modifier state after tension computation. Args: obj -- The blender object for which to restore suspended modifiers """ supended_modifiers = obj.data.tension_props.suspended_modifiers for modifier in supended_modifiers: if modifi...
5,331,816
def upsert_game(cur, session, guess): """ Add or update a users guess for a game to the db :param cur: the database cursor :param session: the current session :param guess: the users guess (-1 for lower, 1 for higher) :return: """ latest_quake = cur.execute( "SELECT QuakeID FROM ...
5,331,817
def app_get_cmd(args): """Extract an application description from an execution.""" exec_api = ZoeExecutionsAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass()) execution = exec_api.get(args.id) if execution is None: print("no such execution") else: json.dump(execution['descriptio...
5,331,818
def make_file_list_for_RTI_Rwanda(): """ This function makes the training and testing file list for RTI Rwanda imagery """ # folder = '/home/sr365/Gaia/Rwanda_RTI/RTI_data_set/train' # folder = '/home/sr365/Gaia/Rwanda_RTI/RTI_data_set/all' # folder = '/home/sr365/Gaia/Rwanda_RTI/RTI_data_s...
5,331,819
def is_holiday(date) -> bool: """ Return True or False for whether a date is a holiday """ name = penn_holidays.get(date) if not name: return False name = name.replace(' (Observed)', '') return name in holiday_names
5,331,820
def tokenize_text(text): """ Tokenizes a string. :param text: String :return: Tokens """ token = [] running_word = "" for c in text: if re.match(alphanumeric, c): running_word += c else: if running_word != "": token.append(running_w...
5,331,821
def generate_dummy_probe(elec_shapes='circle'): """ Generate a 3 columns 32 channels electrode. Mainly used for testing and examples. """ if elec_shapes == 'circle': electrode_shape_params = {'radius': 6} elif elec_shapes == 'square': electrode_shape_params = {'width': 7} eli...
5,331,822
def try_decode(message): """Try to decode the message with each known message class; return the first successful decode, or None.""" for c in MESSAGE_CLASSES: try: return c.decode(message) except ValueError: pass # The message was probably of a different type. re...
5,331,823
def build_where_clause(args: dict) -> str: """ This function transforms the relevant entries of dict into the where part of a SQL query Args: args: The arguments dict Returns: A string represents the where part of a SQL query """ args_dict = { 'source_ip': 'source_ip.va...
5,331,824
def matrix_scale(s): """Produce scaling transform matrix with uniform scale s in all 3 dimensions.""" M = matrix_ident() M[0:3,0:3] = np.diag([ s, s, s ]).astype(np.float64) return M
5,331,825
def arm(seconds): """Arm HW watchdog""" result = int(platform_watchdog.arm(seconds)) if result < 0: click.echo("Failed to arm Watchdog for {} seconds".format(seconds)) else: click.echo("Watchdog armed for {} seconds".format(result))
5,331,826
def magnitude_datapoints(data: DataPoint) -> List: """ :param data: :return: """ if data is None or len(data) == 0: return [] input_data = np.array([i.sample for i in data]) data = norm(input_data, axis=1).tolist() return data
5,331,827
def capture_output(): """Captures standard output and error during the context. Returns a tuple of the two streams as lists of lines, added after the context has executed. .. testsetup:: from attest import capture_output >>> with capture_output() as (out, err): ... print 'Captured'...
5,331,828
def test_load_submission_file_c_fain(mock_db_cursor): """ Test load submission management command for File C records with only a FAIN """ models_to_mock = [ { "model": TreasuryAppropriationAccount, "treasury_account_identifier": -1111, "allocation_transfer_ag...
5,331,829
def prediction(pdb_filename): """Run the CheShift CS prediction routine""" cmd.set('suspend_updates', 'on') pose, residues, total_residues, states = pose_from_pdb(pdb_filename) Db = load(path) raw(pose, residues, total_residues, states, Db) print '<'*80 + '\nYou didn`t provide a file with chemi...
5,331,830
def generate_config(data, config_name=None, validate=True, base_config=None): """ Generates the *OpenColorIO* config from given data. Parameters ---------- data : ConfigData *OpenColorIO* config data. config_name : unicode, optional *OpenColorIO* config file name, if given the c...
5,331,831
def svn_stringbuf_from_aprfile(*args): """svn_stringbuf_from_aprfile(svn_stringbuf_t result, apr_file_t file, apr_pool_t pool) -> svn_error_t""" return apply(_core.svn_stringbuf_from_aprfile, args)
5,331,832
def _check_iterative_process_compatibility(iterative_process): """Checks the compatibility of an iterative process with the training loop.""" error_message = ( 'The iterative_process argument must be of ' 'type`tff.templates.IterativeProcess`, and must have an ' 'attribute `get_model_weights`, whi...
5,331,833
def Arrow_Head_A (cls, elid = "SVG:Arrow_Head_A", design_size = 12, ref_x = None, stroke = "black", marker_height = 6, marker_width = 6, fill = "white", fill_opacity = 1, ** kw) : """Return a marker that is an arrow head with an A-Shape. >>> mrk = Marker.Arrow_Head_A () >>> svg = Document (Root (view_box...
5,331,834
def signup() -> Response | str | tuple[dict[str, str | int], int]: """Sign up""" # Bypass if user is logged in if current_user.is_authenticated: return redirect(url_for("home")) # Process user data try: # Return template if request.method is GET assert request.method != "GE...
5,331,835
def evaluate_all_configs(hparams, agent_model_dir): """Evaluate the agent with multiple eval configurations.""" def make_eval_hparams(hparams, policy_to_action, max_num_noops): hparams = copy.copy(hparams) hparams.add_hparam("num_agents", hparams.eval_num_agents) hparams.add_hparam("policy_to_actions_la...
5,331,836
def showcase_create_non_quaranteed_bit_rate_subscription_for_live_streaming(): """ This example showcases how you can create a subscription to the 5G-API in order to establish a Non-Guaranteed Bit Rate (NON-GBR) QoS. In order to run this example you need to follow the instructions in readme.md in ord...
5,331,837
def determinize(seed: Optional[int] = None, be_deterministic: bool = True) -> None: """ Seeds more random sources and cares about the environment to be or don’t be deterministic. -------------- @Params: -> seed: Optional[int] = None The number to use as seed for manual seeding....
5,331,838
def shape(a: Matrix) -> Tuple[int, int]: """ Returns the num of rows and columns of A """ num_rows = len(a) num_cols = len(a[0]) if a else 0 # number of elements so columns in first element if it exists return num_rows, num_cols
5,331,839
def solve(A, b): """ :param A: Matrix R x C :param b: Vector R :return: Vector C 'x' solving Ax=b >>> M = Mat(({'a', 'b', 'c', 'd'}, {'A', 'B', 'C', 'D'}), { \ ('a', 'A'): one, ('a', 'B'): one, ('a', 'D'): one, \ ('b', 'A'): one, ('b', 'D'): one, \ ('c', 'A'): one, ('c', 'B')...
5,331,840
def token_groups(self): """The groups the Token owner is a member of.""" return self.created_by.groups
5,331,841
def get_html_content_in_text(url): """ Grab all the content in webpage url and return it's content in text. Arguments: url -- a webpage url string. Returns: r.text -- the content of webpage in text. """ r = requests.get(url) return r.text
5,331,842
def subscribe(): """Subscribe new message""" webhook_url = request.form.get("webhook_url") header_key = request.form.get("header_key") header_value = request.form.get("header_value") g.driver.subscribe_new_messages(NewMessageObserver(webhook_url, header_key, header_value)) return jsonify({"succe...
5,331,843
def evaluate_model_old( model_path: str, report_output_path: str, seg_criterion: torch.nn, det_criterion: typing.Callable, net: torch.nn.Module, data_loaders: typing.Tuple[ torch.utils.data.DataLoader, torch.utils.data.DataLoader, torch...
5,331,844
def checkAttribute(node, attribute, value): """Check that an attribute holds the expected value, and that the corresponding accessor method, if provided, returns an equivalent value.""" # v1 = getattr(node, attribute) if v1 != value: raise AssertionError( "attribute value doe...
5,331,845
def seek_tell(fileobj, offset): """ Seek in `fileobj` or check we're in the right place already Parameters ---------- fileobj : file-like object implementing ``seek`` and (if seek raises an IOError) ``tell`` offset : int position in file to which to seek """ try: fil...
5,331,846
def SegAlign(ea, alignment): """ Change alignment of the segment @param ea: any address in the segment @param alignment: new alignment of the segment (one of the sa... constants) @return: success (boolean) """ return SetSegmentAttr(ea, SEGATTR_ALIGN, alignment)
5,331,847
def create_bitlink(logger, headers='', long_url='google.com'): """ Функция создает короткие ссылки из длинных :param logger: logger object :param headers: Generic Access Token сформированнный на сайте :param long_url: Ссылка которую надо укоротить :return: созданная короткая ссылка """ u...
5,331,848
def compute_neq(count_mat): """ Compute the Neq for each residue from an occurence matrix. Parameters ---------- count_mat : numpy array an occurence matrix returned by `count_matrix`. Returns ------- neq_array : numpy array a 1D array containing the neq values """ ...
5,331,849
def _GetOptionsParser(): """Get the options parser.""" parser = optparse.OptionParser(__doc__) parser.add_option('-i', '--input', dest='inputs', action='append', default=[], help='One or more input files to calcul...
5,331,850
def spikalize_img(experiment, image, label): """ Transform image to spikes. Spike with poisson distributed rate proportional to pixel brightness. :param experiment: :param image: :param label: :return: """ image_shape = np.append(np.array(experiment.timesteps), np.array(image.shape)) ...
5,331,851
def retrieve_value(step,standard,entity_property): """ Function attempts to retrieve entity property from datastore :param standard: Bibliographic standard or schema being tested :param entity_property: Entity property being extracted from schema """ world.redis_property_key = entity_property ...
5,331,852
def update_security_schemes(spec, security, login_headers, security_schemes, unauthorized_schema): """Patch OpenAPI spec to include security schemas. Args: spec: OpenAPI spec dictionary Returns: Patched spec """ # login_headers = {'Set-Cookie': # ...
5,331,853
def get_geckodriver_url(version): """ Generates the download URL for current platform , architecture and the given version. Supports Linux, MacOS and Windows. :param version: the version of geckodriver :return: Download URL for geckodriver """ platform, architecture = get_platform_architectu...
5,331,854
def get_graph_size(depth: int): """returns how many nodes are in fully-equipped with nodes graph of the given depth""" size = 1 cur_size = 1 ln = len(expand_sizes) for i in range(min(ln, depth)): cur_size *= expand_sizes[i] size += cur_size if ln < depth: size += cur_siz...
5,331,855
def inherits_from(obj, parent): """ Takes an object and tries to determine if it inherits at *any* distance from parent. Args: obj (any): Object to analyze. This may be either an instance or a class. parent (any): Can be either instance, class or python path to class. R...
5,331,856
def AddDescriptionFlag(parser): """Add the description argument. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed. """ parser.add_argument('--description', help='Optional...
5,331,857
def load_df_from_googlesheet( url_string: str, skiprows: Optional[int] = 0, skipfooter: Optional[int] = 0, ) -> pd.DataFrame: """Load a Pandas DataFrame from a google sheet. Given a file object, try to read the content as a CSV file and transform into a data frame. The skiprows and skipfooter a...
5,331,858
def decomp(bits, dummies=default_dummies, width=default_width): """Translate 0s and 1s to dummies[0] and dummies[1].""" words = (dummies[i] for i in bits) unwrapped = ' '.join(words) return wrap_source(unwrapped, width=width)
5,331,859
def get_word_node_attrs(word: Word) -> WordNodeAttrs: """Create the graph's node attribute for a `Word`. Build an attribute dict with the word's features. Note that we're using the term `Word` instead of `Token` to be closer to the implementation of these data structures in stanza. From stanza's docume...
5,331,860
def numpy_bbox_to_image(image, bbox_list, labels=None, scores=None, class_name=[], config=None): """ Numpy function used to display the bbox (target or prediction) """ assert(image.dtype == np.float32 and image.dtype == np.float32 and len(image.shape) == 3) if config is not None and config.normalized_m...
5,331,861
def loads(text, template=None, colored=None, comments=None, **kwargs): """ Deserialize `text` (a `str` or `unicode` instance containing a JSON document supporting template references `{$.key}`) to a Python object. :param text: serialized JSON string :type text: str :param template: (optional) N...
5,331,862
def redact_tiff_tags(ifds, redactList, title): """ Redact any tags of the form *;tiff.<tiff name name> from all IFDs. :param ifds: a list of ifd info records. Tags may be removed or modified. :param redactList: the list of redactions (see get_redact_list). :param title: the new title for the item....
5,331,863
def AsyncSleep(delay, name=None): """Pause for `delay` seconds (which need not be an integer). This is an asynchronous (non-blocking) version of a sleep op. It includes any time spent being blocked by another thread in `delay`. If it is blocked for a fraction of the time specified by `delay`, it only calls `sl...
5,331,864
def palide(string, length, ellipsis="...", pad=" ", position=1.0, left=False): """ A combination of `elide` and `pad`. """ return globals()["pad"]( elide(string, length, ellipsis=ellipsis, position=position), length, pad=pad, left=left)
5,331,865
def get_email_adderess(email_addr): """ Return dict from opalstack for given email address, or None """ mails = get_request("mail/list/") for record in mails['mails']: if record['address'] == email_addr: return get_request("mail/read/{}".format(record['id'])) return None
5,331,866
def main(app, env_file, api_key, set_alt, dump): """ CLI tool to manipulate environment variables on Heroku with local .env files, through the Heroku API. It is recommended for security purposes that you set API key as an environment variable like this: export HEROKU_API_KEY=a1b12c24-ab1d-123f...
5,331,867
def GK3toUTM(ea, no=None, zone=32): """Transform Gauss-Krueger zone 3 into UTM (for backward compatibility).""" return GKtoUTM(ea, no, zone, gkzone=3)
5,331,868
def test_command(): """ """ projection = __create_viirs_projection("mollweide") print(type(projection))
5,331,869
def test_bad_username(client: TestClient, session: db.Session): """Logging in with invalid username must generate an error""" user, password = utils.create_user_password(session) bad_email = f"nope_{user.email}" response = client.post("/v2/token", {"username": bad_email, "password": password}) asser...
5,331,870
def get_all_predictions( model: nn.Module, dataloader: DataLoader, device: _Device, threshold_prob: Optional[float] = None, decouple_fn: Optional[_DecoupleFnTest] = None, ) -> _TestResult: """ Make predictions on entire dataset and return raw outputs and optionally class predictions and ...
5,331,871
def plot_perf_stats(returns, factor_returns): """ Create box plot of some performance metrics of the strategy. The width of the box whiskers is determined by a bootstrap. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanat...
5,331,872
def create(user): """ This function creates a new user in the database based on the passed-in user data. :param user: User to create in database :return: 201 on success, 400 on bad postal code, 406 on user exists """ username = user.get("username", None) postalcode = user.get("post...
5,331,873
def show_profile(uid): """ Return serializable users data :param uid: :return String: (JSON) """ user = get_user_by_id(uid) return jsonify(user.serialize)
5,331,874
def degree_correlation(coeffs_1, coeffs_2): """ Correlation per spherical harmonic degree between two models 1 and 2. Parameters ---------- coeffs_1, coeffs_2 : ndarray, shape (N,) Two sets of coefficients of equal length `N`. Returns ------- C_n : ndarray, shape (nm...
5,331,875
def parse_args(): """ Add file_path to the default cdr_cleaner.args_parser argument list :return: an expanded argument list object """ import cdr_cleaner.args_parser as parser help_text = 'path to csv file (with header row) containing pids whose observation records are to be removed' additi...
5,331,876
def name(model): """A repeatable way to get the formatted model name.""" return model.__name__.replace('_', '').lower()
5,331,877
def render_fields( fields: List[Field], instance_name: Optional[str] = None ) -> List[str]: """Renders fields to string. Arguments: fields: The fields to render. instance_name: The name of model instance for which the fields are written. If given, automat...
5,331,878
def get_primary_tasks_for_service(service_arn): """Get the task ARN of the primary service""" response = ecs.describe_services(cluster=cluster, services=[service_arn]) for deployment in response['services'][0]['deployments']: if deployment['status'] == 'PRIMARY': return get_tasks_for_tas...
5,331,879
def post_to_slack(alarm_name, reason, config): """ Send message text to slack channel INPUTS: * alarm_name - subject of the message * reason - message text """ # get params from config file proxy_server = config['proxy_server'] if proxy_server !='': os.environ['HTTP_P...
5,331,880
def load_data(csv_file): """ @type csv_file: string @param csv_file: path to csv file Loads data from specified csv file @rtype: pandas.DataFrame @return: DataFrame from csv file without Month column """ return pd.read_csv(csv_file).drop('Month', 1)
5,331,881
def nearest(array,value): """ Find the index of the array that is close to value Args: array (array): array to be tested value (float): value to be tested Returns: int: index """ return (np.abs(array-value)).argmin()
5,331,882
async def test_read_current_mode(hass, utcnow): """Test that Ecobee mode can be correctly read and show as human readable text.""" helper = await setup_test_component(hass, create_service_with_ecobee_mode) # Helper will be for the primary entity, which is the service. Make a helper for the sensor. ecob...
5,331,883
def fine_tune_model(trainX: np.ndarray, trainy: np.ndarray, cv: int = 5) -> SVC: """Receives training set and run a grid search to find the best hyperparameters. It returns the best model, already trained. Args: trainX (np.ndarray): train array containg embedding images. trainy (np.ndarray...
5,331,884
def get_empty_array_year(year=datetime.now().year, start_end=True, variable_list=['TEST', ], variable_list_dtype=None, record_interval='HH'): """ Allocates and returns new empty record array for given year using list of dtypes (or variable labels as 8byte floats if no dtype list provided) for variables plus...
5,331,885
def service_account_update(sid, groups): """Update service_account groups""" display.vvv("DC/OS: IAM update service_account {}".format(sid)) for g in groups: display.vvv("Assigning service_account {} to group {}".format( sid,g)) cmd = [ 'dcos', 'security...
5,331,886
def validate_geojson(data): """ Validate geojson """ if not (isinstance(data, dict)): return False if not isinstance(data.get('features'), list): return False gj = geojson.FeatureCollection([geojson.Feature(f) for f in data['features']]) return gj.is_valid
5,331,887
def run_wps(conn, config_wpsprocess, **kwargs): """ primary function to orchestrate running the wps job from submission to download (if required) Parameters: ----------- conn: dict, Connection parameters Example: conn = {'domain': 'https://earthobs.defra.gov.uk', ...
5,331,888
def save_episode_to_db(identifier, season, episode, provider, lang, meta): """ save episode's meta info tp database Args: identifier: identifier of the item season: season number of the episode episode: episode number of the episode provider: metadata provider to sabe info fo...
5,331,889
def test_award_category_endpoint(client, award_spending_data): """Test the award_category endpoint.""" # Test that like results are combined and results are output in descending obligated_amount order resp = client.get('/api/v2/award_spending/award_category/?fiscal_year=2017&awarding_agency_id=111') as...
5,331,890
def get_redirect_url(user): """ Analyse user and redirect: Instructor: onboarding is disabled - to /ctms/ onboarding is enabled and not achieved needed percent - to /ctms/onboarding/ onboarding is enabled and achieved needed percent - to /ctms/ Student: ...
5,331,891
def _ds_to_arrraylist( ds, bands, time_dim, x_dim, y_dim, percentile_stretch, image_proc_func=None ): """ Converts an xarray dataset to a list of numpy arrays for plt.imshow plotting """ # Compute percents p_low, p_high = ds[bands].to_array().quantile(percentile_stretch).values array_list ...
5,331,892
def derive_key(secret, salt, iterations=1000, keylen=32): """ Computes a derived cryptographic key from a password according to PBKDF2. .. seealso:: http://en.wikipedia.org/wiki/PBKDF2 :param secret: The secret. :type secret: bytes or unicode :param salt: The salt to be used. :type salt: b...
5,331,893
def copy_ecu(ecu_or_glob, source_db, target_db): # type: (typing.Union[canmatrix.Ecu, str], canmatrix.CanMatrix, canmatrix.CanMatrix) -> None """ Copy ECU(s) identified by Name or as Object from source CAN matrix to target CAN matrix. This function additionally copy all relevant Defines. :param ecu...
5,331,894
def pseudo_import( pkg_name ): """ return a new module that contains the variables of pkg_name.__init__ """ init = os.path.join( pkg_name, '__init__.py' ) # remove imports and 'from foo import' lines = open(init, 'r').readlines() lines = filter( lambda l: l.startswith('__'), lines) cod...
5,331,895
def calc_params_l2_norm(model: torch.nn.Module, bf16: bool): """Calculate l2 norm of parameters """ # args = get_args() if not isinstance(model, list): model = [model] # Remove duplicate params. params_data = [] for model_ in model: for param in model_.parameters(): i...
5,331,896
def gradient_descent(f,init_val_dict, learning_rate=0.001, max_iter=1000, stop_stepsize=1e-6,return_history=False): """ Gradient Descent finding minimum for a single expression INPUTS ======= f: expression init_val_dict:dictionary containing initial value of variables learning_rat...
5,331,897
def my_email(request, recipients, subject, body, sender=None): """ Sends email message """ mailer = get_mailer(request) if not sender: #sender = apex_settings('sender_email') if not sender: sender = 'nobody@example.com' message = Message(subject=subject, ...
5,331,898
def replace_literal_nulls(layer_name): """Replaces literal string representation of null, '<Null>', with a true null value (None in Python). Parameters: layer_name - The name of the layer to replace literal nulls. Returns: None """ logger.debug('Start replacing...
5,331,899