content
stringlengths
22
815k
id
int64
0
4.91M
def train_callbacks(loop:Loop)->"A cluster of callback function": """ call backs allow optimizing model weights """ loop.core.metric_tab = MetricTab() @loop.every_start_FORWARD def switch_model_to_train(loop:Loop): loop.model("train")() @loop.on_DATA_PROCESS def opt_zero_grad(loop:Loop...
5,327,000
def pb_set_defaults(): """Set board defaults. Must be called before using any other board functions.""" return spinapi.pb_set_defaults()
5,327,001
def count_routes_graph(graph, source_node, dest_node): """ classic tree-like graph traversal """ if dest_node == source_node or dest_node - source_node == 1: return 1 else: routes = 0 for child in graph[source_node]: routes += count_routes_graph(graph, child, dest...
5,327,002
def pluck_state(obj: Dict) -> str: """A wrapper to illustrate composing the above two functions. Args: obj: The dictionary created from the json string. """ plucker = pipe(get_metadata, get_state_from_meta) return plucker(obj)
5,327,003
def value( parser: Callable[[str, Mapping[str, str]], Any] = nop, tag_: Optional[str] = None, var: Optional[str] = None, ) -> Parser: """Return a parser to parse a simple value assignment XML tag. :param parser: The text parser to use for the contents of the given `tag_`. It will a...
5,327,004
def list_locations_command(): """Getting all locations """ locations = list_locations().get("value") outputs = list() if locations: for location in locations: if location.get("properties") and location.get("properties").get( "homeRegionName" ): ...
5,327,005
def compute_Rnorm(image, mask_field, cen, R=12, wid=1, mask_cross=True, display=False): """ Compute (3 sigma-clipped) normalization using an annulus. Note the output values of normalization contain background. Paramters ---------- image : input image for measurement mask_field : mask map wi...
5,327,006
def add_filter( self, gene_filter=None, transcript_filter=None, ref_transcript_filter=None ): """Defines and assigns filter flags, which can be used by iter_transcripts. Filters are defined as dict, where the key is a filter identifier, and the value is an expression, which gets evaluated on the gene/t...
5,327,007
def inject_timeout(func): """Decorator which injects ``timeout`` parameter into request. On client initiation, default timeout is set. This timeout will be injected into any request if no explicit parameter is set. :return: Value of decorated function. """ @six.wraps(func) def decorator(s...
5,327,008
def chunkify(lst, n): """Yield successive n-sized chunks from lst.""" for i in range(0, len(lst), n): yield lst[i:i + n]
5,327,009
def test_match_partial(values): """@match_partial allows not covering all the cases.""" v, v2 = values @match_partial(MyType) class get_partial_value(object): def MyConstructor(x): return x assert get_partial_value(v) == 3
5,327,010
def assert_sim_of_model_with_itself_is_approx_one(mdl: nn.Module, X: Tensor, layer_name: str, metric_comparison_type: str = 'pwcca', metric_as_sim_or_dist: str = 'dist') ...
5,327,011
def cver(verstr): """Converts a version string into a number""" if verstr.startswith("b"): return float(verstr[1:])-100000 return float(verstr)
5,327,012
def test_if_supported_tags_are_valid(client): """ GIVEN a Request object WHEN validating the tags property of the object THEN is allows only valid and up-to-date choices """ r = Request() actual = r.fields["tag"].choices expected = [entry["tag"] for entry in client.retrie...
5,327,013
def log_and_raise_exception(error_message): """input: error_message (error message string) logs error and raises exception """ logger.error(error_message) raise Exception(error_message)
5,327,014
def test_float_const(message_type): """ message Message { float value = 1 [(validate.rules).float.const = 4.2]; } """ validate(message_type(value=4.2)) with pytest.raises(ValidationError, match="value not equal to"): validate(message_type(value=2.4))
5,327,015
def _GetGaeCookie(host, service, auth_token, secure): """This function creates a login cookie using the authentication token obtained after logging in successfully in the Google account. Args: host: Host where the user wants to login. service: Service code where the user wants to login. auth_token: A...
5,327,016
async def ping_handler() -> data.PingResponse: """ Check server status. """ return data.PingResponse(status="ok")
5,327,017
def add_era5_global_attributes(ds, creation_datetime): """Adds global attributes to datasets""" global_attrs = { r"conventions": r"CF-1.7", r"contact": r"l.c.denby[at]leeds[dot]ac[dot again]uk s.boeing[at]leeds[dot]ac[dot again]uk", r"era5_reference": r"Hersbach, H., Bell, B., Berrisford...
5,327,018
def test_degree(poly_equation): """ The degree is correct. """ equation = poly_equation A = 1e10 degree = np.log(equation.flux(A)/equation.flux(1))/np.log(A) npt.assert_allclose(equation.degree(), degree)
5,327,019
def main(): """Start a child process, output status, and monitor exit.""" args = docopt.docopt(__doc__, options_first=True, version=__version__) command = " ".join(args["<command>"]) timeout = parse_time(args["--timeout"]) # Calculate the time at which we will kill the child process. now = now_...
5,327,020
def duplicate_keypair_name(): """ Duplicate key pair name. @raise Ec2stackError: Defining a bad request and message. """ raise Ec2stackError( '400', 'InvalidKeyPair.Duplicate', 'The keypair already exists.' )
5,327,021
def get_columns_sql(table): """Construct SQL component specifying table columns""" # Read rows and append column name and data type to main container template_path = os.path.join(os.environ['MYSQL_TABLE_TEMPLATES_DIR'], f'{table}.csv') with open(template_path, newline='') as f: template_reader...
5,327,022
def publish_alert_to_sns(binary: BinaryInfo, topic_arn: str) -> None: """Publish a JSON SNS alert: a binary has matched one or more YARA rules. Args: binary: Instance containing information about the binary. topic_arn: Publish to this SNS topic ARN. """ subject = '[BinaryAlert] {} match...
5,327,023
def create_session_cookie(): """ Creates a cookie containing a session for a user Stolen from https://stackoverflow.com/questions/22494583/login-with-code-when-using-liveservertestcase-with-django :param username: :param password: :return: """ # First, create a new test user user =...
5,327,024
def is_excluded(src_path: Path, globs: Optional[List[str]] = None) -> bool: """ Determine if a src_path should be excluded. Supports globs (e.g. folder/* or *.md). Credits: code inspired by / adapted from https://github.com/apenwarr/mkdocs-exclude/blob/master/mkdocs_exclude/plugin.py Args: ...
5,327,025
def get_seattle_streets(filename=None, folder="."): """ Retrieves processed data from `Seattle Streets <https://data.seattle.gov/dataset/Street-Network-Database/ afip-2mzr/data)>`_. @param filename local filename @param folder temporary folder where to download files ...
5,327,026
def _replace_oov(original_vocab, line): """Replace out-of-vocab words with "UNK". This maintains compatibility with published results. Args: original_vocab: a set of strings (The standard vocabulary for the dataset) line: a unicode string - a space-delimited sequence of words. Returns: a unicode ...
5,327,027
def linear_CMD_fit(x,y,xerr,yerr): """ Does a linear fit to CMD data where x is color and y is amplitude, returning some fit statistics Parameters ---------- x : array-like color y : array-like magnitude xerr : array-like color errors yerr : array-like ...
5,327,028
def save_vehicle(vehicle): """ 新增车辆 :parameter: vehicle 车辆信息元组( 客户ID,车牌号,型号,车辆登记日期,公里数,过户次数, 贷款产品,贷款期次,贷款年限,贷款金额,贷款提报日期,贷款通过日期,放款日期, 承保公司ID,险种,保险生效日期,保险到期日期, 备注) """ # 数据库对象 db = sqlite.Database() # 操作语句 sql = "INSERT INTO T_VEHICLE VALUES (?, ?, ?, ?, ...
5,327,029
def find_uts_hlines(ndvar): """Find horizontal lines for uts plots (based on contours) Parameters ---------- ndvar : NDVar Data to be plotted. Returns ------- h_lines : iterator Iterator over (y, kwa) tuples. """ contours = ndvar.info.get('contours', None) if co...
5,327,030
def _verify_path_value(value, is_str, is_kind=False): """Verify a key path value: one of a kind, string ID or integer ID. Args: value (Union[str, int]): The value to verify is_str (bool): Flag indicating if the ``value`` is a string. If :data:`False`, then the ``value`` is assumed t...
5,327,031
def test_count(client, index): """ count """ yield from client.index(index, 'testdoc', MESSAGES[0], '1', refresh=True) yield from client.index(index, 'testdoc', MESSAGES[1], '2', refresh=True) ...
5,327,032
def abort(*args, **kwargs) -> None: """ Abort execution without an additional error """ logging.info(*args, **kwargs) counted_error_at_exit()
5,327,033
def _is_tipologia_header(row): """Controlla se la riga corrente e' una voce o l'header di una nuova tipologia di voci ("Personale", "Noli", etc). """ if type(row.iloc[1]) is not str: return False if type(row.iloc[2]) is str: if row.iloc[2] != HEADERS["units"]: return Fal...
5,327,034
def validateFloat( value, blank=False, strip=None, allowRegexes=None, blockRegexes=None, min=None, max=None, lessThan=None, greaterThan=None, excMsg=None, ): # type: (str, bool, Union[None, str, bool], Union[None, Sequence[Union[Pattern, str]]], Union[None, Sequence[Union[Pat...
5,327,035
def send_sms(mobile: str, sms_code: str) -> Dict[str, Any]: """发送短信""" sdk: SmsSDK = SmsSDK( celery.app.config.get("SMS_ACCOUNT_ID"), celery.app.config.get("SMS_ACCOUNT_TOKEN"), celery.app.config.get("SMS_APP_ID") ) try: ret: str = sdk.sendMessage( celery.app....
5,327,036
def from_dataframe(df, name='df', client=None): """ convenience function to construct an ibis table from a DataFrame EXPERIMENTAL API Parameters ---------- df : DataFrame name : str, default 'df' client : Client, default new PandasClient client dictionary will be mutated wi...
5,327,037
def make_parser() -> argparse.ArgumentParser: """Make parser for CLI arguments.""" parser = argparse.ArgumentParser() parser.add_argument( "site_name", help="name of the site you want to get data for", ) parser.add_argument( "--no-expand-meta", action="store_true", he...
5,327,038
def get_files_to_parse(relative_path): """Walks through given directory and returns all files with ending with an accepted file extension Arguments: relative_path {string} -- path to pull files from recursively Returns: List<String> -- list of filenames with fullpath """ f...
5,327,039
async def stat_data(full_path: str, isFolder=False) -> dict: """ only call this on a validated full path """ file_stats = os.stat(full_path) filename = os.path.basename(full_path) return { 'name': filename, 'path': full_path, 'mtime': int(file_stats.st_mtime*1000), # giv...
5,327,040
def start_browser(cfg): """ Start browser with disabled "Save PDF" dialog Download files to data folder """ my_options = Options() if cfg.headless: my_options.headless = True my_options.add_argument('--window-size=1920,1200') my_profile = webdriver.FirefoxProfile() my_pro...
5,327,041
def filter_list(prev_list, current_list, zeta): """ apply filter to the all elements of the list one by one """ filtered_list = [] for i, current_val in enumerate(current_list): prev_val = prev_list[i] filtered_list.append( moving_average_filter(current_val, prev_val...
5,327,042
def CleanRules(nodes, marker=IPTABLES_COMMENT_MARKER): """Removes all QA `iptables` rules matching a given marker from a given node. If no marker is given, the global default is used, which clean all custom markers. """ if not hasattr(nodes, '__iter__'): nodes = [nodes] for node in nodes: AssertCom...
5,327,043
def has_prefix(sub_s): """ :param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid :return: (bool) If there is any words with prefix stored in sub_s """ for word in dict_list: if word.startswith(sub_s): return True return False
5,327,044
def get_dir_size_recursive(directoryPath): """ Returns the size of a directory's contents (recursive) in bytes. :param directoryPath: string, path of directory to be analyzed :return: int, size of sum of files in directory in bytes """ # Collect directory size recursively total_size = 0 ...
5,327,045
def test_pause( decoy: Decoy, engine_client: SyncClient, subject: ProtocolContext, ) -> None: """It should be able to issue a Pause command through the client.""" subject.pause() decoy.verify(engine_client.pause(message=None), times=1) subject.pause(msg="hello world") decoy.verify(engin...
5,327,046
def test_as_custom_details_ignores_custom_fields(): """Publishers - PagerDuty - as_custom_details - Ignore Magic Keys""" alert = get_alert(context={'context': 'value'}) alert.created = datetime(2019, 1, 1) alert.publishers = { 'pagerduty': [ 'stream_alert.shared.publisher.DefaultPubl...
5,327,047
def main(): """ """ try: # read parameters configuration file yaml with open(setupcfg.extraParam, "r") as stream: try: param = yaml.safe_load(stream) except yaml.YAMLError as exc: print(exc) # check parameters file return _...
5,327,048
def MSXopen(nomeinp): """Opens the MSX Toolkit to analyze a particular distribution system Arguments: nomeinp: name of the msx input file """ ierr= _lib.MSXopen(ctypes.c_char_p(nomeinp.encode())) if ierr!=0: raise MSXtoolkitError(ierr)
5,327,049
def primary_key(field_type): """ * Returns the field to be treated as the "primary key" for this type * Primary key is determined as the first of: * - non-null ID field * - ID field * - first String field * - first field * * @param {object_type_definition} type *...
5,327,050
def get_discussion_data_list_with_percentage(session: Session, doi, limit: int = 20, min_percentage: float = 1, dd_type="lang"): """ get discussion types with count an percentage from postgresql """ query = """ WITH result AS ( ...
5,327,051
def validate(config, model, val_iterator, criterion, scheduler=None): """Runs one standard validation pass over the val_iterator. This function automatically measures timing for various operations such as host to device transfer and processing time for the batch. It also automatically detects and plac...
5,327,052
def fix_path(file_path): """fixes a path so project files can be located via a relative path""" script_path = os.path.dirname(__file__) return os.path.normpath(os.path.join(script_path, file_path))
5,327,053
def cmd(cmd_name, source, args: list = [], version={}, params={}): """Wrap command interaction for easier use with python objects.""" in_json = json.dumps({ "source": source, "version": version, "params": params, }) command = ['/opt/resource/' + cmd_name] + args output = sub...
5,327,054
def update_gateway_software_now(GatewayARN=None): """ Updates the gateway virtual machine (VM) software. The request immediately triggers the software update. See also: AWS API Documentation Exceptions Examples Updates the gateway virtual machine (VM) software. The request immediately trigg...
5,327,055
def geq_indicate(var, indicator, var_max, thr): """Generates constraints that make indicator 1 iff var >= thr, else 0. Parameters ---------- var : str Variable on which thresholding is performed. indicator : str Identifier of the indicator variable. var_max : int An uppe...
5,327,056
def parse_manpage_number(path): """ Parse number of man page group. """ # Create regular expression number_regex = re.compile(r".*/man(\d).*") # Get number of manpage group number = number_regex.search(path) only_number = "" if number is not None: number = number.group(1...
5,327,057
def sample_coordinates_from_coupling(c, row_points, column_points, num_samples=None, return_all = False, thr = 10**(-6)): """ Generates [x, y] samples from the coupling c. If return_all is True, returns [x,y] coordinates of every pair with coupling value >thr """ index_samples = sample_indices_fro...
5,327,058
def delete(path): """ Send a DELETE request """ response = client.delete(url=path) click.echo(format_response(response))
5,327,059
def is_suppress_importerror(node: ast.With): """ Returns whether the given ``with`` block contains a :func:`contextlib.suppress(ImportError) <contextlib.suppress>` contextmanager. .. versionadded:: 0.5.0 (private) :param node: """ # noqa: D400 item: ast.withitem for item in node.items: if not isinstance(i...
5,327,060
def random_flip_left_right(data): """ Randomly flip an image or batch of image left/right uniformly Args: data: tensor of shape (H, W, C) or (N, H, W, C) Returns: Randomly flipped data """ data_con, C, N = _concat_batch(data) data_con = tf.image.random_flip_left_right(data_con)...
5,327,061
def copyfileobj_example(source, dest, buffer_size=1024*1024*1024): """ Copy a file from source to dest. source and dest must be file-like objects, i.e. any object with a read or write method, like for example StringIO. """ while True: copy_buffer = source.read(buffer_size) ...
5,327,062
def test_triangle_circumradius(point1, point2, point3, expected_radius): """ Verify that the circumradius function returns expected values """ triangle = decide.Triangle( decide.Point(point1), decide.Point(point2), decide.Point(point3) ) assert triangle.circumradius() == pytest.approx(ex...
5,327,063
def run_cnfs(fets, args, sims): """ Trains a model for each provided configuration. """ # Assemble configurations. cnfs = [ {**vars(args), "features": fets_, "sims": sims, "sync": True, "out_dir": path.join(args.out_dir, subdir), "tmp_dir": path.join("/tmp", subdir)} for fe...
5,327,064
def ParseArgs(argv): """Parses command line arguments.""" parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '-b', '--bundle-identifier', required=True, help='bundle identifier for the application') parser....
5,327,065
def GetCurrentBaselinePath(): """Returns path of folder containing baseline file corresponding to the current test.""" currentTestPath = os.path.dirname(os.getenv('PYTEST_CURRENT_TEST').split(":")[0]) currentBaselinePath = baselinePath + "/" + currentTestPath + "/" return currentBaselinePath
5,327,066
def get_all_lobbyists(official_id, cycle=None, api_key=None): """ https://www.opensecrets.org/api/?method=candContrib&cid=N00007360&cycle=2020&apikey=__apikey__ """ if cycle is None: cycle = 2020 # I don't actually know how the cycles work; I assume you can't just take the current year? #...
5,327,067
def get_sale(this_line): """Convert the input into a dictionary, with keys matching the CSV column headers in the scrape_util module. """ sale = {} sale['consignor_name'] = this_line.pop(0) sale['consignor_city'] = this_line.pop(0).title() try: maybe_head = this_line[0].split() ...
5,327,068
def validate_besseli(nu, z, n): """ Compares the results of besseli function with scipy.special. If the return is zero, the result matches with scipy.special. .. note:: Scipy cannot compute this special case: ``scipy.special.iv(nu, 0)``, where nu is negative and non-integer. The correc...
5,327,069
def delete_by_ip(*ip_address: Any) -> List: """ Remove the rules connected to specific ip_address. """ removed_rules = [] counter = 1 for rule in rules(): if rule.src in ip_address: removed_rules.append(rule) execute("delete", counter, force=True) else: ...
5,327,070
def findMaxWindow(a, w): """ :param a: input array of integers :param w: window size :return: array of max val in every window """ max = [0] * (len(a)-w+1) maxPointer = 0 maxCount = 0 q = Queue() for i in range(0, w): if a[i] > max[maxPointer]: max[maxPointer...
5,327,071
def filtering_news(news: list, filtered_news: list): """ Filters news to remove unwanted removed articles Args: news (list): List of articles to remove from filtered_news (list): List of titles to filter the unwanted news with Returns: news (list): List of articles with undesir...
5,327,072
def update_persona_use_counts_file( fptah: str, counts: Dict[str, int], sorted_order=True ): """ Writes the persona use counts to file. This is to keep track of use counts for the next time that the task was restarted. See `load_previously_used_personas_counts` function above. """ logging.i...
5,327,073
def extract_subsequence(sequence, start_time, end_time): """Extracts a subsequence from a NoteSequence. Notes starting before `start_time` are not included. Notes ending after `end_time` are truncated. Args: sequence: The NoteSequence to extract a subsequence from. start_time: The float time in second...
5,327,074
def read_data(filename): """Read the raw tweet data from a file. Replace Emails etc with special tokens """ with open(filename, 'r') as f: all_lines=f.readlines() padded_lines=[] for line in all_lines: line = emoticonsPattern.sub(lambda m: rep[re.escape(m.group(0))], li...
5,327,075
def client(): """AlgodClient for testing""" client = _algod_client() client.flat_fee = True client.fee = 1000 print("fee ", client.fee) return client
5,327,076
def GRU_sent_encoder(batch_size, max_len, vocab_size, hidden_dim, wordembed_dim, dropout=0.0, is_train=True, n_gpus=1): """ Implementing the GRU of skip-thought vectors. Use masks so that sentences at different lengths can be put into the same batch. sent_seq: sequence of tokens c...
5,327,077
def process_contours(frame_resized): """Get contours of the object detected""" blurred = cv2.GaussianBlur(frame_resized, (11, 9), 0) hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV) mask = cv2.inRange(hsv, constants.blueLower, constants.blueUpper) mask = cv2.erode(mask, None, iterations=2) mask = ...
5,327,078
def add_ignore_file_arguments(files: Optional[List[str]] = None) -> List[str]: """Adds ignore file variables to the scope of the deployment""" default_ignores = ["config.json", "Dockerfile", ".dockerignore"] # Combine default files and files ingore_files = default_ignores + (files or []) return li...
5,327,079
def compute_accuracy(logits, targets): """Compute the accuracy""" with torch.no_grad(): _, predictions = torch.max(logits, dim=1) accuracy = torch.mean(predictions.eq(targets).float()) return accuracy.item()
5,327,080
def division_by_zero(number: int): """Divide by zero. Should raise exception. Try requesting http://your-app/_divide_by_zero/7 """ result = -1 try: result = number / 0 except ZeroDivisionError: logger.exception("Failed to divide by zero", exc_info=True) return f"{number} divi...
5,327,081
def additional_setup_linear(args: Namespace): """Provides final setup for linear evaluation to non-user given parameters by changing args. Parsers arguments to extract the number of classes of a dataset, correctly parse gpus, identify if a cifar dataset is being used and adjust the lr. Args: a...
5,327,082
def is_ELF_got_pointer_to_external(ea): """Similar to `is_ELF_got_pointer`, but requires that the eventual target of the pointer is an external.""" if not is_ELF_got_pointer(ea): return False target_ea = get_reference_target(ea) return is_external_segment(target_ea)
5,327,083
def _check_same_nobs(*argv): """Raise an arror if elements in argv have different number of obs.""" n_obs = set(obj.n_obs for obj in argv) if len(n_obs) > 1: raise ValueError("Elements do not have the same number" " of observations.")
5,327,084
def adv_search_product_of_two_seq(seq: str): """ Check If the Sequence is The Product of Two Sequences seq: A string that contains a comma seperated numbers returns: nothing """ numeric_seq = utils.convert_str_to_list(seq, True, False) result_list = [] for i in range(0, len(seq_list_num...
5,327,085
def _normalise_dataset_path(input_path: Path) -> Path: """ Dataset path should be either the direct imagery folder (mtl+bands) or a tar path. Translate other inputs (example: the MTL path) to one of the two. >>> tmppath = Path(tempfile.mkdtemp()) >>> ds_path = tmppath.joinpath('LE07_L1GT_104078_20...
5,327,086
def callLater(delay, func, *args, **kwargs): """ Call a function on the Main thread after a delay (async). """ pool = NSAutoreleasePool.alloc().init() runner = PyObjCMessageRunner.alloc().initWithPayload_((func, args, kwargs)) runner.callLater_(delay) del runner del pool
5,327,087
def get_customers(): """returns an array of dicts with the customers Returns: Array[Dict]: returns an array of dicts of the customers """ try: openConnection with conn.cursor() as cur: result = cur.run_query('SELECT * FROM customer') cur.close() ...
5,327,088
def fixtureid_es_server(fixture_value): """ Return a fixture ID to be used by pytest for fixture `es_server()`. Parameters: fixture_value (:class:`~easy_server.Server`): The server the test runs against. """ es_obj = fixture_value assert isinstance(es_obj, easy_server.Server) ...
5,327,089
def topn_vocabulary(document, TFIDF_model, topn=100): """ Find the top n most important words in a document. Parameters ---------- `document` : The document to find important words in. `TFIDF_model` : The TF-IDF model that will be used. `topn`: Default = 100. Amount of top words. ...
5,327,090
def embedding_table(inputs, vocab_size, embed_size, zero_pad=False, trainable=True, scope="embedding", reuse=None): """ Generating Embedding Table with given parameters :param inputs: A 'Tensor' with type 'int8' or 'int16' or 'int32' or 'int64' containing the ids to be looked up in '...
5,327,091
def get_trading_dates(start_date, end_date): """ 获取某个国家市场的交易日列表(起止日期加入判断)。目前仅支持中国市场。 :param start_date: 开始日期 :type start_date: `str` | `date` | `datetime` | `pandas.Timestamp` :param end_date: 结束如期 :type end_date: `str` | `date` | `datetime` | `pandas.Timestamp` :return: list[`datetime.date`...
5,327,092
def event_loop(): """Create an instance of the default event loop for all test cases.""" loop = asyncio.get_event_loop_policy().new_event_loop() yield loop loop.close()
5,327,093
def drawFigure7(): """Draws Figure 7 (impact of the format combination).""" colors = [colorRed, colorGray, colorBlue, colorGreen] order = ["ActualWorst{}", "Uncompr", "StaticBP32", "ActualBest{}"] labels = ["worst combination", "uncompressed", "Static-BP-32", "best combination"] filename = "fi...
5,327,094
def gm_put(state, b1, b2): """ If goal is ('pos',b1,b2) and we're holding b1, Generate either a putdown or a stack subtask for b1. b2 is b1's destination: either the table or another block. """ if b2 != 'hand' and state.pos[b1] == 'hand': if b2 == 'table': return [('a_putdown...
5,327,095
def cs_management_client(context): """Return Cloud Services mgmt client""" context.cs_mgmt_client = CSManagementClient(user=os.environ['F5_CS_USER'], password=os.environ['F5_CS_PWD']) return context.cs_mgmt_client
5,327,096
def createTemporaryDirectory(): """Create temporary directory and chdir into it.""" global tmp_dir time_tuple = time.localtime(time.time()) current_time = "%4i-%2i-%2i_%2i-%2i_" % (time_tuple[0],time_tuple[1], time_tuple[2],time_tuple[3], ...
5,327,097
def pad_to_shape_label(label, shape): """ Pad the label array to the given shape by 0 and 1. :param label: The label for padding, of shape [n_batch, *vol_shape, n_class]. :param shape: The shape of the padded array, of value [n_batch, *vol_shape, n_class]. :return: The padded label array. ...
5,327,098
def download_report( bucket_name: str, client: BaseClient, report: str, location: str ) -> bool: """ Downloads the original report to the temporary work area """ response = client.download_file( Bucket=bucket_name, FileName=report, Location=location ) return response
5,327,099