content
stringlengths
22
815k
id
int64
0
4.91M
def init_validator(required, cls, *additional_validators): """ Create an attrs validator based on the cls provided and required setting. :param bool required: whether the field is required in a given model. :param cls: the expected class type of object value. :return: attrs validator chained correct...
4,700
def test_network_switch_forwards_packets_received_from_network_interfaces(): """Validate packet with destination matching one interface is routed up. We send three packets: one from 'eth', one from 'wifi' and one from 'user'. Make sure that in any case the packet is routed to user. """ sim, ns, wif...
4,701
def upload_results(target_folder, local_folder_path): """ Uploads results folder containing the bam file (and associated output) :param bam_s3_path: S3 path to upload the alignment results to :param local_folder_path: local path containing the alignment results """ upload_folder(target_folder, ...
4,702
def init_app(app): """添加日志记录器""" app.logger.addHandler(_file_handler())
4,703
def next_search(request, *args, **kwargs): """ Handle search requests :param request: :return: """ server = FhirServerUrl() in_fmt = "json" get_fmt = get_format(request.GET) if settings.DEBUG: print("Server:", server) print("Kwargs:",kwargs) context = {'display...
4,704
def ShiftRight(x, **unused_kwargs): """Layer to shift the tensor to the right by padding on axis 1.""" if not isinstance(x, (list, tuple)): # non-chunked inputs pad_widths = [(0, 0)] * len(x.shape) pad_widths[1] = (1, 0) # Padding on axis=1 padded = np.pad(x, pad_widths, mode='constant') return pa...
4,705
def calc_weights(): """ Initialize focus weights matrix following parabolic equation. Used to give higher priority to pixels located closer to the center of the ROI. """ global focusWeights focusWeights = np.empty((looseBound[3], looseBound[2]), np.float32) # weight = a * sqr(x - b) + c ...
4,706
def connect_kafka_producer(): """Return a MSK client to publish the streaming messages.""" # Use a global variable so Lambda can reuse the persisted client on future invocations global kafka_client if kafka_client is None: logger.debug('Creating new Kafka client.') try: ...
4,707
def empty_record(): """Create an empty record.""" record = dump_empty(Marc21RecordSchema) record["metadata"] = "<record> <leader>00000nam a2200000zca4500</leader></record>" record["is_published"] = False record["files"] = {"enabled": True} return record
4,708
def illuminanceToPhotonPixelRate(illuminance, objective_numerical_aperture=1.0, illumination_wavelength=0.55e-6, camera_pixel_size=6.5e-6, objective_magnification=1, ...
4,709
def stop_tuning(step): """ stop tuning the current step method """ if hasattr(step, 'tune'): step.tune = False elif hasattr(step, 'methods'): step.methods = [stop_tuning(s) for s in step.methods] return step
4,710
def assemble_english(): """Assemble each statement into """ if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') stmts = stmts_from_json(stmts_json) sentences = {} for st in stmts:...
4,711
def test_json_schema_component_to_modelldcatno_returns_empty() -> None: """Test that empty ParsedSchema is returned if invalid JSON Schema is passed.""" json_schema_dict: Dict[str, str] = {} base_uri = "http://uri.com" schema = Schema(base_uri, json_schema_dict) path: List[str] = [] parsed_sche...
4,712
def schema_class(classname, schema, schemarepr=None, basename='SchemaBase'): """Generate code for a schema class Parameters ---------- classname : string The name of the class to generate schema : dict The dictionary defining the schema class basename : string (default: "SchemaB...
4,713
def orthology_events(ids='R-HSA-6799198,R-HSA-168256,R-HSA-168249', species='49633'): """ Reactome uses the set of manually curated human reactions to computationally infer reactions in twenty evolutionarily divergent eukaryotic species for which high-quality whole-genome sequence data are available, an...
4,714
def judge(name): """ Return some sort of score for automatically ranking names based on all the features we can extract so far. I guess we'll just add the scores * weights up for now. """ score = 0 for scoreID, scorer, weight in weights: subscore = scorer(name) score += subs...
4,715
def parse_year(inp, option='raise'): """ Attempt to parse a year out of a string. Parameters ---------- inp : str String from which year is to be parsed option : str Return option: - "bool" will return True if year is found, else False. - Return year int / rais...
4,716
def retry_import(e, **kwargs): """ When an exception occurs during channel/content import, if * there is an Internet connection error or timeout error, or HTTPError where the error code is one of the RETRY_STATUS_CODE, return return True to retry the file transfer * the file ...
4,717
def register_random_state_impl(clz=None, *, scalar=None, batch=None): """ Register an implementation for the function generating random state for the given Hilbert space class. The rule can be implemented both as a scalar rule and as a batched rule, but the best performance will be obtained by impl...
4,718
def cvCloneMat(*args): """cvCloneMat(CvMat mat) -> CvMat""" return _cv.cvCloneMat(*args)
4,719
def run_episode(kwargs) -> [Trajectory]: """ Runs a single episode and collects the trajectories of each agent """ total_controller_time = 0 env_dict: Callable = kwargs.get("env_dict") obs_builder = kwargs.get("obs_builder") controller_creator: Callable = kwargs.get("controller_creator") ...
4,720
def init_output_logging(): """ Initialize output logger """ global output_logger if output_logger is None: output_logger = OutputLogger() sys.stdout = TeeOutputStream([sys.stdout, output_logger], autoflush=True) sys.stderr = TeeOutputStrea...
4,721
async def _reverse_proxy_handler(request: web.Request) -> web.Response: """ - Adds auth layer - Adds access layer - Forwards request to catalog service SEE https://gist.github.com/barrachri/32f865c4705f27e75d3b8530180589fb """ user_id = request[RQT_USERID_KEY] # path & quer...
4,722
def get_data(request: Request): """ Get the data page. Parameters ---------- request : Request The request object. Returns ------- HTMLResponse The data page. """ return templates.TemplateResponse("data.html", {"request": request})
4,723
def remove_last_measurements(dag_circuit, perform_remove=True): """Removes all measurements that occur as the last operation on a given qubit for a DAG circuit. Measurements that are followed by additional gates are untouched. This operation is done in-place on the input DAG circuit if perform_pop=Tru...
4,724
def get_html(url): """ Given a URL, will return the HTML using urllib3. :param url: The url to extract the HTML from :return: If extracted successfully, the HTML is returned. If there is a failure, a message with HTTP status. If an exception is thrown, -1 is returned witha description of the error ...
4,725
def J(*args, **kwargs): """Wrapper around jsonify that sets the Content-Type of the response to application/vnd.api+json. """ response = jsonify(*args, **kwargs) response.mimetype = "application/vnd.api+json" return response
4,726
def readable_dir(prospective_dir): """ check if dir is exist or acessable""" if not os.path.isdir(prospective_dir): sys.exit("{} is not a valid path".format(prospective_dir)) if os.access(prospective_dir, os.R_OK): return prospective_dir else: sys.exit("{} is not a readable dir"...
4,727
def is_gzipped(filename): """ Returns True if the target filename looks like a GZIP'd file. """ with open(filename, 'rb') as fh: return fh.read(2) == b'\x1f\x8b'
4,728
def test_tan(): """Test of tan method.""" # Test for sin with Rnode objects x = Rnode(1.0) z = Elem.tan(x) z.grad_value = 1.0 try: assert z.value == np.tan(x.value) assert x.grad() == 1 / (np.cos(x.value) ** 2) except AssertionError as e: print(e) # Test for tan...
4,729
def load_schedule_data( neo4j_session: neo4j.Session, data: List[Dict], update_tag: int, ) -> None: """ Transform and load schedule information """ ingestion_cypher_query = """ UNWIND {Schedules} AS schedule MERGE (u:PagerDutySchedule{id: schedule.id}) ON CREATE SET u.html_url = ...
4,730
def load_data(loc='./data/'): """ Load the SICK semantic-relatedness dataset """ trainA, trainB, devA, devB, testA, testB = [],[],[],[],[],[] trainS, devS, testS = [],[],[] with open(os.path.join(loc, 'sick_train.txt'), 'r') as f: for line in f: text = line.strip().split('\t...
4,731
def tag_helper(tag, items, locked=True, remove=False): """ Simple tag helper for editing a object. """ if not isinstance(items, list): items = [items] data = {} if not remove: for i, item in enumerate(items): tagname = '%s[%s].tag.tag' % (tag, i) data[tagname] = i...
4,732
def send_email_updates(poller_name): """ Takes a school name and updates its course data and then sends all open course notifications. """ requests = UpdateDB(poller_name) for request in requests: emails = [] for entry in request[0]: emails.append(entry.email) db.ses...
4,733
def _check_stata_output(output): """.. Check Stata output""" regex = "end of do-file[\s]*r\([0-9]*\);" if re.search(regex, output): error_message = 'Stata program executed with errors.' error_message = format_message(error_message) raise_from(ProgramError(error_message, ...
4,734
def test_ap_wps_upnp_http_proto_chunked(dev, apdev): """WPS AP and UPnP/HTTP protocol testing for chunked encoding""" ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e" add_ssdp_ap(apdev[0], ap_uuid) location = ssdp_get_location(ap_uuid) url = urlparse(location) conn = HTTPConnection(url.netloc)...
4,735
def test_buchtitelgenerator_returns_mocked_books(mock_buchtitelgenerator: Mock) -> None: """It returns a list.""" books = randombuch.buchtitelgenerator() assert "Foo" in books
4,736
def get_keys_from_file(csv): """Extract the credentials from a csv file.""" lines = tuple(open(csv, 'r')) creds = lines[1] access = creds.split(',')[2] secret = creds.split(',')[3] return access, secret
4,737
def _handle_api_error_with_json(http_exc, jsondata, response): """Handle YOURLS API errors. requests' raise_for_status doesn't show the user the YOURLS json response, so we parse that here and raise nicer exceptions. """ if 'code' in jsondata and 'message' in jsondata: code = jsondata['code...
4,738
async def roll(ctx, *, param:re_convert=re_convert.defaults): """Rolls a dice in NdN format.""" rolls, limit = map(int, param["dice"].split('d')) result = ', '.join(str(random.randint(1, limit)) for r in range(rolls)) await ctx.send(result)
4,739
def fix_model(project, models, invert=False): """Fix model name where file attribute is different from values accepted by facets >>> fix_model('CMIP5', ['CESM1(BGC)', 'CESM1-BGC']) ['CESM1(BGC)', 'CESM1(BGC)'] >>> fix_model('CMIP5', ['CESM1(BGC)', 'CESM1-BGC'], invert=True) ['CESM1-BGC', 'CESM1-BG...
4,740
def rectified_linear_unit(x): """ Returns the ReLU of x, or the maximum between 0 and x.""" # TODO return np.maximum(0, X)
4,741
def register_npzd_data(vs, tracer): """ Add tracer to the NPZD data set and create node in interaction graph Tracers added are available in the npzd dynamics and is automatically included in transport equations Parameters ---------- tracer An instance of :obj:`veros.core.npzd_tracer.NP...
4,742
def create_save_directory(path, directory_name): """ This function makes the directory to save the data. Parameters ---------- path : string Where the the directory_name will be. directory_name : string The directory name where the plots will be save Returns ----------...
4,743
def bwt_compress(filename): """Compress with bwt.""" with open(filename, "rb") as in_stream: with open(filename + ".bwt", "wb") as out_stream: bwt_encoded = bwt_encode(in_stream) rle_encoded = rle_encode(bwt_encoded) out_stream.write(rle_encoded) os.remove(filenam...
4,744
def encode_to_filename(folder, animal, session, ftypes="processed_all"): """ :param folder: str folder for data storage :param animal: str animal name: e.g. A2A-15B-B_RT :param session: str session name: e.g. p151_session1_FP_RH :param ftype: list or str: ...
4,745
def _get_choices(choices: Union[str, List]) -> List[Tuple[str, str]]: """Returns list of choices, used for the ChoiceFields""" result = [('', '')] if isinstance(choices, str): result.append((choices, choices)) else: for choice in choices: result.append((choice, choice)) ...
4,746
def invalid_file(): """Create an invalid filename string.""" return "/tmp/INVALID.FILE"
4,747
def ingest_aw1c_manifest(): """ Entrypoint for CVL AW1C Manifest Ingestion workflow """ with GenomicJobController(GenomicJob.AW1C_INGEST, bucket_name=None, bucket_name_list=config.GENOMIC_CENTER_BUCKET_NAME, sub_fo...
4,748
def get_model(app_label, model_name): """ Fetches a Django model using the app registery. All other methods to acces models might raise an exception about registery not being ready yet. This doesn't require that an app with the given app label exists, which makes it safe to call when the regis...
4,749
def main(): """main""" pass
4,750
def add_title(file: '_io.TextIOWrapper', ext: str, title: str, link: str) -> None: """Add title and link of URL to the document. Format depends on file ext. @param File file: File to add to. @param str ext: File extension. @param str title: URL title. @param str link: URL link. @return: No...
4,751
def hexdump(adr_data_tuple, output=sys.stdout): """\ Print a hex dump. :param adr: address :param memstr: memory contents (bytes/string) :param output: file like object to write to """ adr, memstr = adr_data_tuple # conversion to byte array only needed for python 2.xx as bytes would retu...
4,752
def test_main() -> None: """Should load dry (no config) and with empty config""" filename = f"tests/fixtures/temp_{NOW}" assert not os.path.isfile(filename) with patch.object(prfile, "CONFIG_FILE", filename): with patch("builtins.input", lambda user_in: "mock"): with patch.object(p...
4,753
def affaires_view(request): """ Return all affaires """ # Check connected if not check_connected(request): raise exc.HTTPForbidden() query = request.dbsession.query(VAffaire).order_by(VAffaire.id.desc()).all() return Utils.serialize_many(query)
4,754
def metric_try_to_float(s: str) -> Union[float, str]: """ Try to convert input string to float value. Return float value on success or input value on failure. """ v = s try: if "%" in v: v = v[:-1] return float(v) except ValueError: return str(s)
4,755
def calculate_boot_time(pngs_dir, fps, refer_end_pic): """ 通过一系列的截图文件,计算出启动时间 :param pngs_dir: 截图所在目录 :param fps: 帧数 :param refer_end_pic: 结束位置参考图片 :return: 启动时间 """ # 找启动的开始(点击响应)、结束时间(渲染首页内容)点 pngs = os.listdir(pngs_dir) pngs.sort() start_t, end_t, boot_time = 0, 0, 0 ...
4,756
def _table_difference(left: TableExpr, right: TableExpr): """ Form the table set difference of two table expressions having identical schemas. A set difference returns only the rows present in the left table that are not present in the right table Parameters ---------- left : TableExpr ...
4,757
def test_timerange_ispropersuperset(): """timerange_ispropersuperset(TimeRange, TimeRange) -> bool""" timerange_a = TimeRange(Time(1000), Time(2000)) timerange_b = TimeRange(Time(2500), Time(3000)) timerange_c = TimeRange(Time(2000), Time(2500)) timerange_d = TimeRange(Time(1500), Time(2500)) ti...
4,758
def select(receivers, senders, exceptions, timeout): """ receivers - list of one element, the simulated receiver socket senders - list of one element, the simulated sender socket exceptions - empty list, the simulated sockets with exceptions ignore timeout - there is no real concurrency here """...
4,759
def _create_local_database(db_file_path): """Create a new local database""" conn = sql.connect(db_file_path) cur = conn.cursor() table = str('CREATE TABLE config (' 'ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,' 'Name TEXT UNIQUE NOT NULL,' 'Valu...
4,760
def parse_args(): """ It parses the command-line arguments. Parameters ---------- args : list[str] List of command-line arguments to parse Returns ------- parsed_args : argparse.Namespace It contains the command-line arguments that are supplied by the user """ par...
4,761
def parse_row(row, entity_dict, span_capture_list, previous_entity): """ updates the entity dict and span capture list based on row contents """ bio_tag, entity = parse_tag(row.tag) if bio_tag == 'B': # update with previous entity, if applicable entity_dict, span_capture_list, pre...
4,762
def _is_fn_init( tokens: list[Token] | Token, errors_handler: ErrorsHandler, path: str, namehandler: NameHandler, i: int = 0 ): """ "fn" <fn-name> "("<arg>*")" (":" <returned-type>)? <code-body>""" tokens = extract_tokens_with_code_body(tokens, i) if tokens is None ...
4,763
def _toggle_options(event, params): """Toggle options (projectors) dialog""" import matplotlib.pyplot as plt if len(params['projs']) > 0: if params['fig_opts'] is None: _draw_proj_checkbox(event, params, draw_current_state=False) else: # turn off options dialog ...
4,764
async def http_connect(address: str, port: int) -> HttpConnection: """Open connection to a remote host.""" loop = asyncio.get_event_loop() _, connection = await loop.create_connection(HttpConnection, address, port) return cast(HttpConnection, connection)
4,765
def internal_copied_filegroup(name, srcs, strip_prefix, dest, **kwargs): """Macro to copy files to a different directory and then create a filegroup. This is used by the //:protobuf_python py_proto_library target to work around an issue caused by Python source files that are part of the same Python package bei...
4,766
def debug(debug_on=True): """Turn debugging of DICOM file reading and writing on or off. When debugging is on, file location and details about the elements read at that location are logged to the 'pydicom' logger using python's logging module. :param debug_on: True (default) to turn on debugging, ...
4,767
async def run(): """Run the monitoring.""" set_log_levels( logger="info", logger_pyinsteon="info", logger_messages="info", logger_topics=True, ) # await async_connect(host=HOST, username=USERNAME, password=PASSWORD) await async_connect(device=DEVICE) devices.subsc...
4,768
def make_parallel_transformer_config() -> t5_architecture.EncoderDecoder: """Returns an EncoderDecoder with parallel=True.""" dtype = jnp.bfloat16 num_attn_heads = 8 make_dropout = lambda: nn.Dropout(rate=0.1, broadcast_dims=(-2,)) make_layer_norm = layer_norm.T5LayerNorm def _make_encoder_layer(shared_rel...
4,769
def commands(): """ Serve models on RedisAI. To serve a model associated with a run on a tracking server, set the MLFLOW_TRACKING_URI environment variable to the URL of the desired server. """ pass
4,770
def get_device_mapping(embedding_sizes, num_gpus, data_parallel_bottom_mlp, experimental_columnwise_split, num_numerical_features): """Get device mappings for hybrid parallelism Bottom MLP running on device 0. Embeddings will be distributed across among all the devices. Optimal solu...
4,771
def _generate_relative_positions_embeddings(length, depth, max_relative_position, name): """Generates tensor of size [length, length, depth].""" with tf.variable_scope(name): relative_positions_matrix = _generate_relative_positions_matrix( length, max_relative...
4,772
def annotation(): """Annotation file utilities."""
4,773
def continTapDetector( fs: int, x=[], y=[], z=[], side='right', ): """ Detect the moments of finger-raising and -lowering during a fingertapping task. Function detects the axis with most variation and then first detects several large/small pos/neg peaks, then the function determines sample-w...
4,774
def parallelize(df, func): """ Split data into max core partitions and execute func in parallel. https://www.machinelearningplus.com/python/parallel-processing-python/ Parameters ---------- df : pandas Dataframe func : any functions Returns ------- data : pandas Dataframe R...
4,775
def get_functional_groups(alkoxy_mol): """ given a molecule object `alkoxy_mol`. This method returns a dictionary of groups used in the Vereecken SAR with the key being the group and the value being the number of occurances it has. """ #print 'getting groups from {}'.format(alkoxy_mol.toSMIL...
4,776
def rough(material, coverage, scale, det, e0=20.0, withPoisson=True, nTraj=defaultNumTraj, dose=defaultDose, sf=True, bf=True, xtraParams=defaultXtraParams): """rough(material, coverage, scale, det, [e0=20.0], [withPoisson=True], [nTraj=defaultNumTraj], [dose = 120.0], [sf=True], [bf=True], [xtraParams={}]) Mon...
4,777
def test_string_with_correct_type(): """String type""" assert val.is_string('test', desc='test') == 'test'
4,778
def jsonify(comment_lower: str) -> str: """pyNastran: SPOINT={'id':10, 'xyz':[10.,10.,10.]}""" sline = comment_lower.split('=') rhs = sline[1].rstrip() return rhs.replace("'", '"').replace('}', ',}').replace(',,}', ',}')
4,779
def set_attributes_polling(test_case, device_proxy, device_server, poll_periods): """Set attribute polling and restore after test Parameters ---------- test_case : unittest.TestCase instance device_proxy : tango.DeviceProxy instance device_server : tango.Device instance The instance of...
4,780
def test_process_covid_csv_data() -> None: """Checks function test_process_covid_csv_data calculates correct data from set file nation_2021-10-28.csv""" last7days_cases , current_hospital_cases , total_deaths = \ process_covid_csv_data ( parse_csv_data ( 'nation_2021-10-28.csv' ) ) ...
4,781
def get_available_engine( fp16: bool = False, ddp: bool = False, amp: bool = False, apex: bool = False ) -> "IEngine": """Returns available engine based on given arguments. Args: fp16 (bool): option to use fp16 for training. Default is `False`. ddp (bool): option to use DDP for training. De...
4,782
def disk_usage(pathname): """Return disk usage statistics for the given path""" ### Return tuple with the attributes total,used,free in bytes. ### usage(total=118013599744, used=63686647808, free=48352747520) return shutil.disk_usage(pathname)
4,783
def get_default_log_config(): """Get the default logging configuration. Returns: dict: The default logging configuration. """ root = os.path.dirname(__file__) config_file = os.path.join(root, "logging.yaml") with open(config_file, "r") as file_object: data = yaml.load(file_obje...
4,784
def create_new_deployment( runner: Runner, deployment_arg: str, expose: PortMapping, add_custom_nameserver: bool ) -> Tuple[str, str]: """ Create a new Deployment, return its name and Kubernetes label. """ span = runner.span() run_id = runner.session_id runner.show( "Starting net...
4,785
def score_latency( references, reference_wavs, partial_translations, target_language="en-US" ): """Measures the "final" translation lag after all corrections have been made.""" logger = logging.getLogger("evaluation") tokenizer = get_tokenizer(target_language) min_len = min(len(partial_translations...
4,786
def stack_analysis_benchmark(queue, threads, stack_analysis, thread_count, python_payload, maven_payload, npm_payload): """Stack analysis benchmark.""" # TODO: read automagically from the filelist manifests = ( ("maven", "clojure_1_6_0.xml"), ("maven", "clojure_1...
4,787
def shapelet_with_w_term( coords, frequency, coeffs, beta, delta_lm, lm, dtype=np.complex128 ): """ shapelet: outputs visibilities corresponding to that of a shapelet Inputs: coords: coordinates in (u,v) space with shape (nrow, 3) frequency: frequency values with shape (nchan,) c...
4,788
async def mocktext(ctx, *texts): """Converts input into a mocking sentence""" sentence = " ".join(texts[:]) sentence.lower() msg = "".join(choice((str.upper, str.lower))(c) for c in sentence) await ctx.send(msg)
4,789
def test_person__DeletePersonForm__2(person_data, browser): """`DeletePersonForm` can be cancelled.""" browser.login('editor') browser.open(browser.PERSON_DELETE_URL) browser.getControl('No, cancel').click() assert 'Deletion canceled.' == browser.message assert browser.PERSON_EDIT_URL == browser...
4,790
def renderLayerPostProcess(q=1,ki=1,sn="string"): """ http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/renderLayerPostProcess.html ----------------------------------------- renderLayerPostProcess is NOT undoable, queryable, and NOT editable. Post process the results when rendering is d...
4,791
def CylindricalVectorsToCartesian(coordinates, data): """ Project the supplied cylindrical coordinates (r-phi-z) vectors to 3D Cartesian (x-y-z). coordinates must be in Cartesian. """ if optimise.DebuggingEnabled(): assert(len(coordinates) == len(data)) for i, coord in enumerate(coordinates): ...
4,792
def _entropy_counter2(arr): """ calculate the base 2 entropy of the distribution given in `arr` using a `Counter` and the `values` method (for python3) """ arr_len = len(arr) if arr_len == 0: return 0 log_arr_len = np.log2(len(arr)) return -sum(val * (np.log2(val) - log_arr_len) ...
4,793
def update_deleted_strain(_, strain_to_del): """Update ``deleted-strain`` var. This happens after a user clicks the OK btn in the confirm strain deletion modal. We also delete the files associated with the strain at this step. :param _: User clicked the OK btn :param strain_to_del: Strain cor...
4,794
def get_changes_between_models(model1, model2, excludes=None): """ Return a dict of differences between two model instances """ if excludes is None: excludes = [] changes = {} for field in model1._meta.fields: if (isinstance(field, (fields.AutoField, ...
4,795
def write_transaction(connection, signed_transaction): """Write a transaction to the backlog table. Args: signed_transaction (dict): a signed transaction. Returns: The result of the operation. """ raise NotImplementedError
4,796
def get_intersect(x1, y1, x2, y2): """ Returns the point of intersection of the lines or None if lines are parallel Ex. p1=(x1,x2)... line_intersection((p1,p2), (p3,p4)) a1: [x, y] a point on the first line a2: [x, y] another point on the first line b1: [x, y] a point on the second line b2: ...
4,797
def removeDuplicateColumns(df): """ Removes columns that have a duplicate name. :return pd.DataFrame: """ duplicates = getDuplicates(df.columns) done = False idx = 0 df_result = df.copy() additions_dict = {} while not done: if idx >= len(df_result.columns): done = True break colu...
4,798
def load_files(file_path_smh, file_path_ic, datastruct): """Load the files by asking the controller the filepaths smh and ic provided by the user and store the appropriate data in the data structure object (dictionary). Before storing, the data are verified""" dm3_meta_smh = dm3_lib.DM3(file_path_smh) d...
4,799