content
stringlengths
22
815k
id
int64
0
4.91M
def WriteIfContentDifferent(filename, content): """Write file only if content is different or if filename does not exist. Args: filename: filename of file. content: string containing contents of file. """ if os.path.exists(filename): f = open(filename, 'r'); old_content = f.read() ...
42,600
def form_check(form_field: BoundField, col: str = '') -> dict: """ Делаем бутстраповский чекбокс из джанговского поля формы Фичи: - если после валидации нашлись косяки, показываем их - если в поле есть хелп-текст, то показываем его - опционально передаем в form-group CSS-класс для выстраивания п...
42,601
def IncludeFiles(filters, files): """Filter files based on inclusion lists Return a list of files which match and of the Unix shell-style wildcards provided, or return all the files if no filter is provided.""" if not filters: return files match = set() for filter in filters: match |= set(fnmatc...
42,602
def make_fade_window_n(level_start, level_end, N_total, fade_start_end_idx=None): """ Make a fade-in or fade-out window using information on sample amounts and not time. f_start_end defines between which start and stop indexes the fade happens. """ if not fade_start_end_idx: fade_start_idx,...
42,603
def translate_ethosu_tir_call_extern(tir_call_extern): """This is a dispatcher function to dispatch correct translation call depending on the extern call's first argument""" supported_call_extern = { "ethosu_conv2d": translate_ethosu_conv2d, "ethosu_copy": translate_ethosu_copy, ...
42,604
def test_sample_condition_5(): """ Test that the experimental condition is correctly sampled """ condition = ([1, 20, 36.5], [2, 2, 2], [1., -1., 5.]) frametimes = np.linspace(0, 49, 50) reg, rf = sample_condition(condition, frametimes, oversampling=1) assert reg.sum() == 10 assert reg[1] ==...
42,605
def user_jku_by_pass(jwt_json: Dict, url: str) -> None: """ Print for jku bypass method. Parameters ---------- jwt_json: Dict your jwt json (use encode_to_json.Check Doc). url: str your url """ new_jwt = jku_vulnerability( jwt=encode_jwt(jwt_json) + "...
42,606
def _getSinglePosValueKey(valueRecord): """otBase.ValueRecord --> (2, ("YPlacement": 12))""" assert isinstance(valueRecord, ValueRecord), valueRecord valueFormat, result = 0, [] for name, value in valueRecord.__dict__.items(): if isinstance(value, ot.Device): result.append((name, _ma...
42,607
def top_half(bbox=full_frame()): """Returns a bounding box covering the top half of ``bbox``.""" return make_bbox(bbox['x1'], bbox['y1'], bbox['x2'], (bbox['y1'] + bbox['y2']) / 2.)
42,608
def __command(client, command, default_method, use_bytes=False): """ Private function supporting multiple command formats: - string - function - (function, args, kwargs) """ if is_function(command): return command(client) elif is_list(command): a, kw = (), {} ...
42,609
def send(message: Union[str, bytes], socket_object: object = None) -> None: """ Wrapper for encrypt, formats output to be readable for sending, and accesses objects.socket_main to send it. This no longer requires to be used as socket.sendall(interface.send(self, b"message")). :param socket_object: socke...
42,610
def designate_node(fqdn, type): """ """ execCmd = ' '.join([BDVAGENT, OPTION, 'designate', type, fqdn]) return executeCmd(execCmd)
42,611
def ingest_accounting_logs(path, cfg=None): """ Read PBS logs into a dataset """ if not os.path.exists(path): raise ConfigurationError("Specified path to ingest accounting profiles does not exist: {}".format(path)) if not os.path.isfile(path): raise ConfigurationError("Specified pat...
42,612
def keypoints_to_file(config_filepath: str, keypoints: kapture.Keypoints) -> None: """ Writes keypoints to CSV file. :param config_filepath: :param keypoints: """ os.makedirs(path.dirname(config_filepath), exist_ok=True) header = "# name, dtype, dsize" dtype = str(keypoints.dtype) if is...
42,613
def plot_phase_diagram3d(figure_no,s2d,r2d,aee2d,Z01,Z2,Zr,config_dict): """ plot and save 3d phase diagram """ ##generate figure fig = plt.figure() ax3d = fig.gca(projection='3d') ax3d.view_init(22,10) mode = config_dict["mode"] if config_dict["feature"] is None: ax3d.plot_surface(s2d,r2d,Z01[:,:,0],colo...
42,614
def get_identity_for_user(user): """Get the Identity for the user specified via email or ID.""" identity = None if user is not None: # note: this seems like the canonical way to go # 'as_user' can be either an integer (id) or email address u = current_accounts.datastore.get_use...
42,615
def MetaOptNetHead_Ridge(query, support, support_labels, n_way, n_shot, lambda_reg=50.0, double_precision=False): """ Fits the support set with ridge regression and returns the classification score on the query set. Parameters: query: a (tasks_per_batch, n_query, d) Tensor. support: a (t...
42,616
def zenodo_upload_resource(token, resource_id, resource_main_dir, hash_algorithm, file_duplicate_action): """ Upload the files found in the resource_main_dir to the target. Parameters ---------- token : str User's token. resource_id : str ID of the res...
42,617
def getUserZaduzenja(userClass): """ Vraca zaduzenja datog korisnika """ _result = [] for k,v in _rented.items(): if int(k) == userClass.GetCardNumber(): _result.append(v) return _result
42,618
def add_testcase_properties(xml_obj, tcconfig=None): """add properties to testcases""" if xml_obj.tag == "testsuites": expression = "./testsuite/testcase" else: expression = "./testcase" multile_test_ids = {} for testcase in xml_obj.findall(expression): tcproperties = et.El...
42,619
def kin_histo_sig_bg(file_name, sig_divs, bg_divs, out_file_name=None, norm_one=True, labels=None, ylabel=None, colors=None, logx=False, logy=False, save=False, bins=None, binResize=False, xlabel=None, min_x=None, max_x=None, stacked=False, histtypes=None, linestyles=None, ...
42,620
def calc_rho(RhoRef,T,S,alpha=2.0E-4, beta=7.4E-4): """----------------------------------------------------------------------------- calc_rho calculates the density profile using a linear equation of state. INPUT: state: xarray dataframe RhoRef : reference density at the same z as T and S slices. C...
42,621
def lq_test_repo(test_local_engine): """A read-only fixture for LQ tests that gets reused so that we don't clean out the engine after every SELECT query.""" clean_out_engine(test_local_engine) pg_repo_local = make_pg_repo(test_local_engine) # Most of these tests are only interesting for where there...
42,622
def get_request_details(request_id=None, srp_request=None): """Handles responding to all of the :py:class:`~.models.Request` detail functions. The various modifier functions all depend on this function to create the actual response content. Only one of the arguments is required. The ``srp_request``...
42,623
def packSpecialData( data: numpy.ndarray, paramName: str ) -> Tuple[Optional[numpy.ndarray], Dict[str, Any]]: """ Reduce data that wouldn't otherwise play nicely with HDF5/numpy arrays to a format that will. This is the main entry point for conforming "strange" data into something that will bot...
42,624
def swapaxes(x, axis1, axis2): """Swap two axes of a variable. Args: x (~chainer.Variable): Input variable. axis1 (int): The first axis to swap. axis2 (int): The second axis to swap. Returns: ~chainer.Variable: Variable whose axes are swapped. """ return Swapaxes(a...
42,625
def get_table_version_schema( namespace: str, table_name: str, table_version: Optional[str] = None, *args, **kwargs) -> Optional[Union[pa.Schema, str, bytes]]: """ Gets the schema for the specified table version, or for the latest active table version if none is speci...
42,626
def add_header(img, labels, mark_midpoints=True, header_height=20): """Adds labels to the image, evenly distributed across the top. This is primarily useful for showing the names of channels. Args: img: A PIL Image. labels: list of strs. Labels for segments to write across the top. mark_midpoints: b...
42,627
def predict_by_lr_model(test_feature, lr_model): """ predict by lr_model (调用 sklearn 实例方法) """ result_list = [] #存储每个样本label为1的概率 prob_list = lr_model.predict_proba(test_feature) for index in range(len(prob_list)): result_list.append(prob_list[index][1]) #下标为0的对应label为0的概率,下标为1的对应label为1...
42,628
def _default_schedule(outs): """Default schedule for gpu.""" outs = [outs] if isinstance(outs, tvm.tensor.Tensor) else outs s = tvm.create_schedule([x.op for x in outs]) scheduled_ops = [] def traverse(op): if tag.is_broadcast(op.tag) or op.tag in ['bbox_score', 'sorted_bbox']: s...
42,629
def get_track_reviewer_abstract_counts(event, user): """Get the numbers of abstracts per track for a specific user. Note that this does not take into account if the user is a reviewer for a track; it just checks whether the user has reviewed an abstract in a track or not. :return: A dict mapping t...
42,630
def fit_logistic(X, w, var_prior, X_test, initial_phi): """MAP logistic regression. Input: X - (D + 1) * I training data matrix, where D is the dimensionality and I is the number of training examples. w - I * 1 vector containing world states for each e...
42,631
async def muter(moot): """Used for deleting the messages of muted people""" try: from userbot.modules.sql_helper.gmute_sql import is_gmuted from userbot.modules.sql_helper.spam_mute_sql import is_muted except AttributeError: return muted = is_muted(moot.chat_id) gmuted = is_g...
42,632
def middle_drag_and_drop( element_path1: UI_Element, element_path2: UI_Element, duration: Optional[float] = None, mode: Enum = MoveMode.linear, timeout: Optional[float] = None) -> UI_Element: """ Drags and drop with middle button pressed from element_path1 to element_path...
42,633
def get_pi0(pv, lambdas): """ Compute Storey's C{pi0} from p-values C{pv} and C{lambda}. this function is equivalent to:: m = len(pv) return [sum(p >= l for p in pv)/((1.0-l) * m) for l in lambdas] but the above is C{O(m*n)}, while it needs only be C{O(m+n) (n = len(la...
42,634
def read_accelerometer(serial, calibration): """ Reads the raw values from the Arduino, parses them into separate variables and uses the calibration data to normalize the data Args: serial: a reference to the serial connection with the Arduino calibration: a reference to the calibration...
42,635
def eval_one_epoch(sess, ops, next_test_element): """ ops: dict mapping from string to tf ops """ is_training = False # Make sure batch data is of same size cur_batch_xyz = np.zeros((BATCH_SIZE, NUM_POINT, 3)) cur_batch_label = np.zeros((BATCH_SIZE, NUM_POINT), dtype=np.int32) cur_batch_cls_lab...
42,636
def get_access(name): """Get access based on name In Python __var__ refers to a private access _var refers to protected access and var would refer to public access """ assert isinstance(name, str), "Expecting name to be a string" if len(name) > 4 and "__" == name[:2] and "__" == name[-2:]: ...
42,637
def run_query_series(queries, conn): """ Iterates through a list of queries and runs them through the connection Args: ----- queries: list of strings or tuples containing (query_string, kwargs) conn: the triplestore connection to use """ results = [] for item in queries: ...
42,638
def _get_key(block_id, block_dict, extra_args): """ Given a dictionary, return an element by ``key``. block_id: Block id block_dict: key: (Mandatory) Key value to get starting_dict: (Optional) Starting dictionary param ...
42,639
def AP(predictions, scores): """ Computes the average precision per class, the average precision and the interpolated average precision at 11 points :param predictions: list of lists of every class with tp, fp and fn. fps are zeros, the others one, indicating this is a ground truth :param scores: confi...
42,640
def _sample_optimization_test_problems( rng): """Sample an optimization test function problem.""" is_noise = utils.sample_bool(rng, 0.5) return { "problem": rng.choice(sorted(_opt_test_problems.keys())), "noise_stdev": utils.sample_log_float(rng, 0.01, 10.0) if is_noise else 0....
42,641
def _remove_tensors_from_model(model, remove_tensors_idxs): """Remove tensors from model.""" if not remove_tensors_idxs: return if len(model.subgraphs) > 1: logging.info("Skipping the removal of dangled tensors since the model has " "multiple subgraphs and tensors can be used in the diffe...
42,642
def get_domain_id_field(domain_table): """ A helper function to create the id field :param domain_table: the cdm domain table :return: the id field """ return domain_table + '_id'
42,643
def write_csv_large_differences(differences, csv_outfile): """Where the depth difference is greater than 100 m, write out the position, depths and difference into a csv file""" header = ['Date', 'Lat', 'Long', 'Depth1', 'Depth2', 'Depth difference'] csv_writer = csv.writer(csv_outfile) csv_writer.write...
42,644
def construct(symbol, strategy, chains, **kwargs): """ This is a convenience method to allow for creation of option spreads from predefined sources. :param symbol: The symbol of the option chains :param strategy: The option strategy filter to use :param chains: Option chains data to use. This d...
42,645
def write_messages_file(path, messages, mtype): """write messages to translation file""" if not os.path.exists(path): return if not os.path.exists(os.path.join(path, 'locale')): os.makedirs(os.path.join(path, 'locale')) fname = os.path.join(path, 'locale', '_messages_' + mtype + '.json') messages = list(s...
42,646
def get_delete_query(table_name: str) -> str: """Build a SQL query to delete a RDF triple from a MVCC-PostgreSQL table. Argument: Name of the SQL table from which the triple will be deleted. Returns: A prepared SQL query that can be executed with a tuple (subject, predicate, object). """ return f"...
42,647
def _parse_ipv6(a): """ Parse IPv6 address. Ideally we would use the ipaddress module in Python3.3 but can't rely on having this. Does not handle dotted-quad addresses or subnet prefix >>> _parse_ipv6("::") == (0,) * 16 True >>> _parse_ipv6("1234:5678::abcd:0:ff00") (18, 52, 86, 120, 0...
42,648
def _processAndStoreFile(couchDb, inputFile): """ Load input file. Each line corresponds to 1 alert (jsonized). Store one by one into the database. """ decoder = json.decoder.JSONDecoder() with _handleFile(inputFile) as f: for alertStr in f: alert = decoder.decode(alertS...
42,649
def weighted(weights,metric='categorical_accuracy'): """ weighted metric Args: - weights<list>: * a weight for each value in y_true - metric<str|metric>: * snake-case strings will be turned to camel-case * if metric is not a string the passed metric will be r...
42,650
def gcal(poll, quiet, once: bool = False): """Look for events in Google and add them to the cache""" ctx = click.get_current_context() ctx.obj.quiet = quiet if quiet: # Let the user know we started up. print_log("GCAL: Starting service", force_print=True) poll *= 60 while True...
42,651
def send_request_for_warning_popup_to_socketio(nickname, message='', url=None, increase_counter=False): """ Sends request to the socketio server for a warning popup :param nickname: Current users nickname :param message: String :param url: String :param increase_counter: :return: Status cod...
42,652
def jackknife(): """ Do the Jackknife data reduction. """ ########## # # OB06284 # ########## ########## # Kp-band reduction ########## target = 'OB06284' #sci_files = ['i200810_a004{0:03d}_flip'.format(ii) for ii in range(2, 26+1)] OG sci_files = ['i200810_a004...
42,653
def compute_reg_strs(product_graph: TwoPlayerGraph, coop_str: bool = False, epsilon: float = -1) -> Tuple[list, dict, TwoPlayerGraph]: """ A method to compute strategies. We control the env's behavior by making it purely cooperative, pure adversarial, or epsilon gre...
42,654
def make_tanh_warp_grid(matrix: torch.Tensor, warp_factor: float, warped_shape: Tuple[int, int], orig_shape: Tuple[int, int]): """ Args: matrix: bx4x4 matrix. warp_factor: The warping factor. `warp_factor=1.0` represents a vannila Tanh-warping, ...
42,655
def insertion_sort(arr): """ Returns the list 'arr' sorted in nondecreasing order in O(n^2) time. """ for i in range(1,len(arr)): key = arr[i] j = i-1 while j >= 0 and arr[j] > key: arr[j+1] = arr[j] j = j-1 arr[j+1] = key return arr
42,656
def tokens_refresh_post(body=None, project_name=None, scope=None): # noqa: E501 """Refresh tokens for an user Request to refresh OAuth tokens for an user # noqa: E501 :param body: :type body: dict | bytes :param project_name: Project Name :type project_name: str :param scope: Scope for ...
42,657
def load_xml_data(path, start_node="header", search_node="name"): """ load the XML data """ retval = [] fetched_xml = minidom.parse(path) item_list = fetched_xml.getElementsByTagName(start_node) for value in item_list: retval.append(value.attributes[search_node].value) return ret...
42,658
def saturationcheck(thermal_data,startframe,sat_threshold=0.9): """ Determine the fraction of thermal_data that is saturated on or after startframe (0 based). It is assumed the highest temperature recorded in thermal_data for a particular pixel is the saturation value and that the thermal data has alre...
42,659
def test_check_soft_deps(): """Test the _check_soft_deps() function.""" with pytest.raises(ModuleNotFoundError, match=r".* soft dependency .*"): _check_soft_deps("unavailable_module") with pytest.raises(ModuleNotFoundError, match=r".* soft dependency .*"): _check_soft_deps("unavailable_modu...
42,660
def make_image_justification(g, doc_id, boundingbox, system, confidence, uri_ref=None): """ Marks a justification for something appearing in an image. :param rdflib.graph.Graph g: The underlying RDF model :param str doc_id: A string containing the document element (child) I...
42,661
def update_u_gates(drag_params, pi2_pulse_schedules=None, qubits=None, cmd_def=None, drives=None): """ Update the cmd_def with new single qubit gate values Will update U2, U3 Args: drag_params: list of drag params pi2_pulse_schedules: list of new pi/2 gate as a pulse s...
42,662
def import_csv() -> list[pandas.DataFrame]: """Импортирует CSV файлы с таблицами в pandas. Возвращает список с таблицами в виде Pandas.DataFrame""" today = datetime.datetime.now().date() tables = [] if file_is_exist(): for page in range(1, 4): name = str(today) + f'-page-{page}-table...
42,663
def make_acc_fun(network_apply_fun, num_outputs=1): """ Given a network function and number of outputs, returns an accuracy function """ if num_outputs == 1: prediction_function = lambda x: (x >= 0.).astype(jnp.int32) else: prediction_function = lambda x: x.argmax(axis=-1).astype(jnp.int32) @jax.jit...
42,664
def __load_tk_image(filename): """ Load in an image file and return as a tk Image. :param filename: image filename to load :return: tk Image object """ if filename is None: return None if not os.path.isfile(filename): raise ValueError('Image file {} does not exist.'.format...
42,665
def upsert_all( engine: Engine, table: Table, data: Union[Dict[str, Any], List[Dict[str, Any]]], ) -> Tuple[int, int]: """ Update data by primary key columns. If not able to update, do insert. Example:: # define data model t_user = Table( "users", metadata, ...
42,666
def index(): """Root route test""" return "Weights route"
42,667
def externalCommand(command): """Execute External Commands and return stdout and stderr""" command = shlex.split(command) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return proc.communicate()
42,668
def get_backend_health(backend_name: Optional[str] = None, backend_set_name: Optional[str] = None, network_load_balancer_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetBackendHealthResult: """ This data s...
42,669
async def list_jobs( solver_key: SolverKeyId, version: str, user_id: PositiveInt = Depends(get_current_user_id), catalog_client: CatalogApi = Depends(get_api_client(CatalogApi)), webserver_api: AuthSession = Depends(get_webserver_session), url_for: Callable = Depends(get_reverse_url_mapper), ): ...
42,670
def calculate_velocity(start_longitude, start_latitude, start_time, end_longitude, end_latitude, end_time): """ Finds the magnitude of the velicty, in kilometers per hour. """ distance_traveled = calculate_distance(start_longitude, start_latitude, ...
42,671
def get_raw_html_pbp(season, game): """ Loads the html file containing this game's play by play from disk. :param season: int, the season :param game: int, the game :return: str, the html pbp """ with open(get_game_pbplog_filename(season, game), 'r') as reader: page = reader.read()...
42,672
def prepare_inputs_by_partition( df, partition_col, split_date, categorical_cols=None, output_col=0, lookback=12, num_predictions=12, ): """ Lags, splits and normalizes a dataframe based around a partition. """ partitions = df[partition_col].unique() scalers = {} trai...
42,673
def read_fits_data(filename, dtype="float32", **kwargs): """ Read fits image into numpy array. Args: filename (str): The name of ther file to read. dtype (str, optional): The data type for the array. Default: float32. **kwargs: Parsed to fits.getdata. Returns: np.array: The i...
42,674
def streamplot(UV, ax=None, map=None, geodata=None, drawlonlatlines=False, basemap_resolution='l', cartopy_scale="50m", lw=0.5, cartopy_subplot=(1,1,1), axis="on", **kwargs): """Function to plot a motion field as streamlines. Parameters ---------- UV : array-lik...
42,675
def main(): """主函数""" print('test') json_to_excel(json)
42,676
def random_add_text(new_canvas: np.ndarray): """ :param new_canvas: RGBA image. :return RGBA image. """ # font font_list = [ cv2.FONT_HERSHEY_SIMPLEX, cv2.FONT_HERSHEY_PLAIN, cv2.FONT_HERSHEY_DUPLEX, cv2.FONT_HERSHEY_COMPLEX, cv2.FONT_HERSHEY_TRIPLEX, ...
42,677
def main(): """Примеры""" number = 5 print(f'Первые {number} чисел: {look_and_say(number)}') print('-' * 50) print('Бесконечный генератор:') for i, item in enumerate(look_and_say_inf()): if i == number: break print(f'{i}-е число: {item}') print('-' * 50) print...
42,678
def prepare_publish(): """ It copies the .git directory into gh-pages, and change the branch to gh-pages. """ root_dir = dirname(abspath(__file__)) gh_dir = join(root_dir, 'gh-pages') git_dir = join(root_dir, '.git') # Copies .git directory. if isdir(git_dir): # Remove gh-pages ...
42,679
def len_to_mask(len_seq, max_len=None): """len to mask""" if max_len is None: max_len = torch.max(len_seq) mask = torch.zeros((len_seq.size(0), max_len)) for i, l in enumerate(len_seq): mask[i, :l] = 1 return mask
42,680
def get_games_for_steamid(steamid: str) -> set[tuple[int, str]]: """Gets the games owned by a Steam user Parameters ---------- steamid : str The user's 64-bit Steam ID Returns ------- set[tuple[int, str]] The set of games this user owns, in tuples of appid and game name """ body = steam_request('IPlayer...
42,681
def test_single_account_matching_tenant(): """one cached account, tenant specified, tenant matches -> credential should auth that account""" tenant_id = "tenant-id" refresh_token = "refresh-token" scope = "scope" account = get_account_event(uid="uid_a", utid=tenant_id, username="spam@eggs", refresh...
42,682
def CSP_LDA(type, filename): """Does machine learning on data using common spatial patterns and Linear Discriminant Analysis. Parameters ---------- type : str Could be one of: TMI LMI filename : str Name of file to load data from """ if filename is no...
42,683
def m2fs_scatlight(fname, flatfname, fibermapfname, x_begin, x_end, badcolmin, badcolmax, degree=3, maxiter=9, sigmathresh=5.0, make_plot=True, extrapixels=2, verbose=True): """ Scattered light subtraction. The basic idea is to mask out the defined extraction regions in the 2D image, ...
42,684
def normalize(how: str) -> Callable[..., Any]: """Apply a row or column normalization to a pandas DataFrame argument. Parameters ---------- how : str The normalization method to apply. Can be one of {'row', 'colum', 'minmax', 'median_column'}. 'row': Normalize each row to the range [0, ...
42,685
def get_version(): """Get a nice version number from git-describe""" # ensure that we are working in a pysb git repo setup_path = os.path.abspath(os.path.dirname(__file__)) if not os.path.exists(os.path.join(setup_path, '.git')): raise Exception("setup.py is not in the root of a git repository;...
42,686
def extract_data(dirpath, filename): """ This function reads and extracts the NetCDF format data of the given meter channel using a package called xarray. Parameters ---------- dirpath : `dirpath` is the directory path location of the NetCDF file to be read filen...
42,687
def resize_image( image: np.ndarray, target_shape: Union[list, tuple], ground_truth: np.ndarray = None, ): """ @param `image`: Dim(height, width, channels) @param `target_shape`: (height, width, ...) @param `ground_truth`: [[center_x, center_y, w, h, class_id], ...] @return resi...
42,688
def GkemulticloudEndpointOverride(location, track=base.ReleaseTrack.GA): """Context manager to override the GKE Multi-cloud endpoint temporarily. Args: location: str, location to use for GKE Multi-cloud. track: calliope_base.ReleaseTrack, Release track of the endpoint. Yields: None. """ origina...
42,689
def _get_security_item(security_type, exchanges, code=None): """ get the security item. Parameters ---------- code : str the security code,default: None security_type : str the security type exchanges : list the exchanges Returns ------- DataFrame ...
42,690
def test_md022_good_atx_with_code_block_and_good_line_spacing(): """ Test to make sure this rule does not trigger with a document that contains atx headings with good spacing between them and the code blocks on either side. """ # Arrange scanner = MarkdownScanner() supplied_arguments = ...
42,691
def generate_launch_description(): """Launch file for training node to training network.""" return LaunchDescription([ DeclareLaunchArgument( 'yaml_file', default_value=[get_default_file_path('template.yaml')], description='Parameter file for experiment.' ), ...
42,692
def plot_density( data, data_labels=None, var_names=None, credible_interval=0.94, point_estimate="mean", colors="cycle", outline=True, hpd_markers="", shade=0.0, bw=4.5, figsize=None, textsize=None, ): """Generate KDE plots for continuous variables and histograms for ...
42,693
def _vivid_light(a, b): """ :type a: ImageMath._Operand :type b: ImageMath._Operand :rtype: ImageMath._Operand """ color_burn = _color_burn(a, b * 2) color_dodge = _color_dodge(a, 2 * (b - 128)) return color_burn * (b < 128) + color_dodge * (b >= 128)
42,694
def normalize_cookies(cookies): """Takes cookies from Selenium or from Python Requests and converts them to dict. This throws away information that Selenium otherwise has (like the host and such), but a dict is essentially all we need. """ requests_cookies = {} if type(cookies) == list: ...
42,695
def install_disk_info(): """ This function creates the .disk/info metadata and installs it into the cdroot. """ os.mkdir("cdroot/.disk") with open("cdroot/.disk/info", "w") as i: i.write("HELLO")
42,696
def create_graph(data, loan): """Create a graph to show the relationship between principal and time""" x_value = [] # month number y_value = [] # principal value # Loop through data set. Point is a tuple. # point[0] represents a month number, # point[1] represents a principal value for po...
42,697
def from_file(filename): """Create a list structure from a special format of file. Args: filename: in which the formated string is located. Returns: A 2d list object. """ with open(filename, 'r') as f: return from_text(f.read())
42,698
def plot_data(data): """ Returns a scatter plot that visualizes the passed dataframe. Currently, tailored to merely encapsulate very specific visualization. """ # lets play with namedtuples for fun. kinda like a struct-ish PlotArgs = namedtuple('PlotArgs', ['color', 'label', 'marker']) plottin...
42,699