content
stringlengths
22
815k
id
int64
0
4.91M
def check_type(instance, *classes): """Check if object is instance of given class""" for klass in classes: if type(instance).__name__ == klass: return True for T in getmro(type(instance)): if T.__name__ == klass: return True return False
5,328,900
def test_get_earth_imperative_solution(solar_system): """ ## Imperative Solution The first example uses flow control statements to define a [Imperative Solution]( https://en.wikipedia.org/wiki/Imperative_programming). This is a very common approach to solving problems. """ def get_planet...
5,328,901
def test_eeglab_event_from_annot(): """Test all forms of obtaining annotations.""" base_dir = op.join(testing.data_path(download=False), 'EEGLAB') raw_fname_mat = op.join(base_dir, 'test_raw.set') raw_fname = raw_fname_mat event_id = {'rt': 1, 'square': 2} raw1 = read_raw_eeglab(input_fname=raw_...
5,328,902
def parse(request): """ A form that lets an authorized user import and the parse data files in the incoming directory. """ dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'incoming') if request.method == 'POST': parse_form = forms.Form(request.POST) if parse_form...
5,328,903
def animate(map, time, phase0=0.0, res=75, interval=75): """ """ # Load the SPICE data ephemFiles = glob.glob('../data/TESS_EPH_PRE_LONG_2018*.bsp') tlsFile = '../data/tess2018338154046-41240_naif0012.tls' solarSysFile = '../data/tess2018338154429-41241_de430.bsp' #print(spice.tkvrsn('TOOLK...
5,328,904
def get_params_from_ctx(func=None, path=None, derive_kwargs=None): """ Derive parameters for this function from ctx, if possible. :param str path: A path in the format ``'ctx.arbitraryname.unpackthistomyparams'`` to use to find defaults for the function. Default: ``'ctx.mymodulename...
5,328,905
def bresenham(points): """ Apply Bresenham algorithm for a list points. More info: https://en.wikipedia.org/wiki/Bresenham's_line_algorithm # Arguments points: ndarray. Array of points with shape (N, 2) with N being the number if points and the second coordinate representing the (x,...
5,328,906
def radialBeamProfile_flatTop(x,y,a): """Top hat beam profile \param[in] x x-position for profile computation \param[in] y y-position for profile computation \param[in] a radial extension of flat-top component \param[in] R 1/e-width of beam profile \param[ou...
5,328,907
def post_save_count_update(sender, instance, created, **kwargs): """ Receiver that is called after a media file or a comment is created or deleted. Updates num_media and num_comments properties of an observation. """ deleted = hasattr(instance, 'status') and instance.status == 'deleted' if creat...
5,328,908
def assert_has_attr(obj, attribute, msg_fmt="{msg}"): """Fail is an object does not have an attribute. >>> assert_has_attr([], "index") >>> assert_has_attr([], "i_do_not_have_this") Traceback (most recent call last): ... AssertionError: [] does not have attribute 'i_do_not_have_this' T...
5,328,909
def open_url(url): """Open an URL in the user's default web browser. The string attribute ``open_url.url_handler`` can be used to open URLs in a custom CLI script or utility. A subprocess is spawned with url as the parameter in this case instead of the usual webbrowser.open() call. Whether ...
5,328,910
def _split_data(x, y, k_idx, k, perm_indices): """Randomly and coordinates splits two indexable items. Splits items in accordiance with k-fold cross-validatoin. Arguments: x: [?] indexable item y: [?] indexable item k_idx: int index of the k-fold...
5,328,911
def set_neighborhood(G, nodes): """Return a list of all neighbors of every node in nodes. Parameters ---------- G : NetworkX graph An undirected graph. nodes : An interable container of nodes in G. Returns ------- list A list containing all nodes that are a nei...
5,328,912
def orientationCallback(mic): """Orientation callback function. Callback function performing the recording of the voice activity and the direction of arrival angle. Detects the end of a speech and average the measures taken to update the direction of arrival angle. :param mic: Instance of the Tuni...
5,328,913
def resolve_Log( parent: Any, info: gr.ResolveInfo, id: Optional[int] = None, uuid: Optional[str] = None, ) -> ENTITY_DICT_TYPE: """Resolution function.""" return resolve_entity(Log, info, id, uuid)
5,328,914
def _get_path_size(source: Union[Path, ZipInfo]) -> int: """ A helper method that returns the file size for the given source :param source: the source object to get the file size for. :return: the source's size. """ return source.stat().st_size if isinstance(source, Path) else source.file_size
5,328,915
def test_download_ckpt(): """test download ckpt.""" md_path = '../mshub_res/assets/mindspore/gpu/1.0/googlenet_v1_cifar10.md' cell = CellInfo("googlenet") cell.update(md_path) asset_link = cell.asset[cell.asset_id]['asset-link'] asset_sha256 = cell.asset[cell.asset_id]["asset-sha256"] set_h...
5,328,916
def shift_level_box_plot(ax, plot_data, y_label, methods_to_colors, legend_loc=None, hue_order=None, fontsize=22, in_distribution_line_width=0.8)...
5,328,917
def get_graph_subsampling_dataset( prefix, arrays, shuffle_indices, ratio_unlabeled_data_to_labeled_data, max_nodes, max_edges, **subsampler_kwargs): """Returns tf_dataset for online sampling.""" def generator(): labeled_indices = arrays[f"{prefix}_indices"] if ratio_unlabeled_data_to_labeled_d...
5,328,918
def check_comment_exists(comment_id_required=True): """ Decorator to check if a given comment exists. If it does not, it returns an HTTP 400 error. Must be called with (), and may pass the optional argument of whether the id is required. If the id is passed, it will be checked against entities of...
5,328,919
def test_wrong_endpoint(api_client): """ Attempting to query using the wrong endpoint should return a 404 response. Regression test for #505. """ response = api_client.post("/know-me/subscription/apple/foobar/", {}) assert response.status_code == status.HTTP_404_NOT_FOUND
5,328,920
def save_image(img, path): """ Saves a numpy matrix or PIL image as an image Args: img_as_arr (Numpy array): Matrix of shape DxWxH path (str): Path to the image """ if isinstance(img, (np.ndarray, np.generic)): img = format_np_output(img) img = Image.fromarray(img...
5,328,921
def GeoMoonState(time): """Calculates equatorial geocentric position and velocity of the Moon at a given time. Given a time of observation, calculates the Moon's position and velocity vectors. The position and velocity are of the Moon's center relative to the Earth's center. The position (x, y, z) comp...
5,328,922
def get_machine_name(): """ Portable way of calling hostname shell-command. Regarding docker containers: NOTE: If we are running from inside the docker-dev environment, then $(hostname) will return the container-id by default. For now we leave that behaviour. We can override it in...
5,328,923
def pass_through_formatter(value): """No op update function.""" return value
5,328,924
def instantiate(decoder, model=None, dataset=None): """ Instantiate a full decoder config, e.g. handle list of configs Note that arguments are added in reverse order compared to encoder (model first, then dataset) """ decoder = utils.to_list(decoder) return U.TupleSequential(*[_instantiate(d, model=...
5,328,925
def un_normalize(stdevs, arrList): """ Return an arrayList with ith column multiplied by scalar stdevs[i] if stdevs[i] is not zero, and unmodified if it is zero. Args: stdevs: A list of numbers (should be the list output by normalize). arrList: A list of list of numbers that is the (nor...
5,328,926
def activate(context: MapCommandContext): """All subsequent mapping actions will target this folder""" mapping_file_path = Path(context.current_dir) / DEFAULT_MAPPING_NAME if not mapping_file_path.exists(): raise MapperException( f"Could not find mapping file at " f"'{mapping_file_path}'...
5,328,927
def convert_graph(input_path): """ Converts a CRED-like graph into a graph format supported by the igraph library. The input graph must have been generated by cli2 CRED command (look for credResult.json) :param input_path: The path to the CRED graph to convert (credResult.json) """ with open(in...
5,328,928
def get_valid_classes_from_class_input( class_graph: class_dependency.JavaClassDependencyGraph, class_names_input: str) -> List[str]: """Parses classes given as input into fully qualified, valid classes. Input is a comma-separated list of classes.""" class_names = class_names_input.split(',...
5,328,929
def us_ppop(ppop): """ Determines if the ppop is in a valid format to be in the US """ # return false if it's null or not 7 digits long if not ppop or len(ppop) != 7: return False ppop = ppop.upper() if ppop[:2] in g_state_by_code or ppop[:2] in g_state_code_by_fips: return True ...
5,328,930
def get_pygments_lexer(location): """ Given an input file location, return a Pygments lexer appropriate for lexing this file content. """ try: T = _registry[location] if T.is_binary: return except KeyError: if binaryornot.check.is_binary(location): ...
5,328,931
def get_robotstxt_parser(url, session=None): """Get a RobotFileParser for the given robots.txt URL.""" rp = RobotFileParser() try: req = urlopen(url, session, max_content_bytes=MaxContentBytes, allow_errors=range(600)) except Exception: # connect or timeout errors a...
5,328,932
def init_model(config, checkpoint=None, device='cuda:0'): """Initialize a model from config file. Args: config (str or :obj:`mmcv.Config`): Config file path or the config object. checkpoint (str, optional): Checkpoint path. If left as None, the model will not load any we...
5,328,933
def estimate_period(time, y, y_err, clip=True, plot=True, **kwargs): """ Run a Lomb-Scargle Periodogram to find periodic signals. It's recommended to use the allesfitter.time_series functions sigma_clip and slide_clip beforehand. Parameters ---------- time : array of float e.g. time ar...
5,328,934
def get_test_packages(): """Get a list of packages which need tests run. Filters the package list in the following order: * Check command line for packages passed in as positional arguments * Check if the the local remote and local branch environment variables have been set to specify a remote b...
5,328,935
def main(): """Main entry point for the script""" start = time.time() # short explanation: # str(number) - converts number to string # map(int, string) - converts each character to int # sum(list) - sums the list of ints (in this case) print(sum(map(int, str(int(math.pow(2, 1000)))))) ...
5,328,936
def cli_exec( opt, engine_args: List[str], profile: str, profile_path: str, conan_arg: List[str], conan_option: List[str], conan_setting: List[str], preserve_env: bool, override_env: List[str], cache: bool, debug: bool, ) -> None: """Launch cloe-engine with a profile. ...
5,328,937
def decoding_character(morse_character): """ Input: - morse_character : 문자열값으로 get_morse_code_dict 함수로 알파벳으로 치환이 가능한 값의 입력이 보장됨 Output: - Morse Code를 알파벳으로 치환함 값 Examples: >>> import morsecode as mc >>> mc.decoding_character("-") 'T' >>> mc.decoding_character(".") 'E' >>>...
5,328,938
def SparsityParametersAddDimMetadata(builder, dimMetadata): """This method is deprecated. Please switch to AddDimMetadata.""" return AddDimMetadata(builder, dimMetadata)
5,328,939
def check_branch(payload, branch): """ Check if a push was on configured branch. :param payload: Payload from web hook. :param branch: Name of branch to trigger action on. :return: True if push was on configured branch, False otherwise. """ if "ref" in payload: if payload["ref"] == b...
5,328,940
def convert(q: Quantity, new_unit: Union[str, Unit], equivalencies=None) -> Quantity: """Convert quantity to a new unit. :raises InvalidUnit: When target unit does not exist. :raises InvalidUnitConversion: If the conversion is invalid. Customized to be a bit more universal than the original quantities...
5,328,941
def process_files(subdirectory, sd_files, pattern="", verbose=False): """ recursively iterates ofer all files and checks those which meet criteria set by options only """ global total_files for __file in sd_files: current_filename = os.path.join(subdirectory, __file) if current_f...
5,328,942
def randomized_pairwise_t_test(arr1, arr2, output=True): """ Perform a randomized pairwise t-test on two arrays of values of equal size. see Cohen, P.R., Empirical Methods for Artificial Intelligence, p. 168 """ # Make sure both arrays are the same length assert len(arr1) == len(arr2...
5,328,943
def update_metadata(radar, longitude: np.ndarray, latitude: np.ndarray) -> Dict: """ Update metadata of the gridded products. Parameter: ========== radar: pyart.core.Grid Radar data. Returns: ======== metadata: dict Output metadata dictionnary. """ today = datet...
5,328,944
def main(): """ The main routine. """ try: default_output = os.environ["EC_DEFAULT_OUTPUT1"] except KeyError: default_output = CONST_OUTPUT_TABLE # set up command line arguments args = set_command_line_args(default_output) # run the crawl _, _, _ = crawl(args)
5,328,945
def idxsel2xsel(file, isel, dimensions, order): """ convert a index space selection object to an xSelect object """ if not isinstance(isel, idxSelect): raise TypeError('wrong argument type') xsel = {} xsel_size = {} xsel_dims = {} isarray = False interp = False masked = Fal...
5,328,946
def _retrieve_max_kb_s_sent_state(status: FritzStatus, last_value: str) -> float: """Return upload max transmission rate.""" return round(status.max_bit_rate[0] / 1000, 1)
5,328,947
def test_view(app, base_client): """Test view.""" res = base_client.get("/sip2/monitoring") assert res.status_code == 200 assert 'Welcome to Invenio-SIP2' in str(res.data)
5,328,948
def user_detail(request, id, format=None): """ Retrieve, update or delete a server assets instance. """ try: snippet = User.objects.get(id=id) except User.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = UserSeriali...
5,328,949
def _gsmooth_img(args): """ HELPER FUNCTION: private! Smooth an image with a gaussian in 2d """ img,kernel,use_fft,kwargs = args if use_fft: return convolve_fft(img, kernel, normalize_kernel=True, **kwargs) else: return convolve(img, kernel, normalize_kernel=True, **kwargs)
5,328,950
def ParseArgs(): """Parses command line arguments. Returns: args from argparse.parse_args(). """ description = ( 'Handle Whale button click event.' ) parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter, description=description) parser.add_argument('-d', '--deb...
5,328,951
def __logs_by_scan_id(scan_id, language): """ select all events by scan id hash Args: scan_id: scan id hash language: language Returns: an array with JSON events or an empty array """ try: logs = [] for log in send_read_query( "select hos...
5,328,952
def handle_xds110(args): """Helper function for handling 'xds110' command""" session_args = get_session_args(args) if args.cmd == 'xds110-reset': try: result = tiflash.xds110_reset(**session_args) print(result) except Exception as e: __exit_with_error(e) ...
5,328,953
def docs(): """Redirect to documentation on Github Route: /docs Methods: GET Return: redirect to webpage """ return redirect("https://kinsaurralde.github.io/ws_281x-lights/#/")
5,328,954
def std(a, weights=None, axis=None, dtype=None, ddof=0, keepdims=False): """ Compute the weighted standard deviation along the specified axis. :param a: Array containing numbers whose standard deviation is desired. If `a` is not an array, a conversion is attempted. :param weights: Array contain...
5,328,955
def generate_tf_files(): """Generate all Terraform plans for the clusters in variables.json""" LOGGER_CLI.info('Generating Terraform files') env = Environment(loader=PackageLoader('terraform', 'templates')) template = env.get_template('cluster_template') all_buckets = CONFIG.get('s3_event_buckets')...
5,328,956
def createOneHourCandles(markets, database): """ Function that creates tables for one minute candles. :param database: :param markets: :return: """ conn = pymysql.connect(host='localhost', user='jan', password='17051982', database=database) ...
5,328,957
def test_merge2_sql_semantics_outerjoin_multi_keep_Nonelast(): """ Test that merge2 matches the following SQL query: select f.id as foo_id, f.col1 as foo_col1, f.col2 as foo_col2, f.team_name as foo_teamname, b.id as bar_id, b.col1 as bar_col1, ...
5,328,958
def coaddspectra(splist,plotsp=True,outf=None,sn_smooth_npix=10): """ Coadd spectra Parameters ---------- splist : list of XSpectrum1D objects List of spectra to coadd plotsp : bool If True, plot the coadded spectrum outf : str Output file sn_smooth_npix : float ...
5,328,959
def get_rel_sim(relation, question, dataset): """ Get max cosine distance for relations :param relation: :param question: :return: """ query_ngrams = generate_ngrams(question) query_ngrams_vec = [get_avg_word2vec(phr, dataset) for phr in query_ngrams] relation_ngram = get_avg_word2ve...
5,328,960
def mk_request(bits, cn): """ Create a X509 request with the given number of bits in they key. Args: bits -- number of RSA key bits cn -- common name in the request Returns a X509 request and the private key (EVP) """ pk = EVP.PKey() x = X509.Request() rsa = RSA.gen_key(bits,...
5,328,961
def nice(name): """Generate a nice name based on the given string. Examples: >>> names = [ ... "simple_command", ... "simpleCommand", ... "SimpleCommand", ... "Simple command", ... ] >>> for name in names: ... nice(name) ...
5,328,962
def get_outputs(): """Get the available outputs, excluding outputs in the EXCLUDED_OUTPUTS variable.""" outputs = [] tree = connection.get_tree() for node in filter( lambda node: node.type == "output" and node.name not in EXCLUDED_OUTPUTS, tree ): workspaces = node.nodes[1].nodes ...
5,328,963
def set_array_from_itk_image(dataset, itk_image): """Set dataset array from an ITK image.""" itk_output_image_type = type(itk_image) # Save the VTKGlue optimization for later #------------------------------------------ # Export the ITK image to a VTK image. No copying should take place. #expor...
5,328,964
def get_user_owner_mailboxes_tuples(user): """ Return owned mailboxes of a user as tuple """ return ((owned_mailbox.id, owned_mailbox.email_address) for owned_mailbox in get_user_owner_mailboxes_query(user))
5,328,965
def modinv(a, m): """Modular Multiplicative Inverse""" a = a % m g, x, y = egcd(a, m) if g != 1: raise Exception('modular inverse does not exist') else: return x % m
5,328,966
def get_ip(): """Get the ip of the host computer""" s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(('1.1.1.1', 1)) IP = s.getsockname()[0] except Exception: IP = '127.0.0.1' finally: s.close() return IP
5,328,967
def available_structure_info(): """ Lists available attributes for :func:`abagen.mouse.get_structure_info` """ return _STRUCTURE_ATTRIBUTES.copy()
5,328,968
def centos(function): """Decorator to set the Linux distribution to CentOS 7""" def wrapper(*args, **kwargs): hpccm.config.g_linux_distro = linux_distro.CENTOS hpccm.config.g_linux_version = StrictVersion('7.0') return function(*args, **kwargs) return wrapper
5,328,969
def Normalized2(p): """Return vector p normlized by dividing by its squared length. Return (0.0, 1.0) if the result is undefined.""" (x, y) = p sqrlen = x * x + y * y if sqrlen < 1e-100: return (0.0, 1.0) else: try: d = sqrt(sqrlen) return (x / d, y / d) ...
5,328,970
def test_make_struct_type(doctest): """ > (define-values (struct:a make-a a? a-ref a-set!) (make-struct-type 'a #f 2 1 'uninitialized)) > (define an-a (make-a 'x 'y)) > (a-ref an-a 1) 'y > (a-ref an-a 2) 'uninitialized > (define a-first (make-struct-field-accessor a-ref 0)) >...
5,328,971
def findwskeyword(keyword, sol): """Find and return a value for a keyword in the list of the wavelength solution""" i = sol.index(keyword) j = sol[i:].index('\n') return sol[i:i + j].split('=')[1].strip()
5,328,972
def test_dict_format_line() -> None: """Test formatting dictionary details.""" match = MatchError( message="xyz", linenumber=1, details={"hello": "world"}, # type: ignore filename="filename.yml", rule=rule, ) formatter.format(match)
5,328,973
def algorithm(array: numpy.array, start: Tuple[int, int], end: Tuple[int, int], heuristic: Callable = manhattan) -> Union[List, None]: """ Returns a list of all points, for the path between `start` and `end` :param array: a numpy array of Node instances :param start: a tuple (or list) of p...
5,328,974
def execute_psql(temp_sql_file_path, source_path, download_job): """Executes a single PSQL command within its own Subprocess""" download_sql = Path(temp_sql_file_path).read_text() if download_sql.startswith("\\COPY"): # Trace library parses the SQL, but cannot understand the psql-specific \COPY comm...
5,328,975
def MFString(string_list): """ input a list of unicode strings output: a unicode string formed by encoding, enclosing each item in double quotes, and concatenating 27 Nov 2016: The complete case is as yet unimplemented, to avoid sending bad X3D into the world will instead fail with a Ex...
5,328,976
def re_allocate_memory(ptr: VoidPtr, size: int)-> VoidPtr: """ Internal memory free ptr: The pointer which is pointing the previously allocated memory block by allocate_memory. size: The new size of memory block. """ return _rl.MemRealloc( ptr, _to_int(size) )
5,328,977
def get_task_manager(setup_file, **kwargs): """ Create a task manager of a correct type. Parameters ---------- setup_file : string File name of the setup file. kwargs : dict Additional kwargs. Returns ------- manager : TaskManager Created task manager. """ ...
5,328,978
def format_time(time): """ Converts datetimes to the format expected in SAML2 XMLs. """ return time.strftime("%Y-%m-%dT%H:%M:%SZ")
5,328,979
def get_delivery_voucher_discount(voucher, total_price, delivery_price): """Calculate discount value for a voucher of delivery type.""" voucher.validate_min_amount_spent(total_price) return voucher.get_discount_amount_for(delivery_price)
5,328,980
def list_docker_repos(ctx): """ List all git repositories that has docker compose file in the root. The included repositories exists in direct sub-directories of the current directory (or from current directory, if none exists in sub directories). :param ctx: (implicit fabric context param)...
5,328,981
def has_admin_access(request): # type: (Request) -> bool """ Verifies if the authenticated user doing the request has administrative access. .. note:: Any request view that does not explicitly override ``permission`` by another value than the default :envvar:`MAGPIE_ADMIN_PERMISSION` wi...
5,328,982
def safe_remove(path: str) -> bool: """Removes a file or directory This will remove a file if it exists, and will remove a directory if the directory is empty. Args: path: The path to remove Returns: True if `path` was removed or did not exist, False if `path` was a non empty...
5,328,983
def test_can_inspect_last_request_with_ssl(): """HTTPretty.last_request is recorded even when mocking 'https' (SSL)""" HTTPretty.register_uri(HTTPretty.POST, "https://secure.github.com/", body='{"repositories": ["HTTPretty", "lettuce"]}') response = requests.post( 'https...
5,328,984
def model_selection(modelname, num_out_classes=2, pretrain_path=None): """ :param modelname, num_out_classes, pretrained, dropout: :return: model, image size """ return TransferModel(modelchoice=modelname, num_out_classes=num_out_classes, pretrain_pa...
5,328,985
def stack1(x, filters, blocks, stride1=2, dilation=1, name=None): """A set of stacked residual blocks. # Arguments x: input tensor. filters: integer, filters of the bottleneck layer in a block. blocks: integer, blocks in the stacked blocks. stride1: default 2, stride of the firs...
5,328,986
def check_length(df_array, path_array, iteration): """ ずらす回数がデータ数より多ければアラートする。 Input ------ df_array : 読み込んだデータ群の配列 path_array : 元データのファイルパス配列 Raises ------ ずらす回数が、データ数よりも多い時。 """ for df, path in zip(df_array, path_array): if len(df) < iteration: prin...
5,328,987
def ci(config: Config) -> None: # pylint: disable=invalid-name """profile to run in CI""" config.option.newfirst = False config.option.failedfirst = False config.option.verbose = 1 config.option.cacheclear = True
5,328,988
def _CreateDynamicDisplayAdSettings(media_service, opener): """Creates settings for dynamic display ad. Args: media_service: a SudsServiceProxy instance for AdWords's MediaService. opener: an OpenerDirector instance. Returns: The dynamic display ad settings. """ image = _CreateImage(media_servic...
5,328,989
def contacts_per_person_normal_00x30(): """ Real Name: b'contacts per person normal 00x30' Original Eqn: b'10' Units: b'contact/Day' Limits: (None, None) Type: constant b'' """ return 10
5,328,990
def init(ctx, project_type, project_name): """ 生成接口测试项目 使用方法: $ pithy-cli init # 生成接口测试项目 """ generate_project(project_name, project_type)
5,328,991
def create_change_set(StackName=None, TemplateBody=None, TemplateURL=None, UsePreviousTemplate=None, Parameters=None, Capabilities=None, ResourceTypes=None, RoleARN=None, NotificationARNs=None, Tags=None, ChangeSetName=None, ClientToken=None, Description=None, ChangeSetType=None): """ Creates a list of changes ...
5,328,992
def _get_scripts_shell(script_file): # type: (pathlib.Path) -> str """ Returns the shell used in the passed script file. If no shell is recognized exception is raised. Depended on presence of shebang. Supported shells: Bash, Fish, Zsh :param script_file: :return: :raises exceptions.Unknow...
5,328,993
def _process_worker(call_queue, result_queue): """Evaluates calls from call_queue and places the results in result_queue. This worker is run in a separate process. Args: call_queue: A multiprocessing.Queue of _CallItems that will be read and evaluated by the worker. result_queu...
5,328,994
def is_cmd_tool(name): """ Check whether `name` is on PATH and marked as executable. From: https://stackoverflow.com/a/34177358 """ from shutil import which return which(name) is not None
5,328,995
def load_model(model: Model, language=()): """Load geo model and return as dict.""" log.info("Reading geomodel: %s", model) with open(model.path, "rb") as infile: m = pickle.load(infile) result = defaultdict(set) for _geonameid, l in list(m.items()): result[l["name"].lower()].add((l...
5,328,996
def saml_metadata_generator(sp, validated=True, privacypolicy=False, tree=None, disable_entity_extensions=False): """ Generates metadata for single SP. sp: ServiceProvider object validated: if false, using unvalidated metadata privacypolicy: fill empty privacypolicy URLs with default value tree...
5,328,997
def import_from_afd(import_list, vlb_path, working_path, conn): """Imports an Armada Fleets Designer list into a Fleet object""" f = Fleet("Food", conn=conn) start = False obj_category = "assault" # shipnext = False for line in import_list.strip().split("\n"): try: last_...
5,328,998
def CWPProfileToVersionTuple(url): """Convert a CWP profile url to a version tuple Args: url: for example, gs://chromeos-prebuilt/afdo-job/cwp/chrome/ R65-3325.65-1519323840.afdo.xz Returns: A tuple of (milestone, major, minor, timestamp) """ fn_mat = (CWP_CHROME_PROFILE_NAME_P...
5,328,999