content
stringlengths
22
815k
id
int64
0
4.91M
def index(a: protocols.SupportsIndex) -> int: """ Return _a_ converted to an integer. Equivalent to a.__index__(). Example: >>> class Index: ... def __index__(self) -> int: ... return 0 >>> [1][Index()] 1 Args: a: """ return operator....
7,500
def col_to_num(col_str): """ Convert base26 column string to number. """ expn = 0 col_num = 0 for char in reversed(col_str): col_num += (ord(char) - ord('A') + 1) * (26 ** expn) expn += 1 return col_num
7,501
def process_chunk(chunk, verbose=False): """Return a tuple of chunk kind, task-create links, task-create times, task-leave times and the chunk's graph""" # Make function for looking up event attributes get_attr = attr_getter(chunk.attr) # Unpack events from chunk (_, (first_event, *events, last_ev...
7,502
def delazi_wgs84(lat1, lon1, lat2, lon2): """delazi_wgs84(double lat1, double lon1, double lat2, double lon2)""" return _Math.delazi_wgs84(lat1, lon1, lat2, lon2)
7,503
def clipped_zoom(x: np.ndarray, zoom_factor: float) -> np.ndarray: """ Helper function for zoom blur. Parameters ---------- x Instance to be perturbed. zoom_factor Zoom strength. Returns ------- Cropped and zoomed instance. """ h = x.shape[0] ch = int(np...
7,504
def NextFchunk(ea): """ Get next function chunk @param ea: any address @return: the starting address of the next function chunk or BADADDR @note: This function enumerates all chunks of all functions in the database """ func = idaapi.get_next_fchunk(ea) if func: ...
7,505
def test_private_access_through_object(enable_accessify): """ Case: access to the private member through member's class object. Expect: inaccessible due to its protection level error message. """ car = CarWithPrivateEngine() expected_error_message = INACCESSIBLE_DUE_TO_ITS_PROTECTION_LEVEL_EXCE...
7,506
def draw(): """Render everything on the screen once per frame""" # Clear the screen first screen.clear() # noqa: F821 # Set the background color to pink screen.fill("pink") # noqa: F821 # Draw the player player.draw() # Draw the remaining coins for coin in coin_list: co...
7,507
def share_to_group(request, repo, group, permission): """Share repo to group with given permission. """ repo_id = repo.id group_id = group.id from_user = request.user.username if is_org_context(request): org_id = request.user.org.org_id group_repo_ids = seafile_api.get_org_group...
7,508
def test_get_os_platform_windows(): """Get platform from a patched Windows machine.""" with patch("platform.system", return_value="Windows"): with patch("platform.release", return_value="10"): with patch("platform.machine", return_value="AMD64"): os_platform = get_os_platform...
7,509
def change_config(python, backend, cheatsheet, asciiart): """ Show/update configuration (Python, Backend, Cheatsheet, ASCIIART). """ asciiart_file = "suppress_asciiart" cheatsheet_file = "suppress_cheatsheet" python_file = 'PYTHON_MAJOR_MINOR_VERSION' backend_file = 'BACKEND' if asciiart...
7,510
def get_memcached_usage(socket=None): """ Returns memcached statistics. :param socket: Path to memcached's socket file. """ cmd = 'echo \'stats\' | nc -U {0}'.format(socket) output = getoutput(cmd) curr_items = None bytes_ = None rows = output.split('\n')[:-1] for row in rows:...
7,511
def list_installed(executable=None): """ List installed resources """ resmgr = OcrdResourceManager() ret = [] for executable, reslist in resmgr.list_installed(executable): print_resources(executable, reslist, resmgr)
7,512
def _process_video_files(name, filenames, labels, num_shards): """Process and save list of images as TFRecord of Example protos. Args: name: string, unique identifier specifying the data set filenames: list of strings; each string is a path to an image file texts: list of strings; each string is human ...
7,513
def dataset_config(): """Return a DatasetConfig for testing.""" return hubs.DatasetConfig(factory=Dataset, flag=True)
7,514
def combinations(): """Produce all the combinations for different items.""" combined = itertools.combinations('ABC', r=2) combined = [''.join(possibility) for possibility in combined] return combined
7,515
def setup(hass, config): """Create a Honeywell (EMEA/EU) evohome CH/DHW system. One controller with 0+ heating zones (e.g. TRVs, relays) and, optionally, a DHW controller. Does not work for US-based systems. """ evo_data = hass.data[DATA_EVOHOME] = {} evo_data['timers'] = {} evo_data['par...
7,516
def test_api_keys(enter_password, config): """ Test creating, revoking, expiring API keys. Test that they have appropriate scope-limited access. """ # Make alice an admin. Leave bob as a user. config["authentication"]["tiled_admins"] = [{"provider": "toy", "id": "alice"}] with enter_passwor...
7,517
def _check_valid_settings_for_input(input_value: Any, pivot_reg: PivotRegistration): """Check input against settings in `pivot_reg`.""" # Must have one of these specified if not (pivot_reg.func_df_col_param_name or pivot_reg.func_input_value_arg): raise ValueError( "A value for one of 'f...
7,518
def geo_exps_MD(n_nodes, radius, l_0, l_1, K=40, thinRatio=1, gammas=10, max_iter=100, nSamp=50, Niid=1, seed=0): """Solves the Connected Subgraph Detection problem and calculates AUC using Mirror Descent Optimisation for a random geometric graph. Parameters ---------- ...
7,519
def validate_sig_integrity(signer_info: cms.SignedData, cert: x509.Certificate, expected_content_type: str, actual_digest: bytes) -> Tuple[bool, bool]: """ Validate the integrity of a signature for a particular signerInfo object ...
7,520
def linemod_dpt(path): """ read a depth image @return uint16 image of distance in [mm]""" dpt = open(path, "rb") rows = np.frombuffer(dpt.read(4), dtype=np.int32)[0] cols = np.frombuffer(dpt.read(4), dtype=np.int32)[0] return (np.fromfile(dpt, dtype=np.uint16).reshape((rows, cols)) / 1000....
7,521
def findNode(nodes: Iterable[AstNode], name: str) -> Optional[SExpr]: """ Finds a node with given name in a list of nodes """ for node in nodes: if isinstance(node, Atom): continue if len(node.items) == 0: continue nameNode = node.items[0] if isins...
7,522
def test_repository_to_branches(neo4j_session): """ Ensure that repositories are connected to branches. """ _ensure_local_neo4j_has_test_repositories_data(neo4j_session) query = """ MATCH(branch:GitHubBranch)<-[:BRANCH]-(repo:GitHubRepository{id:{RepositoryId}}) RETURN branch.name, repo.id, ...
7,523
def search(keywords=None, servicetype=None, waveband=None): """ execute a simple query to the RegTAP registry. Parameters ---------- keywords : list of str keyword terms to match to registry records. Use this parameter to find resources related to a particular topic. ser...
7,524
def shadingLightRelCtx(*args, **kwargs): """ This command creates a context that can be used for associating lights to shading groups. You can put the context into shading-centric mode by using the -shadingCentric flag and specifying true. This means that the shading group is selected first then light...
7,525
def describe_data_sources(FilterVariable=None, EQ=None, GT=None, LT=None, GE=None, LE=None, NE=None, Prefix=None, SortOrder=None, NextToken=None, Limit=None): """ Returns a list of DataSource that match the search criteria in the request. See also: AWS API Documentation :example: response = cl...
7,526
def copyFile(filename, sourceDir, targetDir, renameTo=None, silent=True): """ Copy file from sourceDir to targetDir. """ if renameTo == None: renameTo = filename fullname_source = os.path.join(sourceDir, filename) fullname_target = os.path.join(targetDir, renameTo) shutil.copy(fullname_source, fullname_target) i...
7,527
def _get_credentials(vcap_services, service_name=None): """Retrieves the credentials of the VCAP Service of the specified `service_name`. If `service_name` is not specified, it takes the information from STREAMING_ANALYTICS_SERVICE_NAME environment variable. Args: vcap_services (dict): A dict ...
7,528
def all_are_independent_from_all(program, xs, ys): """ Returns true iff all xs are statistially independent from all ys, where the xs are from the current iteration and the ys are from the previous iteration. """ for x in xs: if not is_independent_from_all(program, x, ys): return...
7,529
def save_file(window, txt_edit, event=False): # print(txt_edit.get(1.0, tk.END)) """Save the current file as a new file.""" filepath = asksaveasfilename( defaultextension="txt", filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")], ) if not filepath: return with open(filepath, "w") as output...
7,530
def get_exc_short(): """Print only error type and error value. """ exType, exValue, exTb = sys.exc_info() resL1 = traceback.format_exception_only(exType, exValue) return string.join(resL1, "")
7,531
def setup_install_dir(): """Sets up install dir and ensures its owned by Galaxy""" if not exists(env.install_dir): sudo("mkdir -p %s" % env.install_dir) if not exists(env.jars_dir): sudo("mkdir -p %s" % env.jars_dir) # TODO: Fix bug here chown_galaxy(os.path.split(env.install_dir)[0]...
7,532
def is_str_str_dict(x): """Tests if something is a str:str dictionary""" return isinstance(x, dict) and all( isinstance(k, str) and isinstance(v, str) for k, v in x.items() )
7,533
def _ensureListLike(item): """ Return the item if it is a list or tuple, otherwise add it to a list and return that. """ return item if (isinstance(item, list) or isinstance(item, tuple)) \ else [item]
7,534
def rule_asc(n): """ Produce the integer partitions of n as ascending compositions. See: http://jeromekelleher.net/generating-integer-partitions.html """ a = [0 for _ in range(n + 1)] k = 1 a[1] = n while k != 0: x = a[k - 1] + 1 y = a[k] - 1 k -= 1 while ...
7,535
def get_file_from_gitlab(gitpkg, path, ref="master"): """Retrieves a file from a Gitlab repository, returns a (StringIO) file.""" return io.StringIO(gitpkg.files.get(file_path=path, ref=ref).decode())
7,536
def tsne(x, no_dims=2, initial_dims=50, perplexity=30.0, max_iter=1000): """Runs t-SNE on the dataset in the NxD array x to reduce its dimensionality to no_dims dimensions. The syntaxis of the function is Y = tsne.tsne(x, no_dims, perplexity), where x is an NxD NumPy array. """ # Check inputs ...
7,537
def add_corp(): """ 添加投顾信息页面,可以让用户手动添加投顾 :by zhoushaobo :return: """ if request.method == 'GET': fof_list = cache.get(str(current_user.id)) return render_template("add_corp.html", fof_list=fof_list) if request.method == 'POST': name = request.form['name'] alia...
7,538
def reset_circuit() -> None: """ Clear the circuit and create a new one. """ global _current_circuit if _current_circuit is None: return try: _current_circuit.abort(EdzedCircuitError('forced circuit reset')) # abort is ignored if not running except Exception as err:...
7,539
def nll_loss(output: Tensor, target: Tensor): """ Negative log likelihood loss function. ## Parameters output: `Tensor` - model's prediction target: `Target` - training sample targets ## Example usage ```python from beacon.tensor import Tensor from beacon.functional import functio...
7,540
async def album_upload(sessionid: str = Form(...), files: List[UploadFile] = File(...), caption: str = Form(...), usertags: Optional[List[Usertag]] = Form([]), location: Optional[Location] = Form(None), cl...
7,541
def mocked_requests_get(*args, **kwargs): """Mock requests.get invocations.""" class MockResponse: """Class to represent a mocked response.""" def __init__(self, json_data, status_code): """Initialize the mock response class.""" self.json_data = json_data sel...
7,542
def count_disordered(arr, size): """Counts the number of items that are out of the expected order (monotonous increase) in the given list.""" counter = 0 state = { "expected": next(item for item in range(size) if item in arr), "checked": [] } def advance_state(): state...
7,543
def multi_process(directory: str, modifiers: dict, base: str, end: bool = False): """ Verarbeitet ein ganzes Verzeichnis mit Emojis :param directory: Der Ordner :param modifiers: Die Skin-Modifier :param base: Der Name des Basis-Typen :param end: Ob noch eine fe0f-Sequenz angefügt werden soll. ...
7,544
def lookup_flag_values(flag_list: Iterable[str]) -> collections.OrderedDict: """Returns a dictionary of (flag_name, flag_value) pairs for an iterable of flag names.""" flag_odict = collections.OrderedDict() for flag_name in flag_list: if not isinstance(flag_name, str): raise ValueError( 'All f...
7,545
def test_alignment(): """Ensure A.M. cosine's peaks are aligned across joint slices.""" if skip_all: return None if run_without_pytest else pytest.skip() N = 1025 J = 7 Q = 16 Q_fr = 2 F = 4 # generate A.M. cosine ################################################### f1, f2 = ...
7,546
def main(): """ Create an aligned functional group based on command line arguments. """ parser = argparse.ArgumentParser( description='Create a functional group from a smiles pattern', epilog='Example usage: %(prog)s -s OPr -n PropylEther -c "Alkyl Ether" -m OCCC') parser.add_argum...
7,547
def request_text(photo_file, max_results=5): """ Request the Google service to find text in an image :param photo_file: The filename (or path) of the image in a local directory :param max_results: The requested maximum number of results :return: A list of text entries found in the image Note: ...
7,548
def config(request): """render a ProsperConfig object for testing""" return p_config.ProsperConfig(request.config.getini('app_cfg'))
7,549
def flatatt(attrs): """ Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key="value", XML-style pairs. It is assumed that the keys do not need to be XML-escaped. If the passed dictionary is empty, then return an empty string. ...
7,550
def json_io_dump(filename, data): """ Dumps the the JSON data and returns it as a dictionary from filename :arg filename <string> - Filename of json to point to :arg data - The already formatted data to dump to JSON """ with open(filename, encoding='utf-8', mode='w') as json_file: json.dump...
7,551
def get_restaurants(_lat, _lng): """緯度: lat 経度: lng""" response = requests.get(URL.format(API_KEY, _lat, _lng)) result = json.loads(response.text) lat_lng = [] for restaurant in result['results']['shop']: lat = float(restaurant['lat']) lng = float(restaurant['lng']) lat_lng.a...
7,552
def geomfill_GetCircle(*args): """ :param TConv: :type TConv: Convert_ParameterisationType :param ns1: :type ns1: gp_Vec :param ns2: :type ns2: gp_Vec :param nplan: :type nplan: gp_Vec :param pt1: :type pt1: gp_Pnt :param pt2: :type pt2: gp_Pnt :param Rayon: :ty...
7,553
def dwconv3x3_block(in_channels, out_channels, stride, padding=1, dilation=1, bias=False, activation=(lambda: nn.ReLU(inplace=True)), activate=True): """ 3x3 depthwise vers...
7,554
def predict() -> str: """ Creates route for model prediction for given number of inputs. :return: predicted price """ try: input_params = process_input(request.data) print(input_params) predictions = regressor.predict(input_params) return json.dumps({"predicted_price...
7,555
def all_h2h_pairs_all_lanes(matches_df, file_name=''): """Produces all head to head win rates for all lane matchups -- even across different lanes (eg. TOP_SOLO Renekton vs MID_SOLO Xerath).""" df = pd.DataFrame() lanes = dc.get_lanes_roles() for lane1 in lanes: print(lane1) for lane...
7,556
def sort_list_of_dates(b): """ مرتب سازی نویسنده: ندا """ i = 0 while i<len(b)-1: #if b.value("year") in b[i]<b.value("year") in b[i+1]: # if b.value("month") in b[i]<b.value("month") in b[i+1]: # if b.value("day") in b[i]<b.value("day") in b[i+1]: if ear...
7,557
def reload_rules(testcase, rest_url): """ :param TestCase self: TestCase object :param str rest_url: http://host:port :rtype: dict """ resp = requests.get(rest_url + "/rest/reload").json() print("Reload rules response: {}".format(resp)) testcase.assertEqual(resp.get("success"...
7,558
def encryptMessage(key: str, message: str) -> str: """Vigenère cipher encryption Wrapper function that encrypts given message with given key using the Vigenère cipher. Args: key: String encryption key to encrypt with Vigenère cipher. message: Message string to encrypt. Returns: ...
7,559
def pytest_configure(config): """Inject documentation.""" config.addinivalue_line( "markers", "trio: " "mark the test as an async trio test; " "it will be run using trio.run" )
7,560
def rae(label, pred): """computes the relative absolute error (condensed using standard deviation formula)""" #compute the root of the sum of the squared error numerator = np.mean(np.abs(label - pred), axis=None) #numerator = np.sum(np.abs(label - pred), axis = None) #compute AE if we were to ...
7,561
def subset_sum(arr, target_sum, i, cache): """ Returns whether any subset(not contiguous) of the array has sum equal to target sum. """ if target_sum == 0: return True, {} if i < 0: return False, {} if target_sum in cache[i]: return cache[i][target_sum] # Either inclu...
7,562
def set_runtime_parameter_pb( pb: pipeline_pb2.RuntimeParameter, name: Text, ptype: Type[types.Property], default_value: Optional[types.Property] = None ) -> pipeline_pb2.RuntimeParameter: """Helper function to fill a RuntimeParameter proto. Args: pb: A RuntimeParameter proto to be filled in. ...
7,563
def get_loader(content_type): """Returns loader class for specified content type. :type content_type: constants.ContentType :param content_type: Content type. :returns: Loader class for specified content type. :raise ValueError: If no loader found for specified content type. """ for loader_...
7,564
def get_basis_script(max_degree: int, use_pad_trick: bool, spherical_harmonics: List[Tensor], clebsch_gordon: List[List[Tensor]], amp: bool) -> Dict[str, Tensor]: """ Compute pairwise bases matrices for degrees up to max_degree ...
7,565
def get_iterative_process_for_minimal_sum_example(): """Returns an iterative process for a sum example. This iterative process contains the fewest components required to compile to `forms.MapReduceForm`. """ @computations.federated_computation def init_fn(): """The `init` function for `tff.templates.I...
7,566
def test_nbconv_file_contents(tmp_path: Path): """Run ``nbconv`` with the ``exporter`` or ``out_file`` argument.""" nb = make_notebook(tmp_path) assert nbconv(in_file=nb, exporter="html")[1].startswith("<!DOCTYPE html>") assert nbconv(in_file=nb, out_file="o.html")[1].startswith("<!DOCTYPE html") as...
7,567
def get_r_port_p_d_t(p): """玄関ポーチに設置された照明設備の使用時間率 Args: p(int): 居住人数 Returns: ndarray: r_port_p_d_t 日付dの時刻tにおける居住人数がp人の場合の玄関ポーチに設置された照明設備の使用時間率 """ return get_r_i_p_d_t(19, p)
7,568
def remove_comments_from_json(string): """ Removes comments from a JSON string, supports // and /* formats. From Stack Overflow. @param str string: Original text. @return: Text without comments. @rtype: str """ pattern = r"((?<!\\)\".*?(?<!\\)\"|\'.*?\')|(/\*.*?\*/|//[^\r\n]*$)" # first ...
7,569
def visualize_depth(visual_dict, disp_or_error="disp", dataset="KITTI"): """visual_dict:"left_img": raw left image "depth_error" or "disp" "est_left_img": image reprojected from right "depth": output depth "photo_error": photometric error ...
7,570
def put_s3_object(bucket, key_name, local_file): """Upload a local file in the execution environment to S3 Parameters ---------- bucket: string, required S3 bucket that will holds the attachment key_name: string, required S3 key is the destination of attachment local_f...
7,571
def parse_parionssport(url): """ Get ParionsSport odds from url """ if "parionssport" not in sb.TOKENS: try: token = get_parionssport_token() sb.TOKENS["parionssport"] = token except OpenSSL.crypto.Error: return {} if "paris-" in url.split("/")[-1]...
7,572
def get_index(channel_urls=(), prepend=True, platform=None, use_local=False, use_cache=False, unknown=False, prefix=False): """ Return the index of packages available on the channels If prepend=False, only the channels passed in as arguments are used. If platform=None, then the current pl...
7,573
def is__invsign1(*args): """ is__invsign1(ea) -> bool """ return _ida_nalt.is__invsign1(*args)
7,574
def bind(bind_to, bind_with, name): """ A cool hata features, that lets you bind object to existing one. Parameters ---------- bind_to : `type` The type to bind to. bind_with : `type` The type to bind with. name : `str` The name of the binding. Raises ...
7,575
def every(n_steps): """Returns True every n_steps, for use as *_at functions in various places.""" return lambda step: step % n_steps == 0
7,576
def read_files(mousefile,humanfile): """ Read into anndata objects and return """ mouse = sc.read_10x_h5(mousefile) if humanfile != None: human = sc.read_10x_h5(humanfile) else: human = None return(mouse,human)
7,577
def calc_batch_size(num_examples, batches_per_loop, batch_size): """Reduce the batch size if needed to cover all examples without a remainder.""" assert batch_size > 0 assert num_examples % batches_per_loop == 0 while num_examples % (batch_size * batches_per_loop) != 0: batch_size -= 1 return batch_size
7,578
def test_real_distinct_irrational(): """ Test that the roots of x^2 - 2 x + (1 - 10**(-10)) = 0 are 1 \pm 1e-5. """ roots = (1 + 1e-5, 1 - 1e-5) assert_allclose(real_quadratic_roots(1, -2.0, 1.0 - 1e-10), roots, err_msg="Testing x^2-2x+(1-1e-10)=0; roots should be 1 +- 1e-5.")
7,579
def upload_volume(request, *args, **kwargs): """ User upload volume data, delete the original data first. """ if not (request.user and request.user.is_authenticated()): raise PermissionDenied() user = request.user assert 'pid' in kwargs pid = kwargs['pid'] assert 'pk' in kwarg...
7,580
def has_admin_access(user): """Check if a user has admin access.""" return user == 'admin'
7,581
def get_compss_type(value, depth=0): # type: (object, int) -> int """ Retrieve the value type mapped to COMPSs types. :param value: Value to analyse. :param depth: Collections depth. :return: The Type of the value. """ # First check if it is a PSCO since a StorageNumpy can be detected #...
7,582
def pytask_parse_config(config, config_from_cli, config_from_file): """Register the r marker.""" config["markers"]["stata"] = "Tasks which are executed with Stata." config["platform"] = sys.platform if config_from_file.get("stata"): config["stata"] = config_from_file["stata"] else: ...
7,583
def set_namedtuple_defaults(namedtuple, default=None): """ Set *all* of the fields for a given nametuple to a singular value. Modifies the tuple in place, but returns it anyway. More info: https://stackoverflow.com/a/18348004 :param namedtuple: A constructed collections.namedtuple :param d...
7,584
def test_tuple_get_item_merge(): """Test composite function can be merged from pattern containing TupleGetItem nodes.""" pattern_table = [ ("bn_relu", make_bn_relu_pattern()) ] def before(): x = relay.var('x', shape=(1, 8)) gamma = relay.var("gamma", shape=(8,)) beta = r...
7,585
def prepare_data_for_storage(major_version, minor_version, patch_version): """Prepares data to store to file. """ temp = Template( u'''/*Copyright (c) 2016, Ford Motor Company\n''' u'''All rights reserved.\n''' u'''Redistribution and use in source and binary forms, with or without\n''' u'''m...
7,586
def flatten_mock_calls(mock): """ Flatten the calls performed on a particular mock object, into a list of calls with arguments. """ result = [] for call in mock.mock_calls: call = list(call) call_name = call[0] if '.' in str(call_name): call_name = str(call_na...
7,587
def clean_setting( name: str, default_value: object, min_value: int = None, max_value: int = None, required_type: type = None, choices: list = None, ) -> Any: """cleans the user input for an app's setting in the Django settings file Will use default_value if setting is not defined. ...
7,588
def update_not_existing_kwargs(to_update, update_from): """ This function updates the keyword aguments from update_from in to_update, only if the keys are not set in to_update. This is used for updated kwargs from the default dicts. """ if to_update is None: to_update = {} to_update...
7,589
def get_reddit(): """Returns the reddit dataset, downloading locally if necessary. This dataset was released here: https://www.reddit.com/r/redditdev/comments/dtg4j/want_to_help_reddit_build_a_recommender_a_public/ and contains 23M up/down votes from 44K users on 3.4M links. Returns a CSR matrix o...
7,590
def linear_forward(A, W, b): """Returns Z, (A, W, b)""" Z = (W @ A) + b cache = (A, W, b) return Z, cache
7,591
def read_wave(path): """Reads a .wav file. Takes the path, and returns (PCM audio data, sample rate). """ with contextlib.closing(wave.open(path, 'rb')) as wf: num_channels = wf.getnchannels() assert num_channels == 1 sample_width = wf.getsampwidth() assert sample_width =...
7,592
def update_rho_hat(rho_hat_q, rho_hat_g, phi_hat, K, Q, Y_tp1, gamma_t, W): """ rho_hat is an intermediate quantity rho_hat_{n, nu, theta}(x) = 1/n E[ sum_{t=1}^n s(X_{t-1}, X_t, Y_t | Y_{0:n}, X_n=x)] where s() are the sufficient statistics see Cappe (2.5) In our case (discrete emissions ...
7,593
def obtain_dihedral_angles(system_coords, bond_distance): """ system_coords: coords for 1 frame """ ref_selection = system_coords[0] # Process bonds for reference frame (first) bonds = [] sq_bond_distance = bond_distance**2 for i in range(len(ref_selection)-1): for j in rang...
7,594
def piecewise_accel(duration,initial,final): """Defines a piecewise acceleration. Args: duration (float): Length of time for the acceleration to complete. initial (float): Initial value. final (float): Final value. """ a = (final-initial) return lambda t: initial + a * ( ...
7,595
def download_data(symbols, from_date): """Download the desired symbol data from specified date to today, with a daily basis.""" curr_date = datetime.now() from_date = datetime.strptime(from_date, '%Y-%m-%d') for symbol in symbols: link = "http://chart.finance.yahoo.com/table.csv?s={}&a={}&b={}&c={}&d={...
7,596
def get_displayed_views(id): """ get views in window rect by view id str :param res_id: :return: """ return get_solo().get_displayed_views(id)
7,597
def get_build_version(xform): """ there are a bunch of unreliable places to look for a build version this abstracts that out """ version = get_version_from_build_id(xform.domain, xform.build_id) if version: return version, BuildVersionSource.BUILD_ID version = get_version_from_app...
7,598
def get_shortlist(routing_table: 'TreeRoutingTable', key: bytes, shortlist: typing.Optional[typing.List['KademliaPeer']]) -> typing.List['KademliaPeer']: """ If not provided, initialize the shortlist of peers to probe to the (up to) k closest peers in the routing table :param routing_tabl...
7,599