content
stringlengths
22
815k
id
int64
0
4.91M
def execute( schema: GraphQLSchema, document: DocumentNode, root_value: Any=None, context_value: Any=None, variable_values: Dict[str, Any]=None, operation_name: str=None, field_resolver: GraphQLFieldResolver=None ) -> MaybeAwaitable[ExecutionResult]: """Execute a GraphQL oper...
79,500
def create_quadratic_zones(network_base_dir_name, min_edge_length_str, number_aggregation_levels_str, zone_system_name, consider_is_stop_only_str=False, demand_network_dir=None, glob_str=None): """This function creates quadratic zones over the network area defined by the node positions. I...
79,501
def _two_func_initializer(freqs, signal): """ This is a helper function for heuristic estimation of the initial parameters used in fitting dual peak functions _do_two_lorentzian_fit _do_two_gaussian_fit """ # Use the signal for a rough estimate of the parameters for initialization: r_signal = n...
79,502
def task_benchbase_run(): """ BenchBase: run a specific benchmark. """ def invoke_benchbase(benchmark, config, args): if config is None: config = ARTIFACTS_PATH / f"config/postgres/{benchmark}_config.xml" elif not config.startswith("/"): # If config is not an abs...
79,503
def ReadContourStructures(DCM): """Reads a dicom (.dcm) file and returns a dictionary with contour information. The information including colour, name and contour data Contour data include all the (x,y,z) data points used to build the contour """ contours = [] ds = dicom.read_file(DCM) num...
79,504
def list_projects(request): """ Tags: projects --- Lists projects on cloud. Only supported for EquinixMetal. For other providers,returns an empty list READ permission required on cloud. --- cloud: in: path required: true type: string """ auth_context = auth_...
79,505
def collect_fresh_published_articles_devto() -> None: """ Collect count of articles published on Dev.to in the last hour """ metric_storage = storage.MongoStorage() # Count the fresh articles from API url = 'https://dev.to/api/articles?page=1&per_page=1000&state=fresh' result = requests.get(url) ...
79,506
def run_policy_loop(agent, env, max_num_episodes, fps): """Execute the policy and render onto the screen, using the standard agent interface.""" agent.initialize() episode_rewards = [] for _ in range(max_num_episodes): obs, done = env.reset(), False episode_reward = 0 while not...
79,507
def calc_energy_forces_3D(pos, cell_dim, bond_indices, angle_indices, angle_bond_indices, param): """ calc_energy_forces(pos, cell_dim, bond_indices, angle_indices, angle_bond_indices, vdw_coeff, param) Return tot potential energy and forces on each bead in simulation Parameters ---------- dxy: array_like (fl...
79,508
def test_io00_in_filepath_does_not_exist(tmp_dir_path): """Check an error is raised if there is no file at the in_filepath""" # Given: Input file does not exist in_filepath = tmp_dir_path / 'foo.csv' # When: Attempt to validate the filepath # Then: Error thrown with pytest.raises(FileNotFoundErr...
79,509
def test_spearman_relative_distances(): """Compares relative distances of weighted rankings""" r1 = np.array([0.05, 0.2, 0.7, 0.05]) r2 = np.array([0.23, 0.24, 0.26, 0.27]) r3 = np.array([0.22, 0.24, 0.26, 0.28]) # r2 and r3 should be closer than r2 to r1 assert spearman_squared_distance(r2, r3)...
79,510
def gen_range(start, end): """Return a list of the numbers between |start| and |end|. This filters out surrogate pairs. """ return [x for x in range(start, end) if x < 0xd800 or x >= 0xe000]
79,511
def compact_full(spark_session: SparkSession, base_uri: str, compact_base_uri: str, partition_mode: str): """ When the mode is full, this method will process all data in the feature group by recursivley traversing the prefixes. """ logger.info(f'\n********** Compacting full *************') buck...
79,512
def builtin_s_overloaded(self, context, looping=False): """ Sine function of a number. Sort a sequence. Sort a sequence by a key function. """ a = context.pop() if isinstance(a, BNum): context.push(BType.from_python(cmath.sin(a.value)).simplify()) elif isinstance(a, BSeq): av = a.simplify().value av.sort(...
79,513
def test_enumerate_configs_extension(config_dir): """Assert function retrieves only files with the given extension""" results = list(enumerate_configs(config_dir.strpath, '.ini')) assert 'config.cfg' not in results assert 'module.cfg' not in results assert 'extra.ini' in results assert 'README'...
79,514
def cmp_to_key(mycmp): """functools.cmp_to_key backport""" class KeyClass(object): """Key class""" def __init__(self, obj, *args): # pylint: disable=unused-argument self.obj = obj def __lt__(self, other): return mycmp(self.obj, other.obj) < 0 def __gt__(s...
79,515
def compress_ipv6(ipv6_addr): """ Compress ipv6 address, i.e: compress_ipv6(0001:0001:0000:0000:0000:1111:0000:0000') -> '1:1::1111:0:0' """ ipv6_addr = is_valid_ipv6_ret(ipv6_addr) return socket.inet_ntop(socket.AF_INET6, ipv6_addr)
79,516
def _whois(COMMAND, nick, mask='', prefix='', msg=None): """Returns a WHOIS for nick.""" if conf.supybot.protocols.irc.strictRfc(): assert areNicks(nick), repr(nick) if msg and not prefix: prefix = msg.prefix args = (nick,) if mask: args = (nick, mask) return IrcMsg(prefi...
79,517
def fit_learning_curve(train_set_size, error_test, error_train=None, pinit=(1.0, -1.0), funcs=1): """ returns parameters to predict learning curve as a power function with the form y = a + b * x**alpha where x is the training set size, i.e., the independent variable Yo...
79,518
def load_from_args( *, parser: Optional[argparse.ArgumentParser] = None, arguments: Optional[List[str]] = None, ordered: bool = False ) -> (argparse.Namespace, Storage): """Parses command line arguments, loads config and updates it with unknown args Args: parser (Argument...
79,519
def textsize(txt, font=None): """ Calculates the bounding box of the text, as drawn in the specified font. This method is most useful for when the :py:class:`~luma.core.legacy.font.proportional` wrapper is used. :param txt: the text string to calculate the bounds for :type txt: str :param fo...
79,520
def exercise_2(ns=[1,2,5,10], lamb=5, max_t=7, n_samples_kde=10**4, kde_bandwidth=0.1): """ Implements the whole exercise 2, in which we try to find the differences between the kernel density estimation and the theoretical. Function to plot kernel estimation of the n-th arrival of a ...
79,521
def chirp_amp_phase(v,i, t, start=0.0, end=19.9, down_rate=20000.0, min_freq=0.2, max_freq=20.): """ Calculate amplitude and phase of chirp responses Parameters ---------- sweep_set: SweepSet Set of chirp sweeps start: float (optional, default 0.6) Start of chirp stimulus in...
79,522
def push_code( idx, code ) : """ Push code to browser -------------------- idx : CodeMirror editor index code : code to push """ logger.debug("Pushing code, idx = " + str(idx) + " | " + code ) for ch, replacement in escapechars : code = code.replace( ch, replacement ) lock...
79,523
def off_target_coverage(bam, bed, dir): """ Calculate (using mosdepth and the off_target_bed) the mean coverage in the off target regions, with coverage weighted by length of the intervals. Return as dictionary to be inserted in the coverage DataFrame """ df = mosdepth(bam, bed, dir, prefix="off...
79,524
def get_json_data(): """Fixture to return the json data as a Python variable.""" def _method(_file): """Fixture to return the json data as a Python variable, given a file location Args: _file (str): The location of the json file to input data from. Returns: dic...
79,525
def handle_addRandomPayload(coordinator): """Prompt for payload size and add a random text payload.""" editor = coordinator.active_guis['editor'] editor.root.grab_set() nbytes = simpledialog.askinteger("Add Payload", "How many bytes should the payload be?", ...
79,526
def convert_model(saved_model_dir): """ Convert a SavedModel into Tensorflow Lite Format. `saved_model_dir`: the path to the SavedModel directory returns: the converted Tensorflow Lite model """ logger.info('Converting SavedModel from: {}'.format(saved_model_dir)) converter = tf.lite.TFLiteC...
79,527
def connect(): """ Open a connection to the typesense server. """ with open('/etc/typesense/typesense-server.ini') as f: lines = f.readlines() api_key = [line[10:] for line in lines if line.startswith('api-key = ')][0].rstrip() return typesense.Client({ 'nodes': [{ 'host'...
79,528
def _make_url(raw, sig, quick=True): """ Return usable url. Set quick=False to disable ratebypass override. """ if quick and "ratebypass=" not in raw: raw += "&ratebypass=yes" if "signature=" not in raw: if sig is None: raise IOError("Error retrieving url") raw += "&si...
79,529
def get_component_exceptions( cluster: str, environ: str, topology: str, component: str, role: Optional[str]=None, ) -> Any: """Get exceptions for 'component' for 'topology'.""" base_url = create_url(EXCEPTIONS_URL_FMT) params = { "cluster": cluster, "environ": environ, "topo...
79,530
def setup_mvrf(duthost, tbinfo, localhost): """ Setup Management vrf configs before the start of testsuite """ # Backup the original config_db without mgmt vrf config duthost.shell("cp /etc/sonic/config_db.json /etc/sonic/config_db.json.bak") try: logger.info("Configure mgmt vrf") ...
79,531
async def test_auth_failure(opp, config_entry, aioclient_mock): """Test if user's username or password is not accepted.""" await setup_integration(opp, config_entry, aioclient_mock, auth_fail=True) assert config_entry.state is ConfigEntryState.SETUP_ERROR
79,532
def UnpackHWIDDigest(base, header): """Unpacks HWID digest section.""" offset = base + GBB_HWID_DIGEST_OFFSET size = GBB_HWID_DIGEST_SIZE return GBBField(header.hwid_digest.hex(), offset, size)
79,533
def group_into_dict(items, key_fn): """ Groups items into a dictionary based on a key generated by a given function Examples: items = [ Car(make="Honda", model="Civic"), Car(make="Honda", model="Accord"), Car(make="Ford", model="F150"), Car(make="Ford...
79,534
def _get_table_meta(): """gets the meta data about fields from meta.agolitems """ mapping = {} with pyodbc.connect(config.get_source_connection()[6:]) as connection: cursor = connection.cursor() cursor.execute('SELECT [TABLENAME],[AGOL_PUBLISHED_NAME],[GEOMETRY_TYPE] FROM [SGID].[META]...
79,535
def _estimate_ratios_by_kmeans(obs, guess, **kmeans_kws): """ Adapted kmeans to use norm1 distances (identical to euclidean-norm2 for 1D) and using median() for each guess, to ignore outliers and identify "gear-lines". """ def _1d_kmeans(obs, guess, guess_func, thresh=1e-5): """ The "ra...
79,536
def mock_disabled_reminder_today_offset(mocker): """ Use None to disable the offset and always use the default reminder time """ mocker.patch('mstodo.models.preferences.Preferences.reminder_today_offset', new=None)
79,537
def construct_grammar(grammar_config: GrammarConfig, vocab: Collection[str]) -> state_tree.NQCFG: """Builds the grammar according to `grammar_config`.""" productions = [] # Lexical rules. if grammar_config.grammar_type in ( GrammarType.BERT, GrammarType.ONE_TERM_AT_A_TIME, Gr...
79,538
def get_channel_id(username, API_KEY): """ i might have been entering the wrong usernames or something but, this thing only works half of the time """ url = f"https://www.googleapis.com/youtube/v3/channels" payload = {"forUsername":username, "part":"id,snippet", "key":API_KEY} channel_id...
79,539
def pick_npoints_on_hemisphere(N = 2500): """Randomly pick N points on the upper part of a hemisphere. see http://mathworld.wolfram.com/SpherePointPicking.html """ xs, ys, zs = [], [], [] us, vs = np.random.rand(N) * 2 * np.pi, np.arccos(np.random.rand(N)) for i in range(N): x, y, z = u...
79,540
def to_sequence_example(image, decoder, vocab): """Builds a SequenceExample proto for an image-caption pair. Args: image: An ImageMetadata object. decoder: An ImageDecoder object. vocab: A Vocabulary object. Returns: A SequenceExample proto. """ filename = output_file = os.path.joi...
79,541
def plot_histogram( ax, x, maxima: bool = False, maxima_props: dict = None, annotate_props: dict = None, hist_props: dict = None, ax_props: dict = None, plot_props: dict = None, inter_props: dict = None): """Plot a histogram from 1D data A...
79,542
def test_get_account_not_found_error(mocker): """ Given: Incorrect endpoint When: Creating an Account Then: Verify we do not try 3 times to create an Account And the debug.log is empty """ mocker.patch.object(EWSMailSender, 'Account', return_value=MockAccount(404)...
79,543
def purgedeleted(ctx, # Mandatory main parameter volumeid): """PurgeDeletedVolume immediately and permanently purges a volume that has been deleted. You must delete a volume using""" """DeleteVolume before it can be purged. Volumes are purged automatically after a period of time, so usage ...
79,544
def print_columns(response, response_type): """prints a column style output for a list of networks currently only supports 'pureport accounts network list :param response: the response object :type response: array :returns a formatted output string :rtype: str """ column_values = pi...
79,545
def get_geo(hdfname, monotonic_lons=True,root_name=None): """ given the name of any hdf file from the Cloudsat data archive return lat,lon,time_vals,prof_times,dem_elevation for the cloudsat orbital swath usage: lat,lon,date_times,prof_times,dem_elevation=get_geo(filename) Parameters ...
79,546
def get_metadata(tsuid): """ Get metadata from metadata api If `fid` is in the user provided pattern add that to metadata :param tsuid: TSUID to get metadata from IKATS :type tsuid: str :return: the metadata list for this timeseries :rtype dict """ metadata = IkatsApi.md.read(tsui...
79,547
def get_author_list(): """ Get author list --- responses: 200: description: Returns author list schema: id: AuthorList properties: code: type: string message: ...
79,548
def issue_close_done(): """ Closes any issue that is still open in the done column """ parser = argparse.ArgumentParser(description=issue_close_done.__doc__) parser.add_argument("project", help="the project name") parser.add_argument( "--column", default="done", help="the column to clos...
79,549
def run(name, num_workers, gpu, num_cpus, light, dashboard_url): """Start a new run for a benchmark image""" current_run_inputs = {} last_run_inputs_dir_location = os.path.join( os.environ["HOME"], ".local", "share", "mlbench" ) Path(last_run_inputs_dir_location).mkdir(parents=True, exist_o...
79,550
def parse_extra_metadata_to_selector(option: str, operation: str, value: str) -> str: """Method tries to convert the extra metadata received into selectors :param option: option (extra, python_version, sys_platform) :param operation: (>, >=, <, <=, ==, !=) :param value: value after the operation :r...
79,551
def test_help(): """Check that the output of option_help() matches saved output.""" if os.path.isfile(os.path.join('tests', 'options_help.txt')): ofile = os.path.join('tests', 'options_help.txt') elif os.path.isfile('options_help.txt'): ofile = 'options_help.txt' else: raise Exce...
79,552
def vgg11_quantized(num_classes=10, dataset='cifar10'): """VGG 11-layer model (configuration "A")""" return VGG(make_layers(cfg['A']), num_classes, dataset)
79,553
def get_identity_pool_configuration(IdentityPoolId=None): """ Gets the configuration settings of an identity pool. This API can only be called with developer credentials. You cannot call this API with the temporary user credentials provided by Cognito Identity. See also: AWS API Documentation E...
79,554
def get_paint_dc(win): """ A utility function for obtaining a BufferedPaintDC on Windows. """ if get_platform() == 'windows': dc = wx.BufferedPaintDC(win) dc.SetBrush(wx.Brush((win if win.UseBgCol() else win.GetParent()).GetBackgroundColour())) dc.SetPen(wx.TRANSPARENT_PEN) dc.Dr...
79,555
def average_data(df): """ Average data over eval runs then scenario runs """ df = df.astype({"solved": int}) avg_eval_df = df.groupby(["scenario", "agent", "run"]).mean().reset_index() eval_err = df.groupby(["scenario", "agent", "run"]).sem().reset_index() # run_err = avg_eval_df.groupby(["scenario"...
79,556
def get_value_names_from_timestamp(timestamp, file_id=None, mode='r'): """ Returns value_names from the HDF5 file specified by timestamp. :param timestamp: (str) measurement timestamp of form YYYYMMDD_hhmmsss :return: list of value_names """ folder = a_tools.get_folder(timestamp) h5filepath ...
79,557
def get_element(X, bb, shape): """ returns the bounding box area from the image X """ x,y,w,h = bb x,y,w,h = int(x),int(y),int(w),int(h) return resize(X[y:y+h,x:x+w], shape, mode='constant')
79,558
def convert_verbose(verbose): """Convert the results of the --verbose flag into a list of logger names if --verbose is not provided, args.verbose will be None and logging should be at the info level. if --verbose is provided, but not followed by any arguments, then args.verbose = [] and debug loggi...
79,559
def non_psd_kernel(a, b): """An implementation of a non-psd kernel. Args: a: A vector b: A vector """ if(np.allclose(a,b,rtol=1e-5)): return -1 return 0
79,560
def delta_func(beta): """ Compute delta_beta as per Heuristic 1. """ rep = ((pi * beta) ** (1 / beta)) * beta / (2 * pi * exp(1)) rep = rep ** (1 / (2 * (beta - 1))) return rep
79,561
def pit_one_sat_sqlserver(context): """ Define the structures and metadata to perform PIT load """ context.vault_structure_type = "pit" context.hashed_columns = { "STG_CUSTOMER_DETAILS": { "CUSTOMER_PK": "CUSTOMER_ID", "HASHDIFF": {"is_hashdiff": True, ...
79,562
def run_vector_extraction(input, output, layer, type, where): """Helper function to run r.mapcalc in parallel""" try: gscript.run_command("v.extract", input=input, output=output, layer=layer, type=type, where=where, overwrite=gscript.overwrite(), q...
79,563
def encode(plain_text, a_value, b_value): """ Encode text """ if gcd(a_value, 26) != 1: raise ValueError("a and m must be coprime.") plain_text = list(filter(lambda x: x.isalnum(), list(plain_text))) for index, char in enumerate(plain_text): if char.isalpha(): new...
79,564
def pad_to_shape(d, dshape, mode = "constant"): """ pad array d to shape dshape """ if d.shape == dshape: return d diff = np.array(dshape)- np.array(d.shape) #first shrink slices = tuple(slice(-x//2,x//2) if x<0 else slice(None,None) for x in diff) res = d[slices] #then pad...
79,565
def query_memory_timeline(records, db_url, db_name, db_collection, max_items=20, similarity=TIMELINE_SIMILARITY): """ Query database for similar memory items committed previously """ def timeline_key(item): """ Defines order for timeline report entries """ order = 0 for step...
79,566
def addFooter(template, clientAddress=None): """Add a footer:: -- <3 BridgeDB ________________________________________________________________________ Public Keys: https://bridges.torproject.org/keys This email was generated with rainbows, unicorns, and sparkles for ali...
79,567
def _trace_lines(frame, event, arg): """ Function used for tracing executed lines. Inserts into log: lineno : Tuple[line_str, locals] """ global logger co = frame.f_code parent = frame.f_back.f_code func_name = co.co_name if event == 'line': if func_name.split('::')[-1] ...
79,568
def confirm_superuser_changes(request, user_id): """Renders the confirmation page to confirm the successful changes made to the selected user's account settings by the group superuser. Parameters: request - The request object sent with the call to the confirm page if the request...
79,569
def grad_refactor_simple_2(x, y, z): """ add """ return x * y + z + x * y * z + x + x * y
79,570
def heading_section(title: str, to_list: bool = False): """Construct a section heading. """ linelist = [title, hr(len(title), '=')] return linelist if to_list else '\n'.join(linelist)
79,571
def _featureSelectionReport(dataset, destinationPath=None, withArtifactualFiltering=False): """ Report on feature quality Generates a summary of the number of features passing feature selection (with current settings as definite in the SOP), and a heatmap showing how this number would be affected by changes...
79,572
def _GetStarredIssues(cnxn, logged_in_user_id, services): """Get the set of issues that the logged in user has starred.""" starred_iids = services.issue_star.LookupStarredItemIDs( cnxn, logged_in_user_id) return set(starred_iids)
79,573
async def test_s3_upload_file(tmpdir_factory): """Test uploading file to s3. In addition will test deleting a file and listing objects. """ filename = 'hello_world.txt' path = str(tmpdir_factory.mktemp('upload').join(filename)) with open(path, 'w', encoding='utf-8') as file_handle: fil...
79,574
def headnode_delete_hnic(headnode, hnic): """Delete hnic on a given headnode. If the headnode or hnic does not exist, a NotFoundError will be raised. If the headnode's VM has already created (headnode is not "dirty"), raises an IllegalStateError """ headnode = _must_find(model.Headnode, headno...
79,575
def AdaptReadableDatetime(date_obj): """Adapts a datetime.datetime object to its ISO-8601 date/time notation.""" try: date_obj = date_obj.astimezone(pytz.utc) except ValueError: pass # naive datetime object return date_obj.isoformat()
79,576
def iou_loss(true, pred): """ Calcaulate the intersection over union metric """ intersection = true * pred notTrue = 1 - true union = true + (notTrue * pred) return tf.subtract(1.0, tf.reduce_sum(intersection)/tf.reduce_sum(union))
79,577
def get_gop_pos(frame_idx, representation): """given frame idx to find the group idx and the position inside a group""" gop_index = frame_idx // GOP_SIZE gop_pos = frame_idx % GOP_SIZE if representation in ['residual', 'mv', 'flow']: if gop_pos == 0: # use the previous frame's residual and MV...
79,578
async def _get_server_host_key(host, port=(), *, tunnel=(), family=(), flags=0, local_addr=None, client_version=(), kex_algs=(), server_host_key_algs=(), config=(), options=None): """Retrieve an SSH server's host key This is a coroutine which can b...
79,579
async def test_get_computer(client): """Test case for get_computer """ params = [('depth', 56)] headers = { 'Accept': 'application/json', 'Authorization': 'BasicZm9vOmJhcg==', } response = await client.request( method='GET', path='/computer/api/json', ...
79,580
def prompt_choice(length, select_action, per_page): """ Prompt the user for a choice of entry, to continue or to quit. An invalid choice will repeat the prompt. @param length: the largest choosable value @param select_action: description of what choosing an entry will result in. @param per_pag...
79,581
def _e_step(psamples, W_list, b_list, n_steps=100, eps=1e-5): """ Performs 'n_steps' of mean-field inference (used to compute positive phase statistics) Parameters ---------- psamples : array-like object of theano shared variables State of each layer of the DBM (during the inference pro...
79,582
def get_stencils( stencil_sizes: Tuple[int, ...], offset: Tuple[float, ...], steps: Tuple[float, ...] ) -> Tuple[np.ndarray]: """Computes stencils locations. Generates stencils such that the target offset is placed at (0.,)*ndims. This is needed to obtain correct polynomial constraints. This approach...
79,583
def neo_start(self, container_name, project_name, port, pwd): """ 启动neo4j Args: pwd: port: project_name: self: container_name: Returns: """ # 在js取到 data['state'] != 'CREATE NEO4J SANDBOX' 后将配置展示(仅仅展示) self.update_state( state="START NEO4J SAN...
79,584
def normalize(data, axis=None, index=None): """ Normalize data on the given axis data: a multi-dim array. axis: axis or axes which makes subarrays to be normalized together. E.g., axis=-1 means to normalize the innermost dimension. None (i.e., all axes) or int or tuple of int. index: in...
79,585
def generate_script( bin_dir, script_name, executable=None, code_dir=None, inject_coverage=False, inject_sitecustomize=False, ): """ Generate script """ if not os.path.isdir(bin_dir): os.makedirs(bin_dir) cli_script_name = "cli_{}.py".format(script_name.replace("-", ...
79,586
def make_map(connections): """Return the map of caves based on connections.""" neighbors = collections.defaultdict(list) for start, end in connections: neighbors[start].append(end) neighbors[end].append(start) return neighbors
79,587
def des_key_64(K): """ Return an 64-bit des key by adding a zero to the least significant bit of each character. K should be a 7 char string """ in_key = K + "\0" out_key = [K[0]] for ix in xrange(1,len(in_key)): out_key.append(chr( ((ord(in_key[ix-1]) << (8-ix)) & 0xFF) | (ord(i...
79,588
def l2_norm(x): """ Returns ------- normalization of data in range(0,1) with method euclidean distance Parameters ---------- x: x is we data in shape Matrix note -------- most import numpy as np """ a = np.sqrt(np.square(x)) size_of_vector = np.sqrt(np.sum(a ** 2, a...
79,589
def construct_sql_db(schema, schema_path, db_tql_file_path, postgres_username, postgres_password, overwrite_db=False): """ Handles the initial construction of the local DBpedia SQL database. Throws an ...
79,590
def check_get_variables(model, z0, u_inf, B_ans, N_ans, us_ans, ua_ans): """ Check the results of the `Scales.get_variables()` method """ # Get the model answer (B, N, us, ua) = model.get_variables(z0, u_inf) # Check the results assert_approx_equal(B, B_ans, significant=6) assert_approx...
79,591
def info_to_table(rows: list) -> Tuple[list, list]: """ Formats raw row data into a table format that will be used with other render functions. This function is where column headers should be defined. Arguments: rows(list): Rows of data Return: List : List of column...
79,592
def calcExRIndex(inputRasterImage,mode): """ calcExRIndex. :param inputRasterImage: (Image) input raster image. :param mode: (String) mode RGB or GBR :returns outputRasterImage: (Image) output raster image. """ if mode=='RGB' : chRed,chGreen,chBlue = cv2.split(inputRasterImage) else: chGreen,chRed,chBlu...
79,593
def grade_assignments(notebook_dir, image="ucbdsinfra/otter-grader", verbose=False, scripts=False, no_kill=False, output_path="./", debug=False, zips=False, pdfs=False): """ Grades multiple submissions in a directory using a single docker container. If no PDF assignment is wanted, set all three PDF para...
79,594
def random_type(): """Return type of monster.""" types = ( ('Slime'), ('Skeleton'), ('Zombie'), ('Blue Wizard'), ('Red Wizard'), ('Bear'), ('Wolf'), ('Barbarian'), ('Minotaur'), ('Goblin'), ('Ogre'), ) return choice(...
79,595
def get_ip(server, net_type, ip_version): """Return the server's IP of the given type and version.""" if net_type in server.addresses: for ip in server.addresses[net_type]: if ip['version'] == ip_version: return ip['addr']
79,596
def neptune_cluster_parameter_ssl_enforcement_check(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict: """[Neptune.4] Neptune cluster parameter groups should enforce SSL connections to Neptune databases""" response = neptune.describe_db_cluster_parameter_groups() for parametergroup ...
79,597
def random_crop(image, boxes, labels): """ Performs a random crop operation with multiple possibilities as in the paper. Helpful when detecting bigger objects(windows, doors, buildings). Ref: https://github.com/amdegroot/ssd.pytorch/blob/master/utils/augmentations.py """ height, width = image.s...
79,598
def impute_missing_values(data, verbose: int, estimator): """Imputation of missing values using the IterativeImputer method. All categorical features would be encoded using the label encoding and then imputed using Iterative imputer with the estimator chosen Args: new_data (Dataframe): Data to be i...
79,599