content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import random def get_random_string(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'): """ Returns a securely generated random string. The default length of 12 with the a-z, A-Z, 0-9 character set return...
7e113513331a94170948763e15d2de4415eeb0a0
3,616,800
import os import sys def load_cfg(cfg_path): """Load config file""" # Remove a (possible) trailing file-extension from the config path # (importlib doesn't want it) cfg_path = os.path.splitext(cfg_path)[0] try: sys.path.append(os.path.dirname(os.path.realpath(cfg_path))) cfg = impo...
89835b566cf155b9c0523b9fff27a083661dbad1
3,616,801
def chunk_average(epochs): """ Because the number of trials is hugee, ~ 5000, I don't have the patience to wait for the process and the cluster does not have the memory to process such a huge dataset, so I will average every 10 trials to boost the signal-to-noise ratio and decrease the number of t...
377da889f56902cd8db00cd4e610c4936511ad3f
3,616,802
def getField(statefile, fieldname): """ Get field from MITgcm netCDF output statefile : string with /path/to/state.0000000000.t001.nc fieldname : string with the variable name as written on the netCDF file ('Temp', 'S','Eta', etc.)""" StateOut = Dataset(statefile) Fld = StateOut.variables[fieldname][:...
808c302ac0a2daae3d5c11009391bb8bee4fab0c
3,616,803
from typing import List def get_stations_with_n_docks(num: int, stations: List['Station']) -> List[int]: """Return a list containing the station ids for the stations in stations that have at least num docks available, in the same order as they appear in stations. Precondition: num >= 0 >>> get_s...
9e9f1b265dc7721a031369bc996363a5e71629ac
3,616,804
def apply_corrections(fluxes, filters, pd_corrections): """Apply pd correctionst to the fluxes by fitler.""" return np.array([flux*pd_corrections.get(filt, 1) for flux, filt in zip(fluxes, filters)])
1d049fe5187e6c38b1b65ea0e9898e68a97a6178
3,616,805
import os import pickle import json import warnings def read_sim_file(file_path): """Read a sim file. Parameters ---------- file_path : str Path of the file. Returns ------- str, dict, pandas.DataFrame The name, the header and the lcs of the simulation. """ file_...
8ca0e4d673a7b81e7a60766715b6fd8e50b4d5c0
3,616,806
import feedparser # type: ignore def get_posts_details(rss=None): """ Take link of mrss feed as argument """ if rss is not None: # import the library only when url for feed is passed # parsing partner feed partner_feed = partner_feed = feedparser.parse(rss) # getting lists of partner entries vi...
eee63b49ab4cf7c1746b752cb0a436b18fb7201e
3,616,807
import json def _is_json(data): """ Test, if a data set can be expressed as JSON. """ try: json.dumps(data, cls=BlenderEncoder) return True except: print_console('DEBUG', 'Failed to json.dumps custom properties') return False
54453b4e6dafc7d8002206c902d131cee13cec73
3,616,808
def better_repr(v, version): """Work around Python's unorthogonal and unhelpful repr() for primitive float and complex.""" if isinstance(v, float): # float values 'nan' and 'inf' are not directly # representable in Python before Python 3.5. In Python 3.5 # it is accessible via a libr...
30872965790d810d9600819fc2501769d4c61389
3,616,809
def XYZ2Shp(filecsv, t_srs="EPSG:4326", fileout=None): """ XYZ2Shp """ driver = ogr.GetDriverByName('ESRI Shapefile') fileout = forceext(filecsv, "shp") if not fileout else fileout remove(fileout) layername = juststem(fileout) print layername dataset = driver.CreateDataSource(fileout...
5b4c03c34863d1d5ee82bf2f7fbcca8fce4221ad
3,616,810
import copy def __transform_dataframe_to_event_stream_new(dataframe, stream_post_processing=False, compress=False): """ Transforms a dataframe to an event stream Parameters ------------------ dataframe Pandas dataframe stream_post_processing Boolean value that enables the post...
98ca6190434cb68732ee2b554279722b252b1abb
3,616,811
def backward_selection(g, n_, k_=None): """For details, see here. Parameters ---------- g : function n_ : int k_ : int, optional Returns ------- s_star_bwd : list, shape(k_, 1:k_) """ if k_ is None: k_ = n_ # Step 0: Initialize s_star_backw...
cc384b6c6fca68b51d0806c498b0a7328edd2ebd
3,616,812
def auc_score(y_true, y_pred): """Gets the auc score of labels and predictions. Parameters ---------- y_true : torch.tensor The true labels. y_pred : torch.tensor The prediction. Returns ------- numpy.ndarray The auc score. """ y_true, y_pred = prepare...
8e37e1ad60b1593f61d80c88b1fb6f65e5148e9f
3,616,813
def _get_node_names(): """ returns the list of nodes in the cluster :return: the list of nodes in the cluster :rtype: list[str] """ nodes = _get_nodes() node_list = [] for n in nodes: node_list.append(n['name']) return node_list
96a323e6da30c6247d7e53d7306a7d7003f25fb1
3,616,814
import collections def defaultdict(): """defaultdict(...): Dictionary with a value for missing keys.""" kart = collections.defaultdict(lambda: 'unknown') kart['speed'] = 66 return "kart specs are {}".format(''.join( '{} -> {}'.format(key, kart[key]) for key in ('speed', 'sound')))
71f00871b2280ce09581aa90e4645aa0424bf2de
3,616,815
def execute_cast_datetime_to_integer(op, data, type, **kwargs): """Cast datetimes to integers""" return pd.Timestamp(data).value
5448a341adaae6fe58769ef43c5d0da5322aabfd
3,616,816
def ferret_result_limits(efid): """ Abstract axis limits for the shapefile_writeval PyEF """ return ( (1, 1), None, None, None, None, None, )
9e1ef0f1ee1a0126c47e4fa46cbb5c1ee6ed52fb
3,616,817
import warnings def containment(lower_forecast, upper_forecast, actual): """Expects two, 2-D numpy arrays of forecast_length * n series. Returns a 1-D array of results in len n series Args: actual (numpy.array): known true values forecast (numpy.array): predicted values """ with ...
7692a31337705cf5fafc9f3efb664be41e7678b7
3,616,818
def _normalize_newlines(text: str) -> str: """Normalizes the newlines in a string to use \n (instead of \r or \r\n). :param text: the text to normalize the newlines in :return: the text with the newlines normalized """ return "\n".join(text.splitlines())
6b53b42e8cec72a8e63ec0065776f47de2fba835
3,616,819
def getAxlib(libPath=None): """Return the handle to the axon library (CLibrary instance). If libPath is specified, then it must give the location of the AxMultiClampMsg.dll file that should be loaded. Otherwise, a predefined set of paths will be searched. Note: if you want to specify the DLL file usin...
365cd4a57036cc936b27030c2c07bec36c48a171
3,616,820
def create_stanford_article_level_model(rnn_type, embedding_matrix, sentence_size, hidden_size, dense_size, trainable=False, use_dropout=True, dropout=0.5): """ Create RNN model :param rnn_type: :param hidden_size: :param dense_size: :return: """ # Model model = Sequential() # E...
e611441a5c8c14ce23425bba03fb1078be13debc
3,616,821
import requests, json def backdoor(request, userid=None, view=None, list=None): """Provide simple client interface in Django backend.""" if not userid: user = None # perhaps there is no user yet username = request.GET.get('user', 'test001') # default: test001 originname = request.GE...
10b89eb502aaefde4970c4fbc8c19d041f1d22bf
3,616,822
def read_words(f, count=100, encoding="utf-8"): """Reads the given number of words from the specified open file.""" result = [] while len(result) < count: line = wrapped_readline(f, encoding=encoding).strip() words = [w.strip() for w in line.split(" ")] # remove empty words w...
2d6d2a5cd086e1ccdb4ba3035f660597e098e62b
3,616,823
def create_tvshow_tiles_content(tvshows): """ The HTML content for this section of the page """ content = '' for tvshow in tvshows: # Extract the youtube ID from the url youtube_id_match = re.search(r'(?<=v=)[^&#]+', tvshow.trailer_youtube_url) youtube_id_match = youtube_id_match...
9bfe36740497f70e37ad525cb0fefe06180ea419
3,616,824
def pick_from_greatests(dictionary, wobble): """ Picks the left- or rightmost positions of the greatests list in a window determined by the wobble size. Whether the left or the rightmost positions are desired can be set by the user, and the list is ordered accordingly. """ previous = -100 is...
52685877620ab7f58a27eb6997ec25f3b499e3a4
3,616,825
from typing import Iterable import os def resolve_sources(directory: str, sources: Sources) -> Iterable[str]: """ Returns an iterable of absolute paths to the files specified by the sources object. Files are not guaranteed to exist. """ filesystem = get_filesystem() result = {os.path.j...
831383b42a658287a4f555c27f1eddcde6399794
3,616,826
def replace_layer(model, layer_name, replace_fn): """Replace single layer in a (possibly nested) torch.nn.Module using `replace_fn`. Given a module `model` and a layer specified by `layer_name` replace the layer using `new_layer = replace_fn(old_layer)`. Here `layer_name` is a list of strings, each string ...
2e0ee082d6ab8b48979aa49e303a0e12583812b7
3,616,827
def create_html_output(json_docs): """Create html output for the playbook by converting the docs to markdown and then converting to html.""" markdown_docs = create_markdown_output(json_docs) return markdown.markdown(markdown_docs)
0c59d85a06a9d8c842eaee16ec5b50dd5a7507b4
3,616,828
def has_name_pf(name_p, ignore_case=True): """ Predicate factory, returns true if the element name matches the pred parameter * **name_p**: something that can be converted into a string compare predicate * **ignore_case**: should the comparison be case sensitive (default: ignore case) * **return**:...
0392820f5ec7f0540f0eb4f0fbff1f9bf00bd28f
3,616,829
def genInvSBox( SBox ): """ genInvSBox - generates inverse of an SBox. Args: SBox: The SBox to generate the inverse. Returns: The inverse SBox. """ InvSBox = [0]*0x100 for i in range(0x100): InvSBox[ SBox[i] ] = i return InvSBox
8ddf7e338e914f6cb6c309dc25705601326160c0
3,616,830
def get_unassigned(values:dict, unassigned:dict): """ Select Unassigned Variable It uses minimum remaining values MRV and degree as heuristics returns a tuple of: unassigned key and a list of the possible values e.g. ('a1', [1, 2, 3, 4, 5, 6, 7, 8, 9]) """ values_sort = dict() # em...
32ff78f7a6443bfbf4406c420ba87e254e88d5c3
3,616,831
def countvec(): """ 对文本进行特征值化 :return: None """ # 实例化CountVectorizer vector = CountVectorizer() # 调用fit_transform输入并转换数据 # res = vector.fit_transform(["life is short,i like python","life is too long, i dislike python"]) res = vector.fit_transform(["人生苦短,我喜欢python","人生漫长,不用python"])...
c0756a9a072296e6d78001deb55d51cc9de5bf15
3,616,832
def get_auth_token_ssh(account, signature, appid, ip=None): """ Authenticate a Rucio account temporarily via SSH key exchange. The token lifetime is 1 hour. :param account: Account identifier as a string. :param signature: Response to challenge token signed with SSH private key as a base64 encoded...
5ca3b104b0b84bfdbd0df16e349325835970667f
3,616,833
def is_superset_of(value, superset): """Check if a variable is a superset.""" return set(value) <= set(superset)
8b40089430dedef72566e93eb551b35001ec2e96
3,616,834
import requests def _poll_for_status(client_id, device_code): """Polls API to see if user entered the device code This is the second step of the Device Flow. Returns an access token, and also writes the token to a file in the user's home directory. """ header = {"Content-Type": "application/json...
698e21be730a767f604a8be07d73799d8658f028
3,616,835
from datetime import datetime def datetime_to_year(dt: datetime) -> float: """ Convert a DateTime instance to decimal year For example, 1/7/2010 would be approximately 2010.5 :param dt: The datetime instance to convert :return: Equivalent decimal year """ # By Luke Davis from https://st...
5f4ae29d57d13a344e70016ab59dbc0a619db4d8
3,616,836
import struct def read_track(chunk): """Retuns a list of midi events and tempo change events""" # Deviations: The running status should be reset on non midi events, but # some files contain meta events inbetween. # Offset and time signature are not used. tempos = [] events = [] deltasum...
74340ef030a7325e904df2402d9c862371f57e32
3,616,837
def are_adjacent_empty(positions, seats): """Check if all seats from the positions are not OCCUPIED.""" return all( seat != OCCUPIED for seat in get_seats(positions, seats) )
9c14377a658ffd2d6ba04780fd2f407e1d338feb
3,616,838
def one_component_ejecta_relation(time, redshift, mass_1, mass_2, lambda_1, lambda_2, kappa, **kwargs): """ Assumes no velocity projection in the ejecta velocity ejecta relation :param time: observer frame time in days :param redshift: redshift :param mass_1: mass ...
8a4317b0fa7e33e269c4a17e74b711755a5d452b
3,616,839
import json def uhs500_msg_parsed() -> Message: """Expected :class:`~tslumd.messages.Message` object matching data from :func:`uhs500_msg_bytes` """ data = json.loads(MESSAGE_JSON.read_text()) data['scontrol'] = b'' displays = [] for disp in data['displays']: for key in ['rh_tally'...
15a45da5809d29184456959adffbdbbef311c33b
3,616,840
from typing import List def brute_force_matchings(graph: Graph, partial_matchings: List[Matching]) -> List[Matching]: """Recursive algorithm for brute force maximum matching search""" if len(graph.get_edges()) == 0: return partial_matchings updated_matchings = [] for edge in graph.get_edges():...
3f2bb71a70f2883821b48d69b1128a8f795f9242
3,616,841
def status_check(request): """ JSON response for health checks. """ # because the argument is framework we will ignore # pylint: disable=unused-argument resp = {'status': 'up'} return JsonResponse(resp)
ead0070f454b3233a9f3deb3092feae19de19c5f
3,616,842
def ek_R56Q(cell): """ Returns the R56Q reversal potential (in mV) for the given integer index ``cell``. """ reversal_potentials = { 1: -96.0, 2: -95.0, 3: -90.5, 4: -94.5, 5: -94.5, 6: -101.0 } return reversal_potentials[cell]
a61d33426e4c14147677c29b8e37381981f0d1db
3,616,843
def _get_schema(cur: pyodbc.Cursor, table_name: str): """Get schema and table name - returned as tuple """ t_spl = table_name.split(".") if len(t_spl) > 1: return t_spl[0], ".".join(t_spl[1:]) else: return _get_default_schema(cur), table_name
84f25b43f1f1c0707725c2ec64540f1f1348e427
3,616,844
def poincare_tiling(p, q, nlayers, center): """ produce poincare regular tiling p : number of edges per face q : number of faces meeting at a vertex nlayers : number of layers or rings of faces """ max_faces = count_faces(p, q, nlayers) edges_out = [] verts_out = [] faces_out =...
cce0fb8f5f0d12e8fbdb524129e960ce1705f974
3,616,845
def magenta_on_white(string, *funcs, **additional): """Text color - magenta on background color - white. (see sgr_combiner()).""" return sgr_combiner(string, ansi.MAGENTA, *funcs, attributes=(ansi.BG_WHITE,))
53c230bc90442749c5d372f2a50ebf5154e6d90c
3,616,846
import six import re def build(directory, name): """ Build an image using a Dockerfile at a specific path using the full name to tag the resulting image. Arguments: directory (str): The directory containing the Dockerfile for the distribution. name (str): The full name of ...
f5699d7ca0ce4f8d5e7de7ded4e2f30d29a70dc5
3,616,847
import sys def command_validate(opts): """Check a .zs file for errors or data corruption. Usage: zs validate [-j PARALLELISM] [--] <zs_file> Arguments: <zs_file> Path or URL pointing to a .zs file. An argument beginning with the four characters "http" will be treated as a URL. Options: -j P...
f990a3a1964de1ae7f8d9b84d79ecb4ba604e88f
3,616,848
def deriv_activation_func(func_type, z): """ Implements the different kind of derivated activation functions including: line - linear function sigm - sigmoidal tanh - hyperbolic tangent ptanh - smothly hyperbolic tangent relu - Rectfied step - Heavside (binary ste...
1d18fe4df9ca7ef63f381581f466450355d20607
3,616,849
def createStringMacroseismicHeader(header): """ Function that creates NordicMacroseismic list with values being strings :param str header: string from where the data is parsed from :return: NordicMacroseismic object with list of values parsed from header """ nordic_macroseismic = [None]*22 ...
2d651e77ed0abc56116178afbab01cdb35088d18
3,616,850
def code_search(ea, val): """Search forward for the next occurance of val. Return None if no match.""" res = idc.FindBinary(ea, idc.SEARCH_DOWN, val) if res == idaapi.BADADDR: return None else: return res
14b1ca9156bd081c289e78d3145ed7cb947f79c9
3,616,851
def buffer_input(data, buffer, input_data): """Repeats last search with 'input_data' as regexp.""" try: cmd_grep_stop(buffer, input_data) except: return WEECHAT_RC_OK if input_data in ('q', 'Q'): weechat.buffer_close(buffer) return weechat.WEECHAT_RC_OK global search...
51999ff6ed463b0033cc3e3ab19951199b4d7945
3,616,852
def read_input_files(input_file: str) -> list[Seat]: """ Extracts a list of valid passwords from the input file. """ with open(input_file) as input_fobj: seats = [Seat.from_binary_partition(line.strip()) for line in input_fobj] return seats
d56c78c330be9189e83dcb1cbb3baf690d806529
3,616,853
import re import json def mediapackage_channel_mediapackage_endpoint_ddb_items(): """ Identify and format MediaPackage channel to MediaPackage endpoint connections for cache storage. """ items = [] package_key = re.compile("^(.+)Package$") try: # get mediapackage channels media...
da94679df115fda6fc2dbb30e739b921f681afd4
3,616,854
def reinsert_star(seq, gapped_seq): """ Reinserts '*' at end of gapped alignment to make finding the end of the aligned portion more accurate """ length = len(seq) count = 0 for i in range(len(gapped_seq)): if gapped_seq[i] == seq[count] and count == 0: start = i ...
f4ef9428f023d655f43ca50582d3af61bddfe27e
3,616,855
def _functional_groups_stable(geo, thy_save_fs, mod_thy_info): """ look for functional group attachments that could cause molecule instabilities """ # Initialize empty set of product graphs prd_gras = () # Check for instability causing functional groups gra = automol.geom.graph(geo) ...
6f826ccf1f551f775b5bb61b8e5157e73724363a
3,616,856
from typing import Callable from typing import List def get_table_reader() -> Callable[[Engine, Table], List[dict]]: """ When syncing from a relational database, currently MySQL or Postgres, the database has only a single concept of state, that is the current state. We simply capture this state by readin...
d7d5c6349da5a779f1d8495b0851ef42fbf1fe00
3,616,857
def scene_to_raster(scene): """Convert scene to a integer array height x width containing color codes. """ pixels = simulator_bindings.render(serialize(scene)) return np.array(pixels).reshape((scene.height, scene.width))
f4db88f58398228e58cca9dbf0662b3c0ecd89c8
3,616,858
import os def _GetGitOrigin(path): """Returns the URL of the 'origin' remote for the git repo in |path|. Returns None if the 'origin' remote doesn't exist. Raises an IOError if |path| doesn't exist or is not a git repo. """ section = None for line in open(os.path.join(path, '.git', 'config'), 'rb'): m...
633a6361e26d8d803b92ddef7aca1537b1241168
3,616,859
def gtk_menu_position(event, *args): """ Create a menu at the given location for an event. This function is meant to be used as the *func* parameter for the :py:meth:`Gtk.Menu.popup` method. The *event* object must be passed in as the first parameter, which can be accomplished using :py:func:`functools.partial`. ...
2670b4c2b3f5d7ad7fa74a836ec1b918a724c436
3,616,860
def mm2cm(v): """ Converts value from mm to cm Parameters ---------- v: value input value, mm returns: value in cm """ if np.isnan(v): raise ValueError("mm2cm", "Not a number") return v * 0.1
302377993307dbaa6011281b96a71d969c692579
3,616,861
import torch def ssim(x, y): """Calculate ssim value of x (3D) in respect to y (3D). :param x: preprocessed predicted tensor (3D) :type x: torch.Tensor :param y: preprocessed groundtruth tensor (3D) :type y: torch.Tensor """ # pre-computation C1 = (0.01 * 255) ** 2 C2 = (0.03 * 25...
e94d4565f694ecdc8f7e72f692861b9982e66b11
3,616,862
import math def draw_star (im, yc, xc, radius, npoints, inner_radius=None, v=max_image_value, fast=False, fill=False): """ Draw an npoints-pointed star of radius r centred at (yc, xc). Arguments: im image upon which the text is to be written (modified) yc y-va...
75193ebb73be3ab5f7c59d28fcacca9ceb5bf45f
3,616,863
from typing import Any import websockets import json async def songdb(timeout: int = config.TIMEOUT) -> Any: """ 返回 ``song_id`` - 歌名(en|jp) 的字典表 """ async with websockets.connect(config.ESTERTION_URI, timeout=timeout) as ws: await ws.send('constants') r = await ws.recv() await ...
ecd751de2ad1940a7623b46bcf86d1edb16e62b0
3,616,864
def imagenet_resnet_v2_generator(block_fn, layers, num_classes, data_format=None): """Generator for ImageNet ResNet v2 models. Args: block_fn: The block to use within the model, either `building_block` or `bottleneck_block`. layers: A length-4 array denoting the number of blocks to include in each ...
8d5f7ff0c19b6aa8ae88a1954759b26406c16603
3,616,865
import re def get_api_url(request_object, production=False): """ Get api URL and PORT Usefull to handle https and similar unfiltering what is changed from nginx and container network configuration Warning: it works only if called inside a Flask endpoint """ api_url = request_object.url_root...
b8c9850e8379f1d49c717ecf11a2b135c2eeb88c
3,616,866
from typing import List from typing import Dict def get_group_of_dependent_blocks(blocks: List[BuildingBlock]) -> Dict[int, int]: """ Building blocks can be categorized into groups. Blocks that follow each other in the graph (that is, they are connected by one edge) belong to the same group. :param: ...
042b69f9b224c0451a4b81e8567151c837fe5301
3,616,867
def eval_data(dataset): """ Given a dataset as input returns the loss and accuracy. """ # If dataset.num_examples is not divisible by BATCH_SIZE # the remainder will be discarded. # Ex: If BATCH_SIZE is 64 and training set has 55000 examples # steps_per_epoch = 55000 // 64 = 859 # num_ex...
cfcba534913936ba66bb0cd7002e7400383cd42b
3,616,868
def list_blobs(bucket_name): """Lists all the blobs in the bucket.""" # bucket_name = "your-bucket-name" storage_client = storage.Client() # Note: Client.list_blobs requires at least package version 1.17.0. blobs = storage_client.list_blobs(bucket_name) return [i.name for i in blobs] # for...
fe6e4e9d9b5ff73e43c1079d3b0a1decfcf9fafe
3,616,869
def valid_header(header: BlockHeader, difficulty: int) -> bool: """Check if block hash matches header data.""" h = hash.hash(header['timestamp'] + header['previous_hash'] + header['nonce'] + header['merkle_root']) return (header['this_hash'] == h and ...
8b457ec85d25bd965f27c2e55bd5078597d24395
3,616,870
def poisson_gamma(data, sum_w, sum_w2, a=1, b=0): """ Log-likelihood based on the poisson-gamma mixture. This is a Poisson likelihood using a Gamma prior. This implementation is based on the implementation of Austin Schneider (aschneider@icecube.wisc.edu) -- Input variables -- data = data histogram ...
f4d71aca26e262b127baa62526f8a6d85a6a11ea
3,616,871
def a_coreProperties(): """Syntactic sugar to construct a CT_CorePropertiesBuilder instance""" return CT_CorePropertiesBuilder()
4088d48518988df15daa883c310bbfb3ad1ec59b
3,616,872
import copy def model_builder(features, labels, mode, params, config, output_type=ModelBuilderOutputType.MODEL_FN_OPS): """Multi-machine batch gradient descent tree model. Args: features: `Tensor` or `dict` of `Tensor` ...
144432534e21074d6f9f87a00962fa8e0845e2f1
3,616,873
def dmax_curve_z(tddose, shot_y, shot_z): """ Return dmax Z curve for a shot Parameters ---------- tddose: 3ddose object contains dose and boundaries, possible symmetrized shot_y: float Y shot position, mm shot_z: float Z shot position, mm returns: tuple of a...
d557e59a896a88dac9a572e6f35793cae7207dae
3,616,874
import os import json def get_erc20_tokens() -> pd.DataFrame: """Helper method that loads ~1500 most traded erc20 token. [Source: json file] Returns ------- pd.DataFrame ERC20 tokens with address, symbol and name """ file_path = os.path.join( os.path.dirname(os.path.abspat...
bb73ffaeaceca1f41381e93bb2118b45d9c87627
3,616,875
def _2samp_rotate(sim, x, y, p, degree=90, pow_type="samp"): """Generate an independence simulation, rotate it to produce another.""" angle = np.radians(degree) data = np.hstack([x, y]) same_shape = [ "joint_normal", "logarithmic", "sin_four_pi", "sin_sixteen_pi", ...
f0c4a7f5e4e72327359ca51962e554690b0e8e7a
3,616,876
import re def _sort_nd2_files(files): """ The script used on the Nikon scopes is not handling > 100 file names correctly and is generating a pattern like: ESN_2021_01_08_00_jsp116_00_P_009.nd2 ESN_2021_01_08_00_jsp116_00_P_010.nd2 ESN_2021_01_08_00_jsp116_00_P_0100.nd2 ESN_...
17a034323412174beab3fd9cfb23e315a26d4d5a
3,616,877
def trending_up(df: pd.Series, period: int) -> pd.Series: """returns boolean Series if the inputs Series is trending up over last n periods. :param df: data :param period: range :return: result Series """ return pd.Series(df.diff(period) > 0, name="trending_up {}".format(period))
187dbee151d927828d1d17c02ebbb3bb079f6c0d
3,616,878
def get_maxtarget(pairs): """ This method looks at a set of (before_label, after_label) tuples. There are a few informative statistics from this set. - proportion of changed labels: P(before_label != after_label) - maximum proportional class gain: max_i(P(before_label != after_label AND after_l...
6c1bbaa5630f455e2e10169fdcd84f9cb01eb4c6
3,616,879
def _get_formats(region=None): """Return the formats for the region.""" if region: region = _clean_region(region) if region not in _number_formats_per_region: raise InvalidComponent() return [_number_formats_per_region[region]] return _number_formats_per_region.values()
f4962a46f1786bbc97a5991b5749e993efaac814
3,616,880
def jsonCatalog(): """ The function that returns a JSON format output that contains all database data. Including all categories and all items. """ output = {} # Get all the categories from the database categories = session.query(CatalogCategory).all() for category in categories: ...
c7e22fa205bf648b5e6d830946317d6cf73afce1
3,616,881
import types def argmax(values: np.ndarray) -> types.Action: """Argmax with random tie-breaking.""" check_numerics(values) max_value = np.max(values) return np.int32(np.random.choice(np.flatnonzero(values == max_value)))
9cf697e375c1e4ba8d4e8605344bf03955cf272b
3,616,882
def html_parser(): """ Create an HTML5 parser. """ return HTMLParser(strict=True)
0521cc74ae64d592d436a563cafb698fec1d8a69
3,616,883
from sys import path from sys import stderr def main() -> int: """Entry point function.""" argument_parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter) argument_parser.add_argument("INPUT") argument_parser.add_argument("-o", "--output", default="a.dbg") argument_parser.add_argu...
009fcda438b054aa8786340860449dc565562560
3,616,884
def _crop_shape(shape): """Calculates a new, smaller shape after cropping. Args: shape: A shape. Returns: A shape. """ return [int(CROP_RATIO * shape[0]), int(CROP_RATIO * shape[1]), shape[2]]
6e329aa2f37638994d772926b826ed4cc9702e80
3,616,885
def app_context(): """Get app context for tests :return: """ return app.app_context()
ebb9160362c73876631745c9b66ed5d03a84e313
3,616,886
import scipy def fit_linear_least_squares(X, y, weights=None): """Fit linear model Returns ------- coefs : array XXinv : array Inverse of (X*transpose(X)), or None if system is not full rank """ num_coefs = np.size(X,1) if weights is not None: rtw = np.diag(np.sqrt(wei...
bd193b6e6b6a130782af2e9803a0d4f5636d7c4e
3,616,887
def dmp_rem(f, g, u, K): """ Returns polynomial remainder in ``K[X]``. **Examples** >>> from sympy.polys.domains import ZZ, QQ >>> from sympy.polys.densearith import dmp_rem >>> f = ZZ.map([[1], [1, 0], []]) >>> g = ZZ.map([[2], [2]]) >>> dmp_rem(f, g, 1, ZZ) [[1], [1, 0], []] ...
8c03d5d2e5e110c0a323ba1997a4ad2ab1882231
3,616,888
import os def post_process_slides_output(file, pdf, python, slides, exc=True, nblinks=None, fLOG=None, notebook_replacements=None): """ Processes a :epkg:`HTML` file generated from the conversion of a notebook. @param file ...
507a2af99e349bbd156dc19a5e848df3adf2e838
3,616,889
def find_data(*args): """find_data(ea_t ea, int sflag) -> ea_t""" return _idaapi.find_data(*args)
7181f508d09e980c1d8d13b76e6a570eca1a66f1
3,616,890
import array def a_starify(search_map: array): """Beings an a-star search through the input numpy array. :param search_map: Input numpy array. :return: """ end_point = (search_map.shape[1] - 1, search_map.shape[0] - 1) start_node = Node(0, 0, None, 0, end_point[0], end_point[1]) heap = []...
d025f333402a574ef7916c83a30583dd9c750b4f
3,616,891
from bs4 import BeautifulSoup def parse_search_article_result(html): """ 解析一页搜索结果中所有的微信文章条目,包括文章标题、摘要、时间、文章来源 :param html: :return:list """ soup = BeautifulSoup(html, 'html.parser') ul = soup.find('ul', attrs={'class': 'news-list'}) res = list() for li in ul.find_all('li'): ...
ce293b1e78b174a5343417e40cf5285f9cd46464
3,616,892
def generate_ground_image(height, width, focal, principal_point, camera_rotation_matrix, camera_translation_vector, ground_color=(0.43, 0.43, 0.8)): """Generate a...
31ff3b82132e7bf56b0a1347c78b8ea9223833bc
3,616,893
import codecs def get_config(p): """Reads a config file. :return: dict of ('section.option', value) pairs. """ cfg = {} parser = ConfigParser() parser.readfp(codecs.open(p, encoding='utf8')) for section in parser.sections(): for option in parser.options(section): typ...
983ff3363e0b0f6d0e2d7f9f516d484849718d56
3,616,894
def process_key(key): """ 返回32 bytes 的key """ if not isinstance(key, bytes): key = bytes(key, encoding='utf-8') if len(key) >= 32: return key[:32] return pad(key, 32)
39fcab8fe8bb18014307d86432b3bc22c40107bf
3,616,895
def dobro(valor=0, formatc=False): """ -> Dá o dobro de um valor. Parâmetros opcionais :param valor: Valor que será dobrado. :param formatc: Booleano que indica se a formatação no valor será feita :return: Valor dobrado com a formatação ou não. """ res = valor * 2 return res if not f...
dcb79b83a8e347d2fa77d1ee65756f9eedf3c301
3,616,896
def _suppression_polynomial(halo_mass, z, log_half_mode_mass, c_scale, c_power): """ :param halo_mass: halo mass :param z: halo redshift :param log_half_mode_mass: log10 of half-mode mass :param c_scale: the scale where the relation turns over :param c_power: the steepness of the turnover ...
e0d72ae6c092ff01864cfb74d18143b070f075c9
3,616,897
import networkx as nx import warnings def patch_nx(): """Temporary fix for NX's watts_strogatz routine, which has a bug in versions 1.1-1.3 """ # Quick test to see if we get the broken version g = nx.watts_strogatz_graph(2, 0, 0) if g.number_of_nodes() != 2: # Buggy version detected. C...
26c2a567a27b2111f23e05b6036bbae0d623fd30
3,616,898
import torch def KLDiv_loss(x, y): """Wrapper for PyTorch's KLDivLoss function""" x_log = x.log() return torch.nn.functional.kl_div(x_log, y)
e288c3e60fab90a30693b6d5856bd2964f421599
3,616,899