content
stringlengths
22
815k
id
int64
0
4.91M
def _kubeconfig_impl(repository_ctx): """Find local kubernetes certificates""" # find and symlink kubectl kubectl = repository_ctx.which("kubectl") if not kubectl: fail("Unable to find kubectl executable. PATH=%s" % repository_ctx.path) repository_ctx.symlink(kubectl, "kubectl") # TODO...
13,700
def getPrimaryHostIp(): """ Tries to figure out the primary (the one with default route), local IPv4 address. Returns the IP address on success and otherwise '127.0.0.1'. """ # # This isn't quite as easy as one would think. Doing a UDP connect to # 255.255.255.255 turns out to be prob...
13,701
def run(raw_args): """ Parse arguments in parameter. Then call the function registered in the argument parser which matches them. :param raw_args: :return: """ if "--version" in raw_args: print("version: ", __version__) return error.ReturnCode.success.value parser = buil...
13,702
def localize(_bot, _msg, *args, _server=None, _channel=None, **kwargs): """ Localize message to current personality, if it supports it. """ global messages # Find personality and check if personality has an alternative for message. personality = config.get('personality', _server or _current_server, _ch...
13,703
def test_neighbors_valid(sample_graph): """Test that neighbors returns node connections.""" sample_graph[2].add_edge('A', 'B') sample_graph[2].add_edge('A', 'C') sample_graph[2].add_edge('A', 'D') assert sample_graph[2].neighbours('A') == ['B', 'C', 'D']
13,704
def parse_arguments(): """ Parse the argument list and return the location of a geometry file, the location of a data file, whether or not to save images with a timestamp of the four default plot windows and the VisIt session file in the current directory, and whether or not to open the session file...
13,705
def aborting_function(): """There is a 50% chance that this function will AbortAndRestart or complete successfully. The 50% chance simply represents a process that will fail half the time and succeed half the time. """ import random logging.info('In aborting_function') if random.rando...
13,706
def _print_metrics(metrics): """Print one metrics row and save it.""" time_label = metrics.index.get_level_values('Dataset')[0] global _metrics if time_label not in _metrics: _metrics[time_label] = pd.DataFrame() _metrics[time_label] = _metrics[time_label].append(metrics) local_metric...
13,707
def snapshot(source, destination): """Convert a possibly COW layered disk file into a snapshot.""" processutils.execute( 'qemu-img convert --force-share -O qcow2 %s %s' % (source, destination), shell=True)
13,708
def list_events(): """Show a view with past and future events.""" if "username" not in session: return redirect("/") events = actions.get_upcoming_events() past_events = actions.get_past_events() return render_template("events.html", count=len(events), past_count=len(past_events), ...
13,709
def create_parser(): """Create argparser.""" parser = argparse.ArgumentParser() parser.add_argument( '--mode', default='local', choices=['local', 'docker']) parser.add_argument( '--env-file', action="append", help='Job specific environment file') parser.add_argument( '--image...
13,710
def get_duration(df): """Get duration of ECG recording Args: df (DataFrame): DataFrame with time/voltage data Returns: float: duration of ECG recording """ start = df.time.iloc[0] end = df.time.iloc[-1] duration = end - start return duration
13,711
def conv_seq_labels(xds, xhs): """description and hedlines are converted to padded input vectors. headlines are one-hot to label""" batch_size = len(xhs) assert len(xds) == batch_size def process_xdxh(xd,xh): concated_xd = xd+[[3]]+xh padded_xd = lpadd(concated_xd,maxlend) concat...
13,712
def create_task(): """Create new post""" global post_id_counter body = json.loads(request.data) title = body.get("title") link = body.get("link") username = body.get("username") if not title or not link or not username: return json.dumps({"error": "Missing fields in the body"}), 400...
13,713
def _asklong(*args): """_asklong(sval_t value, char format, v(...) ?) -> int""" return _idaapi._asklong(*args)
13,714
def describe_bivariate(data:pd.DataFrame, only_dependent:bool = False, size_max_sample:int = None, is_remove_outliers:bool = True, alpha:float = 0.05, max_num_rows:int = 5000, max_size_cats...
13,715
def pip( args, path='pip', use_sudo=False ): """ Run pip. :param args: a string or sequence of strings to be passed to pip as command line arguments. If given a sequence of strings, its elements will be quoted if necessary and joined with a single space in between. :param path: the path to pip...
13,716
def launch(cmd, args=None, separate_terminal=False, in_color='cyan', silent=False, should_wait=True): """ Launch a system command :param cmd: The command to run :param args: The arguments to pass to that command (a str list) :param separate_terminal: Should we open a new terminal window :param i...
13,717
def random_neuron_index(args): """ Sort the filters randomly. """ total_neuron_nums = args.total_neuron_nums record_filters_folder = args.record_filters_folder os.makedirs(record_filters_folder, exist_ok=True) save_noisy_filter_txt = os.path.join(record_filters_folder, 'noise_index.txt') ra...
13,718
def create_feature_from_area(train_df, test_df): """ One more variable from floor area could be the difference between full area and living area. """ train_df["extra_sq"] = train_df["full_sq"] - train_df["life_sq"] test_df["extra_sq"] = test_df["full_sq"] - test_df["life_sq"]
13,719
def devilry_multiple_examiners_short_displayname(assignment, examiners, devilryrole): """ Returns the examiners wrapped in HTML formatting tags perfect for showing the examiners inline in a non-verbose manner. Typically used for showing all the examiners in an :class:`devilry.apps.core.models_group...
13,720
def main(): """If used as the main module, this method parses the arguments and calls copy or upload""" parser = argparse.ArgumentParser( description='Copy or upload field descriptions for BigQuery tables/views') parser.add_argument('mode', type=str, choices=['desccopy', 'descupload']) parser.ad...
13,721
def colormap_with_fixed_hue(color, N=10): """Create a linear colormap with fixed hue Parameters ---------- color: tuple color that determines the hue N: int, optional number of colors used in the palette """ import seaborn from matplotlib.colors import LinearSegmentedCol...
13,722
def get_news_blacklist() -> list: """Get the users news blacklist from news-blacklist.json. Returns: list: List of blacklisted news article titles """ try: with open("news-blacklist.json", encoding="utf-8") as file: log.info("Getting news blacklist from news-blacklist.json")...
13,723
def calc_triangular_number(n: int): """ A triangular number or triangle number counts objects arranged in an equilateral triangle. More info: https://www.mathsisfun.com/algebra/triangular-numbers.html :param n: :return: """ return int((n * (n + 1)) / 2)
13,724
def assign_task_command(username, task_count): """Print FILENAME.""" db = get_db() user = db.execute( 'SELECT * FROM user WHERE username = ?', (username,) ).fetchone() if user is None: click.echo("The user doesn't exist.") return selected_tasks = get_unassigned_task(user[...
13,725
def wrap_keepdims(func): """ Check that output have same dimensions as input. """ # TODO : check if it's working @wraps(func) def check_keepdims(X, *args, keepdims=False, **kwargs): if keepdims: out = func(X, *args, **kwargs) return out.reshape(out.shape + (1,)) ...
13,726
def get_headers(cred=None, filename=None): """Return headers for basic HTTP authentication. Returns: str: Basic authorization header, including Base64 encoded username and password. """ return { "Authorization": "Basic {}".format( get_base64(cred=cred, filename=...
13,727
def create_xml_content( segmentation: list[dict], lang_text: list[str], split: str, src_lang: str, tgt_lang: str, is_src: bool, ) -> list[str]: """ Args: segmentation (list): content of the yaml file lang_text (list): content of the transcription or translation txt file ...
13,728
def virtualenv(directory, local=False): """ Context manager to activate an existing Python `virtual environment`_. :: from fabric.api import run from fabtools.python import virtualenv with virtualenv('/path/to/virtualenv'): run('python -V') .. _virtual environment...
13,729
def add_deployment(directory, name, templates_dir='templates', deployment_dir='deployment', mode=0777): """ Adds new deployment if not exists """ context = { 'datetime': datetime.datetime.now(), 'name': name, 'project_name': get_project_name(directory) } dd, df = get_deploym...
13,730
def swarm_post_uptest(uptest_results, swarm_id, swarm_trace_id): """ Chord callback that runs after uptests have completed. Checks that they were successful, and then calls routing function. """ logger.info("[%s] Swarm %s post uptests", swarm_trace_id, swarm_id) # uptest_results will be a list...
13,731
def extractall(fzip, dest, desc="Extracting"): """zipfile.Zipfile(fzip).extractall(dest) with progress""" dest = Path(dest).expanduser() with ZipFile(fzip) as zipf, tqdm( desc=desc, unit="B", unit_scale=True, unit_divisor=1024, total=sum(getattr(i, "file_size", 0) for...
13,732
def play(playbook, user, inventory=SITE_INVENTORY, sudo=True, ask_pass=False, ask_sudo_pass=True, ask_vault_pass=True, verbose=False, extra=None, extra_vars=None, key=None, limit=None, tags=None, list_tasks=False): """Run a playbook. Defaults to using the "hosts" inventory""" print('[invoke] Playing {0...
13,733
def style_string(string: str, fg=None, stylename=None, bg=None) -> str: """Apply styles to text. It is able to change style (like bold, underline etc), foreground and background colors of text string.""" ascii_str = _names2ascii(fg, stylename, bg) return "".join(( ascii_str, string, ...
13,734
def select_all_genes(): """ Select all genes from SQLite database """ query = """ SELECT GENE_SYMBOL, HGNC_ID, ENTREZ_GENE_ID, ENSEMBL_GENE, MIM_NUMBER FROM GENE """ cur = connection.cursor() cur.execute(query) rows = cur.fetchall() genes = [] for row in rows: ...
13,735
def test_enum_handler(params): """ 测试枚举判断验证 """ return json_resp(params)
13,736
def get_staff_timetable(url, staff_name): """ Get Staff timetable via staff name :param url: base url :param staff_name: staff name string :return: a list of dicts """ url = url + 'TextSpreadsheet;Staff;name;{}?template=SWSCUST+Staff+TextSpreadsheet&weeks=1-52' \ '&days=1-7&...
13,737
def find_ccs(unmerged): """ Find connected components of a list of sets. E.g. x = [{'a','b'}, {'a','c'}, {'d'}] find_cc(x) [{'a','b','c'}, {'d'}] """ merged = set() while unmerged: elem = unmerged.pop() shares_elements = False for s in merged.copy...
13,738
def read_match_df(_url: str, matches_in_section: int=None) -> pd.DataFrame: """各グループの試合リスト情報を自分たちのDataFrame形式で返す JFA形式のJSONは、1試合の情報が下記のような内容 {'matchTypeName': '第1節', 'matchNumber': '1', # どうやら、Competitionで通しの番号 'matchDate': '2021/07/22', # 未使用 'matchDateJpn': '2021/07/22', 'matchDateWe...
13,739
def tokenize(text): """Tokenise text with lemmatizer and case normalisation. Args: text (str): text required to be tokenized Returns: list: tokenised list of strings """ url_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+' detected_urls =...
13,740
def reinforce_loss_discrete(classification_logits_t, classification_labels_t, locations_logits_t, locations_labels_t, use_punishment=False): """Computes REINFORCE loss for contentious discrete action spaces...
13,741
def train2(num,base_path=base_path): """ this function is used to process train.yzbx.txt format """ #train_data_file="/home/zyyang/RS/train.yzbx.txt" train_data_file=os.path.join(base_path,num,'train.yzbx.txt') b_data=defaultdict(list) fi=open(train_data_file,'r') size=0 maxb=0 for line in fi: s=line.strip(...
13,742
def analyze(binObj, task='skewer', frange=None, distort=True, CenAlpha=None, histbin=False, statistic='mean', suffix='temp', overwrite=False, skewer_index=None, zq_cut=[0, 5], parallel=False, tt_bins=None, verbose=True, nboot=100, calib_kwargs=None, skewer_kwargs=None): """ F...
13,743
def distances(spike_times, ii_spike_times, epoch_length=1.0, metric='SPOTD_xcorr'): """Compute temporal distances based on various versions of the SPOTDis, using CPU parallelization. Parameters ---------- spike_times : numpy.ndarray 1 dimensional matrix containing all spike times ii_spike_...
13,744
def test_hackerone_program_list_command_when_invalid_args_provided(client, args, expected_error): """ Test case scenario when invalid arguments are provided. Given: - invalid command arguments for list program command When - Calling `hackerone-program-list` Then: - Returns th...
13,745
def def_phygrid(nbins, outname="phys_grid.pkl", log=False, \ rootpath=os.getcwd()+'/'): """ Sub-routine that defines the physical grid. Parameters ---------- nbins: int number of the physical grids Keywords -------- outname: str name of the output .pkl file (def: "phys_g...
13,746
def format_object_translation(object_translation, typ): """ Formats the [poi/event/page]-translation as json :param object_translation: A translation object which has a title and a permalink :type object_translation: ~cms.models.events.event.Event or ~cms.models.pages.page.Page or ~cms.models.pois.poi....
13,747
def _FormatKeyValuePairsToLabelsMessage(labels): """Converts the list of (k, v) pairs into labels API message.""" sorted_labels = sorted(labels, key=lambda x: x[0] + x[1]) return [ api_utils.GetMessage().KeyValue(key=k, value=v) for k, v in sorted_labels ]
13,748
def gen_unique(func): """ Given a function returning a generator, return a function returning a generator of unique elements""" return lambda *args: unique(func(*args))
13,749
def app_actualizar(): """ Actualizar datos a través de formulario """ helper.menu() # Seccion actualizar output.span(output.put_markdown("## Sección Actualizar")) output.put_markdown(f"Actualizar una fila") form_update = input.input_group("Actualizar Datos", [ input.input(label="...
13,750
def admin_inventory(request): """ View to handle stocking up inventory, adding products... """ context = dict(product_form=ProductForm(), products=Product.objects.all(), categories=Category.objects.all(), transactions=request.user.account.transact...
13,751
def snippet_list(request): """ List all code snippets, or create a new snippet. """ print(f'METHOD @ snippet_list= {request.method}') if request.method == 'GET': snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return JsonResponse(seriali...
13,752
def generate_submission(args: ArgumentParser, submission: pd.DataFrame) -> pd.DataFrame: """Take Test Predictions for 4 classes to Generate Submission File""" image, kind = args.shared_indices df = submission.reset_index()[[image, args.labels[0]]] df.columns = ["Id", "Label"] df.set_index("Id", inpl...
13,753
def nearest1d(vari, yi, yo, extrap="no"): """Nearest interpolation of nD data along an axis with varying coordinates Warning ------- `nxi` must be either a multiple or a divisor of `nxo`, and multiple of `nxiy`. Parameters ---------- vari: array_like(nxi, nyi) yi: array_like(nxiy, ...
13,754
def registros(): """Records page.""" return render_template('records.html')
13,755
def cal_evar(rss, matrix_v): """ Args: rss: matrix_v: Returns: """ evar = 1 - (rss / np.sum(matrix_v ** 2)) return evar
13,756
def split_path(path): """ public static List<String> splitPath(String path) * Converts a path expression into a list of keys, by splitting on period * and unquoting the individual path elements. A path expression is usable * with a {@link Config}, while individual path elements are usable with a...
13,757
def load_dataset_RGB(split_th = 0.8, ext='.jpg'): """ Default: 80% for training, 20% for testing """ positive_dir = '/media/himanshu/ce640fc3-0289-402c-9150-793e07e55b8c/visapp2018code/RGB/data/positive' negative_dir = '/media/himanshu/ce640fc3-0289-402c-9150-793e07e55b8c/visapp2018code/RGB/data/negative' ...
13,758
def imagetransformer_base_8l_8h_big_cond_dr03_dan_dilated_d(): """Dilated hparams.""" hparams = imagetransformer_base_8l_8h_big_cond_dr03_dan_dilated() hparams.gap_sizes = [0, 16, 64, 16, 64, 128, 256, 0] return hparams
13,759
def leaveOneOut_Input_v4( leaveOut ): """ Generate observation matrix and vectors Y, F Those observations are trimed for the leave-one-out evaluation. Therefore, the leaveOut indicates the CA id to be left out, ranging from 1-77 """ des, X = generate_corina_features('ca') X = np.delete...
13,760
def common_inroom_auth_response(name, request, operate, op_args): """ > 通用的需要通过验证用户存在、已登录、身处 Room 的操作。 参数: - name: 操作名,用于日志输出; - request: Flask 传来的 request; - operate: 具体的操作函数,参数为需要从 request.form 中提取的值,返回值为成功后的response json; - op_args: operate 函数的 参数名 str 组成的列表。 返回:response json 说...
13,761
def tab_printer(args): """ Function to print the logs in a nice tabular format. :param args: Parameters used for the model. """ args = vars(args) t = Texttable() t.add_rows([["Parameter", "Value"]] + [[k.replace("_"," ").capitalize(),v] for k,v in args.iteritems()]) print t.draw()
13,762
def get_pca(acts, compute_dirns=False): """ Takes in neuron activations acts and number of components. Returns principle components and associated eigenvalues. Args: acts: numpy array, shape=(num neurons, num datapoints) n_components: integer, number of pca components to reduce ...
13,763
def refresh_lease(lease_id, client_id, epoch, ttl): """ Update the timeout on the lease if my_id is the lease owner, else fail. :param lease_id: :param client_id: :param ttl: number of seconds in the future to set the expiration to, can lengthen or shorten expiration depending on current value of l...
13,764
def plot_cor_centroids(axs, ctd, zms): """plots coronal centroids on a plane axes Parameters: ---------- axs: matplotlib axs ctd: list of centroids zms: the spacing of the image """ # requires v_dict = dictionary of mask labels for v in ctd[1:]: axs.add_patch(Circle((v[3...
13,765
def checkLastJob(jobsFolder): """Count number of folders in folder :param jobsFolder: directory with jobs :return: number of created jobs """ allFolders = os.listdir(jobsFolder) jobsFolders = [f for f in allFolders if f.startswith('job')] jobsCount = len(jobsFolders) return jobsCoun...
13,766
def canny(img, low_threshold, high_threshold): """Applies the Canny transform""" #imgCopy = np.uint8(img) return cv2.Canny(img, low_threshold, high_threshold)
13,767
def pairwise_two_tables(left_table, right_table, allow_no_right=True): """ >>> pairwise_two_tables( ... [("tag1", "L1"), ("tag2", "L2"), ("tag3", "L3")], ... [("tag1", "R1"), ("tag3", "R3"), ("tag2", "R2")], ... ) [('L1', 'R1'), ('L2', 'R2'), ('L3', 'R3')] >>> pairwise_two_tables( ...
13,768
def augment_stochastic_shifts(seq, augment_shifts): """Apply a stochastic shift augmentation. Args: seq: input sequence of size [batch_size, length, depth] augment_shifts: list of int offsets to sample from Returns: shifted and padded sequence of size [batch_size, length, depth] """ shift_index = ...
13,769
def _SourceArgs(parser): """Add mutually exclusive source args.""" source_group = parser.add_mutually_exclusive_group() def AddImageHelp(): """Returns detailed help for `--image` argument.""" template = """\ An image to apply to the disks being created. When using this option, the size o...
13,770
def get_all_species_links_on_page(url): """Get all the species list on the main page.""" data, dom = get_dom(url) table = dom.find('.tableguides.table-responsive > table a') links = [] for link in table: if link is None or link.text is None: continue links.append(dict( ...
13,771
def gen_image_name(reference: str) -> str: """ Generate the image name as a signing input, based on the docker reference. Args: reference: Docker reference for the signed content, e.g. registry.redhat.io/redhat/community-operator-index:v4.9 """ no_tag = reference.split(":")[0] ...
13,772
def adaptive_confidence_interval(values, max_iterations=1000, alpha=0.05, trials=5, variance_threshold=0.5): """ Compute confidence interval using as few iterations as possible """ try_iterations = 10 while True: intervals = [confidence_interval(values, try_iterations, alpha) for _ in range(trials...
13,773
def get_chat_id(update): """ Get chat ID from update. Args: update (instance): Incoming update. Returns: (int, None): Chat ID. """ # Simple messages if update.message: return update.message.chat_id # Menu callbacks if update.callback_query: return ...
13,774
def action(fun): """Method decorator signaling to Deployster Python wrapper that this method is a resource action.""" # TODO: validate function has single 'args' argument (using 'inspect.signature(fun)') fun.action = True return fun
13,775
def chooseCommertialCity(commercial_cities): """ Parameters ---------- commercial_cities : list[dict] Returns ------- commercial_city : dict """ print(_('From which city do you want to buy resources?\n')) for i, city in enumerate(commercial_cities): print('({:d}) {}'.for...
13,776
def nn_layer(input_tensor, input_dim, output_dim, layer_name, act=tf.nn.relu): """Reusable code for making a simple neural net layer. It does a matrix multiply, bias add, and then uses relu to nonlinearize. It also sets up name scoping so that the resultant graph is easy to read, and adds a number of summary o...
13,777
def move_right_row(row, debug=True): """move single row to right.""" if debug: print(row) row_del_0 = [] for i in row: # copy non-zero blocks if i != 0: row_del_0.append(i) #print(row_del_0) row = row_del_0 i = 0 j = len(row_del_0) - 1 while i < j: # com...
13,778
def enable_debug_mode() -> None: """ Enable PyBryt's debug mode. """ global _DEBUG_MODE_ENABLED _DEBUG_MODE_ENABLED = True
13,779
def escape(s): """ Built-in javascript function to HTML escape a string. The escape() function encodes special characters, with the exception of: * @ - _ + . / Use the unescape() function to decode strings encoded with escape(). For example: >>> escape("?!=...
13,780
def get_validate_platform(cmd, platform): """Gets and validates the Platform from both flags :param str platform: The name of Platform passed by user in --platform flag """ OS, Architecture = cmd.get_models('OS', 'Architecture', operation_group='runs') # Defaults platform_os = OS.linux.value ...
13,781
def get_path_cost(slice, offset, parameters): """ part of the aggregation step, finds the minimum costs in a D x M slice (where M = the number of pixels in the given direction) :param slice: M x D array from the cost volume. :param offset: ignore the pixels on the border. :param parameters: stru...
13,782
def authorize_cache_security_group_ingress(CacheSecurityGroupName=None, EC2SecurityGroupName=None, EC2SecurityGroupOwnerId=None): """ Allows network ingress to a cache security group. Applications using ElastiCache must be running on Amazon EC2, and Amazon EC2 security groups are used as the authorization mecha...
13,783
def delete(profile_name): """Deletes a profile and its stored password (if any).""" message = ( "\nDeleting this profile will also delete any stored passwords and checkpoints. " "Are you sure? (y/n): " ) if cliprofile.is_default_profile(profile_name): message = f"\n'{profile_name...
13,784
def generate_cyclic_group(order, identity_name="e", elem_name="a", name=None, description=None): """Generates a cyclic group with the given order. Parameters ---------- order : int A positive integer identity_name : str The name of the group's identity element Defaults to 'e' ...
13,785
def test_CSVBatchProcessor_DatasetParser(): """CSVBatchProcessor correctly identifies the localization files. """ knownDatasets = ['HeLaS_Control_IFFISH_A647_1_MMStack_Pos0_locResults.dat', 'HeLaS_Control_IFFISH_A647_2_MMStack_Pos0_locResults.dat', 'HeLaS_shTRF...
13,786
def test_gf_low_TA(): """ Ensure mid lats, low res, retrieves proper file """ s1 = Swepy(os.getcwd(), ul="T", lr="T", high_res=False) s1.set_login() date = datetime.datetime(2006, 11, 4) file = s1.get_file(date, "19H") assert file == { "protocol": "http", "server": "local...
13,787
def loadTextureBMP(filepath): """ Loads the BMP file given in filepath, creates an OpenGL texture from it and returns the texture ID. """ data = np.array(Image.open(filepath)) width = data.shape[0] height = data.shape[1] textureID = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, textu...
13,788
def get_pixeldata(ds: "Dataset") -> "np.ndarray": """Return a :class:`numpy.ndarray` of the pixel data. .. versionadded:: 2.1 Parameters ---------- ds : pydicom.dataset.Dataset The :class:`Dataset` containing an :dcm:`Image Pixel <part03/sect_C.7.6.3.html>` module and the *Pixel Da...
13,789
def timeit(method): """ Timing Decorator Function Written by Fahim Sakri of PythonHive (https://medium.com/pthonhive) """ def timed(*args, **kwargs): time_start = time.time() time_end = time.time() result = method(*args, **kwargs) if 'log_time' in kwargs: name = kwarg...
13,790
def allot_projects(): """ The primary function that allots the projects to the employees. It generates a maximum match for a bipartite graph of employees and projects. :return: A tuple having the allotments, count of employees allotted and total project headcount (a project where two people need to...
13,791
def test_ls_name_pattern(cmds): """ Validate we can list object matching provided node name pattern.""" cmds.createNode("transform", name="transformA") actual = cmds.ls("transform*") assert actual == [u"transformA"]
13,792
def set_threshold(scad, threshold): """ Set the threshold in the .sCAD file. None value is ignored and the existing value is kept. """ if threshold: scad['eom_etree'].set('warningThreshold', threshold)
13,793
def upload_record(data, headers, rdr_project_id): """ Upload a supplied record to the research data repository """ request_url = f"https://api.figsh.com/v2/account/projects/{rdr_project_id}/articles" response = requests.post(request_url, headers=headers, json=data) return response.json()
13,794
def datetime_to_ts(str_datetime): """ Transform datetime representation to unix epoch. :return: """ if '1969-12-31' in str_datetime: # ignore default values return None else: # convert to timestamp if '.' in str_datetime: # check whether it has milliseconds or no...
13,795
def is_codenames_player(funct): """ Decorator that ensures the method is called only by a codenames player. Args: funct (function): Function being decorated Returns: function: Decorated function which calls the original function if the user is a codenames player, and returns ot...
13,796
def build_moduledocs(app): """Create per-module sources like sphinx-apidoc, but at build time and with customizations.""" srcdir = app.builder.srcdir moddir = srcdir + '/module' os.makedirs(moddir, exist_ok=True) basedir = os.path.dirname(srcdir) docs = [x[len(basedir)+1:-3].replace('/', '...
13,797
def same_container_2(): """ Another reason to use `same_container=co.SameContainer.NEW` to force container sharing is when you want your commands to share a filesystem. This makes a download and analyze pipeline very easy, for example, because you simply download the data to the filesystem in one no...
13,798
def get(args) -> str: """Creates manifest in XML format. @param args: Arguments provided by the user from command line @return: Generated xml manifest string """ arguments = { 'target': args.target, 'targetType': None if args.nohddl else args.targettype, 'path': args.path, ...
13,799