content
stringlengths
22
815k
id
int64
0
4.91M
def expand_template(template, variables, imports, raw_imports=None): """Expand a template.""" if raw_imports is None: raw_imports = imports env = jinja2.Environment(loader=OneFileLoader(template)) template = env.get_template(template) return template.render(imports=imports, variables=variables, raw_import...
5,346,800
def __contains__(container: Any, item: Any, /) -> bool: """Check if the first item contains the second item: `b in a`.""" container_type = type(container) try: contains_method = debuiltins._mro_getattr(container_type, "__contains__") except AttributeError: # Cheating until `for` is unrav...
5,346,801
def generate_search_url(request_type): """Given a request type, generate a query URL for kitsu.io.""" url = BASE_URL_KITSUIO.format(request_type) return url
5,346,802
def register_magic(func: Callable[[Expr], Expr]): """ Make a magic command more like Julia's macro system. Instead of using string, you can register a magic that uses Expr as the input and return a modified Expr. It is usually easier and safer to execute metaprogramming this way. Parameters ...
5,346,803
def flowcellDirFastqToBwaBamFlow(self, taskPrefix="", dependencies=set()) : """ Takes as input 'flowcellFastqDir' pointing to the CASAVA 1.8 flowcell project/sample fastq directory structure. For each project/sample, the fastqs are aligned using BWA, sorted and merged into a single BAM file. The bam...
5,346,804
def ValidatePregnum(resp): """Validate pregnum in the respondent file. resp: respondent DataFrame """ # read the pregnancy frame preg = nsfg.ReadFemPreg() # make the map from caseid to list of pregnancy indices preg_map = nsfg.MakePregMap(preg) # iterate through the respondent pre...
5,346,805
def is_super_admin(view, view_args, view_kwargs, *args, **kwargs): """ Permission function for things allowed exclusively to super admin. Do not use this if the resource is also accessible by a normal admin, use the is_admin decorator instead. :return: """ user = current_user if not user.is_...
5,346,806
def normalize_depth(val, min_v, max_v): """ print 'nomalized depth value' nomalize values to 0-255 & close distance value has high value. (similar to stereo vision's disparity map) """ return (((max_v - val) / (max_v - min_v)) * 255).astype(np.uint8)
5,346,807
def main(): """Build and package OpenSSL.""" parser = argparse.ArgumentParser(prog='OpenSSL setup', description='This script will compile ' 'OpenSSL 1.0.1+ and optionally create ' 'a native macOS packa...
5,346,808
def test_matrix_split_7(interactions_ds): """Test if error is thrown with an invalid value of item_test_ratio (> 1).""" try: matrix_split(interactions_ds, item_test_ratio=2) except Exception as e: assert str(e) == 'Invalid item_test_ratio of 2: must be in the range (0, 1]'
5,346,809
def parse_iori_block(block): """Turn IORI data blocks into `IoriData` objects. Convert rotation from Quaternion format to Euler angles. Parameters ---------- block: list of KVLItem A list of KVLItem corresponding to a IORI data block. Returns ------- iori_data: IoriData ...
5,346,810
def signal_process(logger, pid, signalnum): """Signal process with signal, N/A on Windows.""" try: os.kill(pid, signalnum) logger.info("Waiting for process to report") time.sleep(5) except OSError as err: logger.error("Hit OS error trying to signal process: %s", err) ex...
5,346,811
def ungap_all(align): """ Removes all gaps (``-`` symbols) from all sequences of the :class:`~data.Align` instance *align* and returns the resulting ~data.Container instance. """ result = data.Container() for n,s,g in align: result.append(n, s.translate(None, '-'), g) ...
5,346,812
def expandBcv(bcv): """If the bcv is an interval, expand if. """ if len(bcv) == 6: return bcv else: return "-".join(splitBcv(bcv))
5,346,813
def plot_makers(args): """ Visualize the differential expression of marker genes across clusters. """ adata = sc.read_h5ad(input_file) # choose the plotting types if len(plot_type) != 0: if "violin" in plot_type: print("plotting violin") sc.pl.violin(ada...
5,346,814
def web(): """Start the salmon web server""" app = create_app() # noqa: F841 click.secho(f"Running webserver on http://127.0.0.1:{config.WEB_PORT}", fg="cyan") loop.run_forever()
5,346,815
def get_starting_dir_abs_path() -> str: """ Returns the absolute path to the starting directory of the project. Starting directory is used for example for turning relative paths (from Settings) into absolute paths (those paths are relative to the starting directory). """ if _starting_dir is None: ...
5,346,816
def cluster_profile_platform(cluster_profile): """Translate from steps.cluster_profile to workflow.as slugs.""" if cluster_profile == 'azure4': return 'azure' if cluster_profile == 'packet': return 'metal' return cluster_profile
5,346,817
def get_price_lambda_star_lp_1_cvxpy(w: np.ndarray, c_plus: np.ndarray, psi_plus: np.ndarray) \ -> float: """ Computes lambda_star based on dual program of the projection of w_star. :param w: current state in workload space. :param c_plus: vector normal to the level set in the monotone region '...
5,346,818
def _get_nodes( network: typing.Union[NetworkIdentifier, Network], sample_size: typing.Optional[int], predicate: typing.Callable, ) -> typing.List[Node]: """Decaches domain objects: Node. """ nodeset = [i for i in get_nodes(network) if predicate(i)] if sample_size is not None: s...
5,346,819
def cdl_key(): """Four-class system (grain, forage, vegetable, orchard. Plus 5: non-ag/undefined""" key = {1: ('Corn', 1), 2: ('Cotton', 1), 3: ('Rice', 1), 4: ('Sorghum', 1), 5: ('Soybeans', 1), 6: ('Sunflower', 1), 7: ('', 5), 8: (''...
5,346,820
def create_signal(fs,N): """ create signal with gaussian noise""" dt = 1./fs t = np.linspace(0,N*dt,N)
5,346,821
def test_ebm(ra, dec, smap=0, nest=False): """Make some tests.""" # Parse input coordinates = SkyCoord(ra=ra, dec=dec, unit=units.degree) # Convert to galactic coordinates. l = coordinates.galactic.l.degree b = coordinates.galactic.b.degree theta = (90. - b) * np.pi / 180. phi = l * np....
5,346,822
def colmeta(colname, infile=None, name=None, units=None, ucd=None, desc=None, outfile=None): """ Modifies the metadata of one or more columns. Some or all of the name, units, ucd, utype and description of the column(s), identified by "colname" can be set by using some or all of the listed ...
5,346,823
def get_confusion_matrix_chart(cm, title): """Plot custom confusion matrix chart.""" source = pd.DataFrame([[0, 0, cm['TN']], [0, 1, cm['FP']], [1, 0, cm['FN']], [1, 1, cm['TP']], ], columns=["actual valu...
5,346,824
def get_ppo_plus_eco_params(scenario): """Returns the param for the 'ppo_plus_eco' method.""" assert scenario in DMLAB_SCENARIOS, ( 'Non-DMLab scenarios not supported as of today by PPO+ECO method') if scenario == 'noreward' or scenario == 'norewardnofire': return md(get_common_params(scenario), { ...
5,346,825
def field_display(name): """ Works with Django's get_FOO_display mechanism for fields with choices set. Given the name of a field, returns a producer that calls get_<name>_display. """ return qs.include_fields(name), producers.method(f"get_{name}_display")
5,346,826
def set_trace(response): """ Set a header containing the request duration and push detailed trace to the MQ :param response: :return: """ if TRACE_PERFORMANCE: req_time = int((time.time() - g.request_start) * 1000) trace = { "duration": req_time, "depth"...
5,346,827
def extract_attachments(payload: Dict) -> List[Image]: """ Extract images from attachments. There could be other attachments, but currently we only extract images. """ attachments = [] for item in payload.get('attachment', []): # noinspection PyProtectedMember if item.get("type"...
5,346,828
def yolo3_mobilenet1_0_custom( classes, transfer=None, pretrained_base=True, pretrained=False, norm_layer=BatchNorm, norm_kwargs=None, **kwargs): """YOLO3 multi-scale with mobilenet base network on custom dataset. Parameters ---------- classes : iterable o...
5,346,829
def calculate_levenshtein_distance(str_1, str_2): """ The Levenshtein distance is a string metric for measuring the difference between two sequences. It is calculated as the minimum number of single-character edits necessary to transform one string into another """ distance = 0 buffer_re...
5,346,830
def make_datetime(value, *, format_=DATETIME_FORMAT): """ >>> make_datetime('2001-12-31T23:59:59') datetime.datetime(2001, 12, 31, 23, 59, 59) """ return datetime.datetime.strptime(value, format_)
5,346,831
def log_batch_account_list(batch_mgmt_client, config, resource_group=None): # type: (azure.mgmt.batch.BatchManagementClient, dict, str) -> None """Log Batch account properties from ARM :param azure.mgmt.batch.BatchManagementClient batch_mgmt_client: batch management client :param dict config: co...
5,346,832
def named_struct_dict(typename, field_names=None, default=None, fixed=False, *, structdict_module=__name__, base_dict=None, sorted_repr=None, verbose=False, rename=False, module=None, qualname_prefix=None, frame_depth=1): """Returns a new subclass of StructDict with all f...
5,346,833
def PytorchONNXRuntimeModel(model, input_sample=None, onnxruntime_session_options=None): """ Create a ONNX Runtime model from pytorch. :param model: 1. Pytorch model to be converted to ONNXRuntime for inference 2. Path to ONNXRuntime saved model. :param input_sample: A...
5,346,834
def get_model_python_path(): """ Returns the python path for a model """ return os.path.dirname(__file__)
5,346,835
def intensity_variance(mask: np.ndarray, image: np.ndarray) -> float: """Returns variance of all intensity values in region of interest.""" return np.var(image[mask])
5,346,836
def permute_array(arr, axis=0): """Permute array along a certain axis Args: arr: numpy array axis: axis along which to permute the array """ if axis == 0: return np.random.permutation(arr) else: return np.random.permutation(arr.swapaxes(0, axis)).swapaxes(0, axis)
5,346,837
def convertGMLToGeoJSON(config, outputDir, gmlFilepath, layerName, t_srs='EPSG:4326', flip_gml_coords=False): """ Convert a GML file to a shapefile. Will silently exit if GeoJSON already exists @param config A Python ConfigParser containing the section 'GDAL/OGR' and option 'PA...
5,346,838
def interactive(pluginpath, preselect=None, content_type="video", compact_mode=False, no_crop=False): """ Execute a given kodi plugin :param unicode pluginpath: The path to the plugin to execute. :param list preselect: A list of pre selection to make. :param str content_type: The content type to li...
5,346,839
def dsmatch(name, dataset, fn): """ Fuzzy search best matching object for string name in dataset. Args: name (str): String to look for dataset (list): List of objects to search for fn (function): Function to obtain a string from a element of the dataset Returns: First e...
5,346,840
def populate_listings(num_listings): """Populates the database with seed data.""" fake = Faker() listing_types = [] listing_types_str = ["Houses", "Condos", "Apartments", "Town Houses"] for listing_type_str in listing_types_str: listing_type = ListingType(type_string=listing_type_str) ...
5,346,841
def _generate_flame_clip_name(item, publish_fields): """ Generates a name which will be displayed in the dropdown in Flame. :param item: The publish item being processed. :param publish_fields: Publish fields :returns: name string """ # this implementation generates names on the following ...
5,346,842
def f(q): """Constraint map for the origami.""" return 0.5 * (np.array([ q[0] ** 2, (q[1] - q[0]) ** 2 + q[2] ** 2 + q[3] ** 2, (q[4] - q[1]) ** 2 + (q[5] - q[2]) ** 2 + (q[6] - q[3]) ** 2, q[4] ** 2 + q[5] ** 2 + q[6] ** 2, q[7] ** 2 + q[8] ** 2 + q[9] ** 2, (q[7...
5,346,843
def resize(clip, newsize=None, height=None, width=None): """ Returns a video clip that is a resized version of the clip. Parameters ------------ newsize: Can be either - ``(height,width)`` in pixels or a float representing - A scaling factor, like 0.5 - A fu...
5,346,844
def test_put_available(): """Test put available.""" env = simpy.Environment() container = core.EventsContainer(env=env) container.initialize_container([{"id": "default", "capacity": 10, "level": 5}]) def process(): at_most_5 = container.get_container_event(level=5, operator="le") at...
5,346,845
def tearDown(self): """ Replacement function of original unittest **tearDown** function """ # call options modules function if registered try: if hasattr(self, '__libs_options'): for opt in self.__libs_options: if 'teardown' in opt.REGISTERED: ...
5,346,846
def save_yaml( input_dict: dict, output_path="output.yaml", parents: bool = False, exist_ok: bool = False, ): """Save dictionary as yaml. Args: input_dict (dict): A variable of type 'dict'. output_path (str or pathlib.Path): Path to save the output file. ...
5,346,847
def calc_rt_pytmm(pol, omega, kx, n, d): """API-compatible wrapper around pytmm """ vec_omega = omega.numpy() vec_lambda = C0/vec_omega*2*np.pi vec_n = n.numpy() vec_d = d.numpy() vec_d = np.append(np.inf, vec_d) vec_d = np.append(vec_d, np.inf) vec_kx = kx.numpy().reshape([-1,1])...
5,346,848
def associate_ms(image_id): """ Associate the monitoring sources, i.e., their forced fits, of the current image with the ones in the running catalog. These associations are treated separately from the normal associations and there will only be 1-to-1 associations. The runcat-monitoring source p...
5,346,849
def statistic_bbox(dic, dic_im): """ Statistic number of bbox of seed and image-level data for each class Parameters ---------- dic: seed roidb dictionary dic_im: image-level roidb dictionary Returns ------- num_bbox: list for number of 20 class's bbox num_bbox_im: list for numb...
5,346,850
def test_apply_filter_sweep( frequencies: List[float], frame_rate: int, kind: str, bands: List[Tuple[Optional[float], Optional[float]]], invert: bool, order: int, frequency: float, waveform: str, spectrogram_params: Dict[str, Any], expected: np.ndarray ) -> None: """Test `apply_filte...
5,346,851
def github_youtube_config_files(): """ Function that returns a list of pyGithub files with youtube config channel data Returns: A list of pyGithub contentFile objects """ if settings.GITHUB_ACCESS_TOKEN: github_client = github.Github(settings.GITHUB_ACCESS_TOKEN) else: ...
5,346,852
def reverse_uint(uint,num_bits=None): """ This function takes an unsigned integer and reverses all of its bits. num_bits is number of bits to assume are present in the unsigned integer. If num_bits is not specified, the minimum number of bits needed to represent the unsigned integer is assumed. If n...
5,346,853
def min_by_tail(lhs, ctx): """Element ↓ (any) -> min(a, key=lambda x: x[-1]) """ lhs = iterable(lhs, ctx=ctx) if len(lhs) == 0: return [] else: return min_by(lhs, key=tail, cmp=less_than, ctx=ctx)
5,346,854
def tests_transaction_is_affordable_agent_is_the_seller(): """Check if the agent has the goods (the agent=sender is the seller).""" currency_endowment = {"FET": 0} good_endowment = {"good_id": 0} ownership_state = OwnershipState( amount_by_currency_id=currency_endowment, quantities_by_good_id=go...
5,346,855
def SecureBytesEqual( a, b ): """Returns the equivalent of 'a == b', but avoids content based short circuiting to reduce the vulnerability to timing attacks.""" # Consistent timing matters more here than data type flexibility # We do NOT want to support py2's str type because iterating over them # (below) pro...
5,346,856
def encode(something): """ We encode all messages as base64-encoded pickle objects in case later on, we want to persist them or send them to another system. This is extraneous for now. """ return base64.b64encode(pickle.dumps(something))
5,346,857
def scrape_proposal_page(browser, proposal_url): """ Navigates to the page giving details about a piece of legislation, scrapes that data, and adds a model to the database session. Returns the new DB model. """ browser.get(proposal_url) file_number = int(extract_text(browser.find_element_by...
5,346,858
def installRecommendation(install, uninstall, working_set=working_set, tuples=False): """Human Readable advice on which modules have to be installed on current Working Set. """ installList = [] for i in install: is_in = False for p in working_set: if i[0] == p.key and i[1...
5,346,859
def obsangle(thetas, phis, alpha_obs): """ Return the cosine of the observer angle for the different shockwave segments and and and observer at and angle alpha_obs with respect to the jet axis (contained in yz plane) """ #u_obs_x, u_obs_y, u_obs_z = 0., sin(alpha_obs), co...
5,346,860
def writeJSON(dbFile: str, db: dict, prettyPrint=False): """Write the given json-serializable dictionary to the given file path. All objects in the dictionary must be JSON-serializable. :param str dbFile: Path to the file which db should be written to :param dict db: The json-serializable dictionary to...
5,346,861
def _image_tensor_input_placeholder(input_shape=None): """Returns input placeholder and a 4-D uint8 image tensor.""" if input_shape is None: input_shape = (None, None, None, 3) input_tensor = tf.placeholder( dtype=tf.uint8, shape=input_shape, name='image_tensor') return input_tensor, inp...
5,346,862
def _load_top_bonds(f, topology, **kwargs): """Take a mol2 file section with the heading '@<TRIPOS>BOND' and save to the topology.bonds attribute.""" while True: line = f.readline() if _is_end_of_rti(line): line = line.split() bond = Bond( connection_membe...
5,346,863
def timelength_to_phrase( timelength: spec.Timelength, from_representation: spec.TimelengthRepresentation = None, ) -> spec.TimelengthPhrase: """convert Timelength to TimelengthPhrase ## Inputs - timelength: Timelength - from_representation: str representation name of input timelength ## R...
5,346,864
def order_columns(self: DataFrame, order: str = "asc", by_dtypes: bool = False): """ Rearrange the columns in alphabetical order. An option of rearrangement by dtypes is possible. :param self: :param by_dtypes: boolean to rearrange by dtypes first """ if order not in ['asc', 'desc']: ...
5,346,865
def main(): """ Place videos in test_videos folder Usage python3 pupil_detect.py --video_file "/test_videos/filename.mkv" Default video python3 pupil_detect.py """ try: default_video = "/pupil_detect/test_videos/sample.mkv" parser = argparse.ArgumentParser() parser.add_ar...
5,346,866
def main(): """ do main work """ cmdArgs = sys.argv[1:] if not cmdArgs: msg = "There is no version in args. Current version: " msg += version.current() print(msg) if GIT_EXE: print("Result of 'git describe': ") print(_runGitCmd('describe')) ms...
5,346,867
def reorderWithinGroup(players_by_wins): """Shuffle players with the same score. Args: players_by_wins: a dictionary returned by splitByScore(). Returns a list of the re-ordered player ids. """ for score in players_by_wins.keys(): random.shuffle(players_by_wins[score]) #...
5,346,868
def writebr(text): """@deprecated: (since='0.8', replacement=logging.debug)""" write(text + "\n")
5,346,869
def selection(population, method): """Apply selection method of a given population. Args: population: (list of) plans to apply the selection on. method: (str) selection method: - rws (Roulette Wheel Selection) - sus (Stochastic Universal Selection) - ts (Tou...
5,346,870
def PSL_prefix(row, cols): """Returns the prefix a domain (www.images for www.images.example.com)""" psl_data = psl.search_tree(row[cols[0]]) if psl_data: return(psl_data[1], psl_data[0]) return (None, None)
5,346,871
def build_model(sess,t,Y,model='sde',sf0=1.0,ell0=[2,2],sfg0=1.0,ellg0=[1e5], W=6,ktype="id",whiten=True, fix_ell=False,fix_sf=False,fix_Z=False,fix_U=False,fix_sn=False, fix_ellg=False,fix_sfg=False,fix_Zg=True,fix_Ug=False): """ Args: sess: TensowFlow session ne...
5,346,872
def region(): """Get current default region. Defaults to the region of the instance on ec2 if not otherwise defined. """ parser = _get_parser() parser.parse_args() print(client_region())
5,346,873
def paginatedUrls(pattern, view, kwargs=None, name=None): """ Takes a group of url tuples and adds paginated urls. Extends a url tuple to include paginated urls. Currently doesn't handle url() compiled patterns. """ results = [(pattern, view, kwargs, name)] tail = '' mtail = re.search(...
5,346,874
def invoke(name, region, namespace, eventdata, type, no_color): """ \b Invoke the SCF remote function. \b Common usage: \b * Invoke the function test in ap-guangzhou and in namespace default $ scf remote invoke --name test --region ap-guangzhou --nam...
5,346,875
def set_context(logger, value): """ Walks the tree of loggers and tries to set the context for each handler :param logger: logger :param value: value to set """ _logger = logger while _logger: for handler in _logger.handlers: try: handler.set_context(value...
5,346,876
def write_index(feat_values, chrom, start, stop, stranded_genome_index, unstranded_genome_index): """ Writing the features info in the proper index files. """ # Writing info to the stranded indexes if feat_values[0] != {}: write_index_line(feat_values[0], chrom, start, stop, "+", stranded_genome_ind...
5,346,877
def _to_intraday_trix(date: pd.Timestamp, provider: providers.DataProvider, period: int)-> Tuple[nd.NDArray, nd.NDArray]: """ Returns an ndarray containing the TRIX for a given +data+ and +provider+, averaged across a given +period+. """ # First, get the triple-smoothed 15 peri...
5,346,878
def _decode(integer): """ Decode the given 32-bit integer into a MAX_LENGTH character string according to the scheme in the specification. Returns a string. """ if integer.bit_length() > 32: raise ValueError("Can only decode 32-bit integers.") decoded_int = 0 # Since each byte has ...
5,346,879
def register(name): """Registers a new data loader function under the given name.""" def add_to_dict(func): _LOADERS[name] = func return func return add_to_dict
5,346,880
def get_api_host(staging): """If 'staging' is truthy, return staging API host instead of prod.""" return STAGING_API_HOST if staging else PROD_API_HOST
5,346,881
def get(path, params={}): """Make an authenticated GET request to the GitHub API.""" return requests.get( os.path.join("https://api.github.com/", path), auth=(USER, PASS), params=params ).json()
5,346,882
def delete_user(auth, client): """ Delete a user :auth: dict :client: users_client object """ log("What user you want to delete?") user_to_delete = find_user_by_username(auth, client) if user_to_delete is False: log("Could not find user.", serv="ERROR") return False ...
5,346,883
def downloadComic(url): """ Downloads the latest comic from a range of sites. """ print('Downloading page ' + url + '...') # Request the url, check the status res = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}) res.raise_for_status() soup = bs4...
5,346,884
def plot_figure(ms_label, ms_counts, left, right, params_dict, save_directory, localizations=None, sumof=None): """ Plots amino acid spatistics. Parameters ---------- ms_label : str Mass shift in string format. ms_counts : int Number of peptides in a mass shift. left : list ...
5,346,885
def get_buildbot_stats(time_window : datetime.datetime) -> BuildStats: """Get the statistics for the all builders.""" print('getting list of builders...') stats = BuildStats() for builder in requests.get(BASE_URL).json().keys(): # TODO: maybe filter the builds to the ones we care about s...
5,346,886
def remove_empty(s): """\ Remove empty strings from a list. >>> a = ['a', 2, '', 'b', ''] >>> remove_empty(a) [{u}'a', 2, {u}'b'] """ while True: try: s.remove('') except ValueError: break return s
5,346,887
def quantum_ia(nb_stick: int, past: list, backend_sim: Aer) -> list: """Quantum IA. Args: nb_stick: nb of stick left past: past turn backend_sim: backend for quantum Return: Prediction to use """ def quadratibot(nb_stick: int, past: list, backend_sim: Aer) -> lis...
5,346,888
def test_generate_fn(): """Test generating filename.""" assert generate_fn(var1="this", var2="that", num=7, zero=0) == "marsdata_var1_this-var2_that-num_7-zero_0.txt"
5,346,889
def construct_model_cnn_gram(num_classes, input_shape): """ construct model architecture :param num_classes: number of output classes of the model [int] :return: model - Keras model object """ model = Sequential() model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_unifo...
5,346,890
def test_failed_forecasting_invalid_horizon(app, clean_redis, setup_test_data): """ This one (as well as the fallback) should fail as the horizon is invalid.""" solar_device1: Asset = Asset.query.filter_by(name="solar-asset-1").one_or_none() create_forecasting_jobs( timed_value_type="Power", ...
5,346,891
def get_basic_data(match_info, event): """input: dictionary | output: dictionary updated""" match_info['status'] = event['status']['type']['name'] match_info['start_time'] = event['date'] match_info['match_id'] = event['id'] match_info['time'] = event['status']['displayClock'] match_info['period...
5,346,892
def run(): """ Main method run for Cloudkeeper-OS """ configuration.configure() server.serve()
5,346,893
def handle_solution(f, problem_id, user, lang): """ When user uploads the solution, this function takes care of it. It runs the grader, saves the running time and output and saves the submission info to database. :param f: submission file (program) :param problem_id: the id o...
5,346,894
def convert_blockgrad(node, **kwargs): """ Skip operator """ return create_basic_op_node('Identity', node, kwargs)
5,346,895
def is_complete(node): """ all children of a sum node have same scope as the parent """ assert node is not None for sum_node in reversed(get_nodes_by_type(node, Sum)): nscope = set(sum_node.scope) if len(sum_node.children) == 0: return False, "Sum node %s has no childr...
5,346,896
def step_inplace(Ts, ae, target, weight, depth, intrinsics, lm=.0001, ep=10.0): """ dense gauss newton update with computing similiarity matrix """ pts = pops.inv_project(depth, intrinsics) pts = pts.permute(0,3,1,2).contiguous() # tensor representation of SE3 se3 = Ts.data.permute(0,3,1,2).co...
5,346,897
def _compute_extent_axis(axis_range, grid_steps): """Compute extent for matplotlib.pyplot.imshow() along one axis. :param axis_range: 1D numpy float array with 2 elements; axis range for plotting :param grid_steps: positive integer, number of grid steps in each dimension :return: 1D numpy float ar...
5,346,898
def normalize_path(filepath, expand_vars=False): """ Fully normalizes a given filepath to an absolute path. :param str filepath: The filepath to normalize :param bool expand_vars: Expands embedded environment variables if True :returns: The fully noralized filepath :rtype: str """ filepath...
5,346,899