content
stringlengths
22
815k
id
int64
0
4.91M
def get_fingerprint_batch(input_list, default_port=443, delay_time=0.5, max_threads=100): """ This is a parallel version of the TLS fingerprint primitive. Params: input_list- the input is a list of host:ports. default_port- default port to use when no port specified ...
72,900
def check_password(password): """Check that the password is long and complex enough. Raise ValueError otherwise.""" if len(password) < settings['MIN_PASSWORD_LENGTH']: raise ValueError("Password must be at least {0} characters long.". format(settings['MIN_PASSWORD_LENGTH']))
72,901
def even_fib(ceiling): """ Returns the sum of all even Fibonacci numbers not exceeding ceiling. """ total = 0 fg = Fibonacci() n = next(fg) while n <= ceiling: if n % 2 == 0: total += n n = next(fg) return total
72,902
def get_table_columns(etcd_client, db, tbl): """ Get primary key column for table db.tbl. :param etcd_client: Etcd client. :param db: database name. :param tbl: table name. :return: Primary key column. :rtype: ColumnSet :raise ProgrammingError: if table or database doesn't exist """...
72,903
def _flatten_multiplicand_list(kernels): """Flatten a list of kernels which may contain _ProductKernel instances. Args: kernels: Python list of `PositiveSemidefiniteKernel` instances Returns: Python list containing the elements of kernels, with any _ProductKernel instances replaced by their `kernels...
72,904
def parse_bool_token(token): """ Parses a string token to convert it to its equivalent boolean value ignoring the case of the string token or leaves the token intact if it cannot. :param token: String to convert to ``True`` or ``False``. :type token: ``str`` :return: ``T...
72,905
def dictionary_writable( model: Union[type, abc.Dictionary] ) -> abc.DictionaryHooks: """ Retrieve a metadata instance. If the instance currently inherits its metadata from a class or superclass, this function will copy that metadata and assign it directly to the model instance. """ return w...
72,906
def log_prb_1l_per_smpl(x, ls): """ x=log(P) is a list of log probability tensors, and it has shape (batch_size, number_of_classes + 1, other dimensions like time, ...) ls is a list of labels with the same length as x. Each sample has one label in range [0, number_of_classes) Return a list ...
72,907
def func_PS_Level(HA_Open, HA_Close, PS_pct_level=[0.35, 0.5, 0.95, 0.97], combine=False): """ 0. This function is for calculating the HA bars' bar size level, or called Price Status(PS). 1. This function has 4 arguments and return 2 arrays as output. 2. Input arguments including: (1) HA_Open: D...
72,908
def pobrisi_tabele(conn): """ Pobriše tabele iz baze. """ conn.execute("DROP TABLE IF EXISTS karta;") conn.execute("DROP TABLE IF EXISTS let;") conn.execute("DROP TABLE IF EXISTS letalisce;") conn.execute("DROP TABLE IF EXISTS linije;") conn.execute("DROP TABLE IF EXISTS prevoznik;")
72,909
def test_grid(): """Test the computation of streaming histogram for a grid.""" data = xr.load_dataset(grid2d_path()).mss hist = StreamingHistogram(data) assert hist.mean()[0] == pytest.approx(data.mean(), abs=1e-4) data = xr.load_dataset(grid3d_path()).tcw hist = StreamingHistogram(data, axis=(...
72,910
def angle(x0, x1): """Compute the angle between two vectors x0, x1 using the dot product""" mx0 = np.dot(x0, x0) mx1 = np.dot(x1, x1) return np.arccos(np.dot(x0,x1)/np.sqrt(mx0*mx1))
72,911
def ipam_release_pool(): """Deletes a new Neutron subnetpool from the given reuest. This function takes the following JSON data and delegates the subnetpool deletion to the Neutron client. :: { "PoolID": string } Then the following JSON response is returned. :: {} ...
72,912
def grubbs(timeseries, end_timestamp, full_duration): """ A timeseries is anomalous if the Z score is greater than the Grubb's score. """ try: series = scipy.array([x[1] for x in timeseries]) stdDev = scipy.std(series) # Issue #27 - Handle z_score agent.py RuntimeWarning - http...
72,913
def _spatial_proximity(data, group_pop_var, total_pop_var, alpha=0.6, beta=0.5): """Calculate Spatial Proximity index. Parameters ---------- data : a geopandas DataFrame with a geometry column. group_pop_var : string The name of variable in data that contains the popula...
72,914
def predelete_handler(sender, instance, **_): """ ``pre_delete`` handler. Gets all dependent objects as pk lists and saves them in thread local storage. """ # get the querysets as pk lists to hold them in storage # we have to get pks here since the queryset will be empty after deletion ...
72,915
def save_img_lbl_inst( src_img_file, src_class_file, src_instance_file, dst_images_path, dst_class_path, dst_instance_path, smaller_size=1000, ): """Resizes images from the src directories and saves them to the dst directories""" lbl = Image.open(src_class_file) image_size = cal...
72,916
def video_content_to_dict(vid_info_list): """Convert YouTube metadata list to dictionary.""" video_dict = {} for video in vid_info_list: if not video: continue title = video["title"] video_dict[title] = {"id": video["id"], "duration": video["duration"]} return video_d...
72,917
def getwcs(dataset, applyomega=True, service="https://hla.stsci.edu/cgi-bin/fitscut.cgi"): """Return dictionary with WCS information for an image. Parameters ---------- dataset : str dataset name applyomega : bool, optional Apply HSC correction? Default value = True service : ...
72,918
def get_redis_from_settings(settings): """Returns a redis client instance from given Scrapy settings object. This function uses ``get_client`` to instantiate the client and uses ``defaults.REDIS_PARAMS`` global as defaults values for the parameters. You can override them using the ``REDIS_PARAMS`` sett...
72,919
async def download(uri): """ Guarda en el disco duro un archivo indicado por una URI Parámetro: > uri (str, por ejemplo 'http://www.inspyration.org/logo.png') Retorno: > contenido de un archivo (bytes, archivo de texto o binario) """ content = wget(uri) if content is None: ...
72,920
def print_symbol_table_node_to_dot(node, cur_id): """ Print the node of a symbol table as html table :param node: symbol table :param cur_id: current node id :return: dot string """ dot = "\t{} [\n\t shape=plaintext \n \tlabel=< <table border=\'0\' cellborder=\'1\' cellspacing=\'0\'\n\t>".fo...
72,921
def create_getter(var_name): """ Given the string name of a variable, creates a getter function for that variable and returns it. Args: var_name the name of the variable for which a getter should be created. """ def getter(self): """ The getter function to be returned.""" return geta...
72,922
def install_dependencies_git(): """ Install all dependencies available from git """ require('environment', provided_by=[dev, prod]) # if this is a production install then install everything that pip that # can be installed gits_ = GIT_INSTALL.copy() if env.environment != 'development': ...
72,923
def validate_receiver_args(signal_instance, receiver_func): """ 校验接收者参数 :param signal_instance: :param receiver_func: :return: """ receiver_func_sign = inspect.signature(receiver_func) receiver_func_params = receiver_func_sign.parameters if len(receiver_func_params) == 1 and len( ...
72,924
def James_Stein_estimator(data, std_noise): """ See Large-scale inference: empirical Bayes methods for estimation, testing, and prediction (Efron, 2010, page 6) """ mean_data = np.mean(data) dev = sum((data - mean_data) ** 2) return mean_data + (1 - (len(data) - 3) * (std_noise ** 2) / dev) * (d...
72,925
def predict_by_moving_avg_growth(stock, s, **_): """Returns predicted value of a stock Predicts the next price of a stock by extrapolating the moving average and its growth. Parameters ---------- stock : :obj:`stock` Stock to be predicted. s : int Number of data points used to...
72,926
def debug(): """ Method to debug server. """ return {'message': 'pong'}, 200
72,927
def cli(): """Fusion-finder calls structural variants from input .bam or .fastq files.""" pass
72,928
def get_admin_log(peer: Union[int, str] = None) -> list: """ Get a list of logs from the admin-logs. This method gets 'Join' and 'Leave' events by default, but you can uncomment the commented items and add them to your result list. :param peer: Union: [id, username]. Peer username or ID. ex. get_a...
72,929
def from_networkx(G): """ Convert a NetworkX graph into a Zen graph object. In creating the object, the NetworkX node object and node/edge data will be copied over (a shallow copy). **Returns**: The return type depends on the input type. * :py:class:`zen.Graph` if the input graph was a :py:class:`network...
72,930
async def test_module_webcomponent(opp): """Test if a js module is found in config panels dir.""" config = { "panel_custom": { "name": "todo-mvc", "module_url": "/local/bla.js", "sidebar_title": "Sidebar Title", "sidebar_icon": "mdi:iconicon", ...
72,931
def find_subpixel_peak_position(corr, subpixel_method='gaussian'): """ Find subpixel approximation of the correlation peak. This function returns a subpixels approximation of the correlation peak by using one of the several methods available. If requested, the function also returns the signal ...
72,932
def parse_preference_papx(c): """ Parser allowing to extract a perference from a string in the papx (or apx) format. This method is invoked in parse_papx, and for it to work the condition stipulated in the latter must be respected. str-->None """ assert type(c) is str, "The argument in this...
72,933
def bulk_video_converter( video_path_tuple: tuple, fps_multiplier: int, dest_path: str = None, tkinter_label_object: Label = None, tkinter_label_percent_object: Label = None, tkinter_progressbar_object: Progressbar = None, tkinter_root_tk_object: Tk = None, tkinter_convert_button: Button...
72,934
def _vec_to_triu(vec): """Take vec and forms strictly upper triangular matrix. Parameters ---------- vec : array_like, shape[..., n] Returns ------- tril : array_like, shape=[..., k, k] where k is (1 + sqrt(1 + 8 * n)) / 2 """ n = vec.shape[-1] triu_shape = vec.shape + ...
72,935
def flash_errors(form, category="warning"): """Flash all errors for a form.""" for field, errors in form.errors.items(): for error in errors: flash("{0} - {1}".format(getattr(form, field).label.text, error), category)
72,936
def import_dll(): """ Import Dlls. """ paths = [ "System.Drawing", "System.Windows.Forms", ] + glob(str(Path(__file__).parents[1].joinpath("bin/x64/*.dll"))) for path in paths: AddReference(path)
72,937
def _compress(s: bytes): """ Compresses bytes for the payload. """ co = zlib.compressobj(wbits=-zlib.MAX_WBITS) b = co.compress(s) + co.flush() return base64.b64encode(''.join(map(chr, b)).encode())
72,938
def render_Board_members_list_overlay(self, h, comp, *args): """Overlay to list all members""" h << h.h2(_('All members')) with h.form: with h.div(class_="members"): h << [m.on_answer(self.handle_event, comp).render(h) for m in self.all_members] return h.root
72,939
def test_set_units_error(tmpdir, value): """Number of values must match band count""" tmptiff = str(tmpdir.join('test.tif')) with rasterio.open( tmptiff, 'w', count=2, height=256, width=256, **default_gtiff_profile) as dst: with pytest.raises(ValueError): dst.unit...
72,940
def _token_to_int(t, token_list, token_cache, size_limit=float('inf')): """Return the int which represents a token, with caching. Throws a ValueError if token t is not in the token_list. There MUST be a _UNK token at the beginning of your vocab, or this may not halt. """ if t not in token_cache: ...
72,941
def print_verbose(dir_path: Path, paths_to_refactor: Iterable[Path], refactored_paths: Optional[Iterable[Path]]) -> None: """ :param dir_path: Directory path whose contents will be refactored :param paths_to_refactor: paths that will be refactored :param refactored_paths: refactored pa...
72,942
def set_label_font(ax, xsize=14, ysize=14, xweight='bold', yweight='bold', **kwargs): """ change x,y label fonts Args: ax (plt.Axes): matplotlib axes xsize (int,optional): xlabel fontsize, default is 14 ysize (int,optional): ylabel fontsize, default is 14 xweight (str,optional): xlabel fontweight...
72,943
def parse_and_run_command(): """ Examples: # python -m telemetry_peak_analyzer \ -b telemetry_peak_analyzer.backends.JsonBackend -n "~/data.*.json" \ -s 2020-07-01 -e 2021-08-01 -t 10 # python -m telemetry_peak_analyzer -c config.ini \ -b telemetry_peak_analyz...
72,944
def select_data(df, countries_list, regions_list, ages_list, genders_list): """Extracts from the dataset the data corresponding to many criterias. Parameters: ----------- df : Pandas DataFrame dataset countries_list : list of str countries to be selected regio...
72,945
def revescape(text): """Any text. Escapes all "special" characters, except @. Forward slashes are escaped twice to prevent web servers from prematurely unescaping them. For example, "@foo bar/baz" becomes "@foo%20bar%252Fbaz". """ return urlreq.quote(text, safe=b'/@').replace(b'/', b'%252F')
72,946
def intersect1d(pda1 : pdarray, pda2 : pdarray, assume_unique : bool=False) -> pdarray: """ Find the intersection of two arrays. Return the sorted, unique values that are in both of the input arrays. Parameters ---------- pda1 : pdarray Input array ...
72,947
def _remove_unicode_encoding(xml_file): """ attempts to remove the "encoding='unicode'" from an xml file as lxml does not support that on a windows node currently see issue #38100 (Search.adml) For some reason this file is encoded 'utf-16' """ with salt.utils.files.fopen(xml_file, "rb") as...
72,948
def plot_att_response_maps(data, model_arch_file, model_weights_file, figure_dir, nb_conv_layers, layer_nb='all', nb_top_feat_maps=4, filename_maps="attentive_response_maps", cmap=cm.hot, plot_all_filters=False, ...
72,949
def add_data_reference(enc_key, enc_data): """Add DataReference to ``enc_data`` in ReferenceList of ``enc_key``. ``enc_data`` should be an EncryptedData node; ``enc_key`` an EncryptedKey node. Add a wsu:Id attribute to the EncryptedData if it doesn't already have one, so the EncryptedKey's URI att...
72,950
def test_python_module_ctia_positive_coa(module_headers, module_tool_client): """Perform testing for coa entity of custom threat intelligence python module ID: CCTRI-161-03b73a5e-b919-4e94-8828-c388e1ba211e Steps: 1. Send POST request to create new coa entity using custom python m...
72,951
def _get_items_as_rows(items_to_add: Sequence[Any], batch_number: int, result: str, operation: str, timestamp: str) -> List[Dict[str, Any]]: """Adds Content API results to the data object to be inserted into Big Query. Args: items_to_add: The items to add. batc...
72,952
def test_check_008(mada_ttFonts): """ Fonts have consistent underline thickness ? """ from fontbakery.specifications.post import com_google_fonts_check_008 as check print('Test PASS with good family.') status, message = list(check(mada_ttFonts))[-1] assert status == PASS # introduce a wronge value in one ...
72,953
def is_subdir(child, parent): """ Determine if "child" is a subdirectory of "parent". If child == parent, returns True. """ child_path = os.path.realpath(child) parent_path = os.path.realpath(parent) if len(child_path) < len(parent_path): return False for i in range(len(parent_path)): if pare...
72,954
def get_available_purchase_count(tab: str = None) -> int: """(internal)""" try: if _ba.get_account_state() != 'signed_in': return 0 count = 0 our_tickets = _ba.get_account_ticket_count() store_data = get_store_layout() if tab is not None: tabs = [(...
72,955
def textops_rawtexttolines(text, linedelimiter="\n"): """ <Purpose> Converts raw text (a string) into lines that can be processed by the functions in this module. <Arguments> text: The text to convert into lines (basically, a sequence of strings). linedelimiter (optional, defaults to...
72,956
def get_display_name(skill_name: str): """Splits camelcase and removes leading/trailing "skill".""" skill_name = skill_name.replace("_", " ").replace("-", " ") skill_name = re.sub(r'(^[Ss]kill|[Ss]kill$)', '', skill_name) return camel_case_split(skill_name).title().strip()
72,957
def generate_images(*, path: pathlib.Path) -> Tuple[files.File, ...]: """ Get the assets images to create. Args: path: the destination path for the images. Returns: A tuple of the images to create. """ images = assets.get_images() return ( files.File(path=path / ima...
72,958
def timestamp2datetime(value): """ 将一个时间戳值转换为系统所在时区的日期时间实例 """ return timezone.make_aware(datetime.fromtimestamp(value))
72,959
def generate_eagle_track( conductivity: np.ndarray, potential: np.ndarray, start_loc: List[int], dirn_restrict: int, nu_par: float ): """ Generate an eagle track """ num_rows, num_cols = conductivity.shape burnin = 200 max_moves = num_rows * num_cols dirn = [...
72,960
def _expm_vjp(exp_matrix, matrix): """ Construct the left-multiplying vector jacobian product function for the matrix exponential. Intuition: `dfinal_dexpm` is the jacobian of `final` with respect to each element `expmij` of `exp_matrix`. `final` is the output of the first function in the b...
72,961
def precook(s, n=4, out=False): """ Takes a string as input and returns an object that can be given to either cook_refs or cook_test. This is optional: cook_refs and cook_test can take string arguments as well. :param s: string : sentence to be converted into ngrams :param n: int : number of ...
72,962
def motorcycle_data(): """ The motorcycle dataset where the targets are normalised to zero mean and unit variance. Returns a tuple of input features with shape [N, 1] and corresponding targets with shape [N, 1]. """ df = pd.read_csv("./data/motor.csv", index_col=0) X, Y = df["times"].values.resh...
72,963
def get_class_distribution(y): """Calculate number of samples per class.""" # y_cls can be one of [OH label, index of class, class label name string] # convert OH to index of class y_cls = flatten_y_if_onehot(y) # y_cls can be one of [index of class, class label name] classset = sorted(list(set(...
72,964
def start(): """Starting place of adventure""" print("You awake in a room with doors labelled,") print("N[orth], S[outh], E[ast] and W[est]") # loop until N is given stuck = True while stuck: heading = direction() if heading == 'S' or heading == 'E' or heading == 'W': ...
72,965
def decryption(self): """Check that `aes_decrypt_mysql` functions accepts `mode` as the first parameter and `ciphertext` as the second parameter and we can convert the decrypted value into the original value with the original data type. """ key = f"{'1' * 64}" iv = f"{'2' * 64}" with Given(...
72,966
def gamma_at_2_coefficient(k): """Reference: https://dlmf.nist.gov/5.7#E3""" if k == 0: return S(0) elif k == 1: return S(1 + digamma(1)) else: return ((-1)**k*(zeta(k) - 1)/k)
72,967
def create_manager_office(sender, instance, created, **kwargs): """ Help-desk Office created by default after Structure is created """ if created: OrganizationalStructureOffice.objects.create(name=settings.DEFAULT_ORGANIZATIONAL_STRUCTURE_OFFICE, ...
72,968
def backwards_move_org_source(apps, schema_editor): """Use source field to set organization account.""" apps.get_model('oauth', 'RemoteOrganization') SocialAccount = apps.get_model('socialaccount', 'SocialAccount') for account in SocialAccount.objects.all(): rows = (account.remote_organizations ...
72,969
def parse_args(): """Parser/validator for the cmd line args.""" parser = get_parser() if len(sys.argv) < 2: parser.print_help() warnings.warn('Too few arguments!', UserWarning) parser.exit(1) # parsing try: params = parser.parse_args() except Exception as exc: ...
72,970
def unverified_user(error): """Displays the front page with an error that the user must verify their email before accessing data. """ messages = { "Email Unverified": [ "Please complete the sign up process by verifying your " "email account. You should receive a verificat...
72,971
def initialize_sampler_lp_(g, batch_size, args, target_idx, evaluate_panrep =False): """ When lp is used different loader is required """ full_node_list = torch.arange(g.number_of_nodes()) target_uns = torch.arange(g.number_of_nodes()) val_pct = 0.1 use_cuda = args.gpu >= 0 and torch.cuda.is_availa...
72,972
def _velocity_factor(velocity_units_in: str, velocity_units_out: str) -> float: """helper method for convert_velocity""" factor = 1.0 if velocity_units_in == 'm/s': factor /= 0.3048 elif velocity_units_in == 'ft/s': pass elif velocity_units_in == 'in/s': factor /= 12. eli...
72,973
def submit_notable(service, notable, num_enrichment_events): """ Submits fetched notable to Splunk for an Enrichment. Three enrichments possible: Drilldown, Asset & Identity. If all enrichment type executions were unsuccessful, creates a regular incident, Otherwise updates the integration context for the ...
72,974
def check_geometry_case4(): """check_geometry_case4""" try: geom = Geometry(10, 1, 1.0, 0.0) for attr, config in geom.__dict__.items(): if config is not None: print("check sampling config: {}: {}".format(attr, config)) except TypeError: print("get geom nam...
72,975
def avoid_my_body(my_body, possible_moves): """ my_body: List of dictionaries of x/y coordinates for every segment of a Battlesnake. e.g. [ {"x": 0, "y": 0}, {"x": 1, "y": 0}, {"x": 2, "y": 0} ] possible_moves: List of strings. Moves to pick from. e.g. ["up", "down", "left", "right"]...
72,976
def image_grid(img, row, col): """ img: N,h,w,x collage: 1,.., x """ bs,h,w,c=img.shape device = img.device collage = torch.zeros(h*row, w*col, c).to(device) for i in range(row): for j in range(col): collage[i*h:(i+1)*h,j*w:(j+1)*w] = img[i*col+j] return colla...
72,977
def sautMini(group1, group2): """Critère du saut minimal""" mini = float("inf") for e in group1: for t in group2: dist = distanceEucl(e,t) if dist < mini: mini = dist return mini
72,978
def add_to_accounts(account_or_ou): """ Add the parameter to the account list of the manifest file :param account_or_ou: A dict describing the the account or the ou to be added """ manifest_commands.add_to_accounts(account_or_ou)
72,979
def main(): """Main program entry.""" """Maybe add two minute delay before code starts to allow Alchol sensor to heat up to adequate temperature""" # add a heading to each data entry into API with open("data.csv", "w") as fp: # adds a set heading fp.write("alcohol concentration \n") ...
72,980
def get_optimal_threshold(y_true, y_prob, grid_spacing=0.01, verbose=False): """For probabilities, find optimal threshold according to f1 score. For a set of groud truth labels and predicted probabilities of these labels, perform...
72,981
def contour_dem(dem_fp, raster_band=1, min_val=None, max_val=None, method='basic', contour_interval=None, n_contours=None, contour_list=None, bbox=None, output_format='features', logger=None): """Contour the DEM using one of two approaches, export geojson. :param dem_fp: the filepath to the DEM...
72,982
def apply_style_transfer(content_uri:str, style_uri:str) -> str: """ Applies the style transfer effect to provided images. Returns base64 image representation. """ content_image = decode_image(content_uri) content_image = process_image(content_image) style_image = decode_image(style_uri) ...
72,983
def get_metadata(order_id: str) -> Optional[dict]: """ Retrieve metadata for an order """ res = table.get_item(Key={ "orderId": order_id, "productId": METADATA_KEY }) return res.get("Item", None)
72,984
def SearchFetchable(session=None, **kwargs): """Search okcupid.com with the given parameters. Parameters are registered to this function through :meth:`~okcupyd.filter.Filters.register_filter_builder` of :data:`~okcupyd.json_search.search_filters`. :returns: A :class:`~okcupyd.util.fetchable.Fetcha...
72,985
def lambda_handler(event, context): """ This handler is meant to be attached to an S3 bucket and triggered when objects are placed into that bucket. If the object has an attachment and header that matches what we're expecting, then the CSV attachment will be ingested into DynamoDB. """ for ...
72,986
def getChildrenByName(rootNode, name): """Returns all child nodes of a specified name. """ return [e for e in rootNode.childNodes if e.localName == name]
72,987
def tcp_traceflow(packet): """Trace packet flow for TCP. Args: packet (pyshark.packet.packet.Packet): Scapy packet. Returns: Tuple[bool, Dict[str, Any]]: A tuple of data for TCP reassembly. * If the ``packet`` can be used for TCP flow tracing. A packet can be reassembled ...
72,988
def plot(rawfile, pvars=None, outimg=None): """Loads the rawspice file and plots the data. Args rawfile: path to the rawspice.raw file pvars: list of variables to plot. If `None`, all variables are plotted. save: path to save file """ # FIXME: some poop logic here... ...
72,989
def main(plugin): """ ノートの歌詞に R が含まれていたらVelocity=100 """ notes = plugin.notes for note in notes: if ('R' != note.lyric) and ('R' in note.lyric): note.set_by_key('Velocity', 100)
72,990
def validateResponse(validator, message, response): """ Checks that response field of a message is correct. """ base_string = "Response from '" + response.source + "' in message '" base_string += message.m_type + "' from '" + message.getSourceName() validate(validator, response.getData(), base_...
72,991
def protocols_with_string(string): """Return a list of protocols matching given string.""" # Normalize string while "//" in string: string = string.replace("//", "/") string = string.strip("/") if not string: return [] ret = [] for name in string.split("/"): ret.appe...
72,992
def ClearFrameworkDirectories(): """Clears the framework directories.""" projectSettings.currentProject.SetValue( "frameworkDirsTemp", [] ) projectSettings.currentProject.SetValue( "tempsDirty", True )
72,993
def percentage(value, precision=2): """Convert `float` to #.##% notation as `str`. A value of 1 = `"100.00%"`; 0.5 = `"50.00%"`""" return f"{value:.{precision}%}"
72,994
def simbadnames(query): """Given a source name, or other SIMBAD query, generates a list of identifier matches See http://simbad.u-strasbg.fr/simbad/sim-fscript """ u = urlopen( """http://simbad.u-strasbg.fr/simbad/sim-script?submit=submit+script&script=format+object+%%22+%%25IDLIST%%22%%0D%%0...
72,995
def decorator(func): """ Glossy Decorator This decorator can be used to make your decorators glossy. It simplifies the creation of decorators by flattening their structure and reducing the number of wrapper functions required. It also adds some additional attributes to both the wrapped and ...
72,996
def compute_cohen(participant_ids): """ """ k_tot = [] for co in combinations(participant_ids, 2): k = cohen_kappa_score(df_feedback.iloc[co[0]], df_feedback.iloc[co[1]]) if math.isnan(k): k=1 k_tot.append(k) c_k = np.mean(k_tot) ...
72,997
def findAlphanumeric(line): """Parse string to extract all non-numeric strings""" return re.findall(r'^\w+', line)
72,998
def strictlyCaseSensitiveFilenames(): """Determines whether case is strictly significant in filenames""" GVars.out.put('checking case-sensitivity of filenames',globals.INFO) GVars.out.push() testname1 = 'TestFileName_tempFile123.mod' testname2 = 'testfilename_tempfile123.mod' # Strategy: #...
72,999