content
stringlengths
22
815k
id
int64
0
4.91M
def get_dimorder(dimstring: str) -> Tuple[Dict, List, int]: """Get the order of dimensions from dimension string :param dimstring: string containing the dimensions :type dimstring: str :return: dims_dict - dictionary with the dimensions and its positions :rtype: dict :return: dimindex_list - li...
60,800
def determine_variable_usage(root, args, symbols, closure_vars): """The helper function for calling the dedicated visitor.""" visitor = PyVariableUsage(args, symbols, closure_vars) visitor.visit(root) return visitor.status
60,801
def read_number_of_states(dpomdp_file): """Returns the number of states in a Dec-POMDP problem Keyword arguments: dpomdp_file -- path to problem file in the .dpomdp format """ with open(dpomdp_file) as file: for line in file: if line.startswith('states:'): return int(line.split(':')[1]) raise V...
60,802
def max_dd_std_ratio(x:pd.DataFrame) -> float: """ """ return max_drawdown(x) / (np.std(x) * np.sqrt(252))
60,803
def hasshmem(type): """Return true iff |type| is shmem or has it buried within.""" class found: pass class findShmem(TypeVisitor): def visitShmemType(self, s): raise found() try: type.accept(findShmem()) except found: return True return False
60,804
def run_stdout( name, cmd, exec_driver=None, stdin=None, python_shell=True, output_loglevel="debug", use_vt=False, ignore_retcode=False, keep_env=None, ): """ Run :py:func:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container name Container nam...
60,805
def get_stats(uid, start_date, end_date): """ Get weather data for the specified weather period """ db = get_db() rows = db.get_stats(start_date=start_date, end_date=end_date, uid=uid) if len(rows) == 0: return plot = {} col_names = rows[0]._asdict().keys() plot["stat_fields"] = ...
60,806
def test_subgraph_names_need_to_be_unique(): """ +--------------------+ +--------------------+ | node1 | | node1 | |--------------------| |--------------------| o in_<> | +--->o in_<{"a": null> | | out %-----...
60,807
def distance(woolrgb, cpixel): """ ricerca il blocco di lana colorata piu' vicino al colore del pixel """ r = cpixel[0] g = cpixel[1] b = cpixel[2] did = 0 dmin = 255*255*3 for i in woolrgb: dr = r - woolrgb[i][0] dg = g - woolrgb[i][1] db = b - woolrgb[i][2] ...
60,808
def AptGetPathToConfig(vm): """Returns the path to the mongodb config file.""" return '/etc/mongodb.conf'
60,809
def make_paths(sheet_list): """ Тихий ужас... Функция парсит формат файла с путями. """ PKM = { "InMarker" : "In", "OutMarker" : "Out" } # Part kind markers PTM = { "DirMarker" : "Dir", "NameMarker" : "Fname", "TypeMarker" : "Ftype" } # Part type markers ...
60,810
def dict_to_ht_metadata(metadata_dict): """ Converts the incoming metadata dictionary into a list of metadata json objects usable by HyperThought endpoints. Parameters ---------- metadata_dict The metadata dictionary that will be converted to a list of metadata json obj...
60,811
def get_filepath_wo_ext(file_spec): """ Get file path without extension Parameters ---------- file_spec : DataStruct The function use attributes output_dir and fname_wo_ext for construct file path Returns ------- out : str Constructed file path """ return file_...
60,812
def add_setup_data(queries, E, output, words1, words2, index1, index2, k, lang1, lang2, categories_path): """Outputs setup data for CLIME session. For each word in [queries], the following information is stored: - [k] nearest neighbors in language 1 using [index 1] - [k] nearest neig...
60,813
def test_user_settings_otp_add_second_confirm( client, logged_in_dummy_user_with_otp, cleanup_dummy_tokens, totp_token, ): """Test posting to the create OTP endpoint""" result = client.post( "/user/dummy/settings/otp/", data={ "confirm-description": "pants token", ...
60,814
def get_dist_params(model: BaseModel = None, data: pd.DataFrame = None, exploration_time: int = 10): """ Dynamic plot for plotting beta distributions for a,b values given in a_b_lists. Parameters ---------- model: NormalDistributionModel or BetaDistributionModel The model of the distribution...
60,815
def _generate_chunk_ranges(file_size: int, ) -> Generator: """ Creates a generator which yields byte ranges and meta data required to make a range request download of url and write the data to file_name located at path. Download chunk sizes are 8MB by default. :param file_siz...
60,816
def _prefix_paths(tree, nodes): """ Generate all paths of tree leading to all item nodes """ for node in nodes: path = [] support = node.count node = node.parent while node.item is not None: path.append(node.item) node = node.parent if path: ...
60,817
def test_should_raise_if_wrong_key_dvc_cmd_meta(): """ Test raise if not expected keyword in dvc cmd meta """ with pytest.raises(MlVToolException): DocstringDvcCommand.from_meta(args=['dvc-wrong'], description='dvc run script')
60,818
def terraform_variable(var): """ Ask terraform console for a variable value. :param var: terraform var to look up :type var: str :return: Terraform's output :rtype: str """ return terraform_value('var', var)
60,819
def open_file(file_handle, **kwargs): """Context manager for opening files provided as several different types. Supports a file handler as a str, unicode, ``pathlib.Path``, or an already-opened handler. Args: file_handle (Union[str, unicode, Path, File]): The item to be opened or is already open. ...
60,820
def pot_frequencies(script_str, geoms, grads, hessians, run_path): """ Calculate the frequencies (need to replace) all input here are dictionaries (like potentials) """ # Initialize hr freqs list hr_freqs = {} for point in geoms.keys(): _, proj_freqs, _, _ = frequencies( ...
60,821
def add_translation_to_file(prev_signs, signs_vocab, prev_transcription, transcription_vocab, prev_tr, translation_lengths, long_trs, very_long_trs, translation_vocab, prev_text, prev_start_line, prev_end_line, signs_file, transcription_file, translation_file, ...
60,822
def np_polyfit(train_X, train_Y, poly_degree): """ 调用numpy.polyfit()方法拟合数据 :param train_X: 训练集的X矩阵 :param train_Y: 训练集的Y向量 :param poly_degree: 多项式次数 :return: 拟合的信息 """ result = np.polyfit(train_X, train_Y, poly_degree) picture = np.poly1d(result) # print(result) return pictur...
60,823
def test_post_existing(client): """Can we POST a new resource properly?""" client.post( '/artist/', data=json.dumps({ 'Name': 'Jeff Knupp', }), headers={'Content-type': 'application/json'}) response = client.post( '/artist/', data=json.dumps({ ...
60,824
def main() -> None: """Output the most recently tagged changelog body to stdout.""" match = RE_BODY.match(Path("CHANGELOG.md").read_text(encoding="utf-8")) assert match body = match.groups()[0].strip() print(body)
60,825
def render_environment_variables(instance: Entity) -> Optional[str]: """ render the environment variable elements by combining the jinja template from an entity with the arguments from an Entity """ variables = getattr(instance.__definition__, "env_vars") if not variables: return None ...
60,826
def _describe_table(x): """ Describes a single TableMetaData table :param x: TableMetaData :return: dict describing x layout """
60,827
def setFrame(self,numero=-1): """ To set frame in visit Parameters --------- numero: int If numero = -1, the last frame chosen, else it select the frame in visit Returns ------- """ self.time=str(numero) with open("tmp.py", "a") as f: if numero == -1: # last f...
60,828
def suite(ctx): """Expectation Suite operations""" directory: str = toolkit.parse_cli_config_file_location( config_file_location=ctx.obj.config_file_location ).get("directory") context: DataContext = toolkit.load_data_context_with_error_handling( directory=directory, from_cli_upg...
60,829
def cli() -> None: """Tracker Command Line interface for PWRCheck.""" parser = argparse.ArgumentParser() parser.add_argument( '-s', '--serial_port', help='serial_port', required=True ) parser.add_argument( '-b', '--serial_speed', help='serial_speed', default=115200 ) parser....
60,830
def test_all_sqlalchemy_model_attribute_names(): """ Test all_sqlalchemy_model_attribute_names() """ assert sa_model_primary_key_names(User) == ('annotated_int',) assert all_sqlalchemy_model_attribute_names(User) == ( # Everything in the order it was defined on the class '_ignored', ...
60,831
def mkdirs(pathname): """ mkdirs - create a folder """ try: if os.path.isfile(pathname): pathname = justpath(pathname) os.makedirs(pathname) except: pass return os.path.isdir(pathname)
60,832
def read_image_files(image_files, image_shape=None, crop=None, use_nearest_for_last_file=True): """ :param image_files: :param image_shape: :param crop: :param use_nearest_for_last_file: If True, will use nearest neighbor interpolation for the last file. This is used because the l...
60,833
def prob_double_roll(x, n): """ Expected probabilities for the sum of two dice.""" # For two n-sided dice, the probability of two rolls summing to x is # (n − |x−(n+1)|) / n^2, for x = 2 to 2n. return (n - abs(x - (n+1))) / n**2
60,834
def extract_features( doc: List[str], window: int = 2, max_n_gram: int = 3 ) -> List[List[str]]: """ Extract features for CRF by sliding `max_n_gram` of tokens for +/- `window` from the current token :param List[str] doc: tokens from which features are to be extracted from :param int window: si...
60,835
def _sum_two_blocks(block0, block1, vol): """Helper function that beats two blocks against each and finds summation of the resulting product. """ b0 = vol[block0] b0 = b0 - b0.mean() b1 = vol[block1] b1 = b1 - b1.mean() CC = np.sum(b0 * b1) lags = [] for n in xrange(block0.nd...
60,836
def perform_db_upgrade(conn: ConnectionPlus, version: int = -1) -> None: """ This is intended to perform all upgrades as needed to bring the db from version 0 to the most current version (or the version specified). All the perform_db_upgrade_X_to_Y functions must raise if they cannot upgrade and be ...
60,837
def draw_sequence(a, sequence, pos, size, direction, color): """draws a sequence of L and R characters""" for char in sequence: pos = forward(a, pos, size, direction, color) if char == 'R': direction = right(direction) else: direction = left(direction) pos = f...
60,838
def get_isni_bio(existing, author): """Returns the isni bio string if an existing author has an isni listed""" auth_isni = re.sub(r"\D", "", str(author.isni)) if len(existing) == 0: return "" for value in existing: if hasattr(value, "bio") and auth_isni == re.sub(r"\D", "", str(value.isn...
60,839
def cost_of_connection(connection_distance, hourly_heat_flow, order=24): """ function estimating the cost of transmission lines. :param connection_distance: distance of the pipe in meters. :type connection_distance: float. :param hourly_heat_flow: hourly heat flow in MW. :type hourly_heat_flow:...
60,840
def _from_records(vals, keys, typs=None, idxs=None): """ create a table from a series of records """ if numpy.size(vals): assert numpy.ndim(vals) in (1, 2) vals = (numpy.array(vals) if numpy.ndim(vals) == 2 else numpy.reshape(vals, (-1, 1))) else: vals = numpy.res...
60,841
def print_tiles(title, tiles): """Print a list of tiles to the log file.""" LOGGER.info("") LOGGER.info("%s:", title) for tile in tiles: LOGGER.info(" %s", tile)
60,842
def _build_rank_str(board, rank): """ Builds string for a given rank (row). Parameters ---------- board : chess.table.Board Board to display rank : int Rank to build string for. Returns ------- str row representation for a given rank. """ rank_str = '%s ...
60,843
def test_list_unsigned_int_enumeration_4_nistxml_sv_iv_list_unsigned_int_enumeration_5_1(mode, save_output, output_format): """ Type list/unsignedInt is restricted by facet enumeration. """ assert_bindings( schema="nistData/list/unsignedInt/Schema+Instance/NISTSchema-SV-IV-list-unsignedInt-enume...
60,844
def get_description(): """ Return a dict describing how to call this plotter """ desc = dict() desc['data'] = True desc['description'] = """This plot displays the directional frequency of day to day changes in high or low temperature summarized by month.""" desc['arguments'] = [ dict(typ...
60,845
def train_discriminator( discriminator_loss, global_step, params, generator_scope, encoder_scope, discriminator_scope): """Returns discriminator's objects needed for training. Args: discriminator_loss: tensor, discriminator's loss with shape []. g...
60,846
def tabulate(*ds: D) -> Dict[Hashable, List[float]]: """ Tabulate data from a sequence of numdicts. Produces a dictionary inheriting its keys from ds, and mapping each key to a list such that the ith value of the list is equal to ds[i][k]. """ tabulation: Dict[Hashable, List[float]] = {} ...
60,847
def amplitude(data): """ Calculates the amplitude of a data list. """ n = len(data) if (n == 0) : amplitude = None else : min_value = min(data) max_value = max(data) amplitude = (max_value + min_value) / 2.0 return amplitude
60,848
def mountpoint_dataset(mountpoint: str): """ Check if dataset at mountpoint is a 'zfs' mount. return dataset, or None if not found """ try: mount_list = _mount_list() except subprocess.CalledProcessError: raise RuntimeError(f"Failed to get mount data") target = re.compile(r'...
60,849
def p_statsopt_delimiter(p): """statsopt : TSTATS_OPT EQ COMMA""" p[0] = ParseTreeNode('EQ', raw='assign') opt = ParseTreeNode('OPTION', raw=p[1]) comma = ParseTreeNode('VALUE', nodetype="NBSTR", raw=p[3]) opt.values.append(comma) p[0].add_child(opt) p[0].add_child(comma)
60,850
def test_iterator_for() -> None: """Iterating through a custom iterator in a `for` loop.""" rev_nums: List[int] = [] for num in Reverse((1, 2, 3)): rev_nums.append(num) assert rev_nums == [3, 2, 1] assert list(Reverse((1, 2, 3))) == rev_nums
60,851
def SwissIterator(handle) : """Breaks up a Swiss-Prot/UniProt file into SeqRecord objects. Every section from the ID line to the terminating // becomes a single SeqRecord with associated annotation and features. This parser is for the flat file "swiss" format as used by: * Swiss-Prot aka SwissPro...
60,852
def monkey_patch_user(): """ Add a property to the defined user model that gives us the visible schemata. Add properties to :class:`django.contrib.auth.models.AnonymousUser` that return empty querysets for visible and all schemata. """ from django.contrib.auth import get_user_model, models ...
60,853
def plot_cc( models, train_data, test_data, target, title="Calibration Plot", ax=None, figsize=None, legend_loc=None, verbose=False ): """ Plots calibration curve, we need the original train dataset to do this (!) """ if not models: raise AttributeError("No mo...
60,854
def debug_on(*exceptions): """Adapted from https://stackoverflow.com/questions/18960242/is-it-possible-to-automatically-break-into-the-debugger-when-a-exception-is-thro/18962528 """ if not exceptions: exceptions = (AssertionError,) def decorator(f): @functools.wraps(f) def wrap...
60,855
def get_force_block_pack( hyps: np.ndarray, name: str, s1: int, e1: int, s2: int, e2: int, same: bool, kernel, cutoffs, hyps_mask, ): """Compute covariance matrix element between set1 and set2 :param hyps: list of hyper-parameters :param name: name of the gp instance....
60,856
def set_lndmanage_home_dir(directory=None): """ Sets the correct path to the lndmanage home folder. :param directory: home folder, overwrites default :type directory: str """ global home_dir, logger_config if directory: home_dir = directory else: # determine home folder...
60,857
def ranks_from_scores(scores): """Return the ordering of the scores""" return sorted(range(len(scores)), key=lambda i: scores[i], reverse=True)
60,858
def validate_url( url: str, username: str | None, password: str, verify_ssl: bool, authentication: str = HTTP_BASIC_AUTHENTICATION, ) -> str: """Test if the given setting works as expected.""" auth: HTTPDigestAuth | HTTPBasicAuth | None = None if username and password: if authent...
60,859
def unpack_word(str, big_endian=False): """ Unpacks a 32-bit word from binary data. """ endian = ">" if big_endian else "<" return struct.unpack("%sL" % endian, str)[0]
60,860
def test_two_to_one_connected(): """Two converging lines. --func1(.)--+ | +-func2(.,.)-- | --func1(.)--+ """ def func1(x): return x * 2 def func2(x, y): return x + y in_actor1 = FuncActor(func1, outports=('...
60,861
def generate_rsa_key(output_file, length_in_bits, password): """Generate a new RSA private key.""" # We take the library's advice here: "If in doubt you should use 65537." # (https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/) public_exponent = 65537 private_key = rsa.generate_pri...
60,862
def ignore(example): """ This function makes sure specific class types like 'PLAIN', 'ELECTRONIC' etc. are left unchanged. Args: example: data example """ cls, _, _ = example if cls in ["PLAIN", "LETTERS", "ELECTRONIC", "VERBATIM", "PUNCT"]: example[2] = "<self>" if exam...
60,863
def parse_source(source, path=None): """Parse python source into an AST.""" path = "<unknown>" if path is None else path return ast.parse(source, filename=path)
60,864
def kill_process_in_guest(vm, pid, guestUser, guestPassword, si): """ Permet de tuer un processus dans l'OS d'une VM :param vm: nom de la VM :param pid: PID du process à tuer :param guestUser: Nom du compte dans l'OS de la VM (doit avoir les droits nécessaires) :param guestPassword: Mot de passe...
60,865
def preprocess_img(img): """ Downsample Gridworld image by a factor of 2. :param img: grid image (25, 25, 3) :return: Grayscale downsample version (105, 80) """ return (img[::2, ::2, :]).astype(np.uint8)
60,866
def annotate_line(l,s,norm_position=0.5,offset_points=10,ax=None,**kwargs): """ line: a matplotlib line object s: string to show norm_position: where along the line, normalized to [0,1] offset_points: how to offset the text baseline relative to the line. """ ax=ax or plt.gca() x,y = l.g...
60,867
def _plot_by_category( summary: pd.DataFrame, currency: str=None, height: int=None, ) -> dict: """ Helper function for :func:`plot`. """ if summary["by_category"].empty: return pg.Figure() f = summary["by_category"].copy() if currency is None: currency = "" ho...
60,868
def validate_date_window(days): """Validate the date range for the Security Fairy query""" window = abs(days) if window > 30 or window < 1: print window raise ValueError('Valid number of days is between 1 and 30 inclusive.') return window
60,869
def delete_publication(name, credentials=None): """Delete a map visualization published by id. Args: name (str): name of the publication to be deleted. credentials (:py:class:`Credentials <cartoframes.auth.Credentials>`, optional): A Credentials instance. If not provided, the creden...
60,870
def get_script_logs(script): """Get a script logs""" logging.info('[ROUTER]: Getting script logs of script %s ' % (script)) try: start = request.args.get('start', None) if start: start = dateutil.parser.parse(start) last_id = request.args.get('last-id', None) logs...
60,871
def test_qt_plugin_list(viewer_factory): """Make sure the plugin list viewer works and has the test plugins.""" view, viewer = viewer_factory() from napari.plugins import _tests from napari.plugins import plugin_manager fixture_path = os.path.join(os.path.dirname(_tests.__file__), 'fixtures') ...
60,872
def validate_parent_calculation(calculation): """Validate whether the given calculation is a valid parent calculation for a HpCalculation. :param calculation: the calculation to validate :raises ValueError: if the calculation is not a valid parent calculation for a HpCalculation """ from aiida.plug...
60,873
def _enumerate_shifted_anchor(anchor_base, feat_stride, height, width): """ 根据上面函数在原图的第(0,0)个特征图感受野中心位置生成的anchor_base, 在原图的特征图感受野中心生成anchors :param anchor_base: anchors的坐标 :param feat_stride: 特征图缩小倍数(步长) :param height: 特征图高度 :param width: 特征图宽度 :return: 原图上所有的anchors坐标,[h * w * #anchor,4] ...
60,874
def test_sort_bylength(n, result): """Test basic use cases for sort_bylength().""" assert sort_by_length(n) == result
60,875
def main() -> None: """Entry point of the script""" mode, value = get_input_data() if mode == 'file': solve_maze_from_file(value) elif mode == 'test': solve_test_mazes() else: display_help()
60,876
def write_static(s): """ Write some text, then backspace to original position Does not work correctly if there is a newline in the string. """ sys.stdout.write('\b%s%s' % (s, '\b' * len(s))) sys.stdout.flush()
60,877
def interaction(data, factors, pairwise, max_factors, min_occurrence, destination_frame=None): """ Categorical Interaction Feature Creation in H2O. Creates a frame in H2O with n-th order interaction features between categorical columns, as specified by the user. Parameters ---------- data : H2OFrame ...
60,878
def GetFloat(ea): """ Get value of a floating point number (4 bytes) This function assumes number stored using IEEE format and in the same endianness as integers. @param ea: linear address @return: float """ tmp = struct.pack("I", Dword(ea)) return struct.unpack("f", tmp)[0]
60,879
def find_cod(query=None): """ Find city or state information. Parameters ---------- query : str or int if str search by name, int find by cod Returns ------- DataFrame Examples -------- >>> find_cod("Rio de Janeiro") cod_ibge ente capital ...
60,880
def test_smart_player_game(): """ Put 3 smart players against each other and ensure the game ends """ import random random.seed(1001) game = Game(4, 0, 0, [1, 3, 5]) game.run_game(3)
60,881
def post_process_arguments(args: argparse.Namespace) -> argparse.Namespace: """ post process sertop arguments :param args: args parsed :return: new name space """ for dirpath in args.coq_args_I: args.sertop_args.extend(("-I", dirpath)) for pair in args.coq_args_R: args.serto...
60,882
async def async_setup(opp, config): """Set up the onboarding component.""" store = OnboadingStorage(opp, STORAGE_VERSION, STORAGE_KEY, private=True) data = await store.async_load() if data is None: data = {"done": []} if STEP_USER not in data["done"]: # Users can already have creat...
60,883
def is_hit(x, y): """Return wheter given coords hit a circular target of r=1.""" return x*x + y*y <= 1
60,884
def get_user_by_id( id: UUID, current_user=Depends(get_current_user) ): """ Get user by ID """ user = find_user_by_id(id) return user
60,885
def set_fpn_weights(training_model, inference_model, verbose=False): """ Set feature pyramid network (FPN) weights from training to inference graph Args: training_model: MaskRCNN training graph, tf.keras.Model inference_model: MaskRCNN inference graph, tf.keras.Model verbose: ...
60,886
def empty_graph(n=0, create_using=None, default=nx.Graph): """Returns the empty graph with n nodes and zero edges. Parameters ---------- n : int or iterable container of nodes (default = 0) If n is an integer, nodes are from `range(n)`. If n is a container of nodes, those nodes appear i...
60,887
def connect(**kwargs) : """Connects to host, port with authorization. Returns client, expname, detname, db_exp, db_det, fs_exp, fs_det, col_exp, col_det """ host = kwargs.get('host', cc.HOST) port = kwargs.get('port', cc.PORT) user = kwargs.get('user', cc.USERNAME) upwd = kwar...
60,888
def initialize(): """ to initialize the parameters :return: stat: type dict, trans_pro: transition probability, trans_rew: transition reward """ num_state = 2 #the number of states num_action = 2 #the number of actions q_value = np.zeros((num_state, num_action)) #size:2x2 trans_pro ...
60,889
def _get_persistent_binding(app, device_addr): """ :return: bool """ x = app.__dict__.get('persistent_binding', False) if x and device_addr is None: msg = ('In case of `persistent_binding` set to `True`, ' 'the `device_addr` should be set and fixed.') raise...
60,890
def build_columns(columns: List[dict], is_temp=False) -> List[str]: """ Build up partial DDL for all non-skipped columns. For our final table, we skip the IDENTITY (which would mess with our row at key==0) but do add references to other tables. For temp tables, we use IDENTITY so that the key colum...
60,891
def upgrade(config_file, manager_path, check, dry_run): """Upgrade a Polyaxon deployment.""" config = read_deployment_config(config_file) manager = DeployManager( config=config, filepath=config_file, manager_path=manager_path, dry_run=dry_run ) exception = None if check: try: ...
60,892
def calcSignatureOverlaps(mode_ensemble, diag=True): """Calculate average mode-mode overlaps for a ModeEnsemble.""" if not isinstance(mode_ensemble, ModeEnsemble): raise TypeError('mode_ensemble should be an instance of ModeEnsemble') if not mode_ensemble.isMatched(): LOGGER.warn('mode...
60,893
def config(config_path: Optional[str] = None) -> ServerConfig: """Retrieve server configuration, loading it from disk once and caching it.""" global _CONFIG # pylint: disable=global-statement if _CONFIG is None: _CONFIG = _load_config(config_path) return _CONFIG
60,894
def repos(args): """ Print a list of organisation repositories """ with cli.catch_api_errors(): org = Organisation(args.org) for repo in org.list_repos(): if args.json: print(json.dumps(repo, indent=2)) else: print(repo['name'])
60,895
def pop_age_data(pop, code, age, percent_pop): """Select and return the proportion value of population for a given municipality, gender and age""" n_pop = pop[pop['code'] == str(code)][age].iloc[0] * percent_pop rounded = int(round(n_pop)) # for small `percent_pop`, sometimes we get 0 # when it...
60,896
def get_messier_object_by_mid(mid): """ Reply with the Messier object based on mid :param mid: :return: """ # perform a case-insensitive search messier_object = messier_collection.find_one({'mid': {'$regex': mid, '$options': '-i'}}) if not messier_object: abort(404) messi...
60,897
def idawrite_async(f): """ Decorator for marking a function as completely async. """ @functools.wraps(f) def wrapper(*args, **kwargs): ff = functools.partial(f, *args, **kwargs) return idaapi.execute_sync(ff, idaapi.MFF_NOWAIT | idaapi.MFF_WRITE) return wrapper
60,898
def port_is_used(port, host="127.0.0.1"): """ Returns if port is used. Port is considered used if the current process can't bind to it or the port doesn't refuse connections. """ unused = _can_bind(port, host) and _refuses_connection(port, host) return not unused
60,899