content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import curses def setup_curses(): """Setup terminal/curses state.""" window = curses.initscr() curses.noecho() window = curses.newwin( WINDOW_HEIGHT + (VERT_PADDING * 2), WINDOW_WIDTH + (HORIZ_PADDING * 2), WINDOW_TOP - VERT_PADDING, WINDOW_LEFT - HORIZ_PADDING, )...
979d53b03b1c5e26cb93eab1a5aa2311e04dca4d
64,116
def refine_network(graph_main, similars_idx, similars, weigh_bounds=(0.6, 1), filename=None, max_cluster_size=100, min_cluster_size=10, max_search_steps=1000, max_cuts=...
cc1a6c1fc69f6491e672d837445edec93837738c
64,117
def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding.""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
b54e233234a6dfe600efa469cf67669688439ca7
64,118
def a_simple_function(a: str) -> str: """ This is a basic module-level function. For a more complex example, take a look at `a_complex_function`! """ return a.upper()
a511eb8577e0440d0026c4762628fdb6de9be643
64,119
from typing import Dict from typing import Any def get_missing_active(config: Settings, table_stats: dict) -> Dict[Any, Any]: """ Args: config: report Settings object table_stats: The overall statistics for the DataFrame. Returns: """ missing_map = { "bar": { ...
ba1c587f0895b9c01f3fc6f7b374a5a33a53fe19
64,122
def paginated_list(full_list, max_results, next_token): """ Returns a tuple containing a slice of the full list starting at next_token and ending with at most the max_results number of elements, and the new next_token which can be passed back in for the next segment of the full list. """ ...
99a20e3af4ff64d3de52eccbc00aea9fda735e00
64,123
from re import U def build_act(make_obs_ph, q_func, num_actions, scope="deepq", reuse=None): """Creates the act function: Parameters ---------- make_obs_ph: str -> tf.placeholder or TfInput a function that take a name and creates a placeholder of input with that name q_func: (tf.Variable,...
23bf715e2c548db12f6d33a85b6c3adac258be0b
64,124
import struct def bi_hash(v): """ Calculate BI hash from given value :param v: :return: """ bh = siphash24(SIPHASH_SEED, str(v)) return int(struct.unpack("!Q", bh)[0] & 0x7FFFFFFFFFFFFFFF)
4bd455970d7b22ff60a800417e4faf36755e576c
64,125
def normalize_with_max(x, axis=(0,1), data_chns='CPLX'): """ x is complex value x = x/(max(abs(x))) """ scalor = np.max(abs(x), axis) if data_chns == 'CPLX': normalized_x = cplx2float(x/scalor) return normalized_x if data_chns == 'MAG': normalized_x = abs(x/scal...
1b73fe60ab1c000f6824d83b1934deeccefa8854
64,126
def celsius_to_kelvin(deg_C): """Convert degree Celsius to Kelvin.""" return deg_C + 273.15
45eb2dd781adbab2db44f5a8ce5042b2834c7c00
64,127
async def get_alters(): """ Get alter fields of all alter objects. ?full=0 for basic information. """ action = {"mode":"get", "args":request.args} outgoing = Manage_DATA(action=action, alters=[Alter(id="*")]) incoming = await manage_post(outgoing) decoding = Manage(**incoming) return Al...
0825338cf53e9fa43fcbe65b3f1a0f2c2d2ab587
64,129
def set_diff(seq0, seq1): """Return the set difference between 2 sequences as a list.""" return list(set(seq0) - set(seq1))
b68abf4ae6eee79e7e9ce4a5c5110f9f298e9e41
64,130
def get_listing_content_type(req): """ Determine the content type to use for an account or container listing response. :param req: request object :returns: content type as a string (e.g. text/plain, application/json) :raises HTTPNotAcceptable: if the requested content type is not acceptable ...
5205ae5ee2b37a25b02ea5f4977198e79d467f97
64,131
from typing import Tuple from typing import Dict import json def list_policies(client: Client, *_) -> Tuple[str, Dict, Dict]: """List all policies. Args: client: Client object with request. *_: Returns: Outputs. """ policies_xml = client.list_policies_request() polici...
64198831175c84d250eeaac200375e33fc725f4a
64,132
def butterfly_support(size): """ Generate a butterfly support of a given size :param size: int :return: numpy array """ assert size % 2 == 0 support = np.kron(np.ones((2, 2)), np.identity(size // 2)) return support
d1c2c7f2861bed3195b47ffc9f64bc0cd41565a6
64,133
import traceback def init_emu(leaf_ends, state_var, cmovs, finfo, fbytes, bitness): """sets up memory, sets hooks, etc""" BASE_ADDRESS = finfo['addr'] try: mode = UC_MODE_32 if bitness == 64: mode = UC_MODE_64 emu = Uc(UC_ARCH_X86, mode) emu.mem_map(page_align(...
3e9aead4ebbe099e256f7bc21c6f4fe79d1d843e
64,135
from typing import Union import abc def object_writable(model: Union[type, abc.Object]) -> abc.ObjectMeta: """ This function returns an instance of [sob.meta.Object](#meta-Object) which can be safely modified. If the class or model instance inherits its metadata from a class or base class, this functi...
adcc0875a04852d66fb64849c4b084e68e68fdd5
64,136
def radiation_pressure_freq_noise( ff, Pin, length, finesse, mass=2.92, lam=1064e-9, ): """Radiation pressure frequency noise for a total cavity in units of Hz/rtHz. Inputs: ------- ff: float audio frequency in Hz Pin: float cavity input power in watts len...
993fb9528857e83b66898f39507961bc81fa906b
64,137
import math def envpartners_all_in_one(dynophore, superfeature_id, frame_range=[0, None], frame_step_size=1): """ Plot interaction data for a superfeature, i.e. occurrences (frame series) and distances (frame series and histogram). Parameters ---------- dynophore : dynophores.Dynophore ...
0fc0aba552e4ce9e2315200ceecd67d1072775cd
64,138
from typing import Optional import time from io import StringIO def create_ap( cnx: Connection, phy: Optional[str] = None, interface: Optional[str] = None, ssid="tkn_walker", channel=1, psk=None, bssid=None, ip="10.1.1.1", ): """Creates Wi-Fi AP with hostapd. Args: cnx...
33604255cf3f9083b9f27fc54529dad7e8bf31c6
64,139
from django.db.models import Count def get_not_exeuted_details(): """ Returns count of not executed jobs, grouped by name, based on job type. """ values = Job.objects.values('name') result = list(values.filter(Q(executed=None) & Q(cancelled__isnull=True)) ...
3610aab34501278672b2d99f1b9f955bb1db32ac
64,140
import re def conviq(string): """ Convert image quality percentile string to decimal value. """ if np.logical_or('Any' in string, 'null' in string): iq = 1. else: iq = float(re.findall(r'[\d\.\d]+', string)[0])/100 if iq <= 0.2: iq = 0.2 # elif 0.2 < iq <...
8749b71083c43148d5dd3d29f8c3661004d86d91
64,142
def replace_field_refs_according_to_new_or_deleted_fields( formula: str, trash_ids_to_names, new_names_to_id ) -> str: """ Given a raw formula string lexs it into a token stream and goes through and replaces all field_by_id references to a id in the provided trash_ids_to_names with a field reference...
48306495f448c13e60bf1f3c00911db1388aa2e8
64,143
def get_age_group_metadata(gbd_round_id: int) -> pd.DataFrame: """ Gets age group metadata. """ df = db_queries.get_age_metadata(age_group_set_id=CascadeConstants.AGE_GROUP_SET_ID, gbd_round_id=gbd_round_id) df.rename(columns={'age_group_years_start': 'age_lower'...
ac1573cf97e032d96793e85f08509f96f364b79d
64,144
import sqlite3 def create_connection(db_file=msid_files['archfiles'].abs): """ create a database connection to the SQLite database specified by the db_file :param db_file: database file :return: Connection object or None """ conn = None try: conn = sqlite3.connect(db_file) ...
566ab1016c8bed8b86687ed7e67c2c7c6a93265e
64,145
import random def choose_param_numerical(min_val, max_val, param_type, sigma, current): """ Chooses a numerical parameter value via a uniformly or normally distributed random choice. Which one is used is determined at random. """ r = random() # sometimes choose value uniformly to avoid bei...
3605c725ce38af36ce87eb0c38e16ce33d9a9eef
64,146
def get_points_2D(outputs, threshold=0.2): """Pour 1 personnage capté: [Pose(keypoints={ <KeypointType.NOSE: 0>: Keypoint(point=Point(x=717.3, y=340.8), score=0.98), <KeypointType.LEFT_EYE: 1>: Keypoint(point=Point(x=716.2, y=312.5), score=0.6), <KeypointType.RIGHT_EYE: 2>: Keypoint(point=Point(x=6...
524b350c7a5cceb60e07008ff00c8ee869e0b71b
64,148
import re def get_replica_prefix_from_node_name(node_name): """Get replica prefix from operation name.""" regex = re.compile(constant.REPLICA_PREFIX_FORMAT.format("([0-9]+)")) res = regex.search(node_name) return "" if res is None else res.group()
50a9470bf54a5827d7ceb1c392339ff624966da9
64,149
def signin_button(): """Returns the button image for sign-in.""" return send_file("templates/signin_button.png", mimetype='image/gif')
ad3bcac0ca0d51325d8b1ebcf961efe4c754dec8
64,150
import ast import typing def evaluate( node: ast.Node, env: objects.Environment ) -> typing.Optional[objects.Object]: """Evaluate AST recursively.""" if isinstance(node, ast.Program): return eval_program(node.statements, env) elif isinstance(node, ast.ExpressionStatement): return evalu...
72b6e0d3dde9595ddc56b1577d1ad271b5e1d50c
64,151
def get_nonbonded_force_from_openmm_system( openmm_system: openmm.System, ) -> openmm.NonbondedForce: """Get a single NonbondedForce object with an OpenMM System.""" for force in openmm_system.getForces(): if type(force) == openmm.NonbondedForce: return force
a34360f3bf127e49c497156626906000ccc85f96
64,152
import math def get_uniform_keys(n_keys, dim, seed): """ Generate random uniform keys (same initialization as nn.Linear). """ rng = np.random.RandomState(seed) bound = 1 / math.sqrt(dim) keys = rng.uniform(-bound, bound, (n_keys, dim)) return keys.astype(np.float32)
a4194cc926b45c052efef18b731159fbbd4ab584
64,153
import logging def return_sites(description): """ Find appropriate resources to deploy infrastructure, but don't do anything """ # Get RADL radl_contents = utilities.get_radl(description) if not radl_contents: logging.critical('RADL must be provided') return None # Get req...
eb9ff461211de759f20f1f53c90032fce7e2c164
64,154
def eig_sort(w, v): """ sort eignenvalues and eigenvectors by eigenvalue. """ ids = np.argsort(w) return w[ids], v[:, ids]
7ce5637073e2599b5bfdc9d2de2e10d43d2b2335
64,155
import binascii def generate_zos_keys(node_public_key): """Generate a new set of wireguard key pair and encrypt the private side using the public key of a 0-OS node. Args: node_public_key (str): hex encoded public key of 0-OS node. This is the format you find ...
39d5821a1d8fcb2937a7156bd259d3a2d43762c8
64,157
def filterMapAttrs(records=getIndex(), **tags): """matches available maps if their attributes match as specified""" if len(tags) == 0: return records # otherwise if unspecified, all given records match ret = [] for record in records: # attempt to match attributes if matchRecordAttrs(record, tags...
b5773be69b1f1e411fb528d3d3da8f8c377c210e
64,158
import random def get_seed(seed): """Get the seed to run the generator Args: seed : input seed Returns: seed to run instruction generator """ if seed >= 0: return seed return random.getrandbits(32)
b8ec781f30c302fe7f87f9182a1fccca0af0fdd7
64,159
def get_user_profile_rank_list_elements(organization_id, viewer_user_id, expression='limit 10', args=None): """ Return a rank list place of the user by id. """ if args is None: args = [] with connection.cursor() as cursor: cursor.execute( PROFILE_RANK_LIST_ELEMENTS_QUERY...
f8ee63f91a29ff0b12192b39632d68bb351c7dc5
64,160
def insurance(): """ Insurance Information Controller """ mode = session.s3.hrm.mode def prep(r): if mode is not None: auth.permission.fail() return True s3.prep = prep output = s3_rest_controller() return output
d5271522db43ee3db54570f5286d844afdfd55e7
64,162
def params_linear_and_squares(factors): """Index tuples for the linear_and_squares production function.""" names = factors + [f"{factor} ** 2" for factor in factors] + ["constant"] return names
8f7505cb2a07e08d3ad2686d52960d631cd7b458
64,163
def scale(df: pd.DataFrame, method: str) -> pd.DataFrame: """ scales features using different methods. Parameters ---------- df: pandas.DataFrame method: {"autoscaling", "rescaling", "pareto"} Scaling method. `autoscaling` performs mean centering scaling of features to unitary v...
2ce286e507e9574be0d33dd22046ce79dae34205
64,164
from typing import Union from typing import Iterable from pathlib import Path from typing import Any def access( path: Union[Pathlike, Iterable[str], Iterable[Path]], mode: str, **kwargs, ) -> Any: """ Access data (arrays and groups) from a variety of hierarchical array storage formats. Para...
71ecc1e9999808feefb544aed00f8ee99a47cb25
64,165
from typing import Tuple def metadataAppendCompatible(meta1: dict, meta2: dict) -> Tuple[bool, str]: """ Verifies two metadata dictionaries match in a set of required fields. If a field is present in only one or neither of the two dictionaries, this is considered a match. This is primarily intend...
8a3fc01d331f2f0c4dadb148819460092619f64c
64,166
def equal_bytes(*args): """equal_bytes(ea_t ea, uchar image, uchar mask, size_t len, bool sense_case) -> bool""" return _idaapi.equal_bytes(*args)
a97ffa4b7b875d2034630b0938bfeaa23603aade
64,167
from typing import Callable import itertools def _word_wrap(paragraph: str, width: float, measure_func: Callable[[str], float]): """Break text in multiple line.""" result = [] for line in paragraph.split("\n"): # handle empty lines if line == "": result.append("\n") ...
721185a4788e08a7126f8755157dc2d2f9442313
64,168
def node_weights(network, attribute=False): """ Obtains a spatial weights matrix of edges in a network if two edges share a node, they are neighbors Parameters: network: a network with/without attributes attribute: boolean if true, attributes of edges are added to a d...
7b3b1e1809e062dc9b6e5fc170b3867888ee4216
64,169
def import_ecdsa_privatekey_from_file(filepath, password=None): """ <Purpose> Import the encrypted ECDSA key file in 'filepath', decrypt it, and return the key object in 'securesystemslib.formats.ECDSAKEY_SCHEMA' format. Which cryptography library performs the cryptographic decryption is determined...
9e7c6e4845ed231dbf4f901d2dacea016fbbe633
64,170
from typing import Any from typing import Dict def rx_from(observable_input: Any) -> Observable: """Convert almost anything to an Observable. Anything means: - a dictionnary in an rx_dict - an async iterable - an iterable - something which can be cast to an Observable (have a ...
d2cecdf291fa781e93f4566b33f84becc8901a4f
64,171
import time def group(request, group): """Returns a page showing all hosts/services of the specified group""" stat, obj = parse() service_dict = {} host_list = hostlist_by_group(stat, obj, group) if not host_list: raise Http404 host_names = map(lambda x: x['host_name'], host_list) ...
407d29a84ea7ec647166b13a2cf24c5b59e1457e
64,172
def set_model_internal_data(model, original_data, modified_data, deleted_data): """ Set internal data to model. """ model.__original_data__ = original_data list(map(model._prepare_child, model.__original_data__)) model.__modified_data__ = modified_data list(map(model._prepare_child, model._...
cf17f9f04342be01706530c79f9bb83cd8c03b73
64,174
def sub_parser_decorator(func=None, **parser_settings): """ Decorated for sub_parser argument definitions """ if not func: return partial(sub_parser_decorator, **parser_settings) def _wrapper(parser): sub_parser = parser.add_parser(**parser_settings) sub_parser.add_argument(...
eaa6c2635fc1e6deb1b7b51f3212a6c909f07e49
64,175
def neg_binomial(x, n, p): """ Get the probability density for a negative binomial distribution. :param x: Edges of bins within which to calculate probability density :type x: :class:`~numpy.ndarray` :param int n: Number of trials (see :data:`~scipy.stats.nbinom`) :param int p: Probability of s...
65359ac707e971370708f143b744162e4b8fde4a
64,177
def convert_mask_data(data): """ Converts a numpy array mask to our internal complex polygon data representation. """ mask = np.uint8(np.array(data) > 0) contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) contours = [contours[i].reshape(-1, 2) for i in range(len(c...
fc486a6fc44d21c1a4a2fc446404f2e1ce676726
64,179
def tuple_as_atom(atom:tuple) -> str: """Return readable version of given atom. >>> tuple_as_atom(('a', (3,))) 'a(3)' >>> tuple_as_atom(('bcd', ('bcd',12))) 'bcd(bcd,12)' """ assert len(atom) == 2 return '{}({})'.format(atom[0], ','.join(map(str, atom[1])))
5c18f34733d839865eef35509f95c2d4d198a903
64,180
def compute_ms_ssim_dic(x_hat, code, max_value=1.): """ Compute (weighted) MS-SSIM for two YUV dictionnaries. Return one value: the ms_ssim """ res = 0 nb_values = 0 for x_hat_channel, code_channel in zip(get_y_u_v(x_hat), get_y_u_v(code)): nb_values += x_hat_channel.numel()...
1f156a7d1121b1d7693204633520da9484e7846c
64,181
def create_ideal_periodic_signal(signal_length): """Create ideal ribo-seq signal. Parameters ---------- signal_length : int Length of signal to create Returns ------- signal : array_like 1-0-0 signal """ uniform_signal = np.array([4 / 6.0] * signal...
0385b2279cb7a8b7eb663c7991d013c8b1b5a245
64,183
def quadrupole_q20(fam_name, strength, simplified=False): """Segmented Q20 quadrupole model.""" segtypes = { fam_name: (fam_name, _pyaccel.elements.quadrupole), } # Q20 model # ========= # this (half) model is based on fieldmap # '2017-02-24_Q20_Model05_Sim_X=-14_14mm_Z=-500_500mm_I...
9768792bddc37e09cb87affc1a0d7b1d66678dc3
64,184
def get_engine(settings: dict, prefix: str = 'sqlalchemy.') -> Engine: """Reads config and create a database engine out of it. :param settings: Application settings :param prefix: Configuration prefixes :return: SQLAlchemy Engine """ url = settings.get('sqlalchemy.url') if not url: ...
c33dd66d13a3413ae6b78a4c04a8385c3500cc78
64,185
import struct def Fbytes(f): """ Return bytes representation of float """ return struct.pack("f", f)
117fb86216ad6983851923ac9dbd0196cc29b92d
64,186
def propMatVisc(zarray, n, params, t=1, Q=1, scaled=False, logtime=False): """Generate the viscous love-number propagator matrix for zarray. Inhomogeneities from elastic deformation and viscous migration of nonadiabatic density gradients are added using gen_viscb. Parameters ---------- z...
4c249c3c89e5a280d70575528fc860be0fb48fa9
64,188
def Vaknin(x): """ Vaknin correction for CSD analysis (Max Sherman [Brown U] implementation) Allows CSD to be performed on all N contacts instead of N-2 contacts See Vaknin et al (1989) for more details """ # Preallocate array with 2 more rows than input array x_new = np.zeros((x.shape[0]+2,...
53baf485af7c87a735f8cf6b62b03be0356ba47b
64,189
import sqlite3 def connect_db(): """ データベースに接続します """ con = sqlite3.connect(app.config['DATABASE']) con.row_factory = sqlite3.Row return con
ef0430affc16989bc9fcfa9c03ef97b969924ccc
64,192
def getOverlappedSpaces(ifc_file): """ Function created to detect overlap spaces """ props = OCC.Core.GProp.GProp_GProps() spaces = ifc_file.by_type("IfcSpace") black_list = [] local_tolerance = 0.1 shapes = {} for sp in spaces: shapes[str(sp.GlobalId)] = ifcopenshell.geom.cr...
ae72058c58db7924f40ba6a2a5c5458d907f32b0
64,193
import six def map_struct(func, struct, map_dict=True, map_list=True, map_tuple=False, map_set=False, cls=None, custom_mappings=None): """ Applies a function *func* to each value of a complex structured object *struct* and returns the output in the same structure. Example: .. code-block:: pyt...
ca4b4f40b286b2890de84788bf1a1319d70b1fef
64,195
def get_rays_relight_np(H, W, focal, c2w, lightdir): """Get ray origins, directions from a pinhole camera.""" i, j = np.meshgrid(np.arange(W, dtype=np.float32), np.arange(H, dtype=np.float32), indexing='xy') dirs = np.stack([(i-W*.5)/focal, -(j-H*.5)/focal, -np.ones_like(i)], -1) ...
362f45e2e41055bce20b01cd3e3eb274d606712a
64,196
def bin_threshold(mat, threshmin=None, threshmax=0.5): """ Generate binary segmentation from probabilities Parameters ---------- mat : np.array The data threshmin : float or None Minimum value on [0,1] to assign binary IDs from probabilities. thresmax : float Maximum...
8595eae8ff19df106d1ab906e1cc66b41d2aabcd
64,197
def get_text(name): """returns some text""" return "Hello "+name
0226a09df5cdbb0d50f4fe4168a0d5686b43b2da
64,198
def ipv4_cidr_to_netmask(bits): """ Convert CIDR bits to netmask """ netmask = '' for i in range(4): if i: netmask += '.' if bits >= 8: netmask += '%d' % (2 ** 8 - 1) bits -= 8 else: netmask += '%d' % (256 - 2 ** (8 - bits)) ...
a4be3fea1c59d77312de78e743a67470b444d651
64,199
def clamp(value, low, high): """Clamp the given value in the given range.""" return max(low, min(high, value))
48303b27d78f8d532b1e74db052457ae19b9f10d
64,200
def simulate2(atomList, *XYZs, **kwargs): """ Simulation of a two-component diffraction pattern """ magnification = kwargs.pop('mag', 0.7) beamSize = kwargs.pop('beamsize', 250e-6) DetectionParameters = fed.Detector(imageSizeX, imageSizeY, cenX, cenY, detDist, pixelSize, magnification) rota...
3a452a1f86764edcc590a95350c7eb6d07c27cb9
64,201
def fmt_n(large_number): """ Formats a large number with thousands separator, for printing and logging. Param large_number (int) like 1_000_000_000 Returns (str) like '1,000,000,000' """ return f"{large_number:,.0f}"
7b23e902a1c9600f1421b45b27623abaa1930f05
64,202
def make_cuda_consistent(refobj, *args): """ Attempt to make the cuda states of args consistent with that of ``refobj``. If any element of args is a Variable and the cuda state of the element is inconsistent with ``refobj``, raise ValueError, since changing the cuda state of a Variable involves rewr...
aefcebef6d0637921d757c7ef03189c5ce2c6682
64,206
def forward_backward_prop(X, labels, params, dimensions): """ Forward and backward propagation for a two-layer sigmoidal network Compute the forward propagation and for the cross entropy cost, the backward propagation for the gradients for all parameters. Notice the gradients computed here are dif...
3b232a6c265b3d87b0a941f15eb22ae9deb2a9f0
64,207
def api_symbols_by_name(): """ /api/v1/resources/symbols?symbol_id=1223 >>> """ current_app.logger.info("[trace]") dat = clib.read_db(path_to_db) if "symbol_id" in request.args: symbol_id = str(request.args["symbol_id"]) else: return "Error: No symbol_id field provided. P...
be185d7461f941cdf421a1471b7875010ffc9007
64,208
def nested_submit(fn, combos, kwds, executor=None): """Recursively submit jobs directly to an executor pool. Parameters ---------- fn : callable Function to submit jobs to. combos : tuple mapping individual fn arguments to sequence of values Mapping of each argument and all its poss...
c128c151d576158967b865b5cafbb0c64dfa43bd
64,209
def euclidean_distance(source, destiny): """ Calculates the euclidean distance between two points in the space. Where each argument is a list = [SSID, signal, channel] """ ret = 0 x_1 = source[0] y_1 = source[1] z_1 = source[2] x_2 = destiny[0] y_2 = destiny[1] z_2 = destin...
0c13bdf81aad184b4c427539a370e8ce53e7c043
64,210
def index(request): """ 前台首页 :param request: 请求 :return: """ news_art = NewsArticle.objects.order_by('-publish_time')[:10] print(len(news_art)) news_list = encapsulation_data(news_art) hot_art = NewsArticle.objects.order_by('-read_total')[:10] hot_list = encapsulation_data(hot_ar...
f4816fc4bbe7042fa82d40caebd3169b817445db
64,211
def convertGeoJsonGeometry(data): """ Convert JSON features into shapely geometry and then convert entire json data object into geopandas dataframe. Accepts a JSON data object. Returns a geopandas geodataframe or an error. """ try: # convert features to shapes so...
40fcee738da4b9d5c97d8abbd21c861c051801ac
64,212
def forecast_svr(X_test_tract1_array, days ,model_svr, lag, scaler): """ multi-step future forecast. for each ticker, forescast Args: X_test_tract1_array, days ,model_svr, lag, scaler return """ last_test_sample = X_test_tract1_array[-1] X_last_test_sample = np.reshape(last_test_sam...
fc4dbb44d071ae9120ec8c55b9d1c9fac727b0db
64,214
import copy async def fetch_html(url: str, session: ClientSession, **kwargs) -> str: """GET request wrapper to fetch page HTML. kwargs are passed to `session.request()`. """ kwargs2 = copy.deepcopy(kwargs) kwargs2.pop('crawler') resp = await session.request(method="GET", url=url, **kwargs2) ...
25e4951e52fc1655e238a0157ce3d2a6106b9959
64,215
import logging from typing import Iterable def track(params_file, directions="det", max_angle=30., sphere=None, seed_mask=None, seed_threshold=0, n_seeds=1, random_seeds=False, rng_seed=None, stop_mask=None, stop_threshold=0, step_size=0.5, min_length=10, max_length=1000, odf_model="DTI"...
309ebac8558bc8a4bf26267b971300f45a2826ef
64,216
def inner_product(L1, L2): """ Take the inner product of the frequency maps. """ result = 0. for word1, count1 in L1: for word2, count2 in L2: if word1 == word2: result += count1 * count2 return result
65ede8eddcf86d75a1b130a76381416c2a272f61
64,217
def aggregate(assignments, exprlist): """aggregates are a assignments with special attribute None > list of subtuple""" lexprs = len(exprlist) if lexprs<1: raise ValueError, "aggregate on no expressions?" lassns = len(assignments) pairs = list(exprlist) for i in xrange(lexprs): ...
f2a685d28afaf8dc6dfd79610666288662a11d4c
64,218
import json def compute_metrics(ent_lst, rel_lst, _2_r_lst, _2_ht_lst, _n_r_lst, _n_ht_lst, _n_a_lst, _n_v_lst, eval_result_file): """ Combine the ranks from batches into final metrics. """ all_ent_ranks = np.array(ent_lst).ravel() all_rel_ranks = np.array(rel_lst).ravel() ...
193476f00dc9866c697dddedf2b49b39bd5f3ebe
64,219
def nb_count_prob(n, rate, r_inv, sim_time): """ Negative binomial count probability. The mean is given by :math:`r \cdot \Delta t` like in the Poisson case. """ g = rate*sim_time if g == 0: return (n == 0).astype(float) r = 1./r_inv log_terms = sps.loggamma(r+n) - sps.logg...
9f90340acd917137386b7a41bbdffa7d2c39176c
64,220
def resnet50(pretrained=False, last_stride=1, use_non_local=False, model_path='', **kwargs): """Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr """ return ...
319f8c55c4541e660fc11f4f56e93ff8de65ae6d
64,221
def img_to_slices(img): """ From 3D image to slices list """ res = [] for i, slice_img in enumerate(img): res.append(slice_img) return res
7776eed3c9abaf3267eb304421b58a6af190a63f
64,222
def x_point_wgt_av(df_agg, x_var): """ Set the x_point to be the weighted average of x_var within the bucket, weighted by stat_wgt. """ if not (x_var + '_wgt_av') in df_agg.columns: raise ValueError( "\n\tx_point_wgt_av: This method can only be used when" "\n\tthe wei...
15d8515efceb67e1dc9062d7fd79250c5935b549
64,223
def numba_find_phys_grid(xv, yv, bdyx, bdyy, inside): """ Computes whether the points spanned by xv, yv are inside of the polygon defined by the x-coordinates bdyx and the y-coordinates bdyy The polgon is assumed not to be closed (the last point is not replicated) """ if inside: result =...
31a82d1faaee6c6558a887ffb2e2bc26a31874a0
64,225
import hashlib def generate_hash(bytes_, hash_algorithm=hashlib.sha256) -> str: """ Return string with hash containing only hexadecimal digits """ return hash_algorithm(bytes_).hexdigest()
2f4bbc9d47d9cf22f005434aea7b2749ae8594bd
64,226
def BRepOffset_Tool_Deboucle3D(*args): """ * Remove the non valid part of an offsetshape 1 - Remove all the free boundary and the faces connex to such edges. 2 - Remove all the shapes not valid in the result (according to the side of offseting) in this verion only the first point is implemented. :param S: ...
aa94002643068ccaa09abb70185215d13ce34bb9
64,227
def GetFixupTgtSel(ea): """ Get fixup target selector @param ea: address to get information about @return: -1 - no fixup at the specified address otherwise returns fixup target selector """ fd = idaapi.get_fixup(ea) if not fd: return -1 return fd.sel
16bbaa668ecd98eda8fc0e064140e644178a3ec8
64,229
def ic_to_gamma(water_level): """ Return the expression needed to compute "gamma_predict" """ below_water = (1.0 - col("depth")) < water_level ti = col("type_index") return ( pl.when(ti > 3.22) .then(11.0) .when((ti <= 3.22) & (ti > 2.76)) .then(16.0) .whe...
dde11a76aee749e6f25969c5a38f41d546219df6
64,230
def set_path(*args): """ set_path(pt, path) Set the file path @param pt: file path type Types of the file pathes (C++: path_type_t) @param path: new file path, use NULL or empty string to clear the file path (C++: const char *) """ return _ida_loader.set_path(*args)
8f5aa01a9459d14a42c090f78a13becfaf17fe6b
64,231
def get_max_trajectory(l_curr, v_curr, acceleration, dt, n_begin=0, n_end=0, upsampling_factor=10): """ returns max braking deceleration bound for a given trajectory point """ dt = dt / upsampling_factor n_end = n_end * upsampling_factor # the returned trajectory includes current position and t...
3c60ab2418b66676bc4f28c7ea07e316fc386a62
64,232
import socket def get_host_by_ipaddr(ipaddr): """ returns a reverse DNS name if available """ try: socket.inet_aton(ipaddr) return socket.gethostbyaddr(ipaddr)[0] except socket.herror: return 'no reverse DNS found' except (socket.error, TypeError): return 'illegal IP a...
36767a2d105318cddb33e400d73ba7c2eee98add
64,233
def simplify_specifiers(spec): """Try to simplify a SpecifierSet by combining redundant specifiers.""" def key(s): return (s.version, 1 if s.operator in ['>=', '<'] else 2) def in_bounds(v, lo, hi): if lo and v not in lo: return False if hi and v not in hi: ...
da2a62caa0b26f646060c2aa15543c829c61f9e1
64,234
from typing import Mapping from typing import Dict from typing import Optional def get_injector_for_testing( providers: Mapping, additional_settings: Dict = None, overrides_registry: Optional[OverridesRegistryBase] = None ) -> Injector: """ Return an :class:`Injector` using a fake craw...
352b189ad5f2af550da801576b6e6654b138fc11
64,235
from re import T def conv1d_md(input, filters, image_shape, filter_shape, border_mode='valid', subsample=(1,), filter_flip=True): """ using multiple dot products """ if border_mode not in ('valid', 0, (0,)): raise RuntimeError("Unsupported border_mode for conv1d_md: " ...
f8f84cb739723ff8ed41b4686f9f13d667dd0c70
64,236
from typing import Mapping from typing import Optional def _rename_nodes_on_tree( node: dict, name_map: Mapping[str, str], save_key: Optional[str] = None, ) -> dict: """Given a tree, a mapping of identifiers to their replacements, rename the nodes on the tree. If `save_key` is provided, then the ...
b8d3df2f2247b27c614b767b28eda7b91e380524
64,237