content
stringlengths
22
815k
id
int64
0
4.91M
def makedir(checkpoint_dir): """Creates a directory if checkpoint_dir does not exist""" if not os.path.exists(checkpoint_dir): os.makedirs(checkpoint_dir, exist_ok = True)
5,305,800
def get_ip_from_mac(): """ A HTTP GET function to fetch the IP address for mentioned MAC and Subnet in the JSON request parameters Parameters --- mac_address : subnet_id : <int> : Subnet ID """ LOGGER.info("Request url -> /dhcp4/getipfrommac") LOGGER.info...
5,305,801
def _proxy_for_evolvable_object(obj): """ :returns: an ``_IRecursiveEvolverProxy`` suitable for the type of ``obj``. """ if not _IEvolvable.providedBy(obj): raise TypeError( "{!r} does not provide {}".format( obj, _IEvolvable.__name__ ) ...
5,305,802
def dir_abs_path(path_str: str) -> Path: """ Validate directory `path_str` and make it absolute. Arguments: path_str -- A path to check. Returns: An absolute path. Raises: argparse.ArgumentTypeError -- If path is not a directory. """ path = Path(path_str).absolute(...
5,305,803
def parse_download_data(data: List[AnimeThemeAnime]) -> List[DownloadData]: """ Parses a list of animethemes api returns for anime. Returns download data. """ out = [] songs = set() for anime in data: last_group = None for tracknumber,theme in enumerate(anime['t...
5,305,804
def parse_glyphs_groups(names, groups): """ Parse a ``gstring`` and a groups dict into a list of glyph names. """ glyph_names = [] for name in names: # group names if name[0] == '@': group_name = name[1:] if group_name in groups: glyph_names +...
5,305,805
def main(command): """ :param command: :return: """ try: try: domainName = os.environ["DomainName"] healthCheckName = os.environ["healthCheckName"] except : print_log("DomainName or healthCheck Name is not given properlly") sys.exit(12...
5,305,806
def projection_test(n): """ This test constructs a two sets of variables related to each other by a simple linear transformation (scale and offset). The time is measured to change a variable on either side of the mapping and to change the scale and offset factors. """ global planner plan...
5,305,807
def ensure_strings_have_quotes_sequence(sequence_object): """Ensures Sequence objects have quotes on string entries. Args: sequence_object (iter): A python iterable object to ensure strings have quotes. Returns: iter: The ``sequence_object`` is returned having its string values with quotes...
5,305,808
def set_parser(): """ set custom parser """ parser = argparse.ArgumentParser(description="") parser.add_argument("-r", "--regions", nargs='+', required=False, default=['R1', 'R2', 'R3'], help="The regions to train on (default is R1 R2 R3)") parser.add_argument("-m", "--weig...
5,305,809
def patient_detail(request, pk): """ View to display patient details (name, ID, fractions) """ patient = get_object_or_404(Patient, pk=pk) fractions = Fraction.objects.filter(patient=pk) url = 'doseapp/static/doseapp/tolerances.json' json_data = open(url)# False tolerances = json.load(js...
5,305,810
def plot_tricentroids(n_clusters, arr, tri_chroms, tri_genes, tri_samples, delta, l, xlabels=None, n_subplots=4, error_bars='range', figsize=(17.075, 8.1125), filename=None, dpi=150, paper_style=False, fontsize=8): """ Plots the centroids of the ...
5,305,811
def event_fixture(): """Return a received event from the websocket client.""" return { "type": "event", "event": { "source": "node", "event": "value updated", "nodeId": 52, "args": { "commandClassName": "Basic", "com...
5,305,812
def test_invalid_search_query_secondname(): """Assert that an invalid search query fails - debtor second name is too long.""" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['criteria']['debtorName']['second'] = 'XXXXXXXXXXXXXX...
5,305,813
def check_and_make_dir(dir): """ Check if a directory exists or contains data before to makedir. If exists, query the user to remove its content. Parameters ---------- dir: str path to a directory """ if os.path.exists(dir) and os.listdir(dir)!=[]: clean = query_yes_no("...
5,305,814
def check_urls(file, urls): """ check urls extracted from a certain file and print the checks results. Args: file (str) : path to file. urls (list) : list of urls to check. """ # get longest url size long_url = str(max([len(url) for url in urls])) # define orint format ...
5,305,815
def test_sa6(): """ Test exceptions. """ a = np.arange(5) with pytest.raises(ValueError): segment_axis(a, 2, 3, end='wrap')
5,305,816
def get_address(click_context, type_): """Get the address associated with the private key.""" ctx = cast(Context, click_context.obj) _verify_or_create_private_keys(ctx) address = _try_get_address(ctx, type_) click.echo(address)
5,305,817
def run_dcos_engine(dcos_engine_url: str, dcos_engine_template): """ Runs the dcos-engine """ tmpdir = tempfile.mkdtemp() # pull down dcos engine in temp dir download_path = os.path.join(tmpdir, 'download.tar.gz') with open(download_path, 'wb') as f: r = requests.get(dcos_engine_url) ...
5,305,818
def tf_idf(train_data, test_data, weight_type, sentence_type): """ :param train_data: :param test_data: :param weight_type: :param sentence_type: :return: """ tfidf_vectorizer = TfidfVectorizer(ngram_range=(1,2),max_df=0.9, min_df=3, use_idf=1, smooth_idf=1, sublinear_tf=1) # tfidf_...
5,305,819
def get_workspace_diff(workflow_a, workflow_b, brief=False, context_lines=5): """Return differences between two workspaces. :param workflow_a: The first workflow to be compared. :type: reana_db.models.Workflow instance. :param workflow_b: The second workflow to be compared. :type: reana_db.models.W...
5,305,820
def receive_product_view(sender, product, user, request, response, **kwargs): """ Receiver to handle viewing single product pages Requires the request and response objects due to dependence on cookies """ return CustomerHistoryManager.update(product, request, response)
5,305,821
def bulk_create_entries( es_client: elasticsearch.Elasticsearch, es_index: Union[str, UUID], journal_id: Union[str, UUID], entries: List[JournalEntryResponse], ) -> str: """ Index a new entry in a journal. Returns the ID of the new document. If an entry with that ID has already been indexed,...
5,305,822
def norm_density(matrix: np.ndarray): """ Calculate normalized density for a given activity matrix. :param matrix: activity matrix :return: normalized density value """ return 1 - abs(1 - 2 * (np.count_nonzero(matrix) / matrix.size))
5,305,823
def kernel(a, b, length_scale=1.): """ GP squared exponential kernel """ n = a.shape[0] m = b.shape[0] K = np.zeros(shape=(n, m), dtype=float) for i in np.arange(n): for j in np.arange(m): dif = a[i, :] - b[j, :] sqdist = dif * dif.T if sqdist.shape[0] != ...
5,305,824
def str_id(qualified_name): """Return PROVN representation of a URI qualified name. Params ------ qualified_name : QualifiedName Qualified name for which to return the PROVN string representation. """ return qualified_name.provn_representation().replace("'", "")
5,305,825
def detect(text_proposals, scores, size): """ Detect text boxes Args: text_proposals(numpy.array): Predict text proposals. scores(numpy.array): Bbox predicts scores. size(numpy.array): Image size. Returns: boxes(numpy.array): Text boxes after connect. """ keep_pr...
5,305,826
def GetImage(): """ 获得Bing壁纸 """ url = 'https://cn.bing.com' # 请求标头 # 获取页面并转为dict格式 req = requests.get(url=url) req.encoding = req.apparent_encoding soup = BeautifulSoup(req.text, 'html.parser') # 用BeautifulSoup库解析网页 head = soup.head # 获得壁纸的地址,需要进行拼接 ul = hea...
5,305,827
def csr_load(data, prefix=None): """ Rematerialize a CSR matrix from loaded data. The inverse of :py:func:`csr_save`. Args: data(dict-like): the input data. prefix(str): the prefix for the data keys. Returns: CSR: the matrix described by ``data``. """ if prefix is None...
5,305,828
def perc_range(n, min_val, max_val, rounding=2): """ Return percentage of `n` within `min_val` to `max_val` range. The ``rounding`` argument is used to specify the number of decimal places to include after the floating point. Example:: >>> perc_range(40, 20, 60) 50 """ ret...
5,305,829
async def test_upgraded_extended_version_sync_analysis_module(concurrency_mode, redis_url, manager): """Tests the ability of a sync analysis module to update extended version data.""" # we want to bail after the first execution of the module class CustomAnalysisModuleManager(AnalysisModuleManager): ...
5,305,830
def _translate_tag_class(tag_class): """ Translate ASN.1 tag class names to pyasn1 equivalents. Defaults to tag.tagClassContext if tag_class is not recognized. """ return _ASN1_TAG_CONTEXTS.get(tag_class, 'tag.tagClassContext')
5,305,831
def memo(f): """Memoization for function $f$""" cache = {} @wraps(f) def wrap(*args): if args not in cache: cache[args] = f(*args) return cache[args] return wrap
5,305,832
def expand_nested_tasks_or_globs(p, tasksglobs_to_filenames): """ Expand globs and tasks "in-line", unless they are the top level, in which case turn it into a list N.B. Globs are only expanded if they are in tasksglobs_to_filenames This function is called for @split descriptors which leave ou...
5,305,833
def process_experience( experience: List[List[agent.ExpTuple]], actor_steps: int, num_agents: int, gamma: float, lambda_: float): """Process experience for training, including advantage estimation. Args: experience: collected from agents in the form of nested lists/namedtuple actor_step...
5,305,834
def associateIpAddress(**kargs): """ Get additional public IP in Selected Zone * Args: - zone(String, Required) : [KR-CA, KR-CB, KR-M, KR-M2] * Examples : print(server.associateIpAddress(zone='KR-M')) """ my_apikey, my_secretkey = c.read_config() if not 'zone' in kargs: ...
5,305,835
def nltk_regex_tokenizer(input_dict): """ The Regex Tokenizer splits a string into substrings using a regular expression. :param :param pattern: The pattern used to build this tokenizer. (This pattern may safely contain capturing parentheses.) :param gaps: True if this tokenizer's pattern shoul...
5,305,836
def load_hetrec_to_df(data_dir_path, encoding='utf-8', ): """ Loads hetrec data into pandas DataFrame. Currently only minimal subset of data, containing info only about users movie rating (identified by pair user_id/movie_id) is being loaded. Note that nans/empty values in general are replaced with dumm...
5,305,837
def main(args): """Call tools in assigned order.""" fasta_ref = args.Reference ref_org = args.ReferenceName do_fastq_pretrim = args.runFastqcPreTrim do_fastq_trim = args.runFastqcPostTrim fasta_ref_file = f'input/references/{fasta_ref}' vcf_ref_file = f'input/references/{args.ReferenceVCF}...
5,305,838
def get_or_create_default_gcs_bucket(options): """Create a default GCS bucket for this project.""" if getattr(options, 'dataflow_kms_key', None): _LOGGER.warning( 'Cannot create a default bucket when --dataflow_kms_key is set.') return None project = getattr(options, 'project', None) region = g...
5,305,839
def lab_to_xyz(image: tf.Tensor) -> tf.Tensor: """ Convert an image from LAB color space to XYZ color space Parameters ---------- image: tf.Tensor Returns ------- tf.Tensor : LAB image """ l, a, b = tf.unstack(image, axis=-1) var_y = (l + 16) / 116 var_x = a / 500 + var...
5,305,840
def onpick3(event): """ Interactive clicking for pyplot scatter plots. Example: fig, ax = plt.subplots() x = ... y = ... col = ax.scatter(x, y, s = 1, picker = True) fig.canvas.mpl_connect('pick_event', onpick3) """ ind = event.ind print('onpick3 scatter:', ind, np.take(x, in...
5,305,841
def test_export_agent(creds, gcs_bucket): """Tests the SCRAPI method export_agent from core/agents.py""" a = agents.Agents(creds_path=creds) ops = operations.Operations(creds_path=creds) lro = a.export_agent( pytest.temp_agent.name, f"gs://{gcs_bucket}/testing_export.json" ) tim...
5,305,842
def set_config_lock(ip, state, script): """ Author - Jonathan Steward Function - Used to set the config lock for a certain device. When setting it gives details of why its being set Uses state to identify if we want to set a config lock or remove it. Inputs - ip - String...
5,305,843
def UQADD(cpu_context: ProcessorContext, instruction: Instruction): """Unsigned saturating add (vector and scalar form)""" logger.debug("%s instruction not currently implemented.", instruction.mnem)
5,305,844
def check_interacting_energy_components(reference_system, alchemical_system, alchemical_regions, positions, all_alchemical_atoms=None, multi_regions=False): """Compare full and alchemically-modified system energies by energy component. Parameters ---------- refer...
5,305,845
def get_index_constituents(constituency_matrix: pd.DataFrame, date: datetime.date, folder_path: str, print_constituents=False) -> pd.Index: """ Return company name list (pd.Index) of index constituents for given date :param print_constituents: Flag indicating whether to print out...
5,305,846
def make_pairs(coords,pair_indices,offset=.01): """Returns list of Polygon objects, given a list of coordinates and indices. - coords: list of [x,y] coordinates, already scaled to matplotlib axes. - pair_indices: indices in the coordinate list that are paired. """ pairs = [] for fir...
5,305,847
def medialive_multiplexes(region): """ Return the MediaLive Multiplexes for the given region. Tags included. """ items = [] service_name = "medialive" if region in boto3.Session().get_available_regions(service_name): service = boto3.client(service_name, region_name=region, config=MSA...
5,305,848
def embed64(filename=None, file=None, data=None, extension='image/gif' ): """ helper to encode the provided (binary) data into base64. Args: filename: if provided, opens and reads this file in 'rb' mode file: if provided, reads this file ...
5,305,849
def sort_sequence_by_key(sequence, key_name, reverse=False): """ often when setting up initial serializations (especially during testing), I pass a list of dictionaries representing a QS to some fn. That list may or may not be sorted according to the underlying model's "order" attribute This fn sort...
5,305,850
def test_run_tenary_eval_with_arguments(args, results, dataset): """Run a wrapped tenary evaluation function with different sets of arguments. """ f = Eval(columns=['A', 'B'], func=my_extract_concat, args=args) values = f.eval(dataset) assert values == results
5,305,851
def process_hdmedia(hdmedia: Union[List, Dict[Any, Any]]) -> Dict[Any, Any]: """Pull out the relevant HDMedia dictionary based on SAP code values :param hdmedia (list): list of HDMedia dictionaries""" # Note: HDMedia can be either a list or a dict, depending on whether # the value is being passed ...
5,305,852
def gauss_newton(x_init, model, cost_thresh=1e-9, delta_thresh=1e-9, max_num_it=10): """Implements nonlinear least squares using the Gauss-Newton algorithm :param x_init: The initial state :param model: Model with a function linearise() the returns A, b and the cost for the current state estimate. :par...
5,305,853
def SRCNNex(input_shape= (None, None, 3), depth_multiplier=1, multi_output=False): #33.12 """ Implementation of SRCNNex. The kernel size of the mapping layer is increased from 1 to 5. @ multi_output : set to True """ inputs = Input(input_shape, name="inputs") # normalize value betw...
5,305,854
def sws_to_sagews(filename): """ Convert a Sage Notebook sws file to a SageMath Cloud sagews file. INPUT: - ``filename`` -- the name of an sws file, say foo.sws OUTPUT: - creates a file foo[-n].sagews and returns the name of the output file """ out = '' import os, tarfile t =...
5,305,855
def create_train_test(csv_train, csv_test, data_path=DATA_PATH): """Create images on `data_path` from data provided by csvs. This is just a wrapper of csv2img to create the images provided by many csvs at once. Args: csv_list ([type]): [description] data_path (str, optional): [descripti...
5,305,856
def identity() -> GradientTransformation: """Stateless identity transformation that leaves input gradients untouched. This function passes through the *gradient updates* unchanged. Note, this should not to be confused with `set_to_zero`, which maps the input updates to zero - which is the transform required f...
5,305,857
def setup_ngrok(): """ Build ngrok tunnel for inbound webhook calls """ logging.info("ngrok enabled. Spinning up tunnels...") # Get Auth token: NGROK_AUTH_TOKEN = os.environ.get("NGROK_TOKEN") if not NGROK_AUTH_TOKEN: logging.error("Missing config item: NGROK_TOKEN. Program will sti...
5,305,858
def width_from_bitdefs(bitdefs): """ Determine how wide an binary value needs to be based on bitdefs used to define it. Args: bitdefs (list(BitDef)): List of bitdefs to find max width of Returns: (int): Maximum width """ max_index = max([bitdef.end for bitdef in bitdefs]) ...
5,305,859
def mercury(url, mercury_cli_path): """Wrap the Mercury Parser command line driver url: URL string to parse mercur_cli_path: path to mercury-parser command line driver """ response = muterun_js( mercury_cli_path, url ) if response.exitcode != 0: print('[ERROR] UR...
5,305,860
def clean_almost_all(): """Example of script to clean all data on server except """ es = init_elastic_client() doc = { 'size': 1000, 'query': { 'match_all': {} } } # doc = { # 'size': 1000, # "query": {"bool": { "must": { # "term": ...
5,305,861
def _mkdir_recursive_local(uri, local=None): """ Recursively create local directory specified by URI. Args: uri: parsed URI to create. local: local context options. Returns: On success: True. On failure: False. """ # same as the non-recursive call return _m...
5,305,862
def build_docs(): """Build docs for package """ subprocess.check_call(['scons', '-f', 'src/SConstruct']) return ['doc/spowtd.1', 'doc/user_guide.pdf']
5,305,863
def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to fi...
5,305,864
def get_intersection_over_union(first_segmentation, second_segmentation): """ Computes intersection over union (IoU) between two segmentation maps. Maps are binary - that is their values are 0s and 1s only. IoU is computed between non-zero elements of both segmentation maps. :param first_segmentatio...
5,305,865
def tmake_customer_version(dict_params): """focse library name""" if dict_params: core.log.e("custom version: {}".format(dict_params)) core.data.deps_mgr.add_conflict_solution(dict_params)
5,305,866
def logLikelihood(params, main_time_series, reply_time_series, verbose=False): """Log-likelihood object function""" " The log-likelihood fucntion is composed with main post stream and reply post stream events " " ...
5,305,867
def getAnglesFromDict(d):# NOTE Fails currently if dict is None """ Converts a dictionary to a angles of a JointState() :param d (dict): The dictionary to be converted :return (sensor_msgs.msg.JointState): The angles """ # print datapath if d is None: rospy.loger...
5,305,868
def propagate_memlets_scope(sdfg, state, scopes): """ Propagate memlets from the given scopes outwards. :param sdfg: The SDFG in which the scopes reside. :param state: The SDFG state in which the scopes reside. :param scopes: The ScopeTree object or a list thereof to start from. :note: This op...
5,305,869
def generate_randomkey(length): """Generate random key, given a number of characters""" chars = string.ascii_letters + string.digits return ''.join([choice(chars) for i in range(length)])
5,305,870
def get_vectorized_series(text_series, vectorizer): """ 사전 훈련된 벡터화 객체를 사용해 입력 시리즈를 벡터화합니다. :param text_series: 텍스트의 판다스 시리즈 :param vectorizer: 사전 훈련된 sklearn의 벡터화 객체 :return: 벡터화된 특성 배열 """ vectors = vectorizer.transform(text_series) vectorized_series = [vectors[i] for i in range(vectors...
5,305,871
def _gen_request_slices(**kwargs): """Creates a TaskRequest.""" now = utils.utcnow() args = { u'created_ts': now, u'manual_tags': [u'tag:1'], u'name': u'Request name', u'priority': 50, u'task_slices': [ task_request.TaskSlice(expiration_secs=30, properties=_gen_properties()), ], ...
5,305,872
def idm_cutin_pars(**kwargs): """ Define the parameters for the IDM model in a cut-in scenario. The reaction time is sampled from the lognormal distribution mentioned in Wang & Stamatiadis (2014) if it not provided through kwargs. :param kwargs: Parameter object that can be passed via init_simulation....
5,305,873
def extractcode(ctx, input, verbose, quiet, shallow, replace_originals, ignore, *args, **kwargs): # NOQA """extract archives and compressed files found in the <input> file or directory tree. Archives found inside an extracted archive are extracted recursively. Extraction for each archive is done in-place ...
5,305,874
def profile(request): """A view handler for fetching the user's profile data.""" profile_id = begin(request) request_id = param_or_null(request, "request_id") cursor = connection.cursor() cursor.execute("""SELECT p.username, p.real_name, p.em...
5,305,875
def save_config(packageormod=None, filename=None): """ Saves all configuration settings to the configuration file for the root package of the requested package/module. This overwrites any configuration items that have been changed in `ConfigurationItem` objects that are based on the configuration file ...
5,305,876
def connection_checker( p_database: str, p_server: str, p_user: str, p_password: str, p_port: int ): """ Проверяет подключение к метаданным """ # выполняет простой запрос на источнике sql_exec( p_database=p_database, p_server=p_server, ...
5,305,877
def snapshot_stabilizer(self, label): """Take a stabilizer snapshot of the simulator state. Args: label (str): a snapshot label to report the result. Returns: QuantumCircuit: with attached instruction. Raises: ExtensionError: if snapshot is invalid. Additional Information...
5,305,878
def normalise_composition(comp): """Normalise rows of an array to unit sum, i.e. rows are compositional vectors.""" s = comp.sum(axis=-1) if type(s) is float: return comp / s return comp / s[..., np.newaxis]
5,305,879
def test_report_collection_diff_different() -> None: """Test reporting of different collections.""" from_collection = ["aaa", "bbb", "ccc", "YYY"] to_collection = ["aZa", "bbb", "XXX", "ccc"] error_message = ( "Different tests were collected between 1 and 2. The difference is:\n" "--- 1\...
5,305,880
def main(): """A simple test case.""" x = [0, 1/3, 1] y = floatX([[51, 51, 127], [51, 127, 51], [255, 102, 51]]) / 255 # x = [0, 0.5, 1] # y = floatX([[20, 80, 120], [40, 60, 160], [255, 255, 200]]) / 255 g = Gradient(x, y, bg=BgColors.LIGHT) x_out, y_out, _ = g.make_gradient(steps=30, bg=Bg...
5,305,881
def _validate_magics_with_black(before: Sequence[str], after: Sequence[str]) -> bool: """ Validate the state of the notebook before and after running nbqa with black. Parameters ---------- before Notebook contents before running nbqa with black after Notebook contents after runn...
5,305,882
async def test_migrate_analyses(mocker, dbi): """ Make sure all of the migration functions compose together correctly. """ settings = { "foo": "bar" } m_rename_results_field = mocker.patch( "virtool.analyses.migrate.rename_results_field", make_mocked_coro() ) m...
5,305,883
def segment_denoise(rec_vol, rhos): """This function computes the segmentation of the denoised image. :param rec_vol: The reconstruction (np.array_like) :param rhos: The segmentation target levels (np.array_like) :returns: The segmented image :rtype: np.array_like """ prnt_str = "...
5,305,884
def test_init_getproctitle(): """getproctitle() returns a sensible value at initial call.""" rv = run_script( """ import setproctitle print(setproctitle.getproctitle()) """, args="-u", ) assert rv == sys.executable + " -u\n"
5,305,885
def _select_variable(work_dir,infile,variablename,remove=False): """ select variables from infile """ cdo=Cdo() oname=work_dir + os.sep + "temp" + os.sep + tempfile.NamedTemporaryFile().name.split('/')[-1] cdo.selname(variablename,input=infile,output=oname,options='-f nc4 -b F32') if remove: ...
5,305,886
def get_gelImage(tags): """Returns pictures from Gelbooru with given tags.""" tags = list(tags) formatted_tags = "" rating = "" ratings = { "re": "rating%3aexplicit", "rq": "rating%3aquestionable", "rs": "rating%3asafe" } if tags: # if there are any tags, check for...
5,305,887
def play(): """ Args: None Returns: None """ driver = webdriver.Firefox(executable_path='/Users/keneudeh/Downloads/geckodriver') driver.get('https://play2048.co/') key_select = [Keys.UP, Keys.DOWN, Keys.LEFT, Keys.RIGHT] gameStatusElem = driver.find_element_by_css_selec...
5,305,888
def deriv_MCP(w, alpha=1., g=3): """Derivative of the MCP, w > 0""" return (w < alpha * g) * (alpha - w / g)
5,305,889
def bidirectional_rnn(cell_fw, cell_bw, inputs, initial_state_fw=None, initial_state_bw=None, dtype=None, sequence_length=None, scope=None): """Creates a bidirectional recurrent neural network. Similar to the unidirectional case above (rnn) but takes input and builds i...
5,305,890
def clean_rdr_dataset(project_id=None, dataset_id=None): """ Run all clean rules defined for the rdr dataset. :param project_id: Name of the BigQuery project. :param dataset_id: Name of the dataset to clean """ if dataset_id is None or dataset_id == '' or dataset_id.isspace(): dataset...
5,305,891
def get_colors(): """ Returns a list of all the available color constants. :rtype: list of :py:class:`Color` """ return GraphicsWindow.colors
5,305,892
def area_circ(r_in): """Calculates the area of a circle with given radius. :Input: The radius of the circle (float, >=0). :Returns: The area of the circle (float).""" if r_in < 0: raise ValueError("The radius must be >= 0.") area_out = np.pi * r_in**2 print("The area of a circle with ra...
5,305,893
def _ve_pdg_format_ ( ve , latex = False ) : """Round value/error accoridng to PDG prescription and format it for print @see http://pdg.lbl.gov/2010/reviews/rpp2010-rev-rpp-intro.pdf @see section 5.3 of doi:10.1088/0954-3899/33/1/001 Quote: The basic rule states that if the three highest orde...
5,305,894
def plot_xkcd_aif_paif(x, ns, kmax): """ Professional scientific plotting ... """ # --- AIF / PAIF --- print("[+] AIF:") aif_ = aif(x, ns, kmax) print("[+] PAIF:") paif_ = paif(x, ns, kmax) # --- Figure --- fs_tix = 14 fs_label = 16 fs_title = 18 xyc = "axes fractio...
5,305,895
def parse_stdout_data(stdout): """解析输出 Args: stdout ([byte]): 标准输出 Returns: [list]: 返回解析后的数据 """ if stdout is None: #判断输出是否为None return pattern = r'[\r\n|\r|\n|=]' # 防止不同平台下回车不同,无法正确解析 res = re.split(pattern,stdout.decode('UTF-8').strip()) #依照回车分割字符串 for i,el in...
5,305,896
def split(array, nrows, ncols): """Split a matrix into sub-matrices.""" return array.reshape(array.shape[1]//nrows, nrows, -1, ncols).swapaxes(1, 2)
5,305,897
async def push_status(req): """Push a status update to a job.""" data = req["data"] if data["state"] == "error" and not data["error"]: raise HTTPBadRequest(text="Missing error information") try: document = await get_data_from_req(req).jobs.push_status( req.match_info["job_i...
5,305,898
def _remove_spans(node): """Return a new ``QASMNode`` with all spans recursively set to ``None`` to reduce noise in test failure messages.""" if isinstance(node, list): return [_remove_spans(item) for item in node] if not isinstance(node, QASMNode): return node kwargs = {} no_ini...
5,305,899