content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def chown( path: Pathable, owner: str, flags: t.Optional[str] = None, sudo: bool = False ) -> ChangeList: """Change a path's owner.""" path = _to_path(path) needs_sudo_w = need_sudo_to_write(path) needs_sudo_r = need_sudo_to_read(path) if needs_sudo_r and not sudo: raise NeedsSudoExcept...
124ba2877dc2ff4396d84c3b8825846c9d057cf5
3,653,000
def metric_dist(endclasses, metrics='all', cols=2, comp_groups={}, bins=10, metric_bins={}, legend_loc=-1, xlabels={}, ylabel='count', title='', indiv_kwargs={}, figsize='default', v_padding=0.4, h_padding=0.05, title_padding=0.1, **kwargs): """ Plots the histogram of given met...
95bbc645abad812585de58d4724787e310424f4a
3,653,001
def get_colors(df, colormap=None, vmin=None, vmax=None, axis=1): """ Function to automatically gets a colormap for all the values passed in, Have the option to normalise the colormap. :params: values list(): list of int() or str() that have all the values that need a color to be map to. ...
7da0c0a8f8542c9a8137121c4664da91485d8cca
3,653,002
def proxy_channels(subreddits): """ Helper function to proxy submissions and posts. Args: subreddits (list of praw.models.Subreddit): A list of subreddits Returns: list of ChannelProxy: list of proxied channels """ channels = { channel.name: channel ...
caab3ecfa5a85b06d94192fe77308724f67b0e96
3,653,003
def anno2map(anno): """ anno: { 'file' ==> file index 'instances': [ { 'class_name': 'class_idx': 'silhouette': 'part': [(name, mask), ...] }, ... ] } """ height, width = anno.instances...
18841b323d4368c5f1681dd34586e82aa8a9d97c
3,653,004
def string_to_bool(val: str): """Convert a homie string bool to a python bool""" return val == STATE_ON
f7fc9768762256fc5c2cf818949793f72948db98
3,653,005
def profile(request): """ Update a User profile using built in Django Users Model if the user is logged in otherwise redirect them to registration version """ if request.user.is_authenticated(): obj = get_object_or_404(TolaUser, user=request.user) form = RegistrationForm(request.POST...
225ac41ec6565e30f54ece3cad76b2a0770a319d
3,653,006
def conj(Q): """Returns the conjugate of a dual quaternion. """ res = cs.SX.zeros(8) res[0] = -Q[0] res[1] = -Q[1] res[2] = -Q[2] res[3] = Q[3] res[4] = -Q[4] res[5] = -Q[5] res[6] = -Q[6] res[7] = Q[7] return res
e0a6d67d322f2c939e2d8249983789222c96363d
3,653,007
def benchmark_summary(benchmark_snapshot_df): """Creates summary table for a benchmark snapshot with columns: |fuzzer|time||count|mean|std|min|25%|median|75%|max| """ groups = benchmark_snapshot_df.groupby(['fuzzer', 'time']) summary = groups['edges_covered'].describe() summary.rename(columns={'...
5cdaa888adb47906659a249076c8a4acb27c6d1d
3,653,008
def is_pio_job_running(*target_jobs: str) -> bool: """ pass in jobs to check if they are running ex: > result = is_pio_job_running("od_reading") > result = is_pio_job_running("od_reading", "stirring") """ with local_intermittent_storage("pio_jobs_running") as cache: for job in targ...
0ed9daf39372ead913ad52d5c93426eeb06f74ed
3,653,009
def encode(text, encoding='utf-8'): """ Returns a unicode representation of the string """ if isinstance(text, basestring): if not isinstance(text, unicode): text = unicode(text, encoding, 'ignore') return text
81d9d2d5cf920c0f15ffc5e50fb670b079ae1f90
3,653,010
def calculate_sparsity(df: pd.DataFrame) -> tuple: """Calculate the data sparsity based on ratings and reviews. Args: df ([pd.DataFrame]): DataFrame with counts of `overall` and `reviewText` measured against total `reviewerID` * `asin`. Returns: [tuple]: Tuple of data sparsity ...
53e6b2682b67ceb8bbb4f5a6857cdbd565321421
3,653,011
def char_fun_est( train_data, paras=[3, 20], n_trees = 200, uv = 0, J = 1, include_reward = 0, fixed_state_comp = None): """ For each cross-fitting-task, use QRF to do prediction paras == "CV_once": use CV_once to fit get_CV_paras == True: just to get paras by using CV Returns ...
51012cc870d9bcd1f86fe69534e26d7d365ad271
3,653,012
def create_tables_for_import(volume_id, namespace): """Create the import or permanent obs_ tables and all the mult tables they reference. This does NOT create the target-specific obs_surface_geometry tables because we don't yet know what target names we have.""" volume_id_prefix = volume_id[:volu...
8e02e98031e4242e2e0d559750258d74180593db
3,653,013
def org_repos(info): """ 处理组织的仓库 :param info: 字典 :return: 两个列表,第一个包含字典(id,全名,url),第二个包含所用到的语言 """ repo_info = [] languages = [] if info: for repo in info: temp = {"id": repo["id"], "full_name": repo["full_name"], "url": repo["url"], "language": repo["language"]} ...
9d5633bf834845e1301e0fd383a57c42f2bd530c
3,653,014
from typing import Union from datetime import datetime def year(yyyy_mm_dd: Union[str, datetime.date]) -> int: """ Extracts the year of a given date, similar to yyyy function but returns an int >>> year('2020-05-14') 2020 """ date, _ = _parse(yyyy_mm_dd, at_least="%Y") return date.year
eb34fb578d5ec7130d5670332aa4bbb9aca186ac
3,653,015
def getTypeLevel(Type): """Checks whether a spectral data type is available in the endmember library. Args: Type: the type of spectra to select. Returns: level: the metadata "level" of the group for subsetting. returns 0 if not found. """ for i in range(4): level = i + 1 ...
6c26f7dc570b5a7f0cacdc1171ae733b005e7992
3,653,016
from typing import Union def construct_creator(creator: Union[dict, str], ignore_email): """Parse input and return an instance of Person.""" if not creator: return None, None if isinstance(creator, str): person = Person.from_string(creator) elif isinstance(creator, dict): pers...
5306f288874f4d15d5823c34268321121909a3ad
3,653,017
def _encode_query(items: dict, *, mask=False) -> str: """Encode a dict to query string per CLI specifications.""" pairs = [] for key in sorted(items.keys()): value = _MASK if mask and key in _MASKED_PARAMS else items[key] item = "{}={}".format(key, _quote(value)) # Ensure 'url' goes ...
918f0aa4198367fb3889eb67bba622d272082af7
3,653,018
def spatial_shape_after_conv(input_spatial_shape, kernel_size, strides, dilation, padding): """ This function calculates the spatial shape after conv layer. The formula is obtained from: https://www.tensorflow.org/api_docs/python/tf/nn/convolution It should be note that current function assumes PS is done ...
a7d924260feb478e44a9ec166fe4248b51632270
3,653,019
def sample_partition(dependency_tensor, null_distribution, updates=100, initial_partition=None ): """ Sample partition for a multilayer network with specified interlayer dependencies :param dependency_tensor: dependency tensor :param null_d...
d6c469054057f18ad1e7ab3abd96103e81931649
3,653,020
import re def normalize_spaces(s: str) -> str: """ 連続する空白を1つのスペースに置き換え、前後の空白を削除した新しい文字列を取得する。 """ return re.sub(r'\s+', ' ', s).strip()
aac95ed5b77b5c65f9ce16cfa685d80c56f0e66f
3,653,021
def power_iter(mat_g, error_tolerance=1e-6, num_iters=100): """Power iteration. Args: mat_g: the symmetric PSD matrix. error_tolerance: Iterative exit condition. num_iters: Number of iterations. Returns: eigen vector, eigen value, num_iters """ mat_g_size = mat_g.shape[-1] def _iter_condit...
11717fda8b3dedce94e9be3157a78d8d95e0e989
3,653,022
from typing import Union from typing import Any def _get_values_target_representation( val: Union[str, Any], target_representation: str, conversion_type: str, conversion_rate: float, n_round: int, split: bool, input_symbol: str, target_symbol: str, ) -> Any: """ Returns the val...
188fe2da51a177fc743ee30c67807b46730a3a34
3,653,023
from typing import OrderedDict def GetResidues(mol, atom_list=None): """Create dictrionary that maps residues to atom IDs: (res number, res name, chain id) --> [atom1 idx, atom2 idx, ...] """ residues = OrderedDict() if atom_list is None: atom_list = range(mol.GetNumAtoms()) for aid...
51f66cf9c3203573df5660205581fd0571826876
3,653,024
def BIC(y_pred, y, k, llf = None): """Bayesian Information Criterion Args: y_pred (array-like) y (array-like) k (int): number of featuers llf (float): result of log-likelihood function """ n = len(y) if llf is None: llf = np.log(SSE(y_pred, y)) return np...
f070400f045b1e8f98b453b8d5f8661271b1969e
3,653,025
def create_abstract_insert(table_name, row_json, return_field=None): """Create an abstracted raw insert psql statement for inserting a single row of data :param table_name: String of a table_name :param row_json: dictionary of ingestion data :param return_field: String of the column name to RETURNI...
8b0a960178a0162b7a0c339682541f0f13520d85
3,653,026
import os def get_childs(root_dir, is_dir=False, extension='.jpg', max_depth=0): """ get files or directories related root dir :param root_dir: :param is_dir: :param extension: :param max_depth: :return: """ if os.path.exists(root_dir) is False: raise FileNotFoundError("not...
6e705d796447dd968aa9a362093a68ec56516b85
3,653,027
def descsum_create(s): """Add a checksum to a descriptor without""" symbols = descsum_expand(s) + [0, 0, 0, 0, 0, 0, 0, 0] checksum = descsum_polymod(symbols) ^ 1 return s + '#' + ''.join(CHECKSUM_CHARSET[(checksum >> (5 * (7 - i))) & 31] for i in range(8))
52ce47b470dada282318cd23c61665adfb7554c3
3,653,028
def _get_header(key): """Return message header""" try: return request.headers[key] except KeyError: abort(400, "Missing header: " + key)
cbdf9928f6ce4c41145529c68039761eab65c3d0
3,653,029
def compute_solution(primes_list, triangle_sequence): """ Auxiliary function to compute the solution to the problem. """ factorise_w_primes = partial(factorise, primes=primes_list) all_factors = vmap(factorise_w_primes)(triangle_sequence) # number of divisors = number of possible combinations of pri...
5df3444b10a4ae316fab1c21c87e3187d4792f14
3,653,030
import platform def key_description(character): """ Return the readable description for a key. :param character: An ASCII character. :return: Readable description for key. """ if "Windows" in platform.system(): for key, value in hex_keycodes.items(): if value == character: ...
9ed5bd198898c2f5cf234cb0c46924286fa18e51
3,653,031
import os def find_paste_config(): """Find freezer's paste.deploy configuration file. freezer's paste.deploy configuration file is specified in the ``[paste_deploy]`` section of the main freezer-api configuration file, ``freezer-api.conf``. For example:: [paste_deploy] config_file ...
db37e317b4684536ce24c5d12ebcfd176c98d34d
3,653,032
def combine_index(df, n1, n2): """將dataframe df中的股票代號與股票名稱合併 Keyword arguments: Args: df (pandas.DataFrame): 此dataframe含有column n1, n2 n1 (str): 股票代號 n2 (str): 股票名稱 Returns: df (pandas.DataFrame): 此dataframe的index為「股票代號+股票名稱」 """ return df.set_index(df[n1].st...
645c62fdc7d8e541c9b55b5f1621d6c442ca683a
3,653,033
def safe_get_stopwords(stopwords_language): """ :type stopwords_language: basestring :rtype: list """ try: return get_stopwords(stopwords_language) except LanguageNotAvailable: return []
f6a32da469e59341aa9a928cac362b0075e5d792
3,653,034
import os def fetch_dataloader(types, data_dir, params): """ Fetches the DataLoader object for each type in types from data_dir. Args: types: (list) has one or more of 'train', 'val', 'test' depending on which data is required data_dir: (string) directory containing the dataset pa...
098747931adb678bcc1513414b9f447a016a6f81
3,653,035
def setup_mock_device(mock_device): """Prepare mock ONVIFDevice.""" mock_device.async_setup = AsyncMock(return_value=True) mock_device.available = True mock_device.name = NAME mock_device.info = DeviceInfo( MANUFACTURER, MODEL, FIRMWARE_VERSION, SERIAL_NUMBER, ...
f39951f9109e5646d1e4cdd4782907cce5ee3a1c
3,653,036
import os def join(*args): """Join multiple path - join('c:', 'pp', 'c.txt') -> 'c:\pp\c.txt'""" assert len(args) >= 2 ret_arg = args[0] for arg in args[1:]: ret_arg = os.path.join(ret_arg, arg) return ret_arg
f628b0fb47898ad9d98714d4329d2ded183242a3
3,653,037
def renyientropy(px,alpha=1,logbase=2,measure='R'): """ Renyi's generalized entropy Parameters ---------- px : array-like Discrete probability distribution of random variable X. Note that px is assumed to be a proper probability distribution. logbase : int or np.e, optional ...
d0b41285f34c79e27b9fab392433d75ea0aa7894
3,653,038
def convert(digits, base1, base2): """Convert given digits in base1 to digits in base2. digits: str -- string representation of number (in base1) base1: int -- base of given number base2: int -- base to convert to return: str -- string representation of number (in base2)""" # Handle up to base 3...
482e7207a27c6acfdaf088ef8195792f29d14452
3,653,039
def h(b, W ,X): """ This function implments the softmax regression hypothesis function Argument: b -- bias W -- predictive weight matrix X -- data matrix of size (numbers_examples, number_predictors) Returns: softmax(XW + b) """ return softmax( (X @ W) + b)
abca116d09993b310a70ddf80fcf0eea73b6d542
3,653,040
def get_random_points(N): """ - Takes number of parameters N - Returns tuple (x1,x2), where x1 and x2 are vectors """ x1 = np.random.uniform(-1,1,N) x2 = np.random.uniform(-1,1,N) return (x1,x2)
e118d2dbbc472bfa31fa30ffe1fabbf625a9c924
3,653,041
def n_bit_color(clk, din, vga_signals, vga_ports): """ Maps n bit input, din, to n bit vga color ports Ex: din=10010101, r=100, g=101, b=01 """ blu = len(vga_ports.blu) grn = len(vga_ports.grn) + blu red = len(vga_ports.red) + grn assert len(din) == red @always(clk.posedge) ...
e760c21c0b87c54d5977e6ba29bed0f5dc20b6ab
3,653,042
from typing import Tuple from typing import Dict def point_cloud_transform_net(point_cloud: nn.Variable, train: bool) -> Tuple[nn.Variable, Dict[str, nn.Variable]]: """T net, create transformation matrix for point cloud Args: point_cloud (nn.Variable): point cloud, shape(batch, number of points, 3) ...
59a3a30ef874dd1ce47a0d9a369c9170b30ac4ea
3,653,043
def diffie_hellman_server(p, g, public_key_pem): """ Function used to apply the Diffie Hellman algorithm in the server. It calculates the private and public components of server. :param p: Shared parameter :param g: Shared parameter :param public_key_pem: Public component of client :return: The private compon...
6c5eb11a4e0775e881b33bc15cf99ff423b0bee6
3,653,044
def posix_getpgid(space, pid): """ posix_getpgid - Get process group id for job control """ try: return space.newint(os.getpgid(pid)) except OSError, e: space.set_errno(e.errno) return space.newbool(False) except OverflowError: return space.newbool(False)
b01f0d363ce7f0937a52c824aefc0a262f739757
3,653,045
def on_display_disconnected(): """Shortcut for registering handlers for ACTION_DISPLAY_DISCONNECTED events. Functions decorated with this decorator will be called when push2-python loses connection with the Push2 display. It will have the following positional arguments: * Push2 object instance ...
bfb4314e6da432193a0b1e9691ad60d0eb7de039
3,653,046
from typing import Union from typing import Dict from typing import Any def parse_received_data(blockpage_matcher: BlockpageMatcher, received: Union[str, Dict[str, Any]], anomaly: bool) -> Row: """Parse a received field into a section of a ro...
30a01d1b045d0f67e279cca34ade90aaf46b9c62
3,653,047
def get_filters(): """ Returns sidebar filters """ filters = { 'organisations': Organisation.objects.all(), 'topics': Topic.objects.all(), 'licenses': License.objects.all(), 'formats': Format.objects.all() } return filters
da137bbcd37d6504358e9e94a6722495bbc81d65
3,653,048
from xdsl.dialects.builtin import DenseIntOrFPElementsAttr, i32 import typing from typing import List from typing import Tuple def irdl_op_builder(cls: typing.Type[OpT], operands: List, operand_defs: List[Tuple[str, OperandDef]], res_types: List, res_defs: List[Tuple[str, Resul...
24c103897b040f2b4959b3d3c1642bc6eca6fda2
3,653,049
def _listify(single: st.SearchStrategy) -> st.SearchStrategy: """ Put the result of `single` strategy into a list (all strategies should return lists) """ @st.composite def listify_(draw): return [draw(single)] strategy = listify_() strategy.function.__name__ = f"listified<{repr...
eb4efb742e2c465754e79ba979b69b412f6c066e
3,653,050
def get_text(selector): """ Type the keys specified into the element, or the currently active element. """ if not get_instance(): raise Exception("You need to start a browser first with open_browser()") return get_text_g(get_instance(), selector)
b2866c93b80dcf3c61b8330fb09e4af054937e0b
3,653,051
from functools import partial import time import textwrap def _eps(code, version, file_or_path, scale=1, module_color=(0, 0, 0), background=None, quiet_zone=4): """This function writes the QR code out as an EPS document. The code is drawn by drawing only the modules corresponding to a 1. They are...
65e3f4d69eea5aa0385c1b53693d164aa0f5db6d
3,653,052
from typing import OrderedDict def _group_energy_terms(ener_xvg): """Parse energy.xvg file to extract and group the energy terms in a dict. """ with open(ener_xvg) as f: all_lines = f.readlines() energy_types = [line.split('"')[1] for line in all_lines if line[:3] == '@ s'] energy_values = [fl...
ac1be9871a01323e52611fb3182060db57b5b813
3,653,053
from typing import List from typing import Dict import click def get_packager_targets( targets: List[Target], connections: Dict[str, Connection], remote_api: ConnectionClient ) -> List[PackagerTarget]: """ Build targets for calling packager. Fetch and base64 decode connections by names using local man...
1aac3748b2176f5f11ed8ed137f78d64bf01c112
3,653,054
def elina_texpr0_permute_dimensions(texpr2, dimperm): """ Permute dimensions of an ElinaTexpr0 following the semantics of an ElinaDimperm. Parameters ---------- texpr2 : ElinaTexpr0Ptr Pointer to the ElinaTexpr0 which dimensions we want to permute. dimperm : ElinaDimpermPtr Poin...
f9c60e6285bc4e934eddf0a0be0511f08a57f45d
3,653,055
def rgb(red: int, green: int, blue: int, background: bool = False) -> Chalk: """Generate a new truecolor chalk from an RGB tuple. Args: red (int): The intensity of red (0-255). green (int): The intensity of green (0-255). blue (int): The intensity of ...
d5c1e79cc1bf7ee37f1e1df17e9518ac0e11f02b
3,653,056
def first(x: pd.Series) -> pd.Series: """ First value of series :param x: time series :return: time series of first value **Usage** Return series with first value of `X` for all dates: :math:`R_t = X_0` where :math:`X_0` is the first value in the series **Examples** Last v...
1a2c856bdff7158ecd7512e43158427530cbc8e4
3,653,057
def simulate(iterations, graph_generator, graph_params, n_nodes, beta, rho, steps, n_infected_init, vacc=None): """Perform `iterations` simulations and compute averages. If vacc is not None, run the simulation using the SIRV model, otherwise use SIR.""" # Initialize arrays for computing averages over simul...
96eeb8be72ceb336d62f858337d983cc8f8d5a9d
3,653,058
import urllib import json def lookup_location(): """ Geolocation lookup of current position. Determines latitude and longitude coordinates of the system's position using the ipinfo.io service. Returns: Tuple (lat, lon) containing the latitude and longitude coordinates associated ...
5d654314aa8d53cbca2b488bb7c9eb3f1f9cf81a
3,653,059
def _str_or_none(value): """Helper: serialize value to JSON string.""" if value is not None: return str(value)
7aa1550f71accaa4111386153b2c331e2ff076bc
3,653,060
def create_song_graph_from_songs(songs: list[Song], parent_graph: song_graph.SongGraph = None, year_separation: int = 10) -> song_graph.SongGraph: """Create and return a song graph from a list of songs. (Optional) Add a parent graph from a large...
647eb1ce77cf0c596c2fabd41aa32062636ca8a4
3,653,061
def convert(secs): """Takes a time in seconds and converts to min:sec:msec""" mins = int(secs // 60) secs %= 60 msecs = int(round(((secs - int(secs)) * 1000))) secs = int(secs) return f'{mins} mins, {secs} secs, {msecs} msecs'
70752f190f94d3bdb4cb3b562b6bf9d1c7d28479
3,653,062
def from_data(symbols, key_matrix, name_matrix, one_indexed=False): """ z-matrix constructor :param symbols: atomic symbols :type symbols: tuple[str] :param key_matrix: key/index columns of the z-matrix, zero-indexed :type key_matrix: tuple[tuple[float, float or None, float or None]] :param nam...
5b3f98b98dca797223a95af967e9aaff311d24f8
3,653,063
def should_drop_from_right_deck(n_left: int, n_right:int, seed: int=None) -> bool: """ Determine whether we drop a card from the right or left sub-deck. Either `n_left` or `n_right` (or both) must be greater than zero. :param n_left: the number of cards in the left sub-deck. :param n_right: the nu...
42bbfc3c8a129f090b50c0979d95e53fd6d6a13f
3,653,064
import os def which(program): """ Locate an executable binary's full path by its name. :param str program: The executable's name. :return: The full path to the executable. :rtype: str """ is_exe = lambda fpath: (os.path.isfile(fpath) and os.access(fpath, os.X_OK)) for path in os.environ['PATH'].split(os.path...
19d77431baf3489288dbca863f1231d8f5c76efe
3,653,065
def EXPOSED(mu=1.0): """ matrix of exposed sites Parameters ---------- mu: rate """ pis = np.array([0.088367,0.078147,0.047163,0.087976,0.004517,0.058526,0.128039,0.056993,0.024856,0.025277,0.045202,0.094639,0.012338,0.016158,0.060124,0.055346,0.051290,0.006771,0.021554,0.036718]) ...
c203eb8affeddd4b2620836759acb35ae6f9114c
3,653,066
async def rename_conflicting_targets( ptgts: PutativeTargets, all_existing_tgts: AllUnexpandedTargets ) -> UniquelyNamedPutativeTargets: """Ensure that no target addresses collide.""" existing_addrs: set[str] = {tgt.address.spec for tgt in all_existing_tgts} uniquely_named_putative_targets: list[Putativ...
9ac25549de1fca5912104135b87a1a17f1cd43fe
3,653,067
def outer2D(v1, v2): """Calculates the magnitude of the outer product of two 2D vectors, v1 and v2""" return v1[0]*v2[1] - v1[1]*v2[0]
b1f80afa3b8537eb11d79b17d0f12903bec9387c
3,653,068
from typing import Union def get_item_indent(item: Union[int, str]) -> Union[int, None]: """Gets the item's indent. Returns: indent as a int or None """ return internal_dpg.get_item_configuration(item)["indent"]
a80997e8c2cfa76a76ff8d09c7308196f0572f86
3,653,069
def V_RSJ_asym(i, ic_pos, ic_neg, rn, io, vo): """Return voltage with asymmetric Ic's in RSJ model""" if ic_pos < 0 or ic_neg > 0 or rn < 0: #or abs(ic_neg/ic_pos) > 1.2 or abs(ic_pos/ic_neg) > 1.2 : # set boundaries for fitting #pass v = 1e10 else: v = np.zeros(len(i...
5005beec6a90bf1a5054836f6f22dbe42dcda6f1
3,653,070
def h2_gas_costs(pipe_dist=-102.75, truck_dist=-106.0, pipeline=True, max_pipeline_dist=2000): """Calculates the transport cost of H2 gas. Requires as input the distance that H2 will be piped and trucked.""" if max_pipeline_dist > pipe_dist > 400: pipe = 0.0004 * pipe_dist + 0.0424 elif pipe_di...
5b3623d33862038a9629349e8052e8214ddba51c
3,653,071
from typing import Union def number_to_words(input_: Union[int, str], capitalize: bool = False) -> str: """Converts integer version of a number into words. Args: input_: Takes the integer version of a number as an argument. capitalize: Boolean flag to capitalize the first letter. Returns...
22c5f7c64354a76404150cdf888e3bc3582659f1
3,653,072
from typing import Dict from typing import OrderedDict def get_size_reduction_by_cropping(analyzer: DatasetAnalyzer) -> Dict[str, Dict]: """ Compute all size reductions of each case Args: analyzer: analzer which calls this property Returns: Dict: computed size reductions ...
ce1aad85d8f971cccc8cb0547b14be8074228261
3,653,073
import re def getProxyFile(path): """ Opens a text file and returns the contents with any setting of a certificate file replaced with the mitmproxy certificate. """ with open(path, "r") as fd: contents = fd.read() certReferences = re.findall("setcertificatesfile\(.*\)", contents, r...
c5c0d562e2b430b79b91b2a9ffd23f6d18320b6f
3,653,074
def bytes_filesize_to_readable_str(bytes_filesize: int) -> str: """Convert bytes integer to kilobyte/megabyte/gigabyte/terabyte equivalent string""" if bytes_filesize < 1024: return "{} B" num = float(bytes_filesize) for unit in ["B", "KB", "MB", "GB"]: if abs(num) < 1024.0: ...
cdeb228de80422f541c5fa682422d77a44d19ca2
3,653,075
def braf_mane_data(): """Create test fixture for BRAF MANE data.""" return { "#NCBI_GeneID": "GeneID:673", "Ensembl_Gene": "ENSG00000157764.14", "HGNC_ID": "HGNC:1097", "symbol": "BRAF", "name": "B-Raf proto-oncogene, serine/threonine kinase", "RefSeq_nuc": "NM_00...
7e62545147ef1a6f81c75e56d85f5ab8df3895e8
3,653,076
import os def get_decopath_genesets(decopath_ontology, gmt_dir: str): """Generate DecoPath gene sets with super pathways.""" concatenated_genesets_dict = {} dc_mapping = defaultdict(list) if not os.path.isdir(gmt_dir): make_geneset_dir() super_pathway_mappings, ontology_df = get_equivale...
63701b37d88eadfef4df55ee31a1a1eb00a4985c
3,653,077
def import_class(path): """ Import a class from a dot-delimited module path. Accepts both dot and colon seperators for the class portion of the path. ex:: import_class('package.module.ClassName') or import_class('package.module:ClassName') """ if ':' in path: m...
dcdf71a3bb665dae1fe5913e19be3a4c0aa3c5d3
3,653,078
import torch def elastic(X, kernel, padding, alpha=34.0): # type: (Tensor, Tensor, int, float) -> Tensor """ X: [(N,) C, H, W] """ H, W = X.shape[-2:] dx = torch.rand(X.shape[-2:], device=kernel.device) * 2 - 1 dy = torch.rand(X.shape[-2:], device=kernel.device) * 2 - 1 xgrid = torch...
580c9600cb4ddd77d114ae94303fc2c2a416cf17
3,653,079
def fixture_make_bucket(request): """ Return a factory function that can be used to make a bucket for testing. :param request: The Pytest request object that contains configuration data. :return: The factory function to make a test bucket. """ def _make_bucket(s3_stub, wrapper, bucket_name, reg...
bdfbbad1b80f43a1b81f5bf8f69db350128e3304
3,653,080
def get_member_struc(*args): """ get_member_struc(fullname) -> struc_t Get containing structure of member by its full name "struct.field". @param fullname (C++: const char *) """ return _ida_struct.get_member_struc(*args)
ac2c226725af8bde1510a6f7fd2fdb64a8c52d01
3,653,081
from datetime import datetime def pop(): """Check the first task in redis(which is the task with the smallest score) if the score(timestamp) is smaller or equal to current timestamp, the task should be take out and done. :return: True if task is take out, and False if it is not the time. """ ...
0472d0bcffee84547d7ee400d547ecbb86e50e87
3,653,082
def xml_to_dictform(node): """ Converts a minidom node to "dict" form. See parse_xml_to_dictform. """ if node.nodeType != node.ELEMENT_NODE: raise Exception("Expected element node") result = (node.nodeName, {}, []) # name, attrs, items if node.attributes != None: attrs = node.attribut...
8fdc07070a32eb34c38e46cb12d23d367d71c606
3,653,083
def TranslateCoord(data, res, mode): """ Translates position of point to unified coordinate system Max value in each direction is 1.0 and the min is 0.0 :param data: (tuple(float, float)) Position to be translated :param res: (tuple(float, float)) Target resolution :param mode: (TranslationMode) Work mode. Availa...
c89515692330ce02c0f6f371c16a9028c51e9bbe
3,653,084
def _get_mutator_plugins_bucket_url(): """Returns the url of the mutator plugin's cloud storage bucket.""" mutator_plugins_bucket = environment.get_value('MUTATOR_PLUGINS_BUCKET') if not mutator_plugins_bucket: logs.log_warn('MUTATOR_PLUGINS_BUCKET is not set in project config, ' 'skipping c...
31073e1fbaf817d63d02de93a2fc224bd2904dec
3,653,085
from io import StringIO def objectify_json_lines(path_buf_stream, from_string=False, fatal_errors=True, encoding=_DEFAULT_ENCODING, ensure_ascii=False, encode_html_chars=False, ...
a3de3cd8f13c7a245573bd34944e67908dfd4786
3,653,086
def gll_int(f, a, b): """Integrate f from a to b using its values at gll points.""" n = f.size x, w = gll(n) return 0.5*(b-a)*np.sum(f*w)
d405e4c3951f9764077508fcdb73e000c107e4d4
3,653,087
import os import random def error404(request, exception): """View for 404 page.""" responses = open(os.path.join(BASE_DIR, 'CollaboDev/404_responses.txt')) responses = responses.read().split('\n') message = random.choice(responses) context = { 'message': message, 'error': exceptio...
cf0b201b23dc06905f260ade10e126f38f169699
3,653,088
def _get_remote_user(): """ Get the remote username. Returns ------- str: the username. """ return input('\nRemote User Name: ')
5f2bb67b5f55ec053a755c015755f488ab6d8c71
3,653,089
import argparse def parse_args(): """Parse the args.""" parser = argparse.ArgumentParser( description='example code to play with InfluxDB') parser.add_argument('--host', type=str, required=False, default='localhost', help='hostname influxdb http API'...
83d8f6e036ceb065492feb6031b16198e57c3d89
3,653,090
def generate_warm_starts(vehicle, world: TrafficWorld, x0: np.array, other_veh_info, params: dict, u_mpc_previous=None, u_ibr_previous=None): """ Generate a dictionar...
021266450f54ee59ae451dc2c9cad544f129f278
3,653,091
def nf_regnet_b4(pretrained=False, **kwargs): """ Normalization-Free RegNet-B4 `Characterizing signal propagation to close the performance gap in unnormalized ResNets` - https://arxiv.org/abs/2101.08692 """ return _create_normfreenet('nf_regnet_b4', pretrained=pretrained, **kwargs)
642ba43a132128a16273bb6cc76178b71be6beaf
3,653,092
from typing import Tuple def load_data_binary_labels(path: str) -> Tuple[pd.DataFrame, pd.DataFrame]: """Loads data from CSV file and returns features (X) and only binary labels meaning (any kind of) toxic or not""" df = pd.read_csv(path) X = df.comment_text.to_frame() y = df[config.LIST_CLASSES]...
e73b99b2d00d388298f9f6e2cdfca15f121a0238
3,653,093
from bs4 import BeautifulSoup def parse(html_url): """Parse.""" html = www.read(html_url) soup = BeautifulSoup(html, 'html.parser') data = {'paragraphs': []} content = soup.find('div', class_=CLASS_NAME_CONTENT) for child in content.find_all(): text = _clean(child.text) if c...
226245618d220db00eb2f298aaf462c1c861c32b
3,653,094
import logging def get_tp_algorithm(name: str) -> GenericTopologyProgramming: """ returns the requested topology programming instance """ name = name.lower() if name == "uniform_tp": return UniformTP() if name == "joint_tp": return JointTP() if name == "ssp_oblivious_tp": r...
6f98613c13becf1ed85cb8a667fc35cfac86973f
3,653,095
def get_first_job_queue_with_capacity(): """Returns the first job queue that has capacity for more jobs. If there are no job queues with capacity, returns None. """ job_queue_depths = get_job_queue_depths()["all_jobs"] for job_queue in settings.AWS_BATCH_QUEUE_WORKERS_NAMES: if job_queue_de...
a23bf9dcef39d1377a1d7cb2a37abbe1186fac0a
3,653,096
def rotations(images, n_rot, ccw_limit, cw_limit): """ Rotates every image in the list "images" n_rot times, between 0 and cw_limit (clockwise limit) n_rot times and between 0 and ccw_limit (counterclockwise limit) n_rot times more. The limits are there to make sense of the data augmentation. E.g: Rotating an...
b1ca7a609faa6ed8903424976b94b477a4798096
3,653,097
def num_range(num): """ Use in template language to loop through numberic range """ return range(num)
7b66e4ffd264ea7b49850a9300c3a6c80282fce1
3,653,098
def datamodel_flights_column_names(): """ Get FLIGHTS_CSV_SCHEMA column names (keys) :return: list """ return list(FLIGHTS_CSV_SCHEMA.keys())
6e5edfa181e02955976602a289576eca307a13bc
3,653,099