content
stringlengths
22
815k
id
int64
0
4.91M
def train_model(model, X_data_train, y_target_train, early_stopping): """ :param model: compiled model :param X_data_train: 3d array :param y_target_train: 1d array :param flag: true if googlnet (output expect 3d array) else false if 1d array for output :return: fitted model """ if earl...
5,310,500
def toPath(prefix, metric): """Translate the metric key name in metric to its OS path location rooted under prefix.""" m = metric.replace(".", "/") + ".wsp" return os.path.join(prefix, m)
5,310,501
def bn_model_pytorch(): """Same as bn_model but with PyTorch.""" import torch import torch.nn as nn bounds = (0, 1) num_classes = 10 class Net(nn.Module): def forward(self, x): assert isinstance(x.data, torch.FloatTensor) x = torch.mean(x, 3) x = t...
5,310,502
def check_point(x, y, d, length, alpha): """ Проверяет точку на принадлежность волноводу Точка в ск Федера """ if -d / 2 <= y <= d / 2: return 0 <= x <= length or is_inside_cone(x - length, y, d, alpha)
5,310,503
def load_result_from_file(filename): """Load a results dictionary file (.json) to a Result object. Note: The json file may not load properly if it was saved with a previous version of the SDK. Args: filename (str): filename of the dictionary Returns: tuple(Result, dict): ...
5,310,504
def comments_list(request, locker_id, submission_id): """Returns a list of comments for the specified submission""" submission = get_object_or_404(Submission, pk=submission_id) if submission.locker.discussion_enabled(): is_owner = submission.locker.is_owner(request.user) is_user = submission...
5,310,505
def runProject(samweb, projectname=None, defname=None, snapshot_id=None, callback=None, deliveryLocation=None, node=None, station=None, maxFiles=0, schemas=None, application=('runproject','runproject',get_version()), nparallel=1, quiet=False ): """ Run a project arguments (use keyword arguments...
5,310,506
def test_add_multiple(data_dir, expected_dir): """Adds a single new file to an index that doesn't have a parent""" with tmp_chdir(data_dir): runner = CliRunner() result = runner.invoke(application.main, ['add', '2012/new_file.txt', 'new_file2.txt']) assert result.exit_code == 0 assert_...
5,310,507
def prepare(ctx, resource_config, **_): """Prepares an AWS Cloudwatch Events Event""" # Save the parameters ctx.instance.runtime_properties['resource_config'] = resource_config
5,310,508
def massage_spectrum(cov, shape): """given a spectrum cov[nl] or cov[n,n,nl] and a shape (stokes,ny,nx) or (ny,nx), return a new ocov that has a shape compatible with shape, padded with zeros if necessary. If shape is scalar (ny,nx), then ocov will be scalar (nl). If shape is (stokes,ny,nx), then ocov will be (sto...
5,310,509
def get_device_by_label(session, label): """get Device by label Args: session: Active database session label: label to get device that matches Returns: device found or None """ return session.query(Resource).filter(Resource.label == label).one_or_none()
5,310,510
def fetch_MX_exchange(sorted_zone_keys, s): """ Finds current flow between two Mexican control areas. Returns a float. """ req = s.get(MX_EXCHANGE_URL) soup = BeautifulSoup(req.text, 'html.parser') exchange_div = soup.find("div", attrs={'id': EXCHANGES[sorted_zone_keys]}) val = exchange...
5,310,511
def mlp(X_train, targets): """Fully Connected Neural Network, known as MLP(Multi-Layer Perceptons). """ feature_number = X_train.shape[1] output_number = targets.shape[1] model = tf.keras.Sequential() model.add(Dense((output_number+feature_number)/2+40, input_dim=feature_numb...
5,310,512
def printYellow(string): """ :param string: (str) """ print(colored(string, 'yellow'))
5,310,513
def add_stop_name(elem, jore_stop): """Add stop name tag in Finnish and/or Swedish from JORE stop object with tag 'name' or 'name:sv' if the tag is missing. """ tags = get_osm_tags(elem) if "name" not in tags.keys(): create_tag(elem, "name", jore_stop.name) STATS["named"] += 1 i...
5,310,514
def test_search_Fibonacci(): """Do we find the Fibonacci snippets we know we have? """ coll = Collection(snippets) for path in list(coll.search("Fibo")): assert re.match("fibo.*\\.py", os.path.basename(path)) != None
5,310,515
def initialize(): """ Initial processing before the comparisons begin. """ print_welcome_text() config.truth_db = PGDetails(**config.truth_db_config) config.test_db = PGDetails(**config.test_db_config) message = click.style("Retrieving details for all tables. This could take awhile... ", fg="yello...
5,310,516
def make_ir_context() -> ir.Context: """Creates an MLIR context suitable for JAX IR.""" context = ir.Context() mhlo.register_mhlo_dialect(context) chlo.register_chlo_dialect(context) return context
5,310,517
def get_fobj(fname, mode='w+'): # pragma: no cover """Obtain a proper file object. Parameters ---------- fname : string, file object, file descriptor If a string or file descriptor, then we create a file object. If *fname* is a file object, then we do nothing and ignore the specified *...
5,310,518
def make_2d_plot(p, noise=None, overlap=None): """ Make a 2D plot for the specified slice. @param p: The full path to the results file. @param noise: The degree of noise to use, if none all are used. @param overlap: The degree of overlap to use, if none all are used. """ # Get the data with ...
5,310,519
def parse_patch(patch_string): """Parse a patch string and return the affected files.""" patch = DiffParser(patch_string.splitlines()) return patch.files
5,310,520
def adjust_color_lightness_scalar(r, g, b, factor): """ r,g,b between 0 and 1 factor between 0 and +infty, but lightness bounded between 0 and 1 """ h, l, s = rgb_to_hls_scalar(r, g, b) l = max(min(l * factor, 1.0), 0.0) r, g, b = hls_to_rgb_scalar(h, l, s) return r,g,b
5,310,521
def update_contour(): """ Finds contours in the current color image and uses them to update contour_center and contour_area """ global contour_center global contour_area image = rc.camera.get_color_image() if image is None: contour_center = None contour_area = 0 els...
5,310,522
def get_sample_ids(fams): """ create a ditionary mapping family ID to sample, to subID Returns: e.g {'10000': {'p': 'p1', 's': 's1'}, ...} """ sample_ids = {} for i, row in fams.iterrows(): ids = set() for col in ['CSHL', 'UW', 'YALE']: col = 'SequencedA...
5,310,523
def mesh_conway_join(mesh): """Generates the join mesh from a seed mesh. Parameters ---------- mesh : Mesh A seed mesh Returns ------- Mesh The join mesh. Examples -------- >>> mesh = Mesh.from_polyhedron(6) >>> join = conway_join(mesh) >>> join.number_...
5,310,524
def add_petitcode_hot_clear(input_path: str, database: h5py._hl.files.File, wavel_range: Optional[Tuple[float, float]] = None, teff_range: Optional[Tuple[float, float]] = None, spec_res: Optional[float] = 100...
5,310,525
def calcbw(K, N, srate): """Calculate the bandwidth given K.""" return float(K + 1) * srate / N
5,310,526
def get_all_devices(auth): """ Function to get all devices for the account linked to the token :param auth: pyawair.auth.AwairAuth object which contains a valid authentication token :return: Object of Dict type which contains a list of all devices for this account """ response = requests.get("ht...
5,310,527
def supports_display(handler_input): # type: (HandlerInput) -> bool """Check if display is supported by the skill.""" #check the incoming request to the skill from the AVS to determine if the device the user invoked the skill on has a screen try: if hasattr(handler_input.request_envelope.context...
5,310,528
def format_sqlexec(result_rows, maxlen): """ Format rows of a SQL query as a discord message, adhering to a maximum length. If the message needs to be truncated, a (truncated) note will be added. """ codeblock = "\n".join(str(row) for row in result_rows) message = f"```\n{codeblock}```" ...
5,310,529
def is_calibration_produced(drs4_pedestal_run_id: int, pedcal_run_id: int) -> bool: """ Check if both daily calibration (DRS4 baseline and charge calibration) files are already produced. """ return ( drs4_pedestal_exists(drs4_pedestal_run_id) and calibration_file_exists(pedcal_run_id...
5,310,530
def parse_date_literal(ast, _variables=None): """ Parse a string value node in the AST. """ if isinstance(ast, StringValueNode): # TODO: Must be a datetime. return ast.value return INVALID
5,310,531
def gen_lubm_graph(destination_folder: Path, count: int) -> Path: """ Generates LUBM graph by specified number of generated graphs to create one LUBM graph :param destination_folder: directory to save the graph :type destination_folder: Path :param count: number of generated graphs :type count:...
5,310,532
def generate_initial_population(network_info, network_layout): """ Generates the initial population for network optimization. :param NetworkInfo network_info: Object storing global network information (information about the whole optimization) :param NetworkLayout ...
5,310,533
def split_zip(zip_code): """ split the zip code into 5 and 4 digit codes """ if not valid_zip(zip_code): return None, None if len(zip_code) == 5: return zip_code[:5], None return zip_code[:5], zip_code[-4:]
5,310,534
def parse_initial_conditions( ic: Dict[str, Any], start_date_simulation: pd.Timestamp, virus_strains: Dict[str, Any], ) -> Dict[str, Any]: """Parse the initial conditions.""" ic = {**INITIAL_CONDITIONS} if ic is None else {**INITIAL_CONDITIONS, **ic} if isinstance(ic["assort_by"], str): ...
5,310,535
def rq2responses(request): """ Converts a request to a list of responses. :param request: Flask Request object :return: list of response strings """ i, responses = 0, [] for i in range(int(request.form['num_questions'])): name = Question.ID_FORMAT % i if request.form.get(nam...
5,310,536
def image_show(image, nrows=1, ncols=1, cmap='gray', **kwargs): """ Taken from : https://github.com/gmagannaDevelop/skimage-tutorials/blob/master/lectures/4_segmentation.ipynb """ fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=(16, 16)) ax.imshow(image, cmap='gray') ax.axis...
5,310,537
def load_logger(env_name, simple=False): """ Load and apply logging settings for given environment name. :param str env_name: environment name :raise: ConfigError if problems loading """ if simple: logging.basicConfig(level=logging.DEBUG) return config_path = get_config_path('lo...
5,310,538
def normalize(arr): """Normalizes an array to its mean values. Parameters ---------- arr : array-like | shape = [N] The array to normalize. Returns ------- normalized_array : np.ndarray | shape = [arr.shape] """ return arr / np.mean(arr)
5,310,539
def find_matching_parens( assertion_str, matched_quotes, errors: List[ValidationError] ) -> Tuple[List[Pair], List[ValidationError]]: """Find and return the location of the matching parentheses pairs in s. Given a string, s, return a dictionary of start: end pairs giving the indexes of the matching par...
5,310,540
def regex_sub_groups_global(pattern, repl, string): """ Globally replace all groups inside pattern with `repl`. If `pattern` doesn't have groups the whole match is replaced. """ for search in reversed(list(re.finditer(pattern, string))): for i in range(len(search.groups()), 0 if search.group...
5,310,541
def _parse( filepath : str ) -> list: """ [summary] Arguments: filepath {str} -- [description] Returns: list -- [description] """ with open( filepath, 'r' ) as f: raw_data = f.read( ) # not readlines( ), as this needs to be one long string data = list( map( int, raw_data.split( ) ) ) return data
5,310,542
def train_generator(dataloader, device, batch_size, n_cv, limit_count=None): """TRAINING BATCH GENERATOR Args: wav_list (str): list of wav files feat_list (str): list of feat files batch_size (int): batch size wav_transform (func): preprocessing function for waveform Return...
5,310,543
def cufftExecD2Z(plan, idata, odata): """Execute double precision real-to-complex forward transform plan.""" status = _libcufft.cufftExecD2Z(plan, idata, odata) cufftCheckStatus(status)
5,310,544
def get_app_sec_eval(config_id: Optional[int] = None, security_policy_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAppSecEvalResult: """ Use this data source to access information about an existing resource. """ __args__ ...
5,310,545
def _flush_dscl_cache(): """ Flush dscl cache """ __salt__["cmd.run"](["dscacheutil", "-flushcache"], python_shell=False)
5,310,546
def write_merged_bioassembly(inpath, outdir, outname, force_rerun=False): """Utility to take as input a bioassembly file and merge all its models into multiple chains in a single model. Args: infile (str): Path to input PDB file with multiple models that represent an oligomeric form of a structure. ...
5,310,547
def get_final_loss(src_logits, src_one_hot_labels, dst_logits, finetune_one_hot_labels, global_step, loss_weights, inst_weights): """Gets the final loss for .""" if FLAGS.uniform_weight: inst_weights = 1.0 src_loss = get_loss(src_logits, inst_weights, src_one_hot_labels) ...
5,310,548
def causal_kernel(alpha): """ The causal kernel. .. math:: w(\\tau) = [\\alpha^2 \\tau \\exp(- \\alpha \\tau)]_+ example: .. code-block:: python >>> kernel('causal', {'alpha': 0.4}) """ def causal(t): v = alpha**2 * t * np.exp(-alpha*t) v[v<0] = 0 return v return caus...
5,310,549
def read_nasa_planets(csv_filename, eliminate=('SWEEPS-11', 'HD 41004 B', 'PSR J1719-1438', 'K2-22'), fill_missing=manual_data, need_ages=True, ...
5,310,550
def e8(s: str) -> str: """ Encode Unicode string with stanard options """ return s.encode('utf-8', 'ignore')
5,310,551
def _get_user_authentication_credentials(client_secret_file, scopes, credential_directory=None, local=False): """Returns user credentials.""" if credential_directory is None: credential_directory = os.getcwd() elif credential_directory == 'global': home_dir = os.path.expanduser('~') ...
5,310,552
def download_metadata(download_dir: PathOrStr = DATA_DIR, verbose: int = 0): """Download and extract metadata archive. Reuses local data if already exists and is up to date. Args: download_path: Optional file path to download to """ download_dir = Path(download_dir).expanduser() download_di...
5,310,553
def download_seed_seqs(acc): """ Download seed sequences from PFAM. Input ----- acc : str Accession number of a Pfam domain Output ------ fasta : str Seed sequences in fasta format """ url = "http://pfam.xfam.org/family/%s/alignment/seed" % acc req = request...
5,310,554
def fit_spline(points, smoothing=None, order=None, force_endpoints=True): """Fit a parametric smoothing spline to a given set of x,y points. (Fits x(p) and y(p) as functions for some parameter p.) Parameters: points: array of n points x,y; shape=(n,2) smoothing: smoothing factor: 0 requires perfect...
5,310,555
def get_list_of_teams(): """Get a list of all teams.""" teamlist = [] for team in cursor.execute('SELECT * from teams'): teamlist.append(team[0]) # man isn't it cool that order matters return teamlist
5,310,556
def test_nearest_num(): """Make sure it calculates the nearest number properly.""" dsc = DamageStatCalc() assert dsc.find_closest_level(4) == (5, -1) assert dsc.find_closest_level(215) == (200, 15) assert dsc.find_closest_level(17) == (15, 2)
5,310,557
def linear_activation_forward(A_prev, W, b, activation): """ activation of forward propagation :param A_prev: np.array, activations from previous layer :param W: np.array, weights matrix of current layer :param b: np.array, biases vector of current layer :param activation: str, activation mode o...
5,310,558
def stoll_auc_subjects(ds, skip_samples=0, dur_samples=10000): """ Calculate AUC for each subject in a dataset using the Stoll (2013) classification method """ aucs = [] for sub in np.unique(ds.trials_ppid): tpr = [] fpr = [] tr = ds.trials[ds.trials_ppid == sub, :] ...
5,310,559
def drop_database(bind: Engine, database: str) -> None: """Drop a database (schema) in postgresql. """ logger.info('[plenario] Drop database %s' % database) connection = bind.connect() connection.execute('commit') connection.execute('drop database %s' % database) connection.close()
5,310,560
def stations_level_over_threshold(stations, tol): """Returns a list of the tuples, each containing the name of a station at which the relative water level is above tol and the relative water level at that station""" output = [] for station in stations: relative_level = station.relative_...
5,310,561
def plot_classification_performance(cm=None, y_true=None, y_pred=None, cmap="RdBu", answer_label="answer", predict_label="predict", ax=None): """Plot model"s classification performance. Args: cm (array) : Confusion matrix whose i-th row and j-th column entry indicates the number of samples wit...
5,310,562
def get_issue_close_comment(testcase): """Generate the closing comment of the issue""" return ISSUE_ClOSE_COMMENT_TEXT.format( bug_information=testcase.bug_information)
5,310,563
def new_membership_approval_handler( sender, instance: MembershipApproval, created=False, **kwargs ): """ :param instance: The MembershipApproval instance :param created: True or False, whether this instance is new or not. """ if created and not instance.processed: if settings.APPROVAL_...
5,310,564
def select_ensembl_species(species, table): """ Filters the species of interests, called group, from a table containing all the species in the Current release """ # Read the species table from Ensembl Genomes df = pd.read_csv(table, sep='\t', index_col=False) # Filter out the species that are ...
5,310,565
def normalize_power_spectrum(Q): """transform spectrum to complex vectors with unit length Parameters ---------- Q : np.array, size=(m,n), dtype=complex cross-spectrum Returns ------- Qn : np.array, size=(m,n), dtype=complex normalized cross-spectrum, that i...
5,310,566
def img2tensor( img: pillow.Image, size: tuple = None, ) -> torch.Tensor: """ Args: img: image to convert size: (W, H) of output tensor Returns: tensor of shape (1, 3, H, W) the first dimension (batch size) is neccesary for the CNN 3 channels are for R...
5,310,567
def handler(event, context): """ function handler """ if 'imageDiscard' in event and event['imageDiscard']: return None if 'imageLocation' not in event or len(event['imageLocation']) == 0: return None if 'imageObjects' not in event or len(event['imageObjects']) == 0: re...
5,310,568
def set_smb_netbios_name(session, smb_netbios_name, force="YES", return_type=None, **kwargs): """ Get VPSA cache :type session: zadarapy.session.Session :param session: A valid zadarapy.session.Session object. Required. :type smb_netbios_name: str :param smb_netbios_name: The smb ne...
5,310,569
def update_one_process_choose_output(process_manager_obj): """Create all widgets with buttons to show output Args: process_manager_obj (JupyterProcessesManager): Processes manager """ list_buttons = [] ##### # BUTTON STDOUT button_show_stdout = ipywidgets.Button( description...
5,310,570
def extract_nice_name(spec, nuke_pattern=True): """ >>> extract_nice_name("foo (bar::baz)") 'bar::baz' """ if nuke_pattern: # get rid of pattern i = spec.find("[") j = spec.find("]", i + 1) if i == -1: assert j == -1 else: assert j != -1 pattern = spec[i + 1:j] match = re_pattern.match(patter...
5,310,571
def reset(): """Re-creates the resources directory. """ MergedResource.objects.all().delete() shutil.rmtree(os.path.join(settings.MEDIA_ROOT, RESOURCES_DIRECTORY)) create_directory()
5,310,572
def _random_correlated_image(mean, sigma, image_shape, alpha=0.3, rng=None): """ Creates a random image with correlated neighbors. pixel covariance is sigma^2, direct neighors pixel covariance is alpha * sigma^2. Parameters ---------- mean : the mean value of the image pixel values. sigma :...
5,310,573
def gen_polygons_cdnp(pdnp, name='cdnp_polygons', radius=.01): """ :param trimeshmodel: :param name: :param radius: TODO :return: author: weiwei date: 20210204 """ collision_node = CollisionNode(name) # counter = 0 for geom in pdnp.findAllMatches('**/+GeomNode'): geom...
5,310,574
def diameter(aabb): """ Compute the length of the diameter of an AABB. :param aabb: AABB defined by its min and max point. :type aabb: Pair of n-dimensional vectors :return: Length of the diameter of the AABB. """ if not is_valid(aabb): return None return np.linalg.norm(aabb[1] ...
5,310,575
def deregister_device(device): """ Task that deregisters a device. :param device: device to be deregistered. :return: response from SNS """ return device.deregister()
5,310,576
async def peko(message): """peko""" """returns [content, embed, view]""" url = "https://holodex.net/api/v2/users/live" params = { "channels": "UC1DCedRgGHBdm81E1llLhOQ,UCdn5BQ06XqgXoAxIhbqw5Rg,UC5CwaMl1eIgY8h02uZw7u8A,UChAnqc_AY5_I3Px5dig3X1Q" } headers = {"Content-Type": "application/js...
5,310,577
def sequential_colors(n): """ Between 3 and 9 sequential colors. .. seealso:: `<https://personal.sron.nl/~pault/#sec:sequential>`_ """ # https://personal.sron.nl/~pault/ # as implemented by drmccloy here https://github.com/drammock/colorblind assert 3 <= n <= 9 cols = ['#FFFFE5', '#FFFB...
5,310,578
def _format_layer_terms(layer): """Get the terms for the given layer for display in Graphviz""" formatter = FormattingHelper(layer) if hasattr(layer, 'inception_date') or hasattr(layer, 'expiry_date'): formatter.append_term('coverage', _format_coverage(layer)) formatter.append('participation',...
5,310,579
def run(filename=WORDLIST_FILE, *, force=False): """ read the wordlist from a file and scrap it """ print('getting wordlist data from {}'.format(filename)) words = get_wordlist(filename) scrap(words, reference=True, force=force)
5,310,580
def certify(): """Authenticate with Twitter using Tweepy and return Twitter API object. :returns: Twitter API object :rtype: Twitter API object """ consumer_key = os.environ["CONSUMER_KEY"].decode("utf_8") consumer_secret = os.environ["CONSUMER_SECRET"].decode("utf_8") access_token = os.env...
5,310,581
def _get_mask(Size, idxi, idxj, win_type): """Compute a mask of zeros with a window at a given position. """ idxi = np.array(idxi).astype(int) idxj = np.array(idxj).astype(int) win_size = (idxi[1] - idxi[0] , idxj[1] - idxj[0]) wind = build_2D_tapering_function(win_size, win_type) mask =...
5,310,582
def rollup_command(): """ Maintain a collection of monthly rollup JSON blobs from raw observation JSON blobs """ direct_name = "w1rollup" _, applied_name = os.path.split(sys.argv[0]) p = LocalArgumentParser() if applied_name != direct_name: p.add_argument('rollup_command') a = p....
5,310,583
def record_state(state): """ Record the application state when this blueprint is registered. Here we exact appropriate configuration values from the application config, if they're available, and use environment variables or defaults if not. """ global EVENTICS_CONFIG app = state.app ...
5,310,584
def _check_tool(cfg: config.Config, bin_name: str, name: str, min_version: Version) -> bool: """Check availability and version of a tool.""" if not _check_availability(bin_name, name): return False bin_path = shutil.which(bin_name) assert bin_path is not None ver_line = execu...
5,310,585
def init_func_global() -> JobInitStateReturn: """ Init function for the job :return: INIT or NOT_INIT state for the job """ return JobInitStateReturn(True)
5,310,586
def get_orbit_from_metadata(mds): """Get orbit for a set of SLC ids. They need to belong to the same day.""" day_dt, all_dts, mission = util.get_date_from_metadata(mds) logger.info("get_orbit_from_metadata : day_dt %s, all_dts %s, mission %s" %(day_dt, all_dts, mission)) return fetch("%s.0" % all_dts[0...
5,310,587
def download_dataset(dataset: str = 'data_testing'): """Download testing data from internet. Args: dataset (str): the name of the dataset to download """ path_dataset: Path = path_repo_root / dataset # Early abort if testing data already exist. if path_dataset.exists(): logger...
5,310,588
def fibonacci(n): """Return the n-th Fibonacci number""" if n in (0,1): return n return (fibonacci(n - 2) + fibonacci(n - 1)) # Can trace the recursive function with a decorator
5,310,589
def clear_managers(): """Remove all current DBAPI2 managers. All pools and connections are disposed. """ for manager in proxies.values(): manager.close() proxies.clear()
5,310,590
def random_color() -> np.ndarray: """Generate a random color (RGB).""" return np.array(np.random.rand(3))
5,310,591
def get_king_moves(): """Generate the king's movement range.""" return [(1, 0), (1, -1), (-1, 0), (-1, -1), (0, 1), (0, -1), (-1, 1), (1, 1)]
5,310,592
def describe_secret(SecretId=None): """ Retrieves the details of a secret. It does not include the encrypted fields. Only those fields that are populated with a value are returned in the response. To run this command, you must have the following permissions: See also: AWS API Documentation Exce...
5,310,593
def v206b_directga(): """ This tries to run """ np.random.seed(42) date = get_date() ray.init(num_cpus=5) @ray.remote def single_func(seed, index, name, game, method, results_directory, args, date, get_pop, w): # A single function to run one seed and one param combination. ...
5,310,594
def _unpack_topk(topk, lp, hists, attn=None): """unpack the decoder output""" beam, _ = topk.size() topks = [t for t in topk] lps = [l for l in lp] k_hists = [(hists[0][:, i, :], hists[1][:, i, :], hists[2][i, :]) for i in range(beam)] if attn is None: return topks, lps, ...
5,310,595
def share_map(map_url_hash): """Create shareable version of current map using crypotgraphic hash at end of address""" user_map = Map.query.filter(Map.map_url_hash == map_url_hash).one() map_id = user_map.map_id places_on_map = Place.query.filter(Place.map_id == map_id, Place.place_active == True).all() ...
5,310,596
def _darknet_reshape(inputs, params, attrs, prefix): """Process the reshape operation.""" new_attrs = {} new_attrs['shape'] = attrs.get('shape') return get_relay_op('reshape')(*inputs, **new_attrs)
5,310,597
def create_import_request(git_source_url, project=None, repository=None, requires_authorization=False, user_name=None, git_service_endpoint_id=None, organization=None, detect=None): """Create a git import request...
5,310,598
def CreateVectorObject(volumeRef, name): """ Creates a c4d.VolumeObject with the VolumeRef passed. Names this VolumeObject with the passed argument. :param volumeRef: The VolumeRef to use within the VolumeObject. :type volumeRef: maxon.frameworks.volume.VolumeRef :param name: The name of the in...
5,310,599