content
stringlengths
22
815k
id
int64
0
4.91M
def get_example_params(example_index): """ Gets used variables for almost all visualizations, like the image, model etc. Args: example_index (int): Image id to use from examples returns: original_image (numpy arr): Original image read from the file prep_img (numpy_arr): Proce...
45,000
def part_two(): """ Solve Part 2. """ with open("inputs/day_01_input.txt", "r") as input_file: print("Basement on step {}".format( get_first_basement_step(input_file.read())))
45,001
def bezier_curve(points, nTimes=500, is_poly=False, is_crv=False): """ Given a set of control points, return the bezier curve defined by the control points. points should be a list of lists, or list of tuples such as [ [1,1], [2,3], [4,5], ..[Xn, Yn] ] ...
45,002
def decorator_with_keywords(func=None, **dkws): # NOTE: ONLY ACCEPTS KW ARGS """ A decorator that can handle optional keyword arguments. When the decorator is called with no optional arguments like this: @decorator def function ... The function is passed as the first argument and decorat...
45,003
def parse_line(line): """ Extract all the data we want from each line. :param line: A line from our log files. :return: The data we have extracted. """ time = line.split()[0].strip() response = line.split(' :') message = response[len(response) - 1].strip('\n') channel = response[1]...
45,004
def semi_lagrangian(field: GridType, velocity: Field, dt: float, integrator=euler) -> GridType: """ Semi-Lagrangian advection with simple backward lookup. This method samples the `velocity` at the grid points of `field` to determine the lo...
45,005
def clear_mpls_ldp_neighbor(device, neighbor_ip): """ clear mpls ldp neighbor {} Args: device ('obj'): Device object neighbor_ip ('str'): neighbor ip Returns: None Raises: SubCommandFailure """ log.info( "clear mpls ldp neighbo...
45,006
def pptx_to_bbox(left, top, width, height): """ Convert matplotlib bounding box format to pptx format Parameters ---------- left : float top : float width : float height : float Returns ------- bottom, left, width, height """ return top-height, left, width, height
45,007
def reindex(labels): """ Given a list of labels, reindex them as integers from 1 to n_labels Also orders them in nonincreasing order of prevalence """ old2new = {} j = 1 for i, _ in Counter(labels).most_common(): old2new[i] = j j += 1 old2newf = lambda x: old2new[x] ...
45,008
def _validate_vg(module, vg): """ Check the current state of volume group. :param module: Ansible module argument spec. :param vg: Volume Group name. :return: True (VG in varyon state) or False (VG in varyoff state) or None (VG does not exist), message. """ lsvg_cmd = module.ge...
45,009
def news_items(news_index_page) -> List[News]: """Fixture providing 10 News objects attached to news_index_page """ rv = [] for _ in range(0, 10): p = _create_news_page(f"Test News Page {_}", news_index_page) rv.append(p) return rv
45,010
def test_attributes_add(site_client): """Test ``nsot attributes add``.""" runner = CliRunner(site_client.config) with runner.isolated_filesystem(): # Create a new attribute result = runner.run( 'attributes add -n device_multi -r device --multi' ) assert_output(res...
45,011
def is_annotated(procedure): """Return True if procedure is annotated.""" procedure = annotatable(procedure) try: ann = procedure.func_annotations return ann.are_for(procedure) and bool(ann) except AttributeError: return False
45,012
def get_dump_path(params): """ Create a directory to store the experiment. """ dump_path = DUMP_PATH if params.dump_path == "" else params.dump_path assert len(params.exp_name) > 0 # create the sweep path if it does not exist sweep_path = os.path.join(dump_path, params.exp_name) if not ...
45,013
def read_matrix(name): """\ Helper function to read a matrix from /ref_matrix. The file extension .txt is added automatically. :return: A tuple of bytearrays """ matrix = [] with io.open(os.path.join(os.path.dirname(__file__), 'ref_matrix/{0}.txt'.format(name)), 'rt') as f: for row ...
45,014
def _enable_disable_pim_config(tgen, topo, input_dict, router, build=False): """ Helper API to enable or disable pim on interfaces Parameters ---------- * `tgen` : Topogen object * `topo` : json file data * `input_dict` : Input dict data, required when configuring from testcase * `route...
45,015
def linear_interpolation_formula( left: Union[float, np.array], right: Union[float, np.array], gamma: Union[float, np.array], ) -> Union[float, np.array]: """ Compute the linear interpolation weighted by gamma on each point of two same shape array. """ return gamma * right + (1 - gamma) * le...
45,016
def test_empty_len(empty_stack): """Test __len__ for empty stack.""" assert empty_stack.__len__() == 0
45,017
def estimate_visib_mask_est(d_test, d_est, visib_gt, delta, visib_mode='bop19'): """Estimates a mask of the visible object surface in the estimated pose. For an explanation of why the visibility mask is calculated differently for the estimated and the ground-truth pose, see equation (14) and related text in Ho...
45,018
def test_tracing_with_limit(): """ Title: Tracing with a limit Scenario 1: When: a VM sends 20 ICMP echo requests over a trace request with limit 10 Then: Trace data appears for the ingress and the egress host, but only for the first 10. Then: when disabled and reenabled, new trace da...
45,019
def cbTimer_temp_triggers(*arg, **kwargs): """Execute CPU temperature triggers.""" trigger.exec_triggers(filter.result(), ids=["fanon", "fanoff"])
45,020
def combine_assertions(input_filename, output_filename): """ Take in a tab-separated, sorted "CSV" files, indicated by `input_filename`, that should be grouped together into assertions. Output a msgpack stream of assertions the file indicated by `output_filename`. The input file should be made ...
45,021
def find_testclass(package, program, testclass, file_required=False): """Find the relative path of the test-class file""" name = f'{program.lower()}.clas.testclasses.abap' for root, _, files in os.walk('.'): if name in files: return os.path.join(root, name)[2:] if file_required: ...
45,022
def sanitize_mobile_number(number): """Add country code and strip leading zeroes from the phone number.""" return "254" + str(number).lstrip("0")
45,023
def fakebaraxis(ticks, painter=fakebarpainter(),*args, **kwargs): """Return a PyX linear axis that can be used to make fake bar plots. Use "keyticks" to create the ticks expected by this function.""" return axis.linear( min=-0.75, max=len(ticks)-0.25, parter=None, manualtick...
45,024
def get_score_sent_pairs_from_tsv(tsv_filepath, encoding="ISO-8859-1"): """expects tokenized sentences in tsv file!""" with open(tsv_filepath, encoding=encoding) as tsvfile: reader = csv.reader(tsvfile, delimiter='\t') score_sent_pairs = [[float(row[0]), row[1]] for row in reader] return score_sent_pairs
45,025
def test_timings_trie(port, individual_test_timings): """Breaks a test name into chunks by directory and puts the test time as a value in the lowest part, e.g. foo/bar/baz.html: 1ms foo/bar/baz1.html: 3ms becomes foo: { bar: { baz.html: 1, baz1.html: 3 } ...
45,026
def prop_end(wf, **kwargs): """Set variables needed to properly conclude a propagation run. Parameters ---------- wf : obj The current WaveFront class object Returns ------- wf.wfarr : numpy ndarray Wavefront array sampling : float Sampling in meters Oth...
45,027
def add_others_ta(df, close, fillna=False): """Add others analysis features to dataframe. Args: df (pandas.core.frame.DataFrame): Dataframe base. close (str): Name of 'close' column. fillna(bool): if True, fill nan values. Returns: pandas.core.frame.DataFrame: Dataframe wit...
45,028
def toggle( id: int = typer.Argument(1), ip: str = typer.Option(..., "--ip", "-i", envvar="HUE_BRIDGE_IP"), user: str = typer.Option(..., "--user", "-u", envvar="HUE_BRIDGE_USER"), ): """Toggle the power state of a light""" light = Light(id, ip=ip, user=user) resp = asyncio.run(light.toggle()) ...
45,029
def _fixture_union(caller_module, name, fixtures, idstyle, scope="function", ids=fixture_alternative_to_str, unpack_into=None, autouse=False, **kwargs): """ Internal implementation for fixture_union :param caller_module: :param name: :param fixtures: :param idstyle: :para...
45,030
def generate_quiet(iterable, next_val): """ Iterate, returning if the generator function raises StopIteration. https://www.python.org/dev/peps/pep-0479/ """ for _ in iterable: try: yield next_val() except StopIteration: return
45,031
def service_class(cls): """ A class decorator enabling the instances of the class to be used as a ``services``-provider in `JSONRpc Objects`_ and `BSONRpc Objects`_. Use decorators ``request``, ``notification``, ``rpc_request`` and ``rpc_notification`` to expose methods for the RPC peer node. ...
45,032
def lightcurveplain(request, tcs_transient_objects_id): """lightcurveplain. Args: request: tcs_transient_objects_id: """ transient = get_object_or_404(TcsTransientObjects, pk=tcs_transient_objects_id) mjdLimit = 55347.0 # Hard wired to 31st May 2010 # 2012-07-18 KWS Changed this...
45,033
def get_metadata(): """ Return metadata for {{ cookiecutter.name }}. """ here = os.path.abspath(os.path.dirname(__file__))
45,034
def locate_address(ip_list, ip_attack): """ for each line in the file pointer define the ip ranges and country codes if the attacking ip is in between the range then return country code :param ip_list - list of ip address ranges and country code: :param ip_attack - attacking ip as an int...
45,035
def invertnd(f, x, *other_vars, kind='linear', vectorized=False): """ Invert a multivariate function numerically Args: f: Function to invert x: Domain to invert the function on (range of inverted function) *other_vars: Domain to invert the function on (parameters of inverted function...
45,036
def most_mentioned(msgs, limit=20): """Top mentions by '@' references """ mentions = {} for m in msgs: for at in preproc.extract_ats_from_text(m['text']): mentions[at] = mentions[at] + 1 if at in mentions else 1 return sorted(mentions.items(), key=lambda x: x[1]...
45,037
def is_valid_matlab_field_label(label): """ Check that passed string is a valid MATLAB field label """ if not label.startswith(tuple(string.ascii_letters)): return False VALID_CHARS = set(string.ascii_letters + string.digits + "_") return set(label).issubset(VALID_CHARS)
45,038
def identity(n, dtype=DEFAULT_FLOAT_DTYPE): """ Returns the identity tensor. Args: n (int): Number of rows and columns in the output, must be larger than 0. dtype (Union[mstype.dtype, str], optional): Designated tensor dtype, can be in format of np.float32, or `float32`. Default...
45,039
def _chain_connectivity(edges, chains): """Returns chain connectivity treated as clustered entities represented by nodes""" chain_connectivity = np.empty((len(edges), 2), dtype=np.int64) starts = defaultdict(list) for section_index, chain in enumerate(chains): starts[chain[0][0]].append(section...
45,040
def reading2celsius(self, reading): """ Converts sensor reading to celsius """ celsius = reading / 50 - 273.15 return celsius
45,041
def image_upload(name, imagefile): """ Will upload an image using glance. Will overwrite existing images with the same name. """ # Starts with a check for existing images with the same name. try: # Try to delete the image image_delete(name) except novaclient.exceptions.NotFound:...
45,042
def evaluate_csp(website_id, test_weights): """ Checks: no fallback to default: base-uri form-action frame-ancestors report-to/uri sandbox upgrade-insecure-requests src: ...
45,043
def check_overlap(claim_id, left, top, dimensions, points, claim_ids): """Create a claim as it would appear on the fabric.""" width, height = dimensions for i in range(width): removed = False for j in range(height): claim = (i+left, j+top) if claim not in points: ...
45,044
def refresh_viewport(): """ Refresh current DCC viewport """ maya.cmds.refresh(currentView=True)
45,045
def get_analysis_alias_from_metadata(eload_cfg): """ Returns analysis alias only if we find a metadata spreadsheet and it has exactly one analysis. Otherwise provides an error message and raise an error. """ metadata_spreadsheet = eload_cfg.query('submission', 'metadata_spreadsheet') if metadata...
45,046
def bios_profile_backup_running(handle, server_id=1, **kwargs): """ Backups up the running configuration of various bios tokens to create a 'cisco_backup_profile'. Will overwrite the existing backup profile if it exists. Args: handle (ImcHandle) server_id (int): Id of the server to p...
45,047
def variantCombinations(items): """ Calculates variant combinations for given list of options. Each item in the items list represents unique value with it's variants. :param list items: list of values to be combined >>> c = variantCombinations([["1.1", "1.2"], ["2.1", "2.2"], ["3.1", "3.2"]]) >>> ...
45,048
def bm_regex(regex_string): """Compile best multiline regex.""" return regex.compile(regex_string, regex.B | regex.M)
45,049
def test_enable_8021q_1(monkeypatch): """Verify that enable_802q_1 function return exception when 802.1q is not supported by current os. """ def mockreturn(command): return CmdStatus("", "", 0) # monkeypatch.setattr(CLISSHNetNS, 'exec_command', mockreturn) lh = GenericLinuxHost(LH_CFG, OPTS...
45,050
def parse_one_page(html): """ 解析HTML代码,提取有用信息并返回 """ # 正则表达式进行解析 pattern = re.compile('<td class="zwmc".*?href="(.*?)" target="_blank">(.*?)</a>.*?' # 匹配职位详情地址和职位名称 '<td class="gsmc">.*? target="_blank">(.*?)</a>.*?' # 匹配公司名称 '<td class="zwyx">(.*?...
45,051
async def test_select_option(opp): """Test select_option methods.""" assert await async_setup_component( opp, DOMAIN, {DOMAIN: {"test_1": {"options": ["some option", "another option"]}}}, ) entity_id = "input_select.test_1" state = opp.states.get(entity_id) assert state....
45,052
def cvt_eval_input(node: pytree.Base, ctx: Ctx) -> ast_cooked.Base: """eval_input: testlist NEWLINE* ENDMARKER Input for the eval() and input() functions. """ raise ValueError(f'eval_input is not used in grammar: {node!r}')
45,053
def test_textual_content_extra_8(): """ Test case extra 8: Single backspace should be escaped """ # Arrange source_markdown = """this character \b is me""" expected_tokens = [ "[para(1,1):]", "[text(1,1):this character \x05\b is me:]", "[end-para:::True]", ] expe...
45,054
def _validate_config(ctx: Context) -> None: """ Validate agent config. :param ctx: Context object. :raises ClickException: if validation is failed. """ try: validate_item_config(AGENT, Path(ctx.cwd)) except AEAConfigException as e: # pragma: no cover raise click.ClickExcep...
45,055
def qlearning_dataset(env, dataset=None, terminate_on_end=False, **kwargs): """ Returns datasets formatted for use by standard Q-learning algorithms, with observations, actions, next_observations, rewards, and a terminal flag. Args: env: An OfflineEnv object. dataset: An optional da...
45,056
def build_save_dataset(corpus_type, fields, opt): # corpus_type: train or valid """ Building and saving the dataset """ assert corpus_type in ["train", "valid"] # Judging whether it is train or valid if corpus_type == "train": src_corpus = opt.train_src # 获取源端、目标端和结构信息的pat...
45,057
def gaussian_filter(image, sigma): """Returns image filtered with a gaussian function of variance sigma**2""" i, j = np.meshgrid(np.arange(image.shape[0]), np.arange(image.shape[1]), indexing='ij') mu = (int(image.shape[0]/2.0), int(image.shape[1]/2....
45,058
def get_lattice_points(strand): """ 格子点の情報を取得 @param ストランドの格子点の対 @return ストランドの格子点の始点と終点 """ strand_list = eval(strand) strand_from = strand_list[0] strand_to = strand_list[1] return strand_from, strand_to
45,059
def while_(condition): """ A while loop that can be used in a workchain outline. Use as:: while_(cls.conditional)( cls.step1, cls.step2 ) Each step can, of course, also be any valid workchain step e.g. conditional. :param condition: The workchain method that will retu...
45,060
def new(init=None): """Return a new Whirlpool object. An optional string argument may be provided; if present, this string will be automatically hashed.""" return Whirlpool(init)
45,061
def split(string, separator, limit): """Return an array of tokens created by splitting the input string according to a provided separator pattern. The result can optionally be constrained to return at most limit tokens. """ raise RuntimeError('split' + error_message)
45,062
def extract_bcr(tab, rep_col='CDR3_aa'): """ Extract BCR repertorie for each patient Args: tab: data table from TRUST BCR outputs rep_col: 'CDR3_aa' or 'complete_CDR3_sequences' or a list of keys Output: a Series vector containing lists of BCR CDR3 sequences """ ta...
45,063
def open_output_file(options: argparse.Namespace): """Open Output File.""" if options.output is None: logging.debug("Piping output to stdout.") def close_output(): pass return sys.stdout, close_output filepath = os.path.abspath(options.output) logging.debug("Piping...
45,064
def filter_labels(a, min_size, max_size=None): """ Remove (set to 0) labeled connected components that are too small or too large. Note: Operates in-place. """ if min_size == 0 and (max_size is None or max_size > np.prod(a.shape)): # shortcut for efficiency return a try: compone...
45,065
def mask(bigtiff,profile,out_mask): """ mask a 1 or 3 band image, band by band for memory saving """ if profile['count']==4: bigtiff1 = bigtiff[0,:,:] bigtiff1[out_mask==1] = profile['nodata'] bigtiff[0,:,:] = bigtiff1 del bigtiff1 bigtiff2 = bigtiff[1,:,:] ...
45,066
def test_decimal008_1882_decimal008_1882_v(mode, save_output, output_format): """ TEST :Facet Schemas for string : value=-1.0 """ assert_bindings( schema="msData/datatypes/decimal.xsd", instance="msData/datatypes/decimal008.xml", class_name="Root", version="1.1", ...
45,067
def quadratic_sum(n: int) -> int: """calculate the quadratic num from 1 ~ n""" sum = 0 for n in range(1, n + 1): sum += n ** 2 return sum
45,068
def run(): """Requirements for Task 1C""" # Build list of stations stations = build_station_list() centre = (52.2053, 0.1218) r = 10 # in km sorted_stations = stations_within_radius(stations, centre, r) names = [] for station in sorted_stations: names.append(station.name) ...
45,069
def shuffled_hdf5_batch_generator(state_dataset, action_dataset, indices, batch_size, transforms=[]): """A generator of batches of training data for use with the fit_generator function of Keras. Data is accessed in the order of the given indices for shuffling. """ state...
45,070
def dag_rules(rules, required_keys): """ Serializing dag parameters from variable. Checking for required fields using required_keys :return dict dag_rules. An example of how they should look, in ..._settings.json, "airflow_settings" """ is_exists_rule_keys = all(key in rules.keys() for key in requir...
45,071
def ip_address(value): """Get IPAddress""" return write_tv(ASN1_IPADDRESS, socket.inet_aton(value))
45,072
def _GetUpdatedMilestoneDict(master_bot_pairs, tests): """Gets the milestone_dict with the newest rev. Checks to see which milestone_dict to use (Clank/Chromium), and updates the 'None' to be the newest revision for one of the specified tests. """ masters = set([m.split('/')[0] for m in master_bot_pairs]) ...
45,073
def test_get_friends(): """ Splitwise calls :return: """ smgr = SplitwiseAccountmanager(userId='123') print smgr.get_friends()
45,074
def chunks(file_obj: TextIO): """ :param file_obj: text file or file-like object opened for reading :return: parsed data dictionaries as an iterator object """ chunk = {} key = None for line in file_obj.readlines(): if line.startswith('#'): continue if not line.st...
45,075
def _hrv_nonlinear_poincare_hra(rri, out): """Heart Rate Asymmetry Indices. - Asymmetry of Poincaré plot (or termed as heart rate asymmetry, HRA) - Yan (2017) - Asymmetric properties of long-term and total heart rate variability - Piskorski (2011) """ N = len(rri) - 1 x = rri[:-1] # rri_n, x...
45,076
def headers(sheet): """Returns the values of the sheet's header row (i.e., the first row).""" return [ stringify_value(h) for h in truncate_row(next(sheet.iter_rows(values_only=True))) ]
45,077
def internal_server_error(message='Internal server error'): """500 Internal server error response""" errors = { '_internal': message } return error(500, errors)
45,078
def get_model(args, test=False): """ Create computation graph and variables. """ nn_in_size = 513 image = nn.Variable([args.batch_size, 3, nn_in_size, nn_in_size]) label = nn.Variable([args.batch_size, 1, nn_in_size, nn_in_size]) mask = nn.Variable([args.batch_size, 1, nn_in_size, nn_in_si...
45,079
def post_config(opt): """post_config""" # init fixed parameters opt.noise_amp_init = opt.noise_amp opt.nfc_init = opt.nfc opt.min_nfc_init = opt.min_nfc opt.scale_factor_init = opt.scale_factor opt.out_ = 'TrainedModels/%s/scale_factor=%f/' % (opt.input_name[:-4], opt.scale_factor) if o...
45,080
def select_device_with_aspects(required_aspects, excluded_aspects=[]): """Selects the root :class:`dpctl.SyclDevice` that has the highest default selector score among devices that have all aspects in the `required_aspects` list, and do not have any aspects in `excluded_aspects` list. The list of SY...
45,081
def get_block_path(tag, block_number): """ Get the absolute path of a specific block identified by a tag and its unique identifier Args: tag: The tag used to identify the type of data stored in the block block_number: The unique identifier of the block Returns: The absolute path to the block """ block_fo...
45,082
def wearing(): """Will say what the player is wearing""" txt("You are currently wearing:\n%s on the head, %s on the torso, %s on the hands, %s on the legs, %s on the feet and %s" % (current_clothes["head"], current_clothes["torso"], current_clothes["hands"], current_clothes["legs"], current_clothes["feet"], current_c...
45,083
def plus(a:int,b:int)->int: """ plus operation :param a: first number :param b: second number :return: a+b """ return a+b
45,084
def linear_upsample_3d(inputs, strides=(2, 2, 2), use_bias=False, trainable=False, name='linear_upsample_3d'): """Linear upsampling layer in 3D using strided transpose convolutions. The upsampling kernel size will be...
45,085
def hc(adata, num_clusters): """ Compute hierarchical clustering using X_pca fits. random_state = 2019 """ hc = AgglomerativeClustering(n_clusters=num_clusters).fit(adata.obsm['X_pca']) adata.obs['hc'] = pd.Series(hc.labels_,index=adata.obs.index).astype('category')
45,086
def sample_ingredient(user: User, name: str = "Cinnamon") -> Ingredient: """Create a sample ingredient""" return Ingredient.objects.create(user=user, name=name)
45,087
def naive_sample_frequency_spectrum(ts, sample_sets, windows=None, mode="site"): """ Naive definition of the generalised site frequency spectrum. """ method_map = { # "site": naive_site_sample_frequency_spectrum, "branch": naive_branch_sample_frequency_spectrum} return method_map[mod...
45,088
def show_spectral_sources( sources, observation=None, norm=None, channel_map=None, show_observed=False, show_rendered=False, show_spectra=True, figsize=None, ): """Plot each source individually. The functions provides an more detailed inspection of every source in the list. P...
45,089
def tcp_servers(): """ a simplistic TCP server mocking Isabelle server behaviour """ with ReusableTCPServer( ("localhost", 9999), DummyTCPHandler ) as server, ReusableTCPServer( ("localhost", 9998), BuggyTCPHandler ) as buggy_server: thread = threading.Thread(target=server.serve_...
45,090
def make_server_request(request, payload, endpoint, auth=None, method='post'): """ makes a json request to channelstream server endpoint signing the request and sending the payload :param request: :param payload: :param endpoint: :param auth: :return: """ server_port = request.regist...
45,091
def nan_helpfcn(myarray): """ Helper function to return the locations of Nan values as a boolean array, plus a function to return the index of the array. Code inspired by: http://stackoverflow.com/questions/6518811/interpolate-nan-values-in-a-numpy-array Input: - myarray, 1d numpy array with...
45,092
def _get_norm_layer(normalization_type='no_norm', name=None): """Get normlization layer. Args: normalization_type: String. The type of normalization_type, only 'no_norm' and 'layer_norm' are supported. name: Name for the norm layer. Returns: layer norm class. """ if normalization_typ...
45,093
def run_single_camera(cam): """ This function acts as the body of the example; please see NodeMapInfo example for more in-depth comments on setting up cameras. :param cam: Camera to setup and run on. :type cam: CameraPtr :return: True if successful, False otherwise. :rtype: bool """ ...
45,094
def all_strs_text(obj): """ PyYAML refuses to load strings as 'unicode' on Python 2 - recurse all over obj and convert every string. """ if isinstance(obj, six.binary_type): return obj.decode('utf-8') elif isinstance(obj, list): return [all_strs_text(x) for x in obj] elif isi...
45,095
def write_jsonnetfile(file: P, deps: Iterable): """ Writes the file `jsonnetfile.json` containing all provided dependencies. """ data = { "version": 1, "dependencies": deps, "legacyImports": True, } with open(file, "w", encoding="utf-8") as f: f.write(json.dumps(...
45,096
def write_data(output, date, data): """Writing data to CSV file.""" short_path = output + '/' + date path = short_path + '/comments.csv' if not os.path.exists(short_path): os.makedirs(short_path) if os.path.exists(path): with open(path, 'a') as csvfile: fieldnames = ['dat...
45,097
def analyze_code(code, closure, symboltable, references, single_pass, previous_passes): """ This function uses uncompyle6 to parse the Python bytecode, resulting in a parsing tree (forerunner of an abstract syntax tree or AST). This parsing tree is passed to "handle", which recursively walks over it. ...
45,098
async def login_user(credentials: OAuth2PasswordRequestForm = Depends()): """Endpoint for logging user in.""" user = services.authenticate_user(email=credentials.username, password=credentials.password) if not user: raise HTTPException(status_code=401, detail="I...
45,099