content
stringlengths
22
815k
id
int64
0
4.91M
async def send_e_wechat_request(method, request_url, data): """ 发送企业微信请求 :param method: string 请求方法 :param request_url: string 请求地址 :param data: json 数据 :return: result, err """ if method == 'GET': try: async with aiohttp.ClientSession() as session: a...
8,500
def bottom(iterable, key=operator.identity): """Generates elements from min to max. >>> tuple(bottom((3, 2, 1))) (1, 2, 3) >>> tuple(bottom((1, 2, 3, 4), lambda x: x % 2 == 0)) (1, 3, 2, 4) """ h = [] for i, value in enumerate(iterable): # Use the index as a tie breaker. ...
8,501
def no_missing_terms(formula_name, term_set): """ Returns true if the set is not missing terms corresponding to the entries in Appendix D, False otherwise. The set of terms should be exactly equal, and not contain more or less terms than expected. """ reqd_terms = dimless_vertical_coordinates[f...
8,502
def initialize(X, num_clusters): """ initialize cluster centers :param X: (torch.tensor) matrix :param num_clusters: (int) number of clusters :return: (np.array) initial state """ num_samples = X.shape[1] bs = X.shape[0] indices = torch.empty(X.shape[:-1], device=X.device, dtype=tor...
8,503
def run_ansible(ansible_playbook, artifacts_directory): """ :param ansible_playbook: dict which is equal to Ansible playbook in YAML :return: empty """ random_id = get_random_int(1000, 9999) os.makedirs(TMP_DIR, exist_ok=True) tmp_current_dir = os.path.join(TMP_DIR, str(random_id)) os.m...
8,504
def check_workspace_id(workspace_id): """ Validate that workspace_id matches the GUID regex """ if workspace_id is None: raise ParameterMissingException('Workspace ID must be provided') search = re.compile(GUIDOnlyRegex, re.M) if not search.match(workspace_id): raise InvalidPara...
8,505
def test_exceptions() -> None: """Test if writer raises correct exceptions when needed """ # create without reader or name exception_flag = False try: writer1 = Writer() print(writer1) writer1.release() except AssertionError as _: exception_flag = True asser...
8,506
def unflatten_satisfies(old_satisfies): """ Convert satisfies from v2 to v1 """ new_satisfies = {} for element in old_satisfies: new_element = {} # Handle exsiting data add_if_exists( new_data=new_element, old_data=element, field='narrative' ...
8,507
def require_backend(required_backend): """ Raise ``SkipTest`` unless the functional test configuration has ``required_backend``. :param unicode required_backend: The name of the required backend. :returns: A function decorator. """ def decorator(undecorated_object): @wraps(undecorat...
8,508
def clip(src, shp): """ :param src: shapefile class with karst polygons. sinks.shp in db. :param shp: shapefile class with basin boundary. :return: shapefile output and class with karst. """ driver = ogr.GetDriverByName("ESRI Shapefile") src_ds = driver.Open(src.path, 0) src_layer = sr...
8,509
def app_advertise_complete(): """executed on disconnect of BLE """ print("app_advertise_complete")
8,510
def fixed_data(input_df, level, db_name): """修复日期、股票代码、数量单位及规范列名称""" # 避免原地修改 df = input_df.copy() df = _special_fix(df, level, db_name) df = _fix_code(df) df = _fix_date(df) df = _fix_num_unit(df) df = _fix_col_name(df) return df
8,511
def get_nsg_e(ocp: AcadosOcp): """ number of slack variables for linear constraints on terminal state and controls """ return int(ocp.constraints.idxsg_e.shape[0])
8,512
def generate_test_samples(y, input_seq_len, output_seq_len): """ Generate all the test samples at one time :param x: df :param y: :param input_seq_len: :param output_seq_len: :return: """ total_samples = y.shape[0] input_batch_idxs = [list(range(i, i + input_seq_len+output_seq_l...
8,513
def ancestors(graph, *args, stop=None): """Iterate over all ancestor nodes in a DiGraph given one or more initial Nodes. """ if stop is None: stop = set() for node in args: if node in stop: pass else: yield node stop.add(node) ...
8,514
def get_tv_torrent_torrentz( name, maxnum = 10, verify = True ): """ Returns a :py:class:`tuple` of candidate episode Magnet links found using the Torrentz_ torrent service and the string ``"SUCCESS"``, if successful. :param str name: the episode string on which to search. :param int maxnum: optional a...
8,515
def plot_diagram_density(dgm, lognorm=True, diagonal=True, show=False, labels=False, ax=None, **hist_style): """ Plot the histogram of point density. Arguments: dgm (Diagram): See for example `init_diagrams`. Keyword Arguments: bins (int): bins for histogram, s...
8,516
def errfunc(p, x, y, numpoly, numharm): """ function to calc the difference between input values and function """ return y - fitFunc(p, x, numpoly, numharm)
8,517
def create_token_column(col): """ Creates a cleaned and tokenised column based on a sentence column in a dataframe """ # Convert it to lowercase col = col.str.lower() # Remove all non-alphanumeric characters col = col.replace(r"\W", " ", regex=True) # Collapse repeated spaces ...
8,518
def get_browser(request, ): """ 获取浏览器名 :param request: :param args: :param kwargs: :return: """ ua_string = request.META['HTTP_USER_AGENT'] user_agent = parse(ua_string) return user_agent.get_browser()
8,519
def test_transformer_pipeline_empty(): """Test that the pipeline doesn't fail with empty input""" orig_config = Config().from_str(cfg_string) nlp = util.load_model_from_config(orig_config, auto_fill=True, validate=True) tagger = nlp.get_pipe("tagger") train_examples = [] for t in TRAIN_DATA: ...
8,520
def predict(X, centroids, ccov, mc): """Predict the entries in X, which contains NaNs. Parameters ---------- X : np array 2d np array containing the inputs. Target are specified with numpy NaNs. The NaNs will be replaced with the most probable result according to the GMM model p...
8,521
def info(*msgs): #=============================================================================== """ Display INFO level messages. """ display_messages(msgs, tag = 'INFO')
8,522
def rotate_image(img, angle): """ Rotate an image around its center # Arguments img: image to be rotated (np array) angle: angle of rotation returns: rotated image """ image_center = tuple(np.array(img.shape[1::-1]) / 2) rot_mat = cv2.getRotationMatrix2D(image_center, angle...
8,523
def standardize_1d(self, func, *args, autoformat=None, **kwargs): """ Interpret positional arguments for the "1D" plotting methods so usage is consistent. Positional arguments are standardized as follows: * If a 2D array is passed, the corresponding plot command is called for each column of data ...
8,524
def build_transformer_crf_model(config): """ """ src_vocab_size = config["src_vocab_size"] src_max_len = config["src_max_len"] n_heads = config["n_heads"] d_model = config["d_model"] d_ff = config["d_ff"] d_qk = config.get("d_qk", d_model//n_heads) d_v = config.get("d_v", d_model//n...
8,525
def test_resource_without_path(config: Config, db: SQLAlchemy): """Test resources that don't have url_prefix.""" class FooDef(Resource): VIEW = View __type__ = 'Foo' def __init__(self, app, import_name=__name__.split('.')[0], static_folder=None...
8,526
def frac_mole_to_weight(nfrac, MM): """ Args: nfrac(np.array): mole fraction of each compound MM(np.array): molar mass of each compound """ return nfrac * MM / (nfrac * MM).sum()
8,527
def get_close_hour_local(): """ gets closing hour in local machine time (4 pm Eastern) """ eastern_tz = timezone('US/Eastern') eastern_close = datetime.datetime(year=2018, month=6, day=29, hour=16) eastern_close = eastern_tz.localize(eastern_close) return str(eastern_close.astimezone().hour...
8,528
def parse_structure(node): """Turn a collapsed node in an OverlayGraph into a heirchaical grpah structure.""" if node is None: return None structure = node.sub_structure if structure is None: return node.name elif structure.structure_type == "Sequence": return {"Sequence" : [parse_structure(n) f...
8,529
def softmax_kl_loss(input_logits, target_logits, sigmoid=False): """Takes softmax on both sides and returns KL divergence Note: - Returns the sum over all examples. Divide by the batch size afterwards if you want the mean. - Sends gradients to inputs but not the targets. """ assert input_...
8,530
def default_init_weights(module_list, scale=1, bias_fill=0, **kwargs): """Initialize network weights. Args: module_list (list[nn.Module] | nn.Module): Modules to be initialized. scale (float): Scale initialized weights, especially for residual blocks. Default: 1. bias_fill (...
8,531
def cut_rod_top_down_cache(p, n): """ Only difference from book is creating the array to n+1 since range doesn't include the end bound. """ r = [-100000 for i in range(n + 1)] return cut_rod_top_down_cache_helper(p, n, r)
8,532
def column_ids_to_names(convert_table, sharepoint_row): """ Replace the column ID used by SharePoint by their column names for use in DSS""" return {convert_table[key]: value for key, value in sharepoint_row.items() if key in convert_table}
8,533
def recursive_olsresiduals(res, skip=None, lamda=0.0, alpha=0.95, order_by=None): """ Calculate recursive ols with residuals and Cusum test statistic Parameters ---------- res : RegressionResults Results from estimation of a regression model. skip : int, defau...
8,534
def main(): """Fetches and saves attachments from emails using Gmail API. Creates a Gmail API service object and applies custom query, then fetches all attachments and saves them along message metadata into seperate folders. """ credentials = get_credentials() http = credentials.authorize(h...
8,535
def is_RationalField(x): """ Check to see if ``x`` is the rational field. EXAMPLES:: sage: from sage.rings.rational_field import is_RationalField as is_RF sage: is_RF(QQ) True sage: is_RF(ZZ) False """ return isinstance(x, RationalField)
8,536
def add_nearest_neighbor_value_field(ptype, coord_name, sampled_field, registry): """ This adds a nearest-neighbor field, where values on the mesh are assigned based on the nearest particle value found. This is useful, for instance, with voronoi-tesselations. """ field_name = ("deposit", f"{pty...
8,537
def create_directory_if_not_exists(dir_path): """ Create directory path if it doesn't exist """ if not path_exists(dir_path): mkdir_p(dir_path) print('Creating {}'.format(dir_path)) return True return False
8,538
def test_hel_gal(): """ Note: slight offsets between Astropy / gary transformation and this transformation are expected because this assumes (l,b)=(0,0) is the Galactic center. Astropy uses a more modern measurement of the position of the GC. """ np.random.seed(42) RSUN = 8.*u.kpc V...
8,539
def rdkit_smiles(): """Assign the SMILES by RDKit on the new structure.""" new_smiles = "" mol = Chem.MolFromMolFile("output.sdf") new_smiles = Chem.MolToSmiles(mol, isomericsmiles=False) return new_smiles
8,540
def load_ref_case(fname, name): """Loads PV power or Load from the reference cases :param fname: Path to mat file :type fname: string :param name: Identifier for PV Power or Load :type name: string :return: Returns PV power or load from the reference case :rtype: numpy array ...
8,541
def make_unique_id(): """Make a new UniqueId.""" return uuid.uuid4() # return UniqueId(uuid.uuid4())
8,542
def read_uni(filename): """ Read a '*.uni' file. Returns the header as a dictionary and the content as a numpy-array. """ with gzip.open(filename, 'rb') as bytestream: header = _read_uni_header(bytestream) array = _read_uni_array(bytestream, header) return header, array
8,543
def _F(startmat,endmat): """Calculate the deformation tensor to go from start to end :startmat: ndarray :endmat: ndarray :returns: ndarray """ F=np.dot(endmat,np.linalg.inv(startmat)) return F
8,544
def get_docstrings(target, functions): """ Proceses functions in target module and prompts user for documentation if none exists. :param target: Loaded target python module :param functions: List of defined functions in target module :returns: Dict containing raw comments entered by user """ ne...
8,545
def calculatePredictions(ReviewsD, userIDTest, scoreTest, simmilarities): """ Function finds userIDTest in all simmilar items and uses all the scores for prediction calculation Returns actualScore and predictedScore for further calculations of finding rmse and mse values ""...
8,546
def plotPSD(): """Enter plot menu""" freq_range= ui.PSDEdit.text() msg=subprocess.run(["python", os.path.join(script_dir,r"cli.py"), "plot", "--freq", freq_range, '--plot_type','psd']) if msg.returncode != 0: ui.errorBrowser.setText(_translate("SAKEDSP","Check Terminal for Errors"))
8,547
def ensure_absolute_url(query_url): """This function adds the base URL to the beginning of a query URL if not already present. .. versionadded:: 3.2.0 :param query_url: The query URL that will be utilized in an API request :type query_url: str :returns: The query URL that includes a top-level doma...
8,548
def create_data_source( simiotics_client: Simiotics, source_id: str, s3_root: str, ) -> data_pb2.Source: """ Registers an S3 data source against a Simiotics data registry Args: simiotics_client Simiotics client -- see the simiotics.client module source_id ...
8,549
def func_2(x: float, c: float, d: float) -> float: """ Test function 2. """ return x + c + d
8,550
async def async_get(server: t.Union[Server, str], view_or_url: str, view_data: Kwargs = None, session: aiohttp.ClientSession = None, params: Kwargs = None, **kwargs) -> Response: """Sends a GET request.""" return await async_request('get', server, view_or_url, view_data=v...
8,551
def DictionaryAddSchemaVersion(builder, schemaVersion): """This method is deprecated. Please switch to AddSchemaVersion.""" return AddSchemaVersion(builder, schemaVersion)
8,552
def test_generate_model_circuit(): """Test that a model circuit is randomly generated.""" model_circuit = quantum_volume.generate_model_circuit( 3, 3, random_state=np.random.RandomState(1)) assert len(model_circuit) == 24 # Ensure there are no measurement gates. assert list( model_c...
8,553
def isInner(x1, y1, x2, y2, scale): """ Currently, it's a rectangular kernal Other options: rectangular f(x) = 1 if a <= scale <= b else 0 I don't get the rest of them http://saravananthirumuruganathan.wordpress.com/2010/04/01/introduction-to-mean-shift-algorithm/ """ dis...
8,554
def main(args): """ Main function that calls all other functions Parameters ---------- args: Input arguments to the script """ global model_init global survey global path_to_figures global mf_type survey = args.survey machine = args.machine nproc = arg...
8,555
def add_sulci(fig, dataview, extents=None, height=None, with_labels=True, overlay_file=None, **kwargs): """Add sulci layer to figure Parameters ---------- fig : figure or ax figure into which to plot image of curvature dataview : cortex.Dataview object dataview containing data to be...
8,556
def build_puller_tdwhdfs_config_param( cluster_name, connector, data_id, topic, kafka_bs, fs_default_name, hadoop_job_ugi, hdfs_data_dir, username, secure_id, secure_key, ): """ tdw 数据拉取任务配置 :param cluster_name: 集群名 :param connector: 任务名 :param data_id: da...
8,557
def generate_error_reply(message): """ Send an error to the user """ # Construct header, question = ORIGINAL_HEADER, ORIGINAL_QUESTION header._rcode = Header.RCODE_SRVFAIL reply = header.pack() + question.pack() # Send ss.sendto(reply, ORIGINAL_ADDRESS)
8,558
def make_url(issue, sites=[]): """ Compose search terms and sites with url safe encoding. """ print('issue', issue) terms = issue.strip().split() terms = [quote(x, safe='') for x in terms] # TODO test with just spaces url = 'https://duckduckgo.com/?q=' + '+'.join(terms) if sites: url +=...
8,559
def order_by_digestibility(sv_reg, pft_id_set, aoi_path): """Calculate the order of feed types according to their digestibility. During diet selection, animals select among feed types in descending order by feed type digestibility. Because digestibility is linearly related to crude protein content...
8,560
def match(pattern, sexp, known_bindings={}): """ Determine if sexp matches the pattern, with the given known bindings already applied. Returns None if no match, or a (possibly empty) dictionary of bindings if there is a match Patterns look like this: ($ . $) matches the literal "$", no bindings (...
8,561
def who_is_it(image_path, database, model): """ Implements face recognition for the happy house by finding who is the person on the image_path image. Arguments: image_path -- path to an image database -- database containing image encodings along with the name of the person on the image ...
8,562
def generate_map_bin(geo, img_shape): """Create a q map and the pixel resolution bins Parameters ---------- geo : pyFAI.geometry.Geometry instance The calibrated geometry img_shape : tuple, optional The shape of the image, if None pull from the mask. Defaults to None. Returns ...
8,563
def parse_pileup(instream): """ Given a stream of the output of samtools mpileup, count the number of reads at each position supporting the reference allele and the number supporting a non-reference allele. Arguments: - instream: input file stream containing samtools mpileup output ...
8,564
def read_poly_data(filename): """ This function.. :param filename: :return: """ # Check which PolyData reader should be used if ".vtk" in filename: reader = vtk.vtkPolyDataReader() reader.SetFileName(filename) reader.Update() return reader.GetOutput() eli...
8,565
def main(): """Clean and convert pandas DataFrame main data, and save it as .csv. Function is used in github acrion. For details look at .github/workflows/dataloader.yml """ file_id = '1iAgNVDOUa-g22_VcuEAedR2tcfTlUcbFnXV5fMiqCR8' file_url = 'https://docs.google.com/spreadsheets/d/{file_id}/gviz/tq...
8,566
def wklobjective_converged(qsum, f0, plansum, epsilon, gamma): """Compute finale wkl value after convergence.""" obj = gamma * (plansum + qsum) obj += epsilon * f0 obj += - (epsilon + 2 * gamma) * plansum return obj
8,567
def addFavDirections(request): """ Add favourite stop of currently logged in user by number. Currently works with the URL: http://localhost:8000/api/add-fav-stop/<number> """ try: user = request.user origin = str(request.query_params.get('origin')) destination = str(reque...
8,568
def hpat_pandas_dataframe_index(df): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.DataFrame.index Examples -------- .. literalinclude:: ../../../examples/dataframe/dataframe_index.py :language: python :lines...
8,569
def divide(a, b): # pragma: no cover """Divide two tensors. Args: a (tensor): First tensor. b (tensor): Second tensor. Returns: tensor: `a` divided by `b`. """
8,570
def _get_should_cache_fn(conf, group): """Build a function that returns a config group's caching status. For any given object that has caching capabilities, a boolean config option for that object's group should exist and default to ``True``. This function will use that value to tell the caching decora...
8,571
def set_difference(lst1, lst2): """returns the elements and indicies of elements in lst1 that are not in lst2""" elements = [] indicies = [] for indx, item in enumerate(lst1): if item not in lst2: elements.append(item) indicies.append(indx) return elements, indicies
8,572
def test_split_sentences(): """ Test shallow tokenization """ s = ( "3.janúar sl. keypti ég 64kWst rafbíl. Hann kostaði € 30.000. \n" "200.000 manns mótmæltu.\n" "Hér byrjar ný setning" ) g = t.split_into_sentences(s) sents = list(g) assert len(sents) == 4 assert s...
8,573
def dub( videoFile, outputDir, srcLang, targetLangs=[], storageBucket=None, phraseHints=[], dubSrc=False, speakerCount=1, voices={}, srt=False, newDir=False, genAudio=False, noTranslate=False): """Translate and dub a movie. Args: videoFile (String): File to dub o...
8,574
def _get_dict(path): """ Parameters __________ path: string or array Path to json file. In case a list of paths is provided instead, read them all and merge then into a single dict. Assumes depth two. Returns _______ d: dict Dictionary containing marker information....
8,575
def _super_check(args, names, op, fmt, msg, val_err): """ A flexible function is used to check whether type or value of variables is valid, which supports in both graph/pynative mode. Args: args(any): 'args' is used as one of argument for operation function and format function. names(an...
8,576
def train(*args, **kwargs): """Generate a training request """ yield from _generate(*args, **kwargs) req = jina_pb2.Request() req.request_id = 1 req.train.flush = True yield req
8,577
def obter_novo_username() -> str: """ -> Pede um novo nome de usuário. :return: Retorna o novo nome de usuário. """ username = input('Qual é o seu nome? ') arquivo = 'arquivos_json/nome_de_usuario.json' with open(arquivo, 'w') as obj_arq: json.dump(username, obj_arq) return us...
8,578
def print_head(df): """ Print the first five lines of df. Parameters ---------- df : pandas dataframe """ print(df.head(n=5))
8,579
def BDD100K_MOT2020(path: str) -> Dataset: """`BDD100K_MOT2020 <https://bdd-data.berkeley.edu>`_ dataset. The file structure should be like:: <path> bdd100k_box_track_20/ images/ train/ 00a0f008-3c67908e/ ...
8,580
def _parse_block_postheader(line): """ (209)**************!*****************!!*************... """ parts = line[1:].split(')', 1) qlen = int(parts[0]) if not len(parts[1]) == qlen: logging.warn("postheader expected %d-long query, found %d", qlen, len(parts[1])) r...
8,581
def _remove_dimer_outliers(bond_lengths, energies, zscore_cutoff=3.0): """Removes outliers """ z_score = stats.zscore(energies) idx_keep = np.where(z_score < zscore_cutoff)[0] return bond_lengths[idx_keep], energies[idx_keep]
8,582
def get_auth_token(cmd_args=None): """ :param cmd_args: An optional list of additional arguments to pass on the command line :return: The current user's token """ r = Result("whoami") r.add_action(oc_action(cur_context(), "whoami", cmd_args=['-t', cmd_args])) r.fail_if("Unable to determine ...
8,583
def _is_toplevel_repository_dir(directory): """Returns if a directory is a git or mercurial directory. This works by searching for a file or directory named `.git` or `.hg` in the directory. This works for both submodules and normal repositories. """ return (os.path.exists(os.path.join(directory, "...
8,584
def breakOnException(func=None, *, exceptionList=Exception, debugger='pdb'): """ A function wrapper that causes debug mode to be entered when the wrapped function throws a specified exception. Parameters ---------- func : The function to wrap. exceptionList : An exception or tuple of excep...
8,585
def hash_sid(sid: str) -> str: """ Hash a SID preserving well-known SIDs and the RID. Parameters ---------- sid : str SID string Returns ------- str Hashed SID """ if re.match(WK_SID_PATTERN, sid): return sid usr_sid = re.match(SID_PATTERN, sid) ...
8,586
def horizontal_move(t, h_speed=-2/320): """Probe moves horizontally at h_speed [cm/s]""" return 0.*t, h_speed*t, 2/16 + 0*t
8,587
def fix_pdp_post(monkeypatch): """monkeyed request /decision/v1 to PDP""" def monkeyed_policy_rest_post(uri, json=None, **kwargs): """monkeypatch for the POST to policy-engine""" return MockHttpResponse("post", uri, json=json, **kwargs) _LOGGER.info("setup fix_pdp_post") pdp_client.Poli...
8,588
def del_project(): """ @api {post} /v1/interfaceproject/del InterfaceProject_删除项目 @apiName interfaceProDel @apiGroup Interface @apiDescription 删除项目 @apiParam {int} id 子项目id @apiParam {int} all_project_id 总项目id @apiParamExample {json} Request-Example: { "id": 1, "all_p...
8,589
def draw_pattern_fill(viewport, psd, desc): """ Create a pattern fill. """ pattern_id = desc[Enum.Pattern][Key.ID].value.rstrip('\x00') pattern = psd._get_pattern(pattern_id) if not pattern: logger.error('Pattern not found: %s' % (pattern_id)) return None, None panel = get_p...
8,590
def register_post(): """Registriraj novega uporabnika.""" username = bottle.request.forms.username password1 = bottle.request.forms.password1 password2 = bottle.request.forms.password2 # Ali uporabnik že obstaja? c = baza.cursor() c.execute("SELECT 1 FROM uporabnik WHERE username=%s", [usern...
8,591
def check_format_input_vector( inp, dims, shape_m1, sig_name, sig_type, reshape=False, allow_None=False, forbid_negative0=False, ): """checks vector input and returns in formatted form - inp must be array_like - convert inp to ndarray with dtype float - inp shape must be ...
8,592
def get_proyecto_from_short_url(short_url): """ :param short_url: :return: item for Proyecto """ item = Proyecto.objects.get(short_url=short_url) if item.iniciativas_agrupadas is not None and \ item.iniciativas_agrupadas != '' and '{' in \ item.iniciativas_agrupadas: ...
8,593
def select_x(data, order=None): """ Helper function that does a best effort of selecting an automatic x axis. Returns None if it cannot find x axis. """ if data is None: return None if len(data) < 1: return None if order is None: order = ['T', 'O', 'N', 'Q'] els...
8,594
def map_clonemode(vm_info): """ Convert the virtualbox config file values for clone_mode into the integers the API requires """ mode_map = {"state": 0, "child": 1, "all": 2} if not vm_info: return DEFAULT_CLONE_MODE if "clonemode" not in vm_info: return DEFAULT_CLONE_MODE ...
8,595
def update_dashboard(dashboard_slug): """Update Dashboard Update an existing Dashboard --- tags: - "Dashboards" parameters: - name: dashboard_slug in: path type: string required: true - name: name in: body schema: ...
8,596
def dqn(n_episodes=2000, max_t=1000, eps_start=1.0, eps_end=0.01, eps_decay=0.995, target=100.0, model='checkpoint.pth'): """Deep Q-Learning. Params ====== n_episodes (int): maximum number of training episodes max_t (int): maximum number of timesteps per episode eps_star...
8,597
def latLon2XY(xr, yr, lat, lon, ieast=1, azimuth=0): """ Calculate the cartesian distance between consecutive lat,lon points. Will bomb at North and South Poles. Assumes geographical coordinates and azimuth in decimal degrees, local Cartesian coordinates in km. :param xr: Reference longitude, n...
8,598
def create_pipeline_opts(args): """Create standard Pipeline Options for Beam""" options = pipeline_options.PipelineOptions() options.view_as(pipeline_options.StandardOptions).runner = args.runner google_cloud_options = options.view_as(pipeline_options.GoogleCloudOptions) google_cloud_options.project = args....
8,599