content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def change_password(request, password_change_form=PasswordChangeForm, template_name='woodstock/registration/change_password.html'):
"""
Displays the change password form
"""
user = request.user
if request.method == 'POST':
form = password_change_form(user, request.POST)
if form.is_va... | e3fd6546a21e74713670cfe9153d1891c9d97213 | 43,074 |
def compute_average_passengers_per_stop(instance, passengerData, tram_tour, tram_time_arrival, tram_time_departure):
"""
INFO
function to compute the average number of passengers per stop
"""
waitPas = compute_waiting_passenger(instance, passengerData, tram_tour, tram_time_arrival, tram_ti... | e114868e59d5b0d13a38182ce5c99eec287662ff | 43,076 |
from .. import kinda
def import_data(filepath, use_pickle = False):
""" Imports a KinDA object as exported in the format specified by export_data()
Imports:
- domains, strands, complexes, reactions, resting-sets, resting-set reactions
- resting-set stats:
=> similarity-threshold
=> c_ma... | 183133aec94a980751dfe05de531b0ed06e54b72 | 43,077 |
import base64
def invoke_lambda_and_get_duration(lambda_client, payload, function_name):
"""
Invokes Lambda and return the duration.
:param lambda_client: Lambda client.
:param payload: payload to send.
:param function_name: function name.
:return: duration.
"""
response = lambda_clien... | c8d2b77e4f7bc338efcdfd21db4f7297a625b05c | 43,078 |
def test_816_edge_case(entities, use_ip, save):
"""
Test that #770 protocol only triggers when the
depending deletion is towards the same asn AND
not already handled (dependency == noop)
"""
data = setup_test_data("ixf.member.1")
network = entities["net"]["UPDATE_DISABLED_2"]
ixlan = en... | 996b6c16b1d17a7b5ce519f9e230ff1226b59ed2 | 43,079 |
def is_table(doctype):
"""Returns True if `istable` property (indicating child Table) is set for given DocType."""
def get_tables():
return db.sql_list("select name from tabDocType where istable=1")
tables = cache().get_value("is_table", get_tables)
return doctype in tables | ad4f7a4bd6d907886a69986ee357d5578309d965 | 43,080 |
def _scroll_plot4(images, names, init_z):
"""
Creates a plot 2x2 image plot of 3d volume images
Scrolling changes the displayed slices
Parameters
----------
images: list of 4 arrays
Each array of shape (z,y,x) or (z,y,x,RGB)
names: list of 4 strings
Names for each image
Us... | 86435ada994aa9e02b1f6cf85050f665869da589 | 43,081 |
def n_tree():
"""
This is the format of this tree
t 1
a b c 3
aa ab ba bb ca cb 6
aaa aab aba abb baa bab bba bbb caa cab cba ... | f43a3f90b816b4fc1b172e879e2bb8a56b012747 | 43,082 |
import re
def reglux_list(mydict,response):
"""
遍历正则抓取数据
:param mydict: 字典类型{key:正则表达式,}
:param response: request.text需要正则匹配的字符串
:return: 字典类型
"""
temp = {}
for m,n in mydict.items():
if '' != n:
pattern = re.compile(n)
matchs = pattern.findall(response)... | f75cad96991fedc6e1ab91a17abc1b8b91be6cdd | 43,083 |
def correct_archetype_areas(prop_architecture_df, architecture_DB, list_uses):
"""
Corrects the heated area 'Hs_ag' and 'Hs_bg' for buildings with multiple uses.
:var prop_architecture_df: DataFrame containing each building's occupancy, construction and renovation data as
well as the architectural... | bcb577750bca2de04ec488f213b16a8a5c5a4215 | 43,084 |
import random
def read_stat():
"""
Mocks read_stat as this is a Linux-specific operation.
"""
return [
{
"times": {
"user": random.randint(0, 999999999),
"nice": random.randint(0, 999999999),
"sys": random.randint(0, 999999999),
... | 06889ca31c24aa890637ac63283091b096e48443 | 43,085 |
def getMaxDouble_DImage(Image):
"""getMaxDouble_DImage(Image) -> double"""
return _ImageFunctions.getMaxDouble_DImage(Image) | 4ec93e03ea7d2bc92a71b3a504647166f7848326 | 43,087 |
def bfs(graph):
"""Function that recreates the Breath First Search
algorithm, using a queue as its data structure.
In this algorithm, when a node is analyzed, it is
marked as visited and all of its children are
added to the queue (if they are not in it already).
The next node to be analyzed is g... | a14671a30d0c61389378ae44641901ec8dce8ac2 | 43,088 |
def create_known_points_layer_2d():
"""Create points layer with known coordinates
Returns
-------
layer : napari.layers.Points
Points layer.
n_points : int
Number of points in the points layer
known_non_point : list
Data coordinates that are known to contain no points. U... | ab944490f81b75c6da808cb468359e67b008fc5c | 43,089 |
def expand_grid_point(point, factor, xoffset, yoffset):
"""Expand a given georeferenced point by an integer factor, knowing the
size of horizontal and vertical area
Parameters
----------
point : shapely.geometry.Point
Raw point that must be expanded
factor : int
Number of new po... | c911a839461ece6980872ec77c236970c5ceade3 | 43,090 |
from typing import Sequence
import secrets
import math
def weighted_choice(values: Sequence[TValue]) -> TValue:
"""
A simple weighted choice which favors the items later in the list.
Weighting is linear with the first item having a weight of 1, the second
having a weight of 2 and so on.
values =... | 50e741cb7e30fd1814298a16c7aaacec3a4b6943 | 43,091 |
def add_prefix(prefix, name):
"""Adds prefix to name."""
return "/".join((prefix, name)) | f74a40b057059d9cd4527872a17508b301dd6883 | 43,093 |
from pathlib import Path
def next_job_id(output_dir: Path) -> str:
"""Return the next job id."""
# The ids are of form "0001", "0002", ...
# Such ids are used for naming log files "0001.log" etc.
# We look for the first id that haven't been used in the output directory.
def make_job_id(n: int) ->... | 7fa35775e3bef8cf812b1173880c5be1ad3e6465 | 43,094 |
def get_token(request):
"""The same as validate_token, but return the token object to check the
associated user.
"""
# Coming from HTTP, look for authorization as bearer token
token = request.META.get("HTTP_AUTHORIZATION")
if token:
token = token.split(" ")[-1].strip()
try:
... | cefeccf64a07388dde988b01b1f28bb7e6c26f1a | 43,095 |
def isi(spiketrain, axis=-1):
"""
Return an array containing the inter-spike intervals of the SpikeTrain.
Accepts a Neo SpikeTrain, a Quantity array, or a plain NumPy array.
If either a SpikeTrain or Quantity array is provided, the return value will
be a quantities array, otherwise a plain NumPy ar... | 65a89856b2138983bb67d71686701b6d1a5caeb4 | 43,096 |
def instance_power_specs_delete(context, instance_uuid, session=None):
""" Removes an existing Server specs from the Database """
return IMPL.instance_power_specs_delete(context, instance_uuid) | c03aa362ef23d3196d25f6ec03e2d2f28467eb34 | 43,097 |
def POS(POSInt):
"""Returns 'F' if position indicator is present. The AllSportCG sends a * in a specific position to indicate which
team has posession, and this changes that character to an 'F'. Using font Mattbats, F is a football."""
POSText = ""
if POSInt == 42:
POSText = "F"
return(POSText) | 2f0dac3bfd0f803f1a60e740c104414bff29bf27 | 43,098 |
from typing import Dict
from typing import Sequence
def kwargs_2_list(**kwargs) -> Dict[str, Sequence]:
"""
Convert all single values from keyword arguments into lists.
For each argument provided, if the type is not a sequence,
convert the single value into a list.
Strings are not considered as a... | 7a816ee19ceb80c6a311ae142c97c9a1f8ae87dd | 43,099 |
def downscale(box, side, fill_color, background):
"""Downscales box by considering each box of length side as one pixel.
If a downscaled pixel contains more than on color this returns None"""
if side == 1:
return None
w, h = int(box.shape[0] / side), int(box.shape[1] / side)
Y = np.full((w... | 0a7340f7598941199c3913753867ba26fa9d63ab | 43,100 |
import attr
def switch_passive(tokenized):
"""Passive verbs are modifying the phrase before them rather than the
phrase following. For consistency, we flip the order of such verbs"""
if all(not t.match(tokens.Verb, active=False) for t in tokenized):
return tokenized
converted, remaining = [], ... | c6f7a22439f2b0953337c40f9a61380968c034b3 | 43,101 |
def unbox_unicode_str(typ, obj, c):
"""
Convert a unicode str object to a native unicode structure.
"""
ok, data, length, kind, is_ascii, hashv = \
c.pyapi.string_as_string_size_and_kind(obj)
uni_str = cgutils.create_struct_proxy(typ)(c.context, c.builder)
uni_str.data = data
uni_str... | cf8a9aa9229ae7ceabd1e31424b45667a6602724 | 43,102 |
import torch
def get_encoded_batch(sentence, lang_obj, use_cuda):
"""
accepts only bsz = 1.
input: one sentence as a string
output: named tuple with vector and length
"""
sentence = sentence + ' ' + global_variables.EOS_TOKEN;
tensor = lang_obj.txt2vec(sentence).unsqueeze(0)
device = torch.device('cuda') if... | a252c8d9af596afdcc0eeaa6e51a06a19996b1b1 | 43,103 |
from typing import List
def ensure_topological_order(nodes: List[base_node.BaseNode]) -> bool:
"""Helper function to check if nodes are topologically sorted."""
visited = set()
for node in nodes:
for upstream_node in node.upstream_nodes:
if upstream_node not in visited:
return False
visite... | 56d71c306c809bae87c428607a17e91a82f5147f | 43,104 |
import trace
def eval_wavefront(opt_model, fld, wvl, foc,
image_pt_2d=None, num_rays=21, value_if_none=np.NaN):
"""Trace a grid of rays and evaluate the OPD across the wavefront."""
fod = opt_model['analysis_results']['parax_data'].fod
ref_sphere, cr_pkg = trace.setup_pupil_coords(opt_m... | 8dc1c5d9aade54577e86e9f087fb0fd34eed6ec9 | 43,105 |
def _ArrayToVec3(vec3):
"""Convert an array of three doubles into a simple_aero.Vec3."""
if len(vec3) != 3:
raise Vec3FormatException(vec3)
c_vec3 = simple_aero.Vec3()
c_vec3.x = vec3[0]
c_vec3.y = vec3[1]
c_vec3.z = vec3[2]
return c_vec3 | ae060783f923378cd555f94d25bfc98c8ea536a8 | 43,106 |
import importlib
def get_storage(request):
""" Gets a Credentials storage object provided by the Django OAuth2 Helper
object.
Args:
request: Reference to the current request object.
Returns:
An :class:`oauth2.client.Storage` object.
"""
storage_model = oauth2_settings.storage_... | 939f8e9f9db2e1f2a3624532fe7c70c00bd0a475 | 43,107 |
import copy
def default_field(obj, **kwargs):
"""
returns field object that can handle default factory functions properly
"""
return field(default_factory=lambda: copy.copy(obj), **kwargs) | 48b10596c443bd37f0391c4b28fa0e8a14e51b51 | 43,108 |
def is_visited(state, visited):
"""
Determines whether a State has already been visited.
Args:
state:
visited:
Returns:
"""
for visited_state in visited:
if state.shore == visited_state.shore and state.boat == visited_state.boat:
return True
return False | 567f85b63533188d58df4923e7e3a2a72da14943 | 43,109 |
def bf_get_snapshot_input_object_stream(key, snapshot=None):
# type: (Text, Optional[Text]) -> Any
"""Returns a binary stream of the content of the snapshot input object with specified key."""
return restv2helper.get_snapshot_input_object(bf_session, key, snapshot) | 2d19a845f639eeb4b90c5b3aa76078974fc7a008 | 43,110 |
def supplierProducts(supplierId):
"""
Lists out all of the supplier products with the ability
to modify list and delist products into the master
database.
:param supplierId: The supplier id.
"""
page = escape(request.args.get("page"))
limit = request.args.get("limit")
if not limit o... | c902216fa83cfd0347ed9f2590d1ceba28584999 | 43,111 |
def bprop_scalar_to_array(x, out, dout):
"""Backpropagator for primitive `scalar_to_array`."""
return (F.array_to_scalar(dout),) | 16bc8fdabdb9a682f0dd9605a7f4c3530983f3b2 | 43,112 |
def get_sequences(psms: np.recarray, db_seqs:np.ndarray)-> np.ndarray:
"""Get sequences to add them to a recarray
Args:
psms (np.recarray): Recordarray containing PSMs.
db_seqs (np.ndarray): NumPy array containing sequences.
Returns:
np.ndarray: NumPy array containing a subset of s... | c066d524f4dd2cf583ac715dfd85a14343dc41de | 43,113 |
def dual_basis_hamiltonian(n_dimensions, system_size,
plane_wave=False, spinless=True):
"""Return the plane wave dual basis hamiltonian with the given parameters.
Returns: the Hamiltonian as a normal-ordered FermionOperator.
Args:
n_dimensions (int): The number of dimens... | c3155855fb5fc49642c2cdf80d08e6151ba9fe45 | 43,114 |
def get_subject_for_cell(row_num, row, column_spec, table_about_url, shared_subject, column_info):
""" Get the subject for the given cell."""
if column_spec["aboutUrl"]:
return apply_all_subs(column_spec["aboutUrl"], row_num, row, column_info)
elif table_about_url:
return apply_all_subs(tabl... | dc2658d296529affabfb1ed4dd8cf2833655fd1c | 43,115 |
from typing import Sequence
from typing import Optional
from functools import reduce
def merge_confs(
filenames: Sequence[PathLike], default: Optional[str] = "defaults.yml"
) -> Configuration:
"""
Merge configurations in given files.
:param filenames: files to merge
:param default: default config... | f528383fd620cb6177b2912ebb3abc32a09543a7 | 43,116 |
def add_product(body):
"""
Added a new Product
:param body: Product object that needs to be added to the db.
:type body: dict | bytes
:rtype: AddProductResponse
"""
return Products.add_product(connexion) | cb5291670070f2d672979883bc8491dadfd5d272 | 43,117 |
def sineFit(wavelength,frequency,amplitude,phase,offset):
"""
A sine fit function of wavelength, frequency,
amplitude, and phase.
"""
return amplitude * np.sin(frequency * (wavelength - phase)) + offset | 6acf485936323a6fa6911a841180543b028b1ba2 | 43,118 |
from typing import Any
from typing import Tuple
import torch
import contextlib
def cast_floats_to_right_precision(to_fp16: bool, no_grad: bool, *args: Any, **kwargs: Any) -> Tuple[Any, Any]:
"""
Cast floating point Tensors in *args or **kwargs to FP16 or FP32 if they are not.
We also retain the requires_g... | fe31c1751da0bff5e12801a19987e35700567bb0 | 43,119 |
def _BuildIsCompleted(build_dict, build_num):
"""Determine whether build was completed successfully.
Get the build test status. Check whether the build given by |build_num]
was terminated by an error, or is not finished building. If so, return
None. Otherwise, return the build test status dictionary.
Args:
... | 4007a7948327b9f59b20677eb5505d3b170b3cb2 | 43,120 |
def extract_columns(myfile):
"""Returns the columns of a space separated file as a list
let the file be:
a b c
d e f
g h i
the function will return:
[(a,d,g), (b,e,h), (c,f,i)]
"""
lines = extract_lines(myfile)
zipped = zip(*lines)
return list(zipped) | 4ccb474d437fc7bf3857813307f9d68b359a651b | 43,121 |
def assign_label(cross_nn, ref_nn, ref_labels, how='mode'):
"""
Assign label to projected cells based on the labels among their nearest neighbors
in the reference dataset.
Parameters
----------
cross_nn
dense numpy array or scipy sparse array (csr) with projected cells as rows and
... | 4fd0db429ddab8ee084acafe9fb0cb5fbc7c2001 | 43,123 |
def parse_floatingips_to_add(floatingips):
"""
Parse "floatingips" values
:param dict floatingips: Floating ips
:rtype: dict (region, quantity)
"""
result = defaultdict(lambda: 0)
for ip in floatingips:
result[ip.get("region")] += ip.get("quantity")
return result | 0166f9ca469c49051c3c08e2941c3164d6aa736c | 43,124 |
def rgs_var(g, h, xoff, yoff):
"""Radiographs and variance with xoff and yoff offsets"""
gx0, hx0 = xoff, 0
if xoff < 0:
gx0, hx0 = 0, -xoff
nx = min(g.rg.shape[0]-gx0, h.rg.shape[0]-hx0)
gy0, hy0 = yoff, 0
if yoff < 0:
gy0, hy0 = 0, -yoff
ny = min(g.rg.shape[1]-gy0, h.rg.sha... | 17ebaecb34be1c67cb9454117097b574ce14998e | 43,126 |
from vrml import node
def setExternalURL( cls, url ):
"""Set the externproto URL associated with a prototype"""
return node.Node.externalURL.fset( cls, url ) | 1ef4549285b30dfd9ee853b395440b6a0f3be777 | 43,127 |
from typing import Union
def load_fs(root: Union[FS, str]) -> FS:
"""If str is supplied, returns an instance of OSFS, backed by the filesystem."""
if isinstance(root, str):
return pyfs.open_fs(root, create=True)
if isinstance(root, FS):
return root
raise Exception("Not a filesystem or path!") | 0b40f506b0a8624f3b7ab326e965d60d1030f726 | 43,128 |
def _getcontextrange(context, config):
"""Return the range of the input context, including the file path.
Return format:
[filepath, line_start, line_end]
"""
file_i = context['_range']['begin']['file']
filepath = config['_files'][file_i]
line_start = context['_range']['begin']['line'][0]
... | 8367049c450e8d7345478aa71efb2e97e07438f6 | 43,129 |
def prepare_email_content(runresult, subject_name):
"""
:param runresult: 生成的简要分析结果
:param subject_name: html名称
:return: email conetnt
"""
batch_result = {}
batch_result['report_name'] = subject_name
batch_result["tasks"] = runresult["tasks"]
batch_result["pass_task"] = runresult["pa... | b8cff0dd6d40eb295015d6631e56448c21259141 | 43,130 |
def sample_recipe(user, **params):
"""create a dictionnary of a recipe object."""
defaults = {
'title': 'Pitimi ak Pwa Kongo',
'time_minutes': 10,
'price': 5.00,
'description': 'Manje Ayisyen'
}
defaults.update(params)
return Recipe.objects.create(user=user, **default... | dc51f8679bd12ac3f0b892f6a2c87fe7c7a94156 | 43,131 |
def approx_match(stations, name):
"""
:param stations: dict เก็บข้อมูลพิกัดและอุณหภูมิของสถานีต่าง ๆ ในรูปแบบที่อธิบายมาก่อนนี้
:param name: เป็นสตริง
:return: คืนลิสต์ที่เก็บชื่อสถานีที่มีตัวอักษรใน name เป็นส่วนหนึ่งของชื่อสถานี โดยไม่สนใจว่าเป็นตัวพิมพ์เล็กหรือใหญ่
และไม่สนใจเว้นวรรคภายในด้วย (ชื... | 42338574242c7b866917e8480bc4accd4e569133 | 43,132 |
def update_widget(request):
""" Update single Widget """
result = {}
widgets = get_sidebar_widgets()
widget_id = request.POST.get('widget_id', 0)
try:
widget_item = SidebarWidget.objects.get(pk=widget_id)
except SidebarWidget.DoesNotExist:
return result
else:
widget... | 3c78d1d4cd3ea75559633811f4e8c9173928a1e9 | 43,133 |
import random
def simulate(cycles, initSize, offspring, lifespan, crisprFems, popLimit):
""" cycles: the number of cycles this simulation will run.
initSize: the initial size of the population.
offspring: max number of possible children per reproduction.
lifespan: maximum lifespan of an in... | b52422afa689ac613c34514669b0438fe38ef692 | 43,134 |
def rpn_graph(feature_map, anchors_per_location, anchor_stride):
""" Region Proposal Network hesaplama grafiğini oluşturur.
feature_map: omurga özellikleri [toplu iş, yükseklik, genişlik, derinlik]
anchors_per_location: özellik haritasındaki piksel başına çapa sayısı
anchor_stride: Çapa yoğunluğunu ... | 451507842b4af89bd8bfb9e0bf1b1dfa6d599868 | 43,135 |
def get_xml_schema_type():
"""
Get xml schema type.
"""
return '{http://www.w3.org/2001/XMLSchema-instance}type' | 1704b7d6227cd88836f4a55488445192bf63c9aa | 43,136 |
def main_log_set():
"""
メインの統計処理をあれこれする所
"""
# 身内村判定
def get_local_villager(vill_name):
for ng_word in ['ダンガンロンパ', 'ダンロン', 'RP', 'なんJ', '身内', 'クッキー', 'ク☆']: # 除外する村名リスト
if ng_word in vill_name:
return True
return False
# 設定変数
target = dict()
... | 841158e74ff7d0a0f255af30a9758699d59aab23 | 43,137 |
def _get_state(ipaclient, idnsname):
"""Return set of currently defined SRV records."""
current = set()
result = ipaclient.get_dns_record(idnsname)['result']['result']
for item in result:
for record in item.get('srvrecord', []):
_w, _p, port, host = record.split()
current... | 5c77c6c741e1a8260a00539432e857633ed44011 | 43,138 |
from typing import Tuple
def locate_max_drawdown(returns: pd.Series) -> Tuple[pd.Timestamp, pd.Timestamp, float]:
""" 寻找最大回撤周期
:param returns: 收益序列, 已时间为 ``index``
:return: (最大回撤开始时间, 最大回撤结束时间, 最大回撤比例)
"""
if len(returns) < 1:
raise ValueError('returns is empty.')
cumulative = empyri... | 7eb88ee86aa2475df5d8e99b4bc905dc9fb76d2a | 43,139 |
async def make_result_embed(vote, results):
"""
Create a discord.Embed object from a set of results for a vote
:param vote: the vote the results are for
:param results: the results from the vote
:return: discord.Embed object to send
"""
embed = discord.Embed(title=f"{vote.title} Results:")
... | e22f7f82ea63db0ba9740c0dec8636f24a74e7c5 | 43,140 |
def count_bits_above(string: int, pos: int) -> int:
"""Return the number of set bits higher than the position
Args:
string (int) - bit string
pos (int) - position in the bit string
"""
return count_bits(string & ~(2**(pos + 1) - 1)) | 2ec723cb756eaad386211a83e2467c3624dc6397 | 43,141 |
def to_int(value):
"""Convert to integer"""
return value & 0xFF | 9045a7857dae407a196ccb29a142a8e243476b03 | 43,143 |
def remove_ephemeral_entry(self):
"""Return index of the new entry to be added.
The view must be in edit mode, with 'adding_new=True'.
We may or may not have included whatever the user entered as a new entry in 'body',
depending on whether what the user entered satisfies the entry syntax. If yes, then... | 40aa625606764d9e1649553035c69686abeacd8b | 43,144 |
def get_P_fan_rtd_C(V_fan_rtd_C):
"""(12)
Args:
V_fan_rtd_C: 定格冷房能力運転時の送風機の風量(m3/h)
Returns:
定格冷房能力運転時の送風機の消費電力(W)
"""
return 8.0 * (V_fan_rtd_C / 60) + 20.7 | 52c3d887e2c1a9daaedaacfea28207cc31a14d81 | 43,145 |
from datetime import datetime
def generate_timestamp(now=None):
"""Generate an enhanced CDBS-style uniqname."""
if now is None:
now = datetime.datetime.utcnow()
if now.year < 2016:
year = chr(now.year - 2015 + ord('z'))
elif 2016 <= now.year <= 2025:
year = chr(now.year ... | 269ab4206d4a3643ad6d5d1f3d4f50e9f3de06ad | 43,146 |
def crop_2d(pts2d, Prect, bounds):
"""
Expects 2D coordinate points and a dict of bounds of traffic signs
"""
min_x = bounds['x'] - bounds['w']
max_x = bounds['x'] + bounds['w']
min_y = bounds['y'] - bounds['h']
max_y = bounds['y'] + bounds['h']
# print(min_x)
# print(max_x)
# print(min_y)
# print(max_y)
... | 2c218c518cd7a56bcb2c6ca87f9548d8ecc32c78 | 43,147 |
def covid_mask_habit(A_1, A_2, D_inverse, a_1, t_2, t_3, b_1, b_2, p, alpha, beta, r, k, habit_p):
"""
Description
-----------
This funciton simulate the spread of two contagions on two different
networks, where contagions are correlated as described in the project
report.
... | 93f6836cc223c151a44682252e22334c403d1e0d | 43,148 |
def _get_http() -> httplib2.Http:
""" Provides an authorized HTTP object, one per thread """
if not hasattr(_tls, "_HTTP") or _tls._HTTP is None:
http = httplib2.Http(timeout=_TIMEOUT)
# Use application default credentials to make the Firebase calls
# https://firebase.google.com/docs/ref... | 815f01bf820f9584bb9e2e82e594b03c6615770a | 43,149 |
async def read_rental_states(connection=Depends(get_db)):
"""
Fetches rental price average per state forecasted for next 2 years
"""
query = f"""
SELECT state, price, date
FROM forecasted_rentals_states;
"""
df = pd.read_sql(query, connection)
if len(df) > 0... | 3e34c16de1cec13411d50f70bd457d9d8e3e3099 | 43,150 |
from typing import Match
def list_deleted_matches():
"""Return paginated list of deleted matches.
Params:
page (int): Optional. Page number to return
"""
received = request.get_json()
if received:
page = received.get('page', 1)
else:
page = 1
# Query matches
p... | 82adb0aed70cdf44beb810d78ee64cc0529961bb | 43,151 |
from datetime import datetime
def api_post_by_id(id):
"""All user CRUD operations for one single post by ID"""
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
if "lost" in id:
cursor.execute("SELECT * FROM lost_pets WHERE id=%s", [id])
else:
cursor.execute("SELECT * FROM f... | 432a985a7e9d26170576cc674d520d82cb861e83 | 43,152 |
from typing import List
def preprocess_ical(text: str) -> List[str]:
""" Removes VALARM ACTION:NONE from the iCal file (included in some events from Google Calendar)
"""
lines = text.splitlines()
new_lines = []
i = 0
try:
while i < len(lines):
if lines[i] != "BEGIN:VALARM... | ad2d63cdb1f6883a56c48b2652ac19490c6c3f70 | 43,153 |
import logging
import traceback
def rtt_wrapper(args):
""" wrapper for path() that enables trouble shooting in worker and multiple args"""
try:
return rtt(*args)
except Exception:
logging.critical("Exception in worker.")
traceback.print_exc()
raise | b9aa24cadaea47bc1d3b75be9c39b119dd6ec526 | 43,155 |
from typing import Dict
from typing import Tuple
def generate_financial_amount_replacement(
token: Token,
financial_amounts_encountered: Dict,
percentage_financial_amount_variation: int,
) -> Tuple[str, Dict]:
"""
Generate replacements for an amount and currency based on previous amounts generated... | 8ced5028369d6aba79d42053e8838460fd3d5819 | 43,156 |
from datetime import datetime
def command_seen(bot, user, channel, args):
"""Displays the last action by the given user"""
if not args:
return bot.say(channel, "Please provide a nick to search...")
table = get_table(bot, channel)
# Return the first match, there shouldn't be multiples anyway
... | 18476c83072aaa435dfa42f022a57f8e140a7580 | 43,157 |
def decode_parameters(data):
"""
:code-block
'parameters': [{
'required': False,
'name': 'skip',
'allowEmptyValue': True,
'in': 'query',
'enum': [0, 1],
'type': 'integer',
'description': 'offset'
}]
"""
q... | 3bbdebd00ad1ceee8f3ec2d87e2b2d78b12defef | 43,158 |
def rotate_180_bm8(bits: int) -> int:
"""
bit matrixの180度回転
Parameters
----------
bits : int
対象となるbit matrix
"""
return flip_horizontal_bm8(flip_vertical_bm8(bits)) | 5e3f6cf618f39cc9eef5f3f6cc4c8532d7bd66aa | 43,159 |
import requests
def delete(url: str, data: dict, header: dict):
"""
Issue request
Param 1 - url
Param 2 - data
Param 3 - header
Return - response object
"""
res = requests.delete(url, json=data, headers=header)
ret = {'status_code': res.status_code}
try:
ret['response'... | 900076b53b439655d304daf10a015b560ad2a8c6 | 43,160 |
def abspath_from_egg(egg, path):
"""Given a path relative to the egg root, find the absolute
filesystem path for that resource.
For instance this file's absolute path can be found invoking
`abspath_from_egg("dallinger", "dallinger/utils.py")`.
Returns a `pathlib.Path` object or None if the path was ... | 887ca007cd0692ba334e78109b9aaaca6bcff8d4 | 43,161 |
import pathlib
def get_tldname():
"""look in /etc/hosts or /etc/hostname to determine the top level domain to use
"""
basename = tldname = ''
with open('/etc/hosts') as hostsfile:
for line in hostsfile:
if not line.strip().startswith('127.0.0.1'):
continue
... | 5f1c4f7f63d0ffbd39a05d9529bffabaa2c5d216 | 43,162 |
def get_converter(content_type):
"""Returns converter object. All converter objects should have convert
method.
Parameters:
content_type
the type of content to check for a converter
"""
return CONVERTERS[content_type] | 26d20366e7f16ec52403adc116a21fe38359a7fc | 43,163 |
def proper_case(package_name):
"""Properly case project name from pypi.org."""
# Hit the simple API.
r = _get_requests_session().get(
"https://pypi.org/pypi/{0}/json".format(package_name), timeout=0.3, stream=True
)
if not r.ok:
raise IOError(
"Unable to find package {0} ... | 8c79751f3574850c5503d3a37c66476e5215f977 | 43,165 |
def select_from(*args, **kwds):
"""
Returns :py:class:`~.Select` instance and passed arguments are used for list
of tables. Columns are set to `*`.
"""
return Select().from_(*args, **kwds) | ea7afd8d55846393af4dce046eb576a5704d3c97 | 43,166 |
import functools
def configurable(setting):
"""Return a function that only gets called if a setting is enabled."""
def decorator(func):
@functools.wraps(func)
def _configurable(*args, **kwargs):
if settings[setting]:
return func(*args, **kwargs)
return _con... | 451aeebb280b1d8d54b1eec0f521c6f959e31311 | 43,167 |
def rate_bucket(dataset, rate_low, rate_high):
"""Extract the movies within the specified ratings.
This function extracts all the movies that has rating between rate_low and high_rate.
Once you ahve extracted the movies, call the explore_data() to print first few rows.
Keyword arguments:
d... | 540f72ead479041e29fba8467a5b8f41597b0cf2 | 43,168 |
def get_attributes(sitk_image):
"""Get physical space attributes (meta-data) of the image."""
attributes = {}
attributes['orig_pixelid'] = sitk_image.GetPixelIDValue()
attributes['orig_origin'] = sitk_image.GetOrigin()
attributes['orig_direction'] = sitk_image.GetDirection()
attributes['orig_spa... | 0baf1153bf53529026ef205961903fa6695be389 | 43,169 |
import itertools
def build_vocab(tokenized_src_trgs_pairs, opt):
"""Construct a vocabulary from tokenized lines."""
vocab = {}
for src_tokens, trgs_tokens in tokenized_src_trgs_pairs:
tokens = src_tokens + list(itertools.chain(*trgs_tokens))
for token in tokens:
if token not in... | f2f7601f3e2dabd96376291866897e480e3b957f | 43,170 |
def payback(cashflows):
"""The payback period refers to the length of time required
for an investment to have its initial cost recovered.
(This version accepts a list of cashflows)
>>> payback([-200.0, 60.0, 60.0, 70.0, 90.0])
3.1111111111111112
"""
investment, ca... | 0cbd06294b724ca4f356ca2fcb017026a6d660c8 | 43,171 |
import random
import csv
def generate_postal_code(chance=None, variation=False, row=None):
"""
Function to generate the postal code of the profile.
Args:
chance: Integer between 1-100 used for realistic variation. (not required)
variation: Boolean value indicating whether variation is requested. (optional)
... | 725732269489be408a1ce9bb465fe6b7a9528727 | 43,172 |
def vector_by_axis(axis, origin):
"""
Create a vector along the specified axis.
:param str axis: Axis ('x', 'y', or 'z').
:param array_like origin: Origin of vector.
:return: Vector along specified axis.
:rtype: :class:`.Vector`
"""
if not isinstance(origin, Point):
origin = Po... | fe8b3daf8511002818486c609ee02b99e69413df | 43,173 |
def daily_statistics(cube, operator='mean'):
"""
Compute daily statistics.
Chunks time in daily periods and computes statistics over them;
Parameters
----------
cube: iris.cube.Cube
input cube.
operator: str, optional
Select operator to apply.
Available operators: ... | 7bada8c8091358eba5eec1aa0f268bfbd8883037 | 43,174 |
def is_symmetric(t):
"""
Returns True if the root of t is a symmetric node, and False otherwise. If t is a leaf, it returns True:
ex falso quodlibet.
:return: `bool` instance.
"""
return t.is_leaf() or \
all(isomorphic(t.children[0], ch) for ch in t.children[1:]) | 6f0a116aaaa80c5ff19460a23cbdab98c66e5447 | 43,176 |
def fwdkin(robot, theta):
"""
Computes the pose of the robot tool flange based on a Robot object
and the joint angles.
:type robot: Robot
:param robot: The robot object containing kinematic information
:type theta: numpy.array
:param theta: N x 1 array of joint angles. Must ha... | 35116326097f51676db2579fac0ce208a516202a | 43,177 |
def lstm_attention_decoder(inputs, hparams, train, name, initial_state,
encoder_outputs):
"""Run LSTM cell with attention on inputs of shape [batch x time x size]."""
def dropout_lstm_cell():
return tf.contrib.rnn.DropoutWrapper(
tf.nn.rnn_cell.BasicLSTMCell(hparams.hidden_si... | d84958cd0b8e4294422e0185912bee1f8a60e1c5 | 43,179 |
from typing import Any
def check_non_linearity(item: Any) -> bool:
"""Evaluates whether "item" is a torch module
:param item: variable to check
:return: boolean
"""
return isinstance(item(), nn.Module) if item is not None else True | 639796e25c7d73d895bd1ece159fbe8d7c591720 | 43,180 |
import numpy
def mean_average_error(ground_truth, regression, verbose=False):
""" Computes the mean average error (MAE).
Args:
ground_truth (list or 1-dim ndarray): ground truth labels.
regression (list or 1-dim ndarray): label estimations. Must have the same length as the ground tru... | 0bcc7fe67aa97dcf44595a6f2ef63ed242b29837 | 43,181 |
def calcFlashThresholds(loSampleData, hiSampleData):
"""\
Analyses light sensor sample data and returns suggestions for the thresholds needed to detect the flashes.
:param loSampleData: list of sample values, where each value is the lowest seen during that sampling period
:param loSampleData: list ... | a302a0291975434c506f8406293895e75ded24a4 | 43,182 |
def pmd_load_variance(pmd_map):
"""
Get load variance on a set of pmds.
Parameters
----------
pmd_map : dict
mapping of pmd id and its Dataif_Pmd object.
"""
pmd_load_list = list(map(lambda o: o.pmd_load, pmd_map.values()))
return util.variance(pmd_load_list) | a7e7eddb622adabbc6bb29ee3b776457c96d5cea | 43,183 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.