content
stringlengths
22
815k
id
int64
0
4.91M
def monthFormat(month: int) -> str: """Formats a (zero-based) month number as a full month name, according to the current locale. For example: monthFormat(0) -> "January".""" months = [ "January", "February", "March", "April", "May", "June", "July", ...
5,309,400
def test_postponed_resolution_error(): """ This test checks that an unresolvable scopre provider induces an exception. This is checked by using a scope provider which always returns a postponed object. """ ################################# # META MODEL DEF ###############################...
5,309,401
def _jsonEncoder(obj): """ Encodes C{decimal.Decimal} and C{datetime.datetime} objects. """ if isinstance(obj, datetime.datetime): obj = datetime_util.convertToIso8601(obj) elif isinstance(obj, decimal.Decimal): decimalTuple = obj.as_tuple() if decimalTuple.exponent == 0:...
5,309,402
def usage(fd: TextIO = stderr) -> None: """ usage(fd: TextIO = stderr) -> None Print usage information to the specified descriptor. """ fd.write(__doc__.format(argv0=argv[0])) fd.flush()
5,309,403
def optimization_step(A, Y, Z, beta, apply_cg, mode='prox_cg1'): """ Optimization step for several different modes: - 'prox_exact' takes an exact proximal step - 'prox_cgN' takes an approximate proximal step, generated by N conjugate gradient steps - 'gradient' performs a gradient step; ...
5,309,404
def AbdomenLiverSegmentation( task: str, weight: str, image_path: str, save_path: Optional[str] = None, gpus: str = "-1" ) -> Tuple[np.array, np.array]: """ """ from medimodule.Liver import LiverSegmentation Checker.check_input_type(image_path, ["hdr", "img", "nii"]) ...
5,309,405
def get_city_country_continent(city, country, continent): """Get id of city, country, and continent from database.""" if city is not None: if City.objects.filter(name=city).count() == 0: # Create new city object if not already in database city = City(name=city) city.s...
5,309,406
def wcscopy( donor, recipient, dext=1, rext=1, verbose=False ): """ Copy the WCS header keywords from the donor fits file into the header of the recipient fits file. dext and rext specify the fits extensions to use for the donor and recipient, respectively. """ import pyfits donfits = pyfi...
5,309,407
def PIL_decode_parts(parts): """Decode and assemble a bunch of images using PIL.""" tokens = set() rows = [] max_image_size = options["Tokenizer", "max_image_size"] for part in parts: # See 'image_large_size_attribute' above - the provider may have seen # an image, but optimized the ...
5,309,408
def assert_pandas_installed(): """ Assert that pandas is installed. :raises ImportError: When pandas is not installed on the system """ if not is_pandas_installed(): if not is_pandas_installed(): raise ImportError( "You must install the \"pandas\" data analysis l...
5,309,409
def distance2line(line_start, line_end, point): """ Calculate distance from a line between the start and end to an arbitary point in space :param line_start: array, position of the start of the line :param line_end: array, position of the end of the line :param point: array, arbitary position in sp...
5,309,410
def create_linking_info(ctx, user_link_flags, files): """ Creates CcLinkingInfo for the passed user link options and libraries. Args: ctx - rule context user_link_flags - (list of strings) link optins, provided by user files - (LibrariesToLink) provider with the library files """ ...
5,309,411
def build_fnln_contact(individual_contact): """ Expected parameter format for individual_contact ('My Name', 'myname@gmail.com') Sample output: {'email': 'myname@gmail.com', 'name': 'My Name'} """ return { "email": individual_contact[-1], "name": individual_...
5,309,412
def test_expression_comparison(evaluate, memory, input, expected): """Test expression comparison.""" instance = evaluate(input, skip_builtins=True) assert instance.memory == memory(expected)
5,309,413
def add_usdan_day(day_item): """ Unique ID for each day item is the time attr. Assumes a day_item is in the form: { 'time': <time>, 'breakfast':<meal_items>, 'lunch':<meal_items>, 'dinner':<meal_items>, 'brunch'... }y where <meal_items...
5,309,414
def shortcut( sn ) : """ For a given snana.SuperNova object sn, quickly convert the posterior probabilities computed using the 'mid' class fractions prior into the posterior probabilities you get when adopting the 'galsnid' prior. NOTE: we do not account for redshift dependence here, ...
5,309,415
def _create_device_profile(device, pv_type, iprofile_id): """Create a profile disk or partition, depending on the physical volume type.""" device_profile = None if pv_type == constants.PV_TYPE_DISK: device_profile = _create_disk_profile(device, iprofile_id) elif pv_type == constants.PV_T...
5,309,416
def initialize_with_zeros(dim): """ 此函数为w创建一个维度为(dim,1)的0向量,并将b初始化为0。 参数: dim - 我们想要的w矢量的大小(或者这种情况下的参数数量) 返回: w - 维度为(dim,1)的初始化向量。 b - 初始化的标量(对应于偏差) """ w = np.zeros(shape = (dim,1)) b = 0 #使用断言来确保我要的数据是正确的 assert(w.shape == (dim,...
5,309,417
def string_to_datetime(datetime_string): """ Should be in the form: 2012-08-29T04:00:00+0000 This is the inverse of datetime_to_string """ log.debug("Converting string: %s to datetime", datetime_string) dt = datetime.strptime(datetime_string, "%Y-%m-%dT%H:%M:%S+0000") return dt.replace(...
5,309,418
def create_vissat_config_from_ssr_config( vissat_config_ofp, dataset_dp, workspace_dp, ssr_config, clean_data, crop_image, derive_approx, choose_subset, colmap_sfm_perspective, inspect_sfm_perspective, reparam_depth, colmap_mvs, aggregate_2p5d, aggregate_3d, ): ...
5,309,419
def _process_tce(tce): """Processes the light curve for a Kepler TCE and returns an Example proto. Args: tce: Row of the input TCE table. Returns: A tensorflow.train.Example proto containing TCE features. """ all_time, all_flux = preprocess.read_light_curve(tce.kepid, ...
5,309,420
def extract_img(size, in_tensor): """ Args: size (int): size of crop in_tensor (tensor): tensor to be cropped """ dim1, dim2 = in_tensor.size()[2:] in_tensor = in_tensor[:, :, int((dim1-size)/2):int((dim1+size)/2), int((dim2-size)/2):int((dim2+size)/2)] return in_tensor
5,309,421
def generate_plot_filename(pair, ticker_interval) -> str: """ Generate filenames per pair/ticker_interval to be used for storing plots """ pair_name = pair.replace("/", "_") file_name = 'freqtrade-plot-' + pair_name + '-' + ticker_interval + '.html' logger.info('Generate plot file for %s', pair...
5,309,422
def loss(guesses): """Returns True if the player loses. The player loses if there are no allowed misses left. Args: guesses: The list of wrongly guessed letters. Returns: True on loss, False otherwise. """ # TODO: Your code goes here
5,309,423
def pdm_prepare_weights_vggs(nets, device="cpu"): """ Note that we only handle the FC parts and leave the conv layers as is """ weights = [] for net_i, net in enumerate(nets): layer_i = 0 statedict = net.state_dict() net_weights = [] for i, (k,v) in enumerate(stated...
5,309,424
def fmod2p(x): """ Floating point modulo 2 pi """ rval = fmod(x, twopi) if(rval < 0): rval += 2*pi return(rval)
5,309,425
def plan_cartesian_path_lin(move_arm, wpose, length, alpha, z_start, cs): """ :type move_arm: class 'moveit_commander.move_group.MoveGroupCommander' :type length: float :type alpha: float """ move_arm.set_start_state(cs) waypoints = [] wpose.position.x += length*math.cos(alpha) wpose.position.y += le...
5,309,426
def channelRelease(BaRange_presence=0, GroupChannelDescription_presence=0, GroupCipherKeyNumber_presence=0, GprsResumption_presence=0, BaListPref_presence=0): """CHANNEL RELEASE Section 9.1.7""" a = TpPd(pd=0x6) b = MessageType(mesType=0xD) # 00001101 c = RrCause(...
5,309,427
def gemm_quantized_impl(M, N, K, unroll, interleave, data_type="uint8"): """Assembly implementation of a blocked gemv. Given a block a of shape (4, k) and a block b' of shape (4, k) produces the output block c = a*b of shape (4,4)""" stepA = min(4, M) stepB = min(4, N) assert data_type in ["uin...
5,309,428
def develop_verbose(): """ We should be able to deal with setup scripts that aren't setuptools based. >>> mkdir('foo') >>> write('foo', 'setup.py', ... ''' ... from setuptools import setup ... setup(name="foo") ... ''') >>> write('buildout.cfg', ... ''' ... [buildout] ... d...
5,309,429
def get_key(h5, songidx=0): """ Get key from a HDF5 song file, by default the first song in it """ return h5.root.analysis.songs.cols.key[songidx]
5,309,430
def poll_dan(msg=config.DEFAULT_MSG): """Debug method to ping just user `dan` """ print('Polling Dan') all_status_msg(name='dan', phone=config.host_phone_num, msg=msg)
5,309,431
def _SetSELinuxContext(path): """Set the appropriate SELinux context, if SELinux tools are installed. Calls /sbin/restorecon on the provided path to set the SELinux context as specified by policy. This call does not operate recursively. Only some OS configurations use SELinux. It is therefore acceptable for ...
5,309,432
def get_driver_for_browser( browser: str = "Chrome", ) -> typing.Union[webdriver.Firefox, webdriver.Chrome]: """get_driver_for_browser Args: browser: Browser Name required for Test. Support "Firefox" and "Chrome". Defaults to Chrome. Returns: Based on user-provided browser name, ...
5,309,433
def get_rapt_token( request, client_id, client_secret, refresh_token, token_uri, scopes=None ): """Given an http request method and refresh_token, get rapt token. Args: request (google.auth.transport.Request): A callable used to make HTTP requests. client_id (str): client id to ...
5,309,434
def change_back_button_ntp(): """ Fonction qui permet de réinisiatiler le texte du bouton 'Test NTP' Paramètres : aucun Return : rien """ NTP_button['text'] = 'Test NTP'
5,309,435
def get_dev_vlans(devId): """Function takes input of devID to issue RESTUL call to HP IMC :param devId: requires devId as the only input parameter :return: list dictionaries of existing vlans on the devices. Device must be supported in HP IMC platform VLAN manager module """ # checks to see if the ...
5,309,436
def read_create_database_object(path: str, filename: str, data_dict: dict): """ Returns a dataframe based on existing files or by creating a new one :param path: str :param filename: str :param data_dict: dict :return: df """ try: # check if an excel file is available df = pd.read_excel(path + ...
5,309,437
def reset_replicate(ridx, assign_obj, reg_out, max_steps=10, accept_tol=1e-3): """Re-initialize a given replicate by cooperative re-initialization (CoRe). On each iteration, we first find the best candidate from the set of all rk clusters to add to the current replicate. We then find the best of the replicate's...
5,309,438
def test_raw_resnik_nouns(id1, id2, similarity): """Tests unnormalized resnik scores for nouns.""" synset1 = germanet_data.get_synset_by_id(id1) synset2 = germanet_data.get_synset_by_id(id2) dist = relatedness_nouns.resnik(synset1, synset2) np.testing.assert_array_almost_equal(dist, similarity, deci...
5,309,439
def get_vulnerability(vulnerability_name_file, logger=structlog.get_logger()): """ Parse name of threat from given parameter(file) :param vulnerability_name_file: string to parse from :param logger: logger for the method :return: name of threat """ pattern = r'^\d{4}-\d{2}-\d{2}-(scan_){0,1}...
5,309,440
def t2d(twt, data, td_depth, td_twt, target_depth): """ Convenience function for converting a well log from depth to time given time-depth pairs. This function both converts from time to depth and resamples the log data to a regular sampling rate in depth. """ f1 = interp1d(td_twt, td_d...
5,309,441
def test_days_of_next_month_exists_after_recreation_on_new_month(): """Test days update - 2 next month created.""" create_initial_days.Command().handle() update_days.Command().handle() days = Day.objects.get_month(1) assert len(days) > 7
5,309,442
def test_template_view_patching(): """ Test to ensure that patching a view does not give it properties it did not have before """ # DEV: `vars(cls)` will give you only the properties defined on that class, # it will not traverse through __mro__ to find the property from a parent class # We...
5,309,443
def r_precision(r): """Score is precision after all relevant documents have been retrieved Relevance is binary (nonzero is relevant). >>> r = [0, 0, 1] >>> r_precision(r) 0.33333333333333331 >>> r = [0, 1, 0] >>> r_precision(r) 0.5 >>> r = [1, 0, 0] >>> r_precision(r) 1.0 ...
5,309,444
def test_enwik9_total_rows_dataset_shuffle_false_parallel_worker_two(): """ Feature: EnWik9Dataset Description: test the function while param shuffle = False Expectation: the samples is ordered """ original_num_parallel_workers = config_get_set_num_parallel_workers(2) original_seed = config_...
5,309,445
def vector_to_symmetric_mat_4(vec): """Builds a symmetric 4x4 matrix using the elements specified in a vector. The elements are copied first to the first row, in order, then to the second row, starting from the element on the diagonal, and so on. """ A = np.zeros((4, 4)) # Fill the top-right tr...
5,309,446
def list_tags_containing(s): """return list of tag records wherein tag's name contains substring s: str, substring to search for """ cue(records) req("TAG", lambda tag: s in tag) srt(CREATED) return val()
5,309,447
def eval(model : nn.Module, valset, truedicts, n, r, batch_size=16, hitsat=[1, 3, 10], filter_candidates=True, verbose=False, elbo=True): """ Evaluates a triple scoring model. Does the sorting in a single, GPU-accelerated operation. :param model: :param val_set: :param alltriples: :param filter:...
5,309,448
def accepts(*types): """ Checks argument types. """ def decorator(f): assert len(types) == f.__code__.co_argcount @functools.wraps(f) def wrapper(*args, **kwds): for (a, t) in zip(args, types): assert isinstance(a, t), "The input argument %r must be of...
5,309,449
def is_void_pointer( type ): """returns True, if type represents C{void*}, False otherwise""" return is_same( type, cpptypes.pointer_t( cpptypes.void_t() ) )
5,309,450
def pass_down(L,L1,map): """map maps L into L1.Populate L1 with values in L""" ## print len(L),len(L1),len(map),max(map) ## print sumsize(L) ## print sumsize(L1) for j in range(len(map)): if L[j] == -1: continue assert L1[map[j]] == -1 or L1[map[j]] == L[j], 'L...
5,309,451
def parse_correctness_stats(filename): """ Parse the results returned from get_Correctness.sh """ results = [] stats_file = open(filename, 'r') line = stats_file.readline() while not line.startswith('Reference:'): line = stats_file.readline() # Add Reference bases. result...
5,309,452
def are_equal_pyxb(a_pyxb, b_pyxb): """Normalize and compare PyXB objects for equality. Args: a_pyxb: PyXB object b_pyxb: PyXB object PyXB objects to compare for equality. Returns: bool: ``True`` if the PyXB objects are semantically equivalent. """ return are_equal_xml(a...
5,309,453
def echo(content: Any, list_delimiter: str = '\n', indent: int = 4, color: str = None, flush: bool = False) -> None: """echo - automatically pretty print or resolve to a printable object :param content: the object to print :param list_delimiter: delimiter to join list; default: \n :param indent: indent...
5,309,454
def compute_misses(n_misses, n_subj): """ This function computes descriptive statistics of missed trials :param n_misses: Number of missed trials :param n_subj: Number of participants :return: n_misses_min: Minimum of misses n_misses_max: Maximum of misses n_misses_mean: Mean ...
5,309,455
def courses_(): """ Render form to register a student to a course, then save the IDs of the student and course to StudentCourses table :return: redirection to student homepage if successful, else html for course form """ return_403('lecturer_id') form = CourseForm() form.reg_num.data ...
5,309,456
def three_phase_to_ground(distgrid,node_name,Df=False, zc=0+0j): """ Calculates the three-phase-grounded short circuit Parameters ---------- distgrid: mygrid.grid.DistGrid node_name: str The name of node fault fs: str Designates which phases participate in the short circuit Options: 'Iab', 'Iac', 'Ibc' a...
5,309,457
def compare_views(v1, v2): """Compare two views.""" assert v1.name == v2.name assert v1.description_text == v2.description_text assert v1.formula == v2.formula assert v1.nrows == v2.nrows
5,309,458
def _get_sender(*sender_params, **kwargs): """ Utility function acting as a Sender factory - ensures senders don't get created twice of more for the same target server """ notify_func = kwargs['notify_func'] with _sender_instances_lock: existing_sender = _sender_instances.get(sender_para...
5,309,459
def test_lossy_waveguide(debug=False): """Test lossy WR-2.8 waveguide.""" # Waveguide imensions a, b, length = 28*sc.mil, 14*sc.mil, 2*sc.inch # Full frequency sweep for WR-2.8 waveguide freq = Frequency(260, 400, 1401, 'ghz') # Create an ideal WR-2.8 waveguide wr2p8 = RectangularWaveguid...
5,309,460
def _simple_execution(cmd): """ Shell simple execution Return only exit status (0 : Good) """ return os.system(cmd)
5,309,461
def whereSubseq(conditionFunc, seq, length, overlap=False): """ >>> a = [1, 3, 2, 3, 2] >>> b = [1, 2] >>> whereSubseq(lambda seq: seq == b, a, 2) [] >>> c = [3, 2] >>> whereSubseq(lambda seq: seq == c, a, 2) [1, 3] >>> whereSubseq(lambda seq: sum(seq) < 8, a, 3) [0] >>> whereSubseq(lambda seq: sum(seq) < 8,...
5,309,462
def bearing(lat1: float, lon1: float, lat2: float, lon2: float) -> float: """Calculate bearing from lat1/lon2 to lat2/lon2 Arguments: lat1 {float} -- Start latitude lon1 {float} -- Start longitude lat2 {float} -- End latitude lon2 {float} -- End longitude Returns: f...
5,309,463
def get_thread_uuid(thread=None): """ Assigns and returns a UUID to our thread, since thread.ident can be recycled. The UUID is used in mapping child threads to their parent threads. """ if not thread: thread = threading.current_thread() ident = thread.ident try: uuid = IDEN...
5,309,464
def config(settings): """ Template settings for Save the Children Philippines """ T = current.T settings.base.system_name = T("IMS") settings.base.system_name_short = T("IMS") # PrePopulate data #settings.base.prepopulate = ("skeleton", "default/users") settings.base.prepopula...
5,309,465
def juggle_axes(xs, ys, zs, zdir): """ Reorder coordinates so that 2D xs, ys can be plotted in the plane orthogonal to zdir. zdir is normally x, y or z. However, if zdir starts with a '-' it is interpreted as a compensation for rotate_axes. """ if zdir == 'x': return zs, xs, ys ...
5,309,466
def test_construct(qtbot): """ Test the construction of the widget. Expectations: The correct default values are assigned to the widget's attributes. Parameters ---------- qtbot : fixture pytest-qt window for widget test """ pydm_frame = PyDMFrame() qtbot.addWidget(pydm...
5,309,467
def compute_loss_function(pz, z, pys, ys, ldj, args): """ Computes the cross entropy loss function while summing over batch dimension, not averaged! :param x_logit: shape: (batch_size, num_classes * num_channels, pixel_width, pixel_height), real valued logits :param x: shape (batchsize, num_channels, pi...
5,309,468
def _filterargs(source): """Juice from a source file the four args needed by decoder.""" argsregex = (r"}\('(.*)', *(\d+), *(\d+), *'(.*)'\." r"split\('\|'\), *(\d+), *(.*)\)\)") args = re.search(argsregex, source).groups() try: return args[0], args[3].split('|'), int(args[1]), ...
5,309,469
def get_title(reg_doc): """ Extract the title of the regulation. """ parent = reg_doc.xpath('//PART/HD')[0] title = parent.text return title
5,309,470
def generate_transmissivity(path): """Generate a file with a transmissivity field from the HERTEN data.""" print("Loading Herten data with pyvista") mesh = pv.read(path) herten = mesh.point_arrays["facies"].reshape(mesh.dimensions, order="F") # conductivity values per fazies from the supplementary d...
5,309,471
def process_filters(query, filters, close=None, error=None): """Process query filters. Process filter results returned by the `_filtered_query` helper. Such filters are meant to be appended to the main query used to fetch logs in order to further filter the stories to be returned. There are two ty...
5,309,472
def single_round_review(questions_df, sheets_list): """docstring""" selected = [] sample_size = math.ceil(len(questions_df.index) / len(sheets_list)) for sheet in sheets_list: wb = Workbook() ws = wb.active ws.append([ "Discussion", "Reviewer", "Status", ...
5,309,473
def requires_auth(permission=None): """ Decorator which checks if the user is logged in and has the requested permission, and give the user to the function """ # Define the decorator def decorator(f): # Define the decorated function def decorated(): # Save the token from...
5,309,474
def load_dataset(img_path, txt_path, img_shape=(64, 64, 3), split_rate=0.1): """ Function: load_dataset Input: img_path: image directory path, txt_path: caption directory path, img_shape: image shape array Output: NumPy array """ print('Acquiring images & labels...') images = dict() texts = dict() ...
5,309,475
def get_rising_submissions(subreddit): """Connects to the Reddit API and queries the top rising submission from the specified subreddit. Parameters ---------- subreddit : str The name of the subreddit without forward slashes. Returns ------- tuple A tuple containing...
5,309,476
def print_last_rows(): """ Get the last rows from the sheet. Return the last row in the worksheet which contains data. """ global last_row_index global worksheet last_row = None count=int(config['INTERFACE']['DisplayRows']) row_index_from = last_row_index - count if (last_row_inde...
5,309,477
def _OpenFileInSplitIfNeeded( filepath ): """Ensure that the supplied filepath is open in a visible window, opening a new split if required. Returns the buffer number of the file and an indication of whether or not a new split was opened. If the supplied filename is already open in a visible window, return jus...
5,309,478
def blockstack_tor_resolve( name ): """ Given the name (a blockchain ID), resolve it to a .onion address. The blockchain ID's zone file must have a TXT record called 'tor', and its text data should be a .onion address. There should be exactly one 'tor' name. Return the .onion address on succes...
5,309,479
def lockf(): """ lockf (fd, operation, length=0, start=0, whence=0) This is essentially a wrapper around the fcntl() locking calls. fd is the file descriptor of the file to lock or unlock, and operation is one of the following values: LOCK_UN - unlock LOCK_SH - acquire a shared lock LOC...
5,309,480
def epoch_cka(experiment_dir, use_batch=True, data_path=None, dataset_name='cifar10', last_epoch=300, curr_epoch=None, use_train_mode=False): """Compute CKA score of each layer in a final model to every other layer of the same model a...
5,309,481
def sqlalchemy_instance_model_extra(sqlalchemy_session_factory): """ Create session-wide database. """ sqlalchemy_session = sqlalchemy_session_factory() # Instances instance_1 = InstanceModel(id=str(uuid.uuid4()), class_path='tests.unit_tests.agents.sqlalchemy_age...
5,309,482
def index(_linked_list : LinkedList[A], idx : int) -> Optional[A]: """ The element at index idx """ assert idx >= 0 if _linked_list.content is None: return None head = _linked_list.content[0] tail = _linked_list.content[1] if idx == 0: return head return index(tail, idx ...
5,309,483
def fetch(input_file: str): """Simulates a real API call.""" with open(input_file, 'r') as f: json = f.read() pb = json_format.Parse(json, gtfs_realtime_pb2.FeedMessage()) return pb.SerializeToString()
5,309,484
def print_board(board): """ This function prints out 6x7 matrix :param board: 6x7 matrix :return: None """ print(np.flip(board, 0))
5,309,485
def preview_cmd(ctx, protocol_name, view, dye_test): """Preview the Autoprotocol output of protocol in the current package.""" api = ctx.obj.api commands.preview(api, protocol_name, view, dye_test)
5,309,486
def read_surface(filepath): """Load in a Freesurfer surface mesh in triangular format.""" with open(filepath, "rb") as fobj: magic = _fread3(fobj) if magic == 16777215: # Quad file nvert = _fread3(fobj) nquad = _fread3(fobj) coords = np.fromfile(fobj, ">i2", ...
5,309,487
def process_submitted(getname, repopath): """reads template plist, writes copy to manifest named via POST data""" templateplist = plistlib.readPlist(template) targetplist = repopath + "/manifests/" + getname if not os.path.isfile(targetplist): filetwo = open(targetplist, 'wb') plistlib...
5,309,488
def E_float2(y, _): """Numerically stable implementation of Muller's recurrence.""" return 8 - 15/y
5,309,489
def get_auth_password(): """Get from script or backward compatibility""" password = os.environ.get('HUE_AUTH_PASSWORD') if password is not None: return password password = AUTH_PASSWORD_SCRIPT.get() if password: return password password = os.environ.get('HUE_LDAP_PASSWORD') if password is not N...
5,309,490
def perturbate_single(init_dict, label, value=None): """Perturbate a single parameter and fix all other parameters for estimation. We also set the bounds for the perturbed parameter to its default bounds. This increases the scope for perturbations. """ old_dict = copy.deepcopy(init_dict) versi...
5,309,491
def compute_packet_csum(pkt): """Computes the checksum for the given GDB packet""" csum = 0 for x in pkt: csum += x csum = csum & 0xFF return csum
5,309,492
def new_headers() -> list: """Return list of new headers with clean names.""" return [ "date", "Rohs FB1", "Rohs FB2", "Rohs gesamt", "TS Rohschlamm", "Rohs TS Fracht", "Rohs oTS Fracht", "Faulschlamm Menge FB1", "Faulschlamm Menge FB2", ...
5,309,493
def state_to_dictionary(state_tuple): """Flatten model state into a dictionary with string keys.""" flattened = {} for state_number, state_value in enumerate(nest.flatten(state_tuple)): prefixed_state_name = "{}_{:02d}".format(feature_keys.State.STATE_PREFIX, state...
5,309,494
def add_decomposed_rel_pos(attn, q, rel_pos_h, rel_pos_w, q_size, k_size): """ Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`. https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950 Args: attn (Tenso...
5,309,495
def gcc(rdg, tau_threshold=2, **kwargs): """Surface detection from relative time delay obtained through generalized cross-correlation of each contiguous range lines Parameters ---------- rdg: 2d-array radargram Return ------ """ #--------------- # Initialization...
5,309,496
def _fix_iris_bug_derived_coord(cube): """Fix iris bug concerning derived coords and aggregation.""" air_pressure_coord = cube.coord('air_pressure') try: altitude_coord = cube.coord('altitude') except iris.exceptions.CoordinateNotFoundError: altitude_coord = None for aux_factory in c...
5,309,497
def calc_file_md5(filepath, chunk_size=None): """ Calculate a file's md5 checksum. Use the specified chunk_size for IO or the default 256KB :param filepath: :param chunk_size: :return: """ if chunk_size is None: chunk_size = 256 * 1024 md5sum = hashlib.md5() with io.open...
5,309,498
def poll(client, container_name): """ poll checks if the jupyterhub-singleuser program is running. """ try: container = client.containers.get(container_name) except pylxd.exceptions.NotFound: return 0 # No container => process not running. if container.status != 'Running': ...
5,309,499