content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _rk4(dparam=None, k0=None, y=None, kwdargs=None): """ a traditional RK4 scheme, with: - y = array of all variables - p = parameter dictionnary dt is contained within p """ if 'itself' in dparam[k0]['kargs']: dy1 = dparam[k0]['func'](itself=y, **kwdargs) dy2 = dpar...
a44e177e6925c36fa9355ed9c5ee41d0604d01bd
28,782
def generate_discord_markdown_string(lines): """ Wraps a list of message into a discord markdown block :param [str] lines: :return: The wrapped string :rtype: str """ output = ["```markdown"] + lines + ["```"] return "\n".join(output)
1c0db2f36f4d08e75e28a1c024e6d4c35638d8f5
28,783
from typing import Optional def _sanitize_ndim( result: ArrayLike, data, dtype: Optional[DtypeObj], index: Optional[Index] ) -> ArrayLike: """ Ensure we have a 1-dimensional result array. """ if getattr(result, "ndim", 0) == 0: raise ValueError("result should be arraylike with ndim > 0") ...
6a1e49e07658ea3f7b9e80915c73464548715419
28,784
from typing import Callable from typing import Any from re import T from typing import List from typing import Dict def from_list_dict(f: Callable[[Any], T], x: Any) -> List[Dict[str, T]]: """Parses list of dictionaries, applying `f` to the dictionary values. All items must be dictionaries. """ assert...
2a1316098165367e8657d22717245a6c695cb96e
28,785
def TSTR_eICU(identifier, epoch): """ """ # get "train" data exp_data = np.load('./experiments/tstr/' + identifier + '_' + str(epoch) + '.data.npy').item() X_synth = exp_data['synth_data'] Y_synth = exp_data['synth_labels'] n_synth = X_synth.shape[0] X_synth = X_synth.reshape(n_synth, -1...
8f719e94689b1354e6463935e6dbdc2c5a110779
28,786
def wizard_active(step, current): """ Return the proper classname for the step div in the badge wizard. The current step needs a 'selected' class while the following step needs a 'next-selected' class to color the tip of the arrow properly. """ if current == step: return 'selected' ...
2daad3f7651df7609f3473af698e116ce419c9df
28,787
def set_token(token: OAuth2Token): """Set dynamics client token in a thread, so it can be done in an async context.""" def task(): name = "dynamics-client-token" expires = int(token["expires_in"]) - 60 cache.set(name, token, expires) with ThreadPoolExecutor() as executor: f...
61b4bfa3dbe1ddd03ff608a476f34905ec2440e9
28,788
def pFind_clumps(f_list, n_smooth=32, param=None, arg_string=None, verbose=True): """ A parallel implementation of find_clumps. Since SKID is not parallelized this can be used to run find_clumps on a set of snapshots from one simulation. **ARGUMENTS** f_list : list A list cont...
85e2c80f3fdb95f2c324b8b934550788faa6c5bb
28,789
import math def gamma_dis(x): """fix gamma = 2 https://www.itl.nist.gov/div898/handbook/eda/section3/eda366b.htm """ x = round(x, 14) res = round(x*math.exp(-x) / TAU_2, 14) return res
a3375b7ae16755d0dab47ecd4f54ebc8c40143b9
28,790
import calendar def get_month_number(year): """ Function to get month from the user input. The month should be number from 1-12. :returns: the number of month enterd by user :rtype: int """ year = int(year) while True: val = input("Please, enter the number of month? (1-12)\n") ...
c2d0f5010b8f1de6d1764a216c43eb1901c8093c
28,792
def reconstruct_with_whole_molecules(struct): """ Build smallest molecule representation of struct. """ rstruct = Structure() rstruct.set_lattice_vectors(struct.get_lattice_vectors()) molecule_struct_list = get_molecules(struct) for molecule_struct in molecule_struct_list: geo_arra...
f3595fdd23e22fc0c24b9a7cfa6e000206eda93f
28,793
def _json_serialize_no_param(cls): """ class decorator to support json serialization Register class as a known type so it can be serialized and deserialzied properly """ return _patch(cls, _get_type_key(cls), 0)
3eaf4c7c53694c316898b1a9e4d41dc4b212afed
28,794
def aireTriangle(a,b,c): """ Aire du triangle abc dans l'espace. C'est la moitié de la norme du produit vectoriel ab vect ac """ u,v=b-a,c-a r=u[2]*v[0]-u[0]*v[2] s=u[0]*v[1]-u[1]*v[0] t=u[1]*v[2]-u[2]*v[1] return 0.5*sqrt(r*r+s*s+t*t)
641aa598d36189c787b91af4a98734f2289173e0
28,795
def ez_admin(admin_client, admin_admin, skip_auth): """A Django test client that has been logged in as admin. When EZID endpoints are called via the client, a cookie for an active authenticated session is included automatically. This also sets the admin password to "admin". Note: Because EZID does not ...
0b2ac749a690ad5ac0dc83ca9c8f3905da5a016b
28,796
import textwrap def _template_message(desc, descriptor_registry): # type: (Descriptor, DescriptorRegistry) -> str """ Returns cls_def string, list of fields, list of repeated fields """ desc = SimpleDescriptor(desc) descriptor_registry[desc.identifier] = desc slots = desc.field_names ...
2586ffe0b81ea683a40bc20700ddb970fc385962
28,797
import re def parse_archive(path, objdump): """Parses a list of ObjectFiles from an objdump archive output. Args: path: String path to the archive. objdump: List of strings of lines of objdump output to parse. Returns: List of ObjectFile objects representing the objects ...
1f30804ba1d723bf8656dd26f522c5a369db4b3d
28,798
async def async_validate_trigger_config( hass: HomeAssistant, config: ConfigType ) -> ConfigType: """Validate config.""" config = TRIGGER_SCHEMA(config) device_registry = await hass.helpers.device_registry.async_get_registry() device = device_registry.async_get(config[CONF_DEVICE_ID]) trigger ...
f43e1b58bd37e0cf989da8076505cf34c4386830
28,799
def get_vgg_dilate_conv(data): """ vgg-16 shared convolutional layers,use dilated convolution in group 5 :param data: Symbol :return: Symbol """ # ====group 1 conv1_1 = mx.symbol.Convolution(data=data, kernel=(3,3), pad=(1,1), \ num_filter=64, name='...
12a25c10e10f2648f21c9e75ae0e2ef034541be1
28,801
from typing import Dict import ast def _get_func_aliases(tree) -> Dict: """ Get __func_alias__ dict for mapping function names """ fun_aliases = {} assignments = [node for node in tree.body if isinstance(node, ast.Assign)] for assign in assignments: try: if assign.targets[0...
13967f2e1ea5e31db8cc700915d9b8af9cbc609d
28,802
def admin_only(view_func): """Restrict page access to only admins""" @wraps(view_func) def wrapper_function(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group == 'profile': return redirec...
6facd5bed6f48541bd9db678606a805a75983232
28,803
def _im_distance(adj1, adj2, hwhm): """Computes the Ipsen-Mikhailov distance for two symmetric adjacency matrices Note : Requires networks with the same number of nodes. The networks can be directed and weighted (with weights in the range [0,1]). Params ------ adj1, adj2 (array): adjacenc...
4e12000194d570235e88fbe36513cca221b43e49
28,804
def get_movement_endtime(dT, T): """ Returns the end time of the movement assuming that the start time is zero. """ _t = 0. for i, _dT in enumerate(T): _t = np.max([_t, np.sum(dT[:i]) + T[i]]) return _t
aca310be41dfbe7292f8f66f9c50159365570045
28,806
def getGroupUpcomingEvents(request, group): """ Return all the upcoming events that are assigned to the specified group. :param request: Django request object :param group: for this group page :rtype: list of the namedtuple ThisEvent (title, page, url) """ # Get events that are a child of a...
ae61166a96635e597452181c30dc7d2945f1e4af
28,807
def get_marginal_probabilities(probs_table): """ Get the marginal probability of each event given a contingency table. """ ind = [] for transp in get_transpositions(probs_table): marginal_probs = [probs_table.transpose(transp)[1, ...].sum(), probs_table.transpo...
e222a11669b0c9920d875960a1ccea9e9e8a971c
28,808
def get_graph_map(): """Get the graph rail network mapbox map. Returns: go.Figure: Scattermapbox of rail network graph """ # Get the nodes and edges and pandas dataframes from the database nodes, edges = get_berths() if nodes is None or edges is None: return None # Plot the...
d6ca3697aa74d23dd79ea93d3211c644cc852c72
28,809
def getFormatter(name): """Return the named formatter function. See the function "setFormatter" for details. """ if name in ( 'self', 'instance', 'this' ): return af_self elif name == 'class': return af_class elif name in ( 'named', 'param', 'parameter' ): return af_name...
216e232d0fa599fb1916cbe833ed3da59d9b03cd
28,811
def _mat_vec(v: PyTree, oks: PyTree) -> PyTree: """ compute S v = 1/n ⟨ΔO† ΔO⟩v = 1/n ∑ₗ ⟨ΔOₖᴴ ΔOₗ⟩ vₗ """ res = tree_conj(vjp(oks, jvp(oks, v).conjugate())) return tree_cast(res, v)
f6f1242f4f4f55df196f75f51887ce1c9c8af067
28,812
def get_recordio_iterator(path_to_rec, batch_size, data_shape=(3, 227, 227)): """ Creates mxnet recordio iterator for recordio files. For more details see https://beta.mxnet.io/api/gluon-related/_autogen/mxnet.image.ImageIter.html """ data_iter = mx.io.ImageRecordIter( path_imgrec=path_to_rec...
dacda63fc01859f249f7dc897a86706129359d44
28,813
from typing import Tuple import ctypes def raxisa(matrix: ndarray) -> Tuple[ndarray, float]: """ Compute the axis of the rotation given by an input matrix and the angle of the rotation about that axis. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/raxisa_c.html :param matrix: Rotation...
79f08a16c38ba261d5faedc0565dea7199d145a9
28,814
import errno from six.moves import builtins def call_errno_test(): """ Test procedure. """ ObjectBrowser.create_browser(errno, 'errno') ObjectBrowser.create_browser(builtins, 'builtins') exit_code = ObjectBrowser.execute() return exit_code
f006bb438d502ccac4b7b70e18d83eb2e8b2b258
28,815
def use_item(entity, player, new_fov_radius, max_fov_radius, sound): """ Item settings when used """ player.fighter.hp += entity.item.healing if player.fighter.hp > player.fighter.max_hp: player.fighter.hp = player.fighter.max_hp sound.play() new_fov_radius = max_fov_radius use_messa...
15ae450fa3d2dc6f2e390c9b861783304ba92f30
28,816
import ast def parse_recommendation(line): """ Parses a recommendation record. Format: userId\t avg_rating\t rmse\t labels Parameters ---------- line : str The line that contains user information Returns ------- list : list A list containing userID, avg_rating, rmse, ...
b49feef1f7010f6cfa35585a86f1b12b314d95c1
28,817
import math def two_props_diff_conf_interval(values1: np.ndarray, values2: np.ndarray, conf_level: float) -> tuple: """Calculates the confidence interval for the diff between two proportions Args: values1 (np.array): sample 1 binary(0/1) values values2 (np.arr...
c87ec7dfe72e13820b197e8b270e49f9ffacdb28
28,818
from typing import Sequence def generate_random_text(n_tokens: int, tokens: Sequence[str], probabilities: Sequence[float]) -> str: """Return random text with tokens chosen based on token probabilities. Parameters ---------- n_tokens: int the length of the text in number of tokens tokens: ...
0d799be072d963f905f87681086820e5653600bf
28,819
def pad(array_like: ArrayLike, begin: Shape, end: Shape, fill_type: BorderType) -> ShapeletsArray: """ Pads an array Parameters ---------- array_like: ArrayLike Input array begin: Shape Full 4 dimensional tuple specifying how many elements to add at the beggining of the ...
6e858e2a9f250a9a80d9664aa3a10c0643e88d78
28,820
from typing import Iterable import itertools def verify(y_f: GFE, v: Iterable[bytes], c: FiniteFieldPolynomial) -> GFE: """Check whether a alleged secret share belongs to a group of shares. The group of shares is specified by the public `v` and `c` values returned by `split`. If the share belongs to the ...
cf682be844245415c85243a0d32fe8ab0387804c
28,822
def compute_bottom_border(b, dims, mat=False): """Compute the bottom border for a given border size.""" x, y = dims return b + _A(b, x, mat)
6853b9cfddc3d727aa5572f5adf7c61c3cfe71f2
28,823
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Load the saved entities.""" # Print startup message _LOGGER.info( "Version %s is starting, if you have any issues please report" " them here: %s", VERSION, ISSUE_URL, ) hass.data.setdefault(DOMAI...
2e744f2c67f9f31fd0e3a58d3c5c645e2c7a65d3
28,824
def name(): """ """ response = PhoneInterface() text = request.form if text: result = to_noun(text['SpeechResult']) response.speak('Is your name {}?'.format(result)) new_user = User.query.get(response.get_user_id()) new_user.name = result db.save() respons...
62638b78806de07067439d337ac6e70f0069db5a
28,825
def bonferonni_posthoc(*args, ttest_type='equal'): """Computes T-Tests between groups, should adjust your significance value, a.k.a. bonferonni correction to minimize family wide error rates Args: group1: Input group 1 as a numpy array group2: Input group 2 as a numpy array ...
9ee5537106d6cd5b6074ff8839ee631a47dc5f5b
28,827
from typing import Dict def list_subject(_type: str, limit: int = 10, offset: int = 0) -> Dict: """ 获取subject列表 """ url_path = "/api/v1/web/subjects" params = {"type": _type, "limit": limit, "offset": offset} return _call_iam_api(http_get, url_path, data=params)
26085a5676263ba425e3306332a380df849e7069
28,828
def get_all_envs(envs_file): """Get list of all intercepted environment variables.""" return list(iter_envs(envs_file))
425cf386b200fe2aa0545c48539c1497d3bdb253
28,830
import six def _deserialize_primitive(data, klass): """Deserializes to primitive type. :param data: data to deserialize. :param klass: class literal. :return: int, long, float, str, bool. :rtype: int | long | float | str | bool """ try: value = klass(data) except UnicodeEncodeError: ...
62f31f9230d33d0120cca3fb187746871f54a8bb
28,831
def highlight_seam(img: np.ndarray, seam: np.ndarray) -> np.array: """ Function to highlight the seam Args: img (np.array): Image array seam (np.array): Seam array with length equals height of the image array The x-coordinates of the pixel to remove from each row Returns: ...
81cc5dd7d28b4240e43cdef6e9bcde364cbf2b01
28,832
def _maybe_encode_unicode_string(record): """Encodes unicode strings if needed.""" if isinstance(record, str): record = bytes(record, "utf-8").strip() return record
2621056ba77fd314b966e3e0db08887da53e3803
28,833
import torch def filter(x): """ applies modified bilateral filter to AB channels of x, guided by L channel x -- B x 3 x H x W pytorch tensor containing an image in LAB colorspace """ h = x.size(2) w = x.size(3) # Seperate out luminance channel, don't use AB channels to measure similarity...
57b650e39d7c552dcdde0fddf39388ed7946716f
28,834
def series_not_found(): """ Formats error message for event with missing series. :return: error message :rtype: str """ error = "event(s) where their series could not be found" return error
10d0915d7e47fd308de8c072cdf9c81f078d2eee
28,835
def compiler(language, config, permit_undefined_jinja=False): """Support configuration of compilers. This is somewhat platform specific. Native compilers never list their host - it is always implied. Generally, they are metapackages, pointing at a package that does specify the host. These in turn may be...
131811e7642e9756e2506de9ba89e5ca304a9498
28,836
from typing import Iterable import itertools def iter_contour_segments(points: Contour) -> Iterable[Segment]: """Given points A, B, ...N returns (A, B), (B, ...), (..., N), (N, A).""" # "contour" frequently has shape (N, 1, 2); remove "1" middle layer. if len(points.shape) > 2: size = points.size ...
8f5911ee02f96be085b09c2143b989e6120e98cc
28,839
def intword(value): """ Converts a large integer to a friendly text representation. Works best for numbers over 1 million. For example, 1000000 becomes '1.0 million', 1200000 becomes '1.2 million' and '1200000000' becomes '1.2 billion'. """ value = int(value) if value < 1000000: retu...
d9f3c776e3bc354cb68434080ca74aa4f52ad1aa
28,840
def __validate_archive_file_arg(required_arg_map): """ Verify that the archive file exists. :param required_arg_map: the required arguments map :return: the archive file name :raises CLAException: if the archive file is not valid """ _method_name = '__validate_archive_file_arg' archive_...
dfc56614d832dee3e4534ac9e0634770e0c13cae
28,841
import inspect def suite(description=None, name=None, rank=None): """ Decorator, mark a class as a suite class. :param description: suite's description (by default, the suite's description is built from the name) :param name: suite's name (by default, the suite's name is taken from the class's name) ...
6d7568196d92c64f6451797c854e90cc80ae9a9f
28,842
def mercator_to_gcj02(mer_matrix): """ Mercator coordinates to National Bureau of Survey and Measurement coordinates :param mer_matrix: :return: """ return wgs84_to_gcj02( mercator_to_wgs84(mer_matrix) )
9e131301dc4c203f6bd1698ffd44c7e3b5e52aad
28,844
def delete_menu_item(current_user, item_id): """Delete menu item by id""" if current_user['admin']: resp = menu_inst.del_menu(item_id) if resp: return jsonify({"Message": "Item deleted"}), 200 return jsonify({"Message": "Item not found"}), 404 return jsonify({"Message": "...
f8ba25ec925489942e6d71f4854bb7d9f7bd427a
28,845
from typing import Tuple from typing import Dict def generate_parameters(system: params.CollisionSystem) -> Tuple[np.ndarray, np.ndarray, int, Dict[int, params.SelectedRange]]: """ Generate the analysis parameters. This can be called multiple times if necessary to retrieve the parameters easily in any functi...
8f743bfcbc998b8f2bfd05d10bb0a6acb0777d04
28,846
def merge_extras(extras1, extras2): """Merge two iterables of extra into a single sorted tuple. Case-sensitive""" if not extras1: return extras2 if not extras2: return extras1 return tuple(sorted(set(extras1) | set(extras2)))
0383e0e99c53844f952d919eaf3cb478b4dcd6d1
28,847
def netdev_get_driver_name(netdev): """Returns the name of the driver for network device 'netdev'""" symlink = '%s/sys/class/net/%s/device/driver' % (root_prefix(), netdev) try: target = os.readlink(symlink) except OSError, e: log("%s: could not read netdev's driver name (%s)" % (netdev,...
fa55fb2e95357534f7630fdae4bf5304bef27f09
28,848
def _get_content(item, base_url=None): """ Return a dictionary of content, for documents, objects and errors. """ return { _unescape_key(key): _primitive_to_document(value, base_url) for key, value in item.items() if key not in ("_type", "_meta") }
91c9e2ea9a74b1a44f6aa83154815941f9d3460d
28,849
def _cluster_by_adjacency(sel_samples): """Function for clustering selected samples based on temporal adjacency. Input arguments: sel_samples - A vector of booleans indicating which samples have been selected. Output arguments: clusters - A vector of cluster numbers indicating...
d2ed71112e0bf4d8bfeaf6069ef46c7e8b7f4b4a
28,850
import requests def send_mail(email, email_string): """ handles email sending procedures :param email :param email_string :return: """ key = MAILGUN_KEY recipient = email request_url = MAILGUN_URL data = { 'from': MAILGUN_TESTMAIL_ADDR, 'to': recipient, ...
f326585a971c26eda9bf3646298f2523fa166555
28,851
import torch def _relu_3_ramp(x): """ Relu(x) ** 3 ramp function returns f(x) = relu(x) ** 3 df/dx(x) = relu(x) ** 2 """ rx = torch.relu(x) ramp = rx.pow(3) grad = rx.pow(2) * 3.0 return ramp, grad
56dfc37ef81209590e020f0c67f8204a6d8d338a
28,852
def get_ham_ising_tube(dtype, Ly, lam=-3.044): """Return the local term for the 2+1D Ising Hamiltonian on a narrow torus. Defines the global Hamiltonian: $H = -\sum_{\langle i, j \rangle} X_i X_j + lam * \sum_i Z_i ]$ Represents the Hamiltonian for the 2D torus as a 1-dimensional Hamiltonian, where each "si...
f0b0ae303422c52b434a05c97992f9f8793d440f
28,853
def processed_for_entities_query_clause(): """ :return: A solr query clause you can use to filter for stories that have been tagged by any version of our CLIFF geotagging engine (ie. tagged with people, places, and organizations) """ return "(tags_id_stories:({}))".format(" ".join([str(t) for t in ...
31818cd67c4a35b73504f14f11316461086cf58c
28,854
def get_shared_prefix(w1, w2): """Get a string which w1 and w2 both have at the beginning.""" shared = "" for i in range(1, min(len(w1), len(w2))): if w1[:i] != w2[:i]: return shared else: shared = w1[:i] return shared
d52850f038bc6bfe65878e3a58d7009e563af0a0
28,855
async def get_poll_ops(op_type=None, block_range=None) -> Result: """Returns a list of 'polls' ops within the specified block or time range.""" sql = SearchQuery.poll_ops( op_type=op_type, block_range=block_range ) result = [] if sql: res = db.db.select(sql) or [] for...
4b26e411047f46aceb03fc98be1a7ba58da71a07
28,856
def list_of_divisors_v1(n): """Return [ list of divisors ]""" """ This is a slow algorithm. But it is correct. """ if n == 1: return [1] if n == 2: return [1,2] L = {} if n > 0: L[1] = True if n > 1: L[n] = True for i in list_of_prime_factors(n): ...
b017d90fc8744a9607fffadaf2c653762af7c25a
28,857
from typing import Optional import re def get_optimal_train_size( nb_vectors: int, index_key: str, current_memory_available: Optional[str], vec_dim: Optional[int], ) -> int: """ Function that determines the number of training points necessary to train the index, based on faiss heuristics for k-means c...
40d63534cd7e98b2a0e9ad73260fe01d4e4cdd8e
28,858
def _initialize_gui(frame, view=None): """Initialize GUI depending on testing mode.""" if _testing_mode(): # open without entering mainloop return frame.edit_traits(view=view), frame else: frame.configure_traits(view=view) return frame
3b453ccaf4341c610e7efec3494833b1ecde437e
28,859
def average_gradients(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradients. Th...
13b87c518086c838f6134c186c8892596601b741
28,860
def cls_token(idx): """ Function helps in renaming cls_token weights """ token = [] token.append((f"cvt.encoder.stages.{idx}.cls_token", "stage2.cls_token")) return token
7f07ca4fe04326b4895e3fd41a3830dddc147f8a
28,861
def fast_betweenness(G, weight=None, kind = 'edge', norm=True, cutoff=None): """ Gets betweenness centrality. For relativelly large graphs, this func is faster than networkx Parameters ---------- G : NetworkX DiGraph or Graph The graph to be considered. weight: string edge...
e06b9b1fb27f517ab2b90738f831ecc91596b3ef
28,863
def regularizer(regularization_type, regularization_rate, params): """ Our params all have different dimensions. So, we loop through each w or b in our params, apply operation, sum, then use the resulting scalar for the next, final sum in either L1 or L2 regularization """ if regulariz...
f75970411a8d9b479b990aa78083ffd9b54064cf
28,864
import collections def get_eq_crc(devices): """ Builds a CRC string based on device id and device status. This function is reverse engineered and translated to python. It is based on the CoderUtils class in the elro app :param devices: An dictionary of devices statuses, where the id of the device is t...
5288935625bde9e8d4bb1518c1f8fb4ff1ee79a7
28,865
import re def get_hash_for_filename(filename, hashfile_path): """Return hash for filename in the hashfile.""" filehash = '' with open(hashfile_path, 'r') as stream: for _cnt, line in enumerate(stream): if line.rstrip().endswith(filename): filehash = re.match(r'^[A-Za-z0...
8e9e74b5995c4bfa627637e8fd9434c17684e4e9
28,866
def resonance_mass_distributions(axes): """ Verification of mass disributions for several resonance species. Grey dashed lines are the Breit-Wigner distributions with mass-dependent width, grey solid lines are the same distributions with momentum integrated out, and colored lines are histograms of ...
69e6d7166f6f4f0e6f5389835c35f9f2a10d51ff
28,869
import logging def get_logger(): """ Get named logger """ return logging.getLogger(__name__)
b89fe9166f25c6eca03c0f54db2bb5863768fc6d
28,870
def word_match(reg_, str_): """function compares words of equal length Invokes char_match for each character""" if not reg_: return True elif not str_: if reg_ == "$": return True return False if len(reg_) == 1: return char_match(reg_[0], str_[0]) if...
8064fef1d8c9dc4e6353a909b64fa1213bfe9b95
28,871
def fdp_to_model(package, table_name, resource, field_translator): """ Create a Babbage Model from a Fiscal DataPackage descriptor :param package: datapackage object :param table_name: db table name to use :param resource: resource to load (in the datapackage object) :param field_translator: dic...
358540a812707e42c8022dcd8e7349a8fe674dfc
28,872
def PN_gen(N_bits,m=5): """ Maximal length sequence signal generator. Generates a sequence 0/1 bits of N_bit duration. The bits themselves are obtained from an m-sequence of length m. Available m-sequence (PN generators) include m = 2,3,...,12, & 16. Parameters ---------- N...
e3e51fdb6dd88483facb143f7c16b87cfb8ee15e
28,873
def df_to_dataset(df: pd.DataFrame, **kwargs): """ :param kwargs: kwargs are additional keys to pass to `df` For example if kwargs is {'some': 3}, than df gets new column `some` with value set to 3 in every row """ df = df.replace(np.nan, '', regex=True) for key, value in kwargs.items(): ...
d434a7ffe72c6c588a2e9f75d1ad6f8e6e406f0a
28,874
def zstandarization(value, distribution=None): """ Apply a z standarization to the value. Value can be another distribution. """ value = np.array([float(i) for i in value]) if distribution: return (np.array(value)-np.mean(np.array(distribution)))/np.std(np.array(distribution)) else: ...
a54ef1abcf5f49e0aba062712799fa2e3aff6a33
28,875
def _determine_default_project(project=None): """Determine default project ID explicitly or implicitly as fall-back. In implicit case, supports three environments. In order of precedence, the implicit environments are: * GCLOUD_PROJECT environment variable * Google App Engine application ID * ...
6e19df4a15ab323a1858421c8f64d1d8be34d1f3
28,876
def collapse(intlist): """Collapse a list of int values of chars into the int they represent.""" f = '' for i in intlist: f += chr(i) return int(f)
7b92a456e78c8b6d8bbdc5af805b22728865ec63
28,877
import click from typing import Union from typing import Tuple from typing import Dict def _validate_environment_variable( ctx: click.core.Context, param: Union[click.core.Option, click.core.Parameter], value: Tuple[str], ) -> Dict[str, str]: """ Validate that environment variables are set as expe...
1e079a858325bf8ce1d185ad464d6c5c23c0c338
28,879
from typing import Tuple def get_settings() -> Tuple[int, int]: """Gets some settings for the board.""" return board_size, num_ships
2c2d0b35b3f86b8b96148995c46e89fef1573b30
28,880
def run_sunset(): """ Sends a tweet about the sunset and captures image """ tweet_sunset() return run_tweeter()
f8d5bbac93025c4a9f9a04969185aa94e3dc26c0
28,881
import pprint def get_data(): """Get the population data.""" # Construct population pop = CosmicPopulation(n_srcs=SIZE, n_days=1, name='standard_candle') pop.set_dist(model='sfr', z_max=2.5, H_0=67.74, W_m=0.3089, W_v=0.6911) pop.set_dm_host(model='constant', value=100) pop.set_dm_igm(model='i...
038d0292a4d158531461d75ccba3e5baa8e50dbd
28,882
def tag_user(request, tag, username): """ Display all `tag` snippets of `username` user """ user = get_object_or_404(User, username=username) snippets = Snippet.objects.filter(author=user).filter( tags__name__in=[tag, ]).all() return render_to_response('tags/view.html', { 'tag': tag, ...
c492f0ca1933ee3ee9875a1d0586a1dc8735c073
28,885
import warnings def extract_keywords(keywlist_handle): """extract_keywords(keywlist_handle) -> list of keywords Return the keywords from a keywlist.txt file. """ warnings.warn("Bio.SwissProt.KeyWList.extract_keywords is deprecated. Please use the function Bio.SwissProt.KeyWList.parse instead to pars...
4679a2774eed9e40783662312b4b661c91e00f36
28,886
def automated_threshold_setting(image, mask_local_max): """Automatically set the optimal threshold to detect spots. In order to make the thresholding robust, it should be applied to a filtered image (bigfish.stack.log_filter for example). The optimal threshold is selected based on the spots distributio...
7e461e225fe5a1a6c10f673f7096814e10a039ff
28,887
from typing import List def _get_raw_test_commands(name: str) -> List[str]: """テストケースのinclude解決を行っていない状態の生のコマンドを取得する Args: name (str): テストケース名 Raises: Exception: 取得に失敗した場合例外を送出します Returns: List[str]: テストコマンド配列 """ testcase = _get_testcase_object(name) return _con...
fcd70f4013dd26436bce48678c45ea0eccc1a8e6
28,888
import inspect def extract_params(func, standard_args): """Return WhyNot parameters for user-defined function. Performs error-checking to ensure parameters are disjoint from standard arguments and all arguments to the function are either standard arguments or parameters. Parameters ---------...
2080bba7db140fbf4305f9138c39e944740c4c7a
28,889
def lark_to_float_value_node(tree: "Tree") -> "FloatValueNode": """ Creates and returns a FloatValueNode instance extracted from the parsing of the tree instance. :param tree: the Tree to parse in order to extract the proper node :type tree: Tree :return: a FloatValueNode instance extracted from...
34549e1615aa0b33c73de999ee43cbac047aa3ee
28,890
def confusion_matrix(pred, gt, thres=0.5): """Calculate the confusion matrix given a probablility threshold in (0,1). """ TP = np.sum((gt == 1) & (pred > thres)) FP = np.sum((gt == 0) & (pred > thres)) TN = np.sum((gt == 0) & (pred <= thres)) FN = np.sum((gt == 1) & (pred <= thres)) return (...
da79757e54247b1fdcdcc5ddb39262386f1d2cbd
28,891
def do_heatmap(df): """ Make a bottom heatmap """ mask = np.zeros_like(df, dtype=np.bool) mask[np.triu_indices_from(mask)] = True cmap = sns.diverging_palette(220, 10, as_cmap=True) sns.heatmap(df.values.tolist(), yticklabels=df.columns, xticklabels=df.columns, vmin=-1, vmax=1, center=0, ...
99b95c8a2dac1781f84200f9ad8807b35466627b
28,894
from typing import List from typing import Optional from typing import Tuple from typing import Dict from typing import Any def docs2omop( docs: List[Doc], extensions: Optional[List[str]] = None, ) -> Tuple[pd.DataFrame, pd.DataFrame]: """ Transforms a list of spaCy docs to a pair of OMOP tables. ...
d8c1325363aa84b5db00daa575d904ab586d79fa
28,895
def getWebVersion(d): """Get the version from the web of the catalog entry in d Use the page at the url specified in d['version']['url'], and the regular expression specified in d['version']['regex'] to find the latest version number of the passed package. The d['version']['regexpos']'th match of the ...
7a25a09c9e28276f9d7f1218a801cbfe8fd868ed
28,896
def stdev_outliers_proxy(self, *args, **kwargs): """ Calls :meth:`.stdev_outliers` on each table in the TableSet. """ return self._proxy('stdev_outliers', *args, **kwargs)
dd929a3278a0893138b6af801bdd9b1263a5a332
28,897
def load_cells(): """Load cell data. This cell dataset contains cell boundaries of mouse osteosarcoma (bone cancer) cells. The dlm8 cell line is derived from dunn and is more aggressive as a cancer. The cells have been treated with one of three treatments : control (no treatment), jasp (jasplakinol...
2f0dc2aef62d01c863133e1d608b7e2afafea2c1
28,898
def approve_story(story: str): """ Moves a story from the pending file to the story file. :param story: The story to approve. :return: """ pending_data = load_pending_list() story_to_approve = pending_data[story.lower()] del pending_data[story.lower()] update_pending_list(pending_da...
9f8c6f86a983637a4ab6574fa7acf3438d4ad1e3
28,899