content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def increase_brightness(img, value=30):
"""Increase image brightness by increase V channel of HSV"""
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)
lim = 255 - value
v[v > lim] = 255
v[v <= lim] += value
final_hsv = cv2.merge((h, s, v))
img = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)
retu... | 1e4eae5f41e5a88dda476adcd6cedd0042d6fb19 | 70,500 |
def logbasechange(a,b):
"""
There is a one-to-one transformation of the entropy value from
a np.log base b to a np.log base a :
H_{b}(X)=np.log_{b}(a)[H_{a}(X)]
Returns
-------
np.log_{b}(a)
"""
return np.log(b)/np.log(a) | 3acdc740ec076ac6614f3fefee67523c98643031 | 70,501 |
def discount_arpu(arpu, timestep, global_parameters):
"""
Discount arpu based on return period.
192,744 = 23,773 / (1 + 0.05) ** (0:9)
Parameters
----------
arpu : float
Average revenue per user.
timestep : int
Time period (year) to discount against.
global_parameters : d... | 591051e285a4b6c5fa8ffd5db81c52e162985289 | 70,502 |
def build_cnn(image_input, image_output, tag_size):
"""
Implement a cnn to embed the images in relation to their tags. For a walkthough
on how to build cnns, please refer to this tensorflow tutorial:
https://www.tensorflow.org/versions/master/tutorials/mnist/pros/index.html#build-a-multilaye... | f55f07e2a6d228a56db7233d6427fb9c4a8b6809 | 70,503 |
import types
from typing import Tuple
from typing import Callable
def init(
typingctx: Context,
inst_typ: types.ClassInstanceType,
user_data: types.Integer,
) -> Tuple[
Signature,
Callable[[BaseContext, Builder, Signature, Tuple[Value, Value]], None],
]:
"""Initialize a `jitclass` by calling i... | 1eb481e659a102fbffdc072311fd856d6c9e038d | 70,504 |
def load_objects(file_name, layer_name, first_gid):
""" loads tiles in object layer from a tmx file.
Returns list of Item objects """
tree = ET.parse(file_name)
root = tree.getroot()
for child in root.findall("objectgroup"):
name = child.get("name")
if name == layer_name:
... | c0dbf51db828e29562d249ff545d2e29adad1fd4 | 70,505 |
from web import morguefile
def morguefile(query, n=10, top=10):
""" Returns a list of colors drawn from a morgueFile image.
With the Web library installed,
downloads a thumbnail from morgueFile and retrieves pixel colors.
"""
images = morguefile.search(query)[:top]
path = choic... | eb89a92ab047ce9f14e230c485fa07fde9ca5024 | 70,506 |
def to_sequence(value: list, shape: list, dtype: DType) -> Tensor:
""" Convert `VALUES` result from RedisAI to `Tensor` """
dtype = DType.__members__[dtype.lower()]
convert_to_num(dtype, value)
return Tensor(value, tuple(shape), dtype, 'VALUES') | b1df3fcb91fd3c7085e93038c2a819dd69ecd5d7 | 70,507 |
import asyncio
async def vif_list(cluster_id: str):
"""Get All from Storage Repos"""
try:
session = create_session(
_id=cluster_id, get_xen_clusters=Settings.get_xen_clusters()
)
vifs = VIF.get_all(session=session)
__santilized_vifs = await asyncio.gather(*[serial... | d632678c580b809f98f2dad91c70e8db254c0795 | 70,508 |
def transform_url(private_urls):
"""
Transforms URL returned by removing the public/ (name of the local folder with all hugo html files)
into "real" documentation links for Algolia
:param private_urls: Array of file links in public/ to transform into doc links.
:return new_private_urls: A list of do... | 17a5c720103294b7535c76d0e8994c433cfe7de3 | 70,509 |
def query_store(request, store_name, query):
"""Queries the store; Returns the result of the query in the form of:
[
{
"oid": <document_id>,
"data": <document_data>,
},
...
]
Keyword arguments:
request -- Django HttpRequest object
store_name -- th... | 5190a2a10bbea6212b26c16066bda0392600c517 | 70,510 |
def gene_MOMA(model, reference=None, constraints=None, reactions=None, solver=None):
""" Perform a gene-wise version of MOMA.
This method minimizes the metabolic adjustment at gene level (rather than reaction level).
It is also possible to introduce constraints directly at gene level as well.
Notes:
... | a2341ab7b327b66d39c28dfa4e82d678a12b2436 | 70,511 |
def _3dsmax_main_window():
"""Return 3dsmax's main window"""
return MaxPlus.GetQMaxMainWindow() | ddf7141a6a08bf44c4438307ff601028105d23a6 | 70,512 |
def hash_nc(data, len=None):
"""Returns a non-cryptographic MD5 hash encoded in base32
Args:
data (AnyStr): Data to hash
len (int, optional): Hash length. Defaults to None.
Returns:
str: Hash
"""
# TODO set md5 usedforsecurity to False when updating to Python 3.9
out =... | 8634d3ba8684cf3b1edf3d3a7f9c91adfb476dc5 | 70,513 |
def artigos(root):
"""
Adiciona tag aos cabeçalhos de colunas de DataFrame definidos.
Caso os cabeçalhos não sejam declarados, todos receberam a tag.
Parameters
----------
DataFrame : pd.DataFrame
DataFrame
tag : str
objeto root devolvido pela função lerXML()
colunas : list
Colunas ... | 81ecfc359e23eb232ba0d61adc5ae6fdb99660cb | 70,514 |
def one_hot(x, n_classes=None):
"""
Returns one_hot encoding of the input vector
Parameters
- x: t.tensor, size=[n], dtype=t.long, integer values range [0, n_classes)
- n_classes: number or None. if None, this value is determined automatically
Returns: t.tensor, size=[n, n_classes], ... | 730103dc166ef5e59c58ecab553a17455c766fc3 | 70,515 |
def get_settings():
"""Expose the settings
:return: Return the settings
:rtype: Settings
"""
return Settings() | 09bd14525d059a9c42cc7c08a5eafa6894fa1286 | 70,516 |
from typing import Dict
from typing import Optional
from typing import Any
from typing import Union
def test_logger_after_fit_predict_test_calls(tmpdir):
"""Make sure logger outputs are finalized after fit, prediction, and test calls."""
class BufferLogger(LightningLoggerBase):
def __init__(self):
... | dab1944789be3eaca8ef5641a5fd2e82d74b8b9d | 70,517 |
def calc_value_counts(
a_gpu, stride, min_value, data_points, custom_binning=False
):
"""
description:
main function to calculate histograms
input:
- a_gpu: gpu array(cuda ndarray) -> 1-column only
- bins: number of bins
output:
frequencies(ndarray), bin_edge_values(n... | c9281828c7db63086fd461d1636df85c27983c7a | 70,518 |
def subscribe_vk():
"""Function for enable subscribe news by vk"""
try:
if 'status' in request.form:
session = create_session()
status = request.form.get('status')
status = bool(int(status))
user = session.query(User).get(current_user.id)
if no... | 073b284eca619cfe6403bcc34b59286862313113 | 70,519 |
def get_scheduler(optimizer, opt):
"""Return a learning rate scheduler
Parameters:
optimizer -- the optimizer of the network
opt (option class) -- stores all the experiment flags needs to be a subclass of BaseOptions.
opt.lr_policy is the name of learnin... | f03bc50eb5e27d2f28a28d82e30e6471f49ffec5 | 70,520 |
def send_feedback_email_task(message):
"""sends an email when feedback form is filled successfully"""
logger.info("Sent feedback email")
#return send_feedback_email(email, message)
print("got %s" % message)
return message | bbc96b60124369ae284fd899c09a654e5c0eaba5 | 70,521 |
def mcat(i):
"""Concatenate a list of matrices into a single matrix using separators
',' and ';'. The ',' means horizontal concatenation and the ';' means
vertical concatenation.
"""
if i is None:
return marray()
# calculate the shape
rows = [[]]
final_rows = 0
final_cols = ... | 238218c7fc63c555a7ef033132eae5eddc52fd80 | 70,522 |
def isolated_recovery_rate_80():
"""
Real Name: b'isolated recovery rate 80'
Original Eqn: b'Isolated 80*(1-fraction of critical cases 80)/isolation duration 80'
Units: b'person/Day'
Limits: (None, None)
Type: component
b''
"""
return isolated_80() * (1 - fraction_of_critical_cases_... | 43ce6d43fd7b1dc27e8dd30ccfe615f7ea318f3f | 70,523 |
def setup_reports_close_tab(qtbot):
"""Set up reports widget, witha handy function to close tabs."""
reports = setup_reports(qtbot)
def close_tab(index):
"""Find the close button and click it."""
for i in [0, 1]: # LeftSide, RightSide
close_button = reports.tabs.tabBar().tabBut... | 370a42260daa04ea901d02b8f645e5f6a9687f23 | 70,524 |
def get_localization_metrics(true_pos, largest_dip_pos):
"""Helper to get accuracy and point spread
Accuracy: Euclidean distance between centroid of top n dipoles and the true
center of activation.
Point Spread: Average Euclidean distance between each of the top n dipoles
and the true cente... | 1219522189c9126320c9b4fb287eee92cb775566 | 70,525 |
def checkinGraph(node_to_check, graph_to_check_in):
"""
Checks for teh nnode in the graph, by looking at all the
keys / parent nodes
:param node_to_check: The node to check for
:type node_to_check: Node type
:param graph_to_check_in: The graph to check in
:ty... | f9a4ffb384bfbe1a7dab05929971ce8142dbe9d4 | 70,526 |
import html
def score_wrapper(log, markup=False):
"""Determine the type of log file and passes the log to the appropriate logchecker."""
try:
analyze_log(log)
except UnrecognizedException as exception:
log.unrecognized = str(exception)
log.full_contents = [html.escape(line) for li... | 5f848270e73b23d4591f259ad0aabb2718fdb89a | 70,527 |
import os
import argparse
def _dependent_globals(this_script, cwd=os.curdir):
"""Compute set of related globals that depend on this script's path."""
script_dir = os.path.dirname(this_script)
# This script lives under 'build/rbe', so the path to the root is '../..'.
default_project_root = os.path.rea... | 392452de8f0e591c1bedca7b3aad4df359d29367 | 70,528 |
def gen_clustree(cluster_df):
"""
Generates a nx.Digraph based clustree.
Can be plotted with:
```python
dg = gen_clustree(cluster_df)
nx.draw_networkx(dg, pos=nx.nx_agraph.graphviz_layout(dg, prog="dot"))
```
Args:
cluster_df (pd.DataFrame):
Dataframe where column ... | 9f2854c1a8e1de7b5a5928e20e2faa72ab3620f6 | 70,529 |
import importlib
import inspect
def pytask_collect_file(session, path, reports):
"""Collect a file."""
if any(path.match(pattern) for pattern in session.config["task_files"]):
spec = importlib.util.spec_from_file_location(path.stem, str(path))
if spec is None:
raise ImportError(f"... | 7e154c75c402e729b69c1611ff7b001f7fca57f1 | 70,530 |
import functools
def to_yaml_tree_metadata(func):
"""Wrapper that will add the metadata and userdata field for ``to_yaml_tree`` methods.
Also removes all "None" values from the initial tree.
Behavior should be similar to ASDF defaults pre v2.8 (ASDF GH #863).
"""
@functools.wraps(func)
def t... | ad58c6cbebeaece4702e1e87084a46dadfdf2777 | 70,531 |
from pathlib import Path
async def get_installation(
installation_id: int = Path(..., gt=0),
requester=Security(get_current_access, scopes=[AccessType.admin, AccessType.user])
):
"""
Based on a installation_id, retrieves information about the specified installation
"""
requested_group_id = awa... | 3af3835afbbf3a3f1e1be2da3b7cc756f1eef533 | 70,532 |
import re
def fingerprint(source=None):
"""Create a new fingerprint of current repositories.
The source argument is parsed to look for the expected output
from a `sync-all` command. If the source is `None` then the
`sync-all` command will be run to get the current fingerprint.
"""
if source is None:
... | b486593150de10f39ba66458644fb7d9fbddb69e | 70,533 |
async def predict(listing: Listing):
"""
Make a prediction for the AirBnB Optimal Listing Price 🔮
### Request Body; listed in ascending order of feature importances
- `review_scores_rating`: overall host review score
- `review_scores_checkin`: host review score for check-in
- `property_type`:... | 59e6a128d24df9539ed2e9199c882c8c11a24ef9 | 70,534 |
def get_env_connect(**kwargs) -> dict:
"""Get URL, API key, API secret, and certwarn from OS env vars.
Args:
**kwargs: passed to :meth:`load_dotenv`
"""
load_dotenv(**kwargs)
return {
"url": get_env_str(key=KEY_URL),
"key": get_env_str(key=KEY_KEY),
"secret": get_env... | 7fbb229855036d1719fe8df005dfac493d697c91 | 70,535 |
import tqdm
def calculate_coverage(aln, reads_mapped):
"""Calculate base and read coverage."""
_base_cov_dict = defaultdict(list)
read_cov_dict = defaultdict(lambda: 0)
allowed_operations = set([0, 7, 8])
with tqdm(total=reads_mapped, unit_scale=True) as pbar:
for read in aln.fetch(until_e... | 46f566fd09a4a6fd439b459845ee16ded1f8b729 | 70,536 |
def get_rna_brain_fantom():
"""Get RNA from mouse brain - FANTOM."""
return _get_data(protein_atlas.ProteinAtlasRnaBrainFantom) | 163f96e5b1263197e47d2f96b432c5b3883ecf92 | 70,537 |
def force_repeat_tie(threshold=True, selector=None) -> ForceRepeatTieCommand:
"""
Makes force repeat-ties command.
"""
return ForceRepeatTieCommand(selector, threshold=threshold) | 9123a63a782cac3e02b22379fe831a2bf2ac10cf | 70,538 |
def list_style_image(token, base_url):
"""``list-style-image`` property validation."""
if token.type != 'function':
if get_keyword(token) == 'none':
return 'none', None
parsed_url = get_url(token, base_url)
if parsed_url:
if parsed_url[0] == 'url' and parsed_url[1... | 77e61463c85874b6b9c2f1da83f67b38250d96ea | 70,539 |
import msgpack
def msgpack_restore(encoded_pytree):
"""Restore data structure from bytes in msgpack format.
Low-level function that only supports python trees with array leaves,
for custom objects use `from_bytes`.
Args:
encoded_pytree: msgpack-encoded bytes of python tree.
Returns:
Python tree o... | 5a49c876eff5ed13509e50f899f7581f1204cccf | 70,540 |
def estimate_log_evidence(samples, param_grid, log_numerator, max_components=5,
grid_fraction=0.1, plot=True, seed=123):
"""Estimate the log evidence using MCMC samples.
The evidence is estimated at each grid point using the ratio of the
log_numerator and the empirical density of ... | 3395f700d7c3d24421ac3eb0a32d3ee41e4deab4 | 70,541 |
from datetime import datetime
def convert_taxonomy_date(s):
"""
Returns a datetime representation of a date (in string format) loaded from the taxonomy. It
is assumed that the input format will be YYYY-MM-DD based upon observed values from within
the taxonomy.
If the input is not valid th... | 5677cbf22903cf274b03004a4cf75d38306a365c | 70,542 |
def OffsetOnSurface3(thisCurve, surface, distance, fittingTolerance, multiple=False):
"""
Offset a curve on a surface. This curve must lie on the surface.
Args:
surface (Surface): A surface on which to offset.
distance (double): A distance to offset (+)left, (-)right.
fittingToleran... | 9d5d795e6d094f380a5fcf5bf343a51ff6a4db4c | 70,543 |
def _create_user(cursor: Cursor, name: str) -> Result[Password]:
"""
Create a PostgreSQL user with a random password, if a user with that name doesn't already exist.
"""
passwd = Password.new()
query(cursor, _format("CREATE USER {} ENCRYPTED PASSWORD %s "
"NOCREATEDB NOSUPE... | b820913fcf1648f673e5c022b09a90a84b0dd3ba | 70,544 |
from datetime import datetime
def sysdate(as_string: bool=True, compact: bool=False):
"""
Get the current date, optionally formatted as a string.
"""
if as_string:
return datetime.datetime.now().strftime('%Y%m%d' if compact else '%Y-%m-%d')
else:
assert not compact, 'Cannot set `co... | 37619cf1cd8a6250f4ba221730343d8f13e7c318 | 70,545 |
from typing import List
def get_filth_dataframe(filth_list: List[Filth]) -> pd.DataFrame:
"""Produces a pandas `DataFrame` to allow debugging and improving detectors.
An example of using this is shown below:
.. code:: pycon
>>> import scrubadub, scrubadub.comparison, scrubadub.detectors.text_bl... | b9cda28fe91df82137ef4249837c6cf4b763ce93 | 70,546 |
def get_user(uid, app=None):
"""Gets the user data corresponding to the specified user ID.
Args:
uid: A user ID string.
app: An App instance (optional).
Returns:
UserRecord: A UserRecord instance.
Raises:
ValueError: If the user ID is None, empty or malformed.
... | b16e31b3eeae883732418d711ff7354d0a8136f8 | 70,547 |
def units_print_view(request, pk, side):
"""
Draft for one part of the rack
"""
rack = _rack(pk)
direction = _direction(pk)
return render(request, 'print.html', {
'side_name': _side_name(side),
'rack': rack,
'start_list': _start_list(pk, direction),
... | a4c2df4e706359ac5982bb25ca8196f764d66fdf | 70,548 |
def opening(values: np.ndarray, window_width: int) -> np.ndarray:
"""
Function to get opening of `values` array with structuring elements with `window_width` width.
Opening ... dilatation of the erosion.
Parameters:
values (np.ndarray): Array fo values that are to be opened.
window_widt... | 75358aff0c019a83c0307eee65a9e5097866cb67 | 70,549 |
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up OwnTracks based off an entry."""
# Restore previously loaded devices
dev_reg = await device_registry.async_get_registry(hass)
dev_ids = {
identifier[1]
for device in dev_reg.devices.values()
for identifier in... | 9076f5b950363bd4218befda8994ed020f05d6b2 | 70,550 |
import requests
def make_secure_api_call(url, headers = {}) -> str:
""" Make API call with error handling
Parameters
----------
url: str
The url to make the api call
headers: dict
The headers used in the api call
"""
try:
response = requests.get(url, headers = head... | b3f80825e2dc3c99a341dcc78386ecb78a642f40 | 70,551 |
def pix_to_non_square_ndc(i, S1, S2):
"""
The default value of the NDC range is [-1, 1].
However in the case of non square images, we scale the NDC range
to maintain the aspect ratio. The smaller dimension has NDC
range from [-1, 1] and the other dimension is scaled by
the ratio of H:W.
e.g.... | a0e41eb9fba7a817391ad6bcf901c608c808b11d | 70,552 |
def drilldown_enrichment(service, notable_data, num_enrichment_events):
""" Performs a drilldown enrichment.
Args:
service (splunklib.client.Service): Splunk service object.
notable_data (dict): The notable data
num_enrichment_events (int): The maximal number of events to return per enr... | 348023b5458314464053b9a2c1b8e3098b57a73d | 70,553 |
def grid_values(grid):
"""
Convert grid string into {<box>: <value>} dict with '.' value for empties.
Args:
grid: Sudoku grid in string form, 81 characters long.
Returns:
Sudoku grid in dictionary form:
- keys: Box labels, e.g. 'A1'.
- values: Value in corresponding box, ... | 8652899a9663c3ffb83dd78234fb1571d857ab3a | 70,554 |
from typing import Tuple
from typing import List
def parsemsg(s: str) -> Tuple[str, str, List]:
"""
Breaks a message from an IRC server into its prefix, command, and
arguments.
"""
prefix = ''
trailing = []
if not s:
raise IRCBadMessage("Empty line.")
if s[0:1] == ':' and ' ' i... | 9168dfa9a257c0ef1f11f84bf60b9d9e657057dc | 70,555 |
def get_valid_nodes(module, oc_exec, exclude_node):
"""Return a list of nodes that will be used to filter running pods"""
call_args = oc_exec + ['get', 'nodes']
res = call_or_fail(module, call_args)
valid_nodes = []
for line in res.split('\n'):
fields = line.split()
if not fields:
... | 464f06a39c924984cbeacc8f7498ddcb9e5cb980 | 70,556 |
def vline(chart: alt.Chart, value: float) -> alt.Chart:
"""Draw a vertical line on an Altair chart object."""
line = alt.Chart().mark_rule(color="grey").encode(x="val:Q")
return _add_line(chart, value, line) | d0bf2f0267041bb48277db610aa4ffd0fcf71b6f | 70,557 |
def d2_psi_heterodyne(t, psi, A, args):
"""
Need to cythonize
X = \\frac{1}{2}(C + C^\\dagger)
Y = \\frac{1}{2}(C - C^\\dagger)
D_{2,1}(\psi, t) = \\sqrt(1/2) (C - \\langle X \\rangle) \\psi
D_{2,2}(\psi, t) = -i\\sqrt(1/2) (C - \\langle Y \\rangle) \\psi
"""
X = 0.... | 39370c10b3df7cb6aa26af779150b377270e1692 | 70,558 |
def shared_prefix(args):
"""
Find the shared prefix between the strings.
For instance:
sharedPrefix(['blahblah', 'blahwhat'])
returns 'blah'.
"""
i = 0
while i < min(map(len, args)):
if len(set(map(itemgetter(i), args))) != 1:
break
i += 1
return args[... | fa80d17cc41b716068dc741ea775c79356a6ad76 | 70,559 |
import re
def to_IPA(text, pos=""):
"""Generates French IPA from spelling.
Implements template `{{fr-IPA}}`_.
.. _{{fr-IPA}}: https://en.wiktionary.org/wiki/Template:fr-IPA
Parameters
----------
text : string
String of fr-IPA text parsed in `{{fr-IPA}}`_ from Wiktionary.
po... | 268aee8ef66be0abc4601fd7c59e7cde88368f9d | 70,560 |
from datetime import datetime
def array_profile(
x: np.ndarray,
name: str = None,
timestamp: datetime.datetime = None,
columns: list = None,
):
"""
Generate a dataset profile for an array
Parameters
----------
x : np.ndarray
Array-like object to track. Will be treated as ... | c55668d8f5669dd3dba837040ef97f22f9d34c71 | 70,561 |
def Vector3_get_dimension():
"""Vector3_get_dimension() -> unsigned int"""
return _RMF.Vector3_get_dimension() | 5b7017be0fc3c1b06ec93710ca674f1fc019b560 | 70,562 |
def quat2dcm(quat):
"""quat2dcm(vec4f quat) -> mat3f"""
return _libvncxx.quat2dcm(quat) | 1f0b39ab9cdeb69613d43679bff989db7b9763e1 | 70,563 |
def cluster_chrom(tracklist, chrom, genome, blacklist, xcov=0.3, whitelist=None,
min_elements=None, n_ele_prop=0.1, min_tracks=None,
n_track_rep_prop=10e-10, neighborhood_dist=10000,
min_crb_separation=10000, max_crb_size=3e10, prefix='CRB'):
"""
Load & cl... | 189ce6b1550f4160741722e1734901e9208fede6 | 70,564 |
import requests
import os
def _winlink_positions(callsign):
"""
Retrieve positions from winlink
"""
error = "Unable to retrieve data from WinLink. Please try again."
pos = []
attempts = 10
while attempts:
attempts = attempts - 1
try:
res = requests.post(
... | 0fb2b9e84b5d65497555f1ecac891089936d8348 | 70,565 |
from operator import concat
def get_inventory(marketplace, address):
"""
Get the items the address owns on a marketplace.
"""
context = GetContext()
# Return the serialized inventory for the address.
inventory_marketplace_key = concat(inventory_key, marketplace)
storage_key = concat(inven... | 655e8120e2e5cbf226c3af379903250353934247 | 70,566 |
def create_app(config):
"""
App factory for Flask app. Setup of database, login, navbar and registering of blueprints
:param config:
:return: running flask app
"""
# create pvtool
app = Flask('pvtool')
app.config.from_object(config)
# database
db.init_app(app)
# create db
... | 62e6e388e003023baab6a51b5619b8db276f23df | 70,567 |
import os
def make_colour_bitmap(colour, size=(16, 16)):
"""Returns a rounded wx.Bitmap filled with specified colour."""
bmp = wx.Bitmap(size)
dc = wx.MemoryDC(bmp)
dc.Background = wx.TRANSPARENT_BRUSH
dc.Clear()
dc.Brush, dc.Pen = wx.Brush(colour), wx.Pen(colour)
dc.DrawRectangle(1, 1, s... | ed351bdd92b20d8b4a829f84620f35ce9fc167a8 | 70,568 |
def make_offspring(parents, noffs=None, dam_list=None, sire_list=None, mu=1e-12, family_name='offs'):
"""
Mate individuals in a base population to create simulated offspring. Lists of
specific sires and dams can be provided with the options dam_list and
sire_list. If only the number of offspring are spe... | e0135eb0cc6cad9df1ea8dca42e35af0738f1540 | 70,569 |
def cosine_similarity(intersection_num, all_items_num,
first_set_len, second_set_len):
"""
Count cosine similarity based on intersection data
:param intersection_num: len of intersection of two sets
:param all_items_num: num of all items, for example, sum of views
:param first_... | 90a8be939730307069f6758fe6a93299d6484b42 | 70,570 |
def suggest(word):
"""Renvoie le mot le plus proche disponible dans le fichier keywords.json"""
return getMatchCoefficient(keywords, word)[0]["value"] | 3b72372243d2369741f96bb299fe11de1ecc8ba9 | 70,571 |
import random
def random_walk(graph, node, steps=8):
"""
Given a graph and a specific node within the graph, returns a node after steps random edge jumps
:param graph:
A networkx graph
:param node:
Any node within the graph
:param steps:
The number of steps within the random walk
:return:
A node within... | ad75cadc8e1df8edf5ebbb030de9b80076ab1f4c | 70,572 |
def get_test_model_full():
"""Returns a maximally complex test model,
using all supported layer types with different parameter combination.
"""
input_shapes = [
(26, 28, 3),
(4, 4, 3),
(4, 4, 3),
(4,),
(2, 3),
(27, 29, 1),
(17, 1),
(17, 4),... | be3e4dd8c0b1f0265c7e09155eca758a0a8fdc1d | 70,573 |
def client_update(model, dataset, initial_weights, client_optimizer):
"""Updates client model.
Args:
model: A `tff.learning.Model`.
dataset: A 'tf.data.Dataset'.
initial_weights: A `tff.learning.Model.weights` from server.
client_optimizer: A `tf.keras.optimizers.Optimizer`.
Returns:
A 'Clie... | 4b2365aed57d17e70e42147a600879659f0208b7 | 70,574 |
from typing import Callable
from typing import Any
def rfc6979(ec: Curve, hf: Callable[[Any], Any], mhd: bytes, q: int) -> int:
"""Return a deterministic ephemeral key following rfc6979"""
if not 0 < q < ec.n:
raise ValueError(f"private key {hex(q)} not in [1, n-1]")
hsize = hf().digest_size
... | 4a0cd11320a8ad327e8b8780d03a37b4e7ee3b16 | 70,575 |
import requests
from typing import List
import urllib
def list_directories(_):
"""Constroi a lista de diretorios do nextcloud no caminho passado
e adiciona as opcoes do promt.
Returns:
List: Lista com as opcoes
"""
try:
response = requests.request(method='PROPFIND',
... | e3cccba962ff93dc0d4f33541ac955fe80373e48 | 70,576 |
def traceBeam(gratAlign,order=1.,wave=2.48,blaze=30.):
"""Traces a beam to grating, applies misalignment,
then traces to focal plane and returns mean
x,y position
x refers to spectral direction
"""
#Compute yaw to achieve Littrow configuration
phi0 = arccos(sin(1.5*pi/180)/cos(blaze*pi/180))... | 8dfc7f796c58cebc2ab7119d75cdba984475166e | 70,577 |
def check_repos(repo_configs: list[RepoInfo], github_token: str = None) -> bool:
"""
Check a list of repos to verify that information provided is accurate
:param repo_configs: list of RepoInfo to check
:param github_token: github token to use for authentication
:return: None
"""
for repo in repo_configs:
... | 6040d78bb2445215da6d5b08033df2bd56a6a6f3 | 70,578 |
def _get_sample_data(random_state=None):
"""
get mnist data
input data is returned after normalization.
objective data is returned after one-hot encoded.
"""
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train = np.expand_dims(X_train, axis=3) / 255.
X_test = np.expand_dims(... | be0a3daed5e93ceca35ef85c2c1bb233875003ba | 70,579 |
def get_n_points(points, point_type):
"""Compute the number of points.
Parameters
----------
points : array-like
Input points.
point_type : str, {'scalar', ''vector', 'matrix'}
Type of input points.
Returns
-------
n_points : int
Number of points.
"""
n_... | 1124f8740fea090d22f7791735000e74116eaa79 | 70,580 |
def fetch_issue_new_stock_info(stock_code):
"""获取发行新股信息"""
url_fmt = 'http://vip.stock.finance.sina.com.cn/corp/go.php/vISSUE_NewStock/stockid/{}.phtml'
url = url_fmt.format(stock_code)
df = pd.read_html(url, attrs={'id': 'comInfo1'})[0]
return df | 2aa9d3ae163f81655a55e01d4c9e567df0524505 | 70,581 |
def vote_for_thread(request, course_id, thread_id, value):
"""
given a course id and thread id vote for this thread
ajax only
"""
thread = cc.Thread.find(thread_id)
result = _vote_or_unvote(request, course_id, thread, value)
return result | 1c64c2611214f69b7e17531e9045e17be8849b09 | 70,582 |
def return_date_of_quantile_sold_q4(df_daily_revenue: pd.DataFrame, percent: float):
"""Returns the date in which a specified percent of the bookings
is made for all rent rooms.
Parameters
----------
df_daily_revenue : pd.DataFrame
Pandas dataframe with information about daily revenue.
... | a398b0e7e572bfc0db0adcc7fc33ca7399bf4fc5 | 70,583 |
from typing import List
from typing import Any
def get_last_key_from_integration_context_dict(feed_type: str, integration_context: List[Any] = []) -> \
str:
"""
To get last fetched key of feed from integration context.
:param feed_type: Type of feed to get last fetched key.
:param integration... | 64eeb53cf00636dfc73866c64c77e2964149209e | 70,584 |
def add_pano_sensors_to_config(config: CN) -> CN:
"""Dynamically adds RGB and Depth cameras to config.TASK_CONFIG, forming
an N-frame panorama. The PanoRGB and PanoDepth observation transformers
can be used to stack these frames together.
"""
num_cameras = config.TASK_CONFIG.TASK.PANO_ROTATIONS
... | 16eda122838cf7a11c197f96019f3a5a3bfa0c36 | 70,585 |
def edit_ttp(cid, old_ttp, new_ttp, analyst):
"""
Edit an existing TTP.
:param cid: ObjectId of the Campaign.
:type cid: str
:param old_ttp: Original value of the TTP.
:type old_ttp: str
:param new_ttp: New value of the TTP.
:type new_ttp: str
:param analyst: The user editing the TT... | 33e45e07e66d32619fdea73bdadce559255969eb | 70,586 |
import re
def english_syllables(word):
"""Simple heuristic for the number of syllables in an English word. 91% agreement with CMUDict."""
pos = ["[aeiouy]+", "[^cgj]eo|[^cgst]ia|ii|[^cgstx]io|io$|[^g]iu|[^qg]ua|[^g]uo", "^mc|(s|th)ms?$", "[aeiouy]ing"]
neg = ["[aeiouy]n?[^aeiouy]h?e$", "[aeiouy]([^aeiouyt... | 000a353633c25067472c131c78a8c16eda45b522 | 70,587 |
def compute_cooccurence(motives, ids=None):
"""compute_cooccurence."""
if ids is None:
ids = [id for id in motives]
seqs_summary = defaultdict(list)
for seq_id, begin, end, i in hits(motives, ids=ids):
seqs_summary[seq_id].append((begin, end, i))
distances = defaultdict(list)
si... | 4f942753cc64703fc297781bbf5f37085014ae85 | 70,588 |
def sequence_contains_non_standard(sequence):
"""
Checks if a sequence contains non-standard nucleotides
"""
return any([x in sequence.lower() for x in NON_STANDARD_NUCLEOTIDES]) | 419b544e429d4d6370d3198b54b17d4356801ca0 | 70,589 |
def employee_to_dict(employee_id):
"""
Returns employee dictionary representation.
:param employee_id: employee id
:return: employee dictionary representation
"""
employee = get_employee_by_id_service(employee_id)
return {
'id': employee.id,
'forename': employee.forename,
... | 3ad97c55e8f356f588f3607660613c2d1dc8c553 | 70,590 |
import os
def get_battery_level():
"""
Calculates and returns the battery level.
Returns:
The battery level.
"""
# Initialize variables.
global battery_level
time_minutes = int(time_seconds) / 60.0
# Get the moisture based on the time of the day.
battery_level = int(pow(... | 25f8df82eeda9c879cac6cc3bd9810aec6938eee | 70,591 |
def parse_file(data_dict):
""" takes the streptomedb dictionary and returns a list of lists with
NPs which is easy to use
data_dict: strep dictionary created with make_dict()
"""
key_list = []
for key in data_dict.keys():
key_list += [key]
value_list = []
for value in d... | ad1c80729bf38b868c839aef2b9b6d76d1ad17d5 | 70,592 |
import scipy
def besinc(x):
"""The sombrero, jinc, or besinc function
(https://en.wikipedia.org/wiki/Sombrero_function --- note this
implementation follows the convention from Blahut, Theory of
Remote Image Formation, 2005, see p. 82).
"""
y = np.empty_like(x)
I = np.where(x != 0)
y[I... | 0bdcec13b84d0bce048dd0ce7398a21c0118a244 | 70,593 |
import time
def sgd_subset_dense(train_X, train_Y, w, iter_sgd, alpha, regParam) :
"""
Computes stochastic gradient descent for a partition (in memory)
Parameter:
train_X : list of pyspark.mllib.linalg dense or sparse vectors
train_Y : list of labels
w : numpy matrix holding the model weights
i... | a0e88fd04886618ce0966fe4d1a206a852fe9954 | 70,594 |
import math
def _parseSeconds(data):
"""
Formats a number of seconds into format HH:MM:SS.XXXX
"""
total_seconds = data.total_seconds()
hours = math.floor(total_seconds / 3600)
minutes = math.floor((total_seconds - hours * 3600) / 60)
seconds = math.floor(total_seconds - hours * 3600 - min... | b01a66f66dc3cdc930aff29069c865cab5278d08 | 70,595 |
def creates_cycle(connections, test):
"""
Returns true if the addition of the 'test' connection would create a cycle, assuming that no cycle already exists in
the graph represented by 'connections'.
:param connections: List of connections, with each connection a tuple of form (sender, receiver)
... | 43d942fb413ee720200081754dceb99ca87bf1cd | 70,596 |
import torch
def PredictRegularizationConstrainR(P, Q, R):
"""
FunkSVD+Regularization+矩阵R的约束(取值只能是0-5, P,Q>0)
"""
B = 0.1 # 正则话的系数
R_pred = torch.mm(P, Q.t()) # 矩阵相乘
N,M = R.shape
loss = 0
for i in range(N):
for j in range(M):
if R[i][j] > 0:
loss =... | f9cb4ced0f780f8002b890e332559e2e51d8fd35 | 70,597 |
import os
import requests
def check_exists(item, rest_url):
"""
Checks the existence of item in ES
@param item: item to check
@param rest_url: rest API endpoint
@return: True if item exists
"""
ptype = "container"
if item.startswith("job"):
ptype = "job_spec"
elif item.sta... | f2445ce2926745333fe307ae3a226a428aa2089f | 70,598 |
def get_top_side_rect(rect):
"""
this function return a manipulator rect for the transform
handler.
_____________*____________
| |
| |
|________________________|
"""
if not rect:
return None
return QtCore.... | d59bb24fbec35e6d5348c8058fcebbf97a7a4f87 | 70,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.