lang
stringclasses
10 values
seed
stringlengths
5
2.12k
python
def test_default_return_errors(self): c = copy(CONFIG_BASE) del c['return_error_details'] data = get_ldap(c) self.assertEqual(data['return_error_details'], DEFAULT_RETURN_ERRORS) """Not specifying a base_dn should fail""" def test_missing_base_dn(self): c = copy(CON...
python
def intersection(lhs: "Data", rhs: "Data", duplicates: bool = False) -> "Data": """(Multi)set intersection of two datasets. This intersection method does not retain duplicates by default. For multiset behaviour, specify 'duplicates=True'. Parameters: lhs: one of the two datasets to intersect...
python
elif (seconds < 26): return "tramp " elif (seconds < 31): return "slut " elif (seconds < 36): return "bitch " elif (seconds < 41): return "bimbo "
python
], ids=["valid_payload", "invalid_payload", "valid_uuid", "invalid_uuid"], ) def test_validators( validator: Callable, expected_output: Union[str, _client.AnyJson], expected_exception: Exception, exception_pattern: Optional[str], ): if expected_exception:
python
def setUp(self): self.new_user = User(f_name = 'Grishon', l_name = 'Gikima', email = '<EMAIL>', password_hash = '<PASSWORD>') self.category = Category(name = 'sports') def test_user_init(self): self.assertTrue(self.new_user.f_name is not None) self.assertTrue(self.new_user.l_na...
python
with open("combined.tex", "w") as combined: with open("tex/paper.tex", "r") as paper: for line in paper: if line.strip()[:7] == "\\input{": with open("tex/" + line.strip()[7:].replace("}", "").replace("\n", ""), "r") as section: combined.writelines(section.rea...
python
register_event_type(IncidentSeverityUpdatedEvent) class IncidentStatusUpdatedEvent(BaseIncidentEvent): event_type = 'incident_status_updated'
python
'interfaces': { 'TenGigabitEthernet1/0/33': { 'duplex': 'a-full', 'speed': 'a-10G', 'status': 'connected', 'type': '100/1000/2.5G/5G/10GBaseTX', 'vlan': '1'
python
if (a==b) : print("[%d] Correct" % idx) else : print("[%d] Failed" % idx) check(1, True, ocean.checkOverlap([5],[4],0,1,[4],[3],7,1)) check(2, False, ocean.checkOverlap([5],[4],0,1,[3],[3],7,1)) check(3, True, ocean.checkOverlap([5,3],[4,1],0,1,[3],[10],-3,1)) check(4, True, ocean.checkOverlap([5,...
python
DfCleaner.clean_column_names_in_place(pd.DataFrame({'seconds': [3600]}, columns=['seconds'])) def test_rename_column_names_in_place_method(self): DfCleaner.rename_column_names_in_place(pd.DataFrame({'seconds': [3600]}, columns=['seconds']), {'seconds':...
python
syntax = ( 'ruby on rails', 'ruby', 'javascript', 'python', 'go', 'html', 'css', 'markdown', 'php', 'haskall',
python
# Forwards message with conn.Producer(routing_key="PLUGIN_ERROR") as producer: producer.publish(newmsg, headers={"source-id": self._queue_name}, priority=message.properties.get("priority")) # Send ack message.ack()
python
target = open("/data2/lbd/kitti/train/" + str(i).zfill(4) + "_td.dat", "wb") with h5py.File(file,'r') as f: events = f["events"] events = rfn.unstructured_to_structured(events, dtype = dtype([('t', '<u8'), ('x', '<f4'), ('y', '<f4'), ('p', '<i4')])) dat_events_tools.write_event_buffe...
python
retval = resource_a.all_names(astype=list) assert ('grassbuffers' in retval) and isinstance(retval, list) def test_all_names_query_contains_GRASSBUFFERS_as_series(resource_a): retval = resource_a.all_names(astype='series')
python
from wtforms import Form, TextField, TextAreaField, StringField, SubmitField, validators import easygui #from identifier_retrieval import retrieve_identifier_semantics # App config. DEBUG = True
python
# # Note: The ball can only be seen if the height of the rebounding ball # is strictly greater than the window parameter. # # Example: # 1) h = 3, bounce = 0.66, window = 1.5, result is 3 # 2) h = 3, bounce = 1, window = 1.5, result is -1 (*) # (*) Condition 2 not fulfilled. #
python
] ) }
python
# limitations under the License. """Cornell Movie Dialog Dataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import os import re from tensor2tensor.data_generators import dialog_abstract from tensor2tensor.data_generators import...
python
sys.exit() # soil moisture data (10-minute) obs = nc.Dataset('observations/cesar_soil_water_lb1_t10_v1.1_200607.nc') sm_03 = obs.variables['TH03'][tidx] sm_08 = obs.variables['TH08'][tidx] sm_20 = obs.variables['TH20'][tidx] # soil moisture data (daily average from prior day) # Julian day for July 2, 2006 is 183, ...
python
def create_invoice(description, amount): """ Call strike's restful api to create a new invoice """ cor_id = uuid.uuid4().hex url = "https://api.strike.me/v1/invoices"
python
if hasattr(data, 'result') or ( isinstance(data, collections.abc.Iterable) and any([hasattr(item, 'result') for item in data])): raise exceptions.ValueError( 'Make a Future of type NDArray instead of NDArray of type Future, or call result() first.') ...
python
from time import sleep from cyberpass import login import cStringIO,StringIO, re import urllib2, os, urllib import os import pycurl import time def login1():
python
default_method_name = f"get_{field_name}" default_write_method_name = f"set_{field_name}" if self.method_name is None: self.method_name = default_method_name if self.write_method_name is None: self.write_method_name = default_write_method_name super(Seria...
python
parser = get_parser() options = parser.parse_args() for pdb_file in options.pdb_files: FILE = open(pdb_file, 'r') lines = FILE.readlines() FILE.close()
python
def __init__(self): self.message = "Override __otp_str__ method to customize output style." super(NoOtpStrMethod, self).__init__(self.message) class Case: """A base class that TestCases will inherit that, by default it will generate a testCase only once you can change that by changing the ...
python
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN...
python
# Test 10: to check the .provides provider10 = providers.Callable(Cat) provides10: Optional[Callable[..., Cat]] = provider10.provides assert provides10 is Cat
python
The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: ...
python
def _insert_at_index(self, arr, val, index): """ The method is only used internally, it inserts in item in an array at a given index and shifts the values after that index to the right. :param list arr: list of floats representing the recommendation score. :param float val:...
python
def exclude_pairs(self): # exclude all pairs with dist >= 4 * tolerance # dist_allowed is invariant under refine_adjusted_shift: # exclude all pairs with dist_allowed >= tolerance # if 0 continuous shifts: dist_allowed == dist: # exclude all pairs with dist >= tolerance timer = user_plus_s...
python
parser.add_argument("field_id", help="Use a value of 'all' to delete all the custom fields for the given object") args = parser.parse_args() logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', stream=sys.stderr, level=logging.DEBUG) logging.getLogger("requests").setLevel(logging.DEBUG)
python
#'sphinx_toolbox.more_autodoc' test required 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.todo', ] templates_path = ['_templates'] language = 'en' exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] def skip(app, what, name, obj, would_skip, options): if name in ( '__init__',):
python
# -*- coding: utf-8 -*- """ Example usage of PyHawk. You can point this at HAWK's server.js example node server. Or you can point it at sample_server.py """ import requests
python
count = 0 foundids = [] tracks = app("iTunes").browser_windows[1].view.tracks for id, track in zip(tracks.database_ID.get(), tracks.get()): if id in foundids: track.delete() count += 1
python
def get_thumbnail_url(self, obj): return obj.imagefile.thumb.url def get_file_url(self, obj): return obj.file.url return ThisClass ImageSerializer = basefileserializer_factory( Image )
python
def __del__(self): llbc.inl.Event_Del(self._cobj) @property def evid(self):
python
from .singletonscanner import SingletonScanner from .reaper import Reaper from .reaperstandalone import reaperstandalone from .prepuller import Prepuller from .prepullerstandalone import prepullerstandalone from .parse_args import parse_args from .primerepocache import prime_repo_cache __all__ = [ScanRepo, SingletonSca...
python
pred_stack = np.vstack((pred(model, base), pred(model, r90), pred(model, r180), pred(model, r270), pred(model, r90_VF), pred(model, r270_VF), pred(m...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # IMPORTS from sqlalchemy import Column, Integer, String import modules.globals as sg
python
Qt.QGraphicsItem.ItemSendsGeometryChanges | Qt.QGraphicsItem.ItemSendsScenePositionChanges | Qt.QGraphicsItem.ItemHasNoContents ) self._size = Qt.QSizeF() # Children are generally overlay items that should appear over anything else rather than z-fighting ...
python
acqs.append(a2.toordinal()) image_pairs=[] for im1 in acqs: for im2 in acqs: if im2>im1: if (im2-im1) in [6,12,18,24,36,48]:
python
num = int(a[aIndex]) + int(b[bIndex]) + flag flag = num / 2 num %= 2 s = str(num) + s aIndex -= 1 bIndex -= 1 while aIndex >= 0: num = int(a[aIndex]) + flag flag = num / 2 num %= 2
python
def upgrade(): op.alter_column( "screenshot", "path", existing_type=sa.VARCHAR(length=100), type_=sa.Unicode(length=200), existing_nullable=False, )
python
''' file = directory_path + "ing-raw-2.0.csv" df_ing = ing.df_extract_ing_releve(directory_path + "ing_raw.csv", directory_path + "ing-rules.csv", 0) df_ing.to_csv(file, index=False) df_ing_raw = pd.read_csv( file, encoding='latin-1', # error_bad_lines=False, sep="," ...
python
Entry point for subclassed commands to add custom arguments. """ pass def get_graph(self, *args, **options): def not_implemented(): raise NotImplementedError("You must implement {}.get_graph() method.".format(self)) return bonobo.Graph(not_implemented) def ...
python
level=logging.DEBUG) console = logging.StreamHandler() console.setLevel(logging.INFO) return None def parse_webanno(): grammarian = GrammarAnnotator(import_dir=args.conll) def get_tsv(): import os for file in os.listdir(args.webannotsv): if file.endswith(".tsv"):...
python
<gh_stars>0 """yatube URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') ...
python
"""Execution results from Jupyter notebooks."""
python
for element in range(input_length): total = 0 # Everything to the left of element is bound to be zero additions. for this_digit in range(element, input_length): total += input_list[this_digit] * pattern_pos(element_number=element + 1, position=this_digit) last_digit = ...
python
class BadStateException(APIException): status_code = 400 class NothingToDoException(APIException): status_code = 400 def unzip(filename, extract_dir): with zipfile.ZipFile(filename) as archive: for entry in archive.infolist():
python
################################################################ # I: Importing & initialising import pygame pygame.init() # D: Display configuration # size = (640, 480) image_size = pygame.image.load("background.jpg").get_size() screen = pygame.display.set_mode(image_size) pygame.display.set_caption('Pygame Examp...
python
import argparse from crypt import crypt chars = '0123456789abcdef' parser = argparse.ArgumentParser(description='Generate random unique local IPv6 prefix')
python
app = Flask(__name__) scraper = Scrapper() @app.route("/") def main(): return render_template("index.html")
python
projects = Project.query.filter(Project.name == 'Test Project').all() assert '422' in resp.status assert len(projects) == 0 assert resp_data['error'] == 422 assert 'Validation error' in resp_data['message']
python
@staticmethod def list(): from Msgrpc.Handle.handler import Handler data = Xcache.list_lazyloader() handlers = Handler.list_handler_config() context = data_return(200, CODE_MSG.get(200), {"lazyloaders": data, "handlers": handlers}) return context @staticmethod de...
python
for i in range(n - 1, 0, -1): c_storage[i] = update_c_right(c_storage[i + 1], mps_b[i], mpo_x[i], mps_a[i]) return c_storage def reduceD_onesite(tensor_a, tensor_x, c_left, c_right): c_left, numind_x = contract_tensors(c_left, 3, (2, ), tensor_a, 3, (0, )) c_left, numind_x = contract_tensors(c...
python
from_city=str_schema(), from_state=str_schema(), to_city=str_schema(), to_state=str_schema(), quote=null_dict_schema( id=num_schema(), transaction_id=num_schema(), vehicle_request_...
python
) urlpatterns += staticfiles_urlpatterns() urlpatterns += patterns(
python
vhdl = '' for library in self.libraries: vhdl += library +';\n'
python
msg = 'Available model checkpoints are:\n' msg += '\n'.join([f'\t{c}' for c in ckpts]) print(msg) return if args.force: p.cleanup_model_export() ckpt = args.checkpoint_name or None try: return_code = p.ex...
python
A views module using views subclassed from BakeView """ help = "Enter an app to bake, or no app label to bake all apps" def add_arguments(self, parser): parser.add_argument('app', nargs='*', type=str, default=[])
python
id = db.Column(db.Integer, primary_key=True) service = db.Column(db.String(50), index=True) username = db.Column(db.String(50), index=True) email = db.Column(db.String(50)) password_enc = db.Column(db.String()) def __init__(self, service, username, email, password, key): self.service = ...
python
'`test_project_id.dataset_id.concept` as vis_2 on ' 'm.visit_source_concept_id = vis_2.concept_id ', 'destination_table_id': 'visit_occurrence', 'write_disposition': 'WRITE_TRUNCATE', ...
python
def test_RESOURCE_lambda_layer_WITH_deployed_lambda_function_EXPECT_execution_successful(): """ Test whether the layer provides necessary functionality. :return: No return. """ # Create client for lambda service. lambda_client = Credentials().boto_session.client('lambda') # Invoke specific...
python
] operations = [ migrations.CreateModel( name='Message',
python
long_description_content_type="text/markdown", license = "MIT Licence", url = "https://github.com/Bertie97/pyctlib/tree/main/micomputing", author = "<NAME>", author_email = "<EMAIL>", packages = find_packages(), include_package_data = True,
python
def main(): x = np.linspace(0, 10) y = np.random.normal(x, 0.5)
python
def main(): parser = argparse.ArgumentParser( description="Get lyrics for currently playing song on Spotify. Either --tab or --cli is required.") parser.add_argument('-t', '--tab', action='store_true', help='Display lyrics in a browser tab.') parser.add_argument('-c', '--cli', action='store_true', help='Display ...
python
) tab.add_row([experiment,elen, "%.2f"%(round(oracle_score_before*100,4)), "%.2f"%(round(oracle_score_after*100,4)), "%.2f"%(round((oracle_score_after-oracle_score_before)*100,4)), "%.2f"%(round(full_acc_before*...
python
# print(Pc.size(), gt_c.size()) cd1 = CD(P1, gt_1)* 1e3 # print(P1.size(), gt_1.size()) cd2 = CD(P2, gt_2)* 1e3 # print(P2.size(), gt_2.size()) cd3 = CD(P3, gt)* 1e3 # print(P3.size(), gt.size()) loss_all = (cdc + cd1 + cd2 + cd3) * 1e3 losses = (cdc, cd1, cd2, cd3)
python
game = GameIDSerializer(read_only=True) pick = TeamIDSerializer(read_only=True) class Meta: model = UserPick fields = ('id', 'team', 'game', 'pick', 'correct') class UserPickPostSerializer(serializers.ModelSerializer):
python
from share import views urlpatterns = [ path('', views.index, name='home'), path('share', views.share, name='share'), path('login', views.login, name='login'), path('register', views.register, name='register'), path('categories', views.categories, name='categories'), ]
python
import time from geopy.geocoders import Nominatim geolocator = Nominatim() def getGPS(place): #location = geolocator.geocode("Acquafredda di Maratea, Italia") location = geolocator.geocode(place) if not location: return 'NOT FOUND' #print(str(place).encode("utf-8")) #print(str(location).e...
python
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do not exceed four million, # find the sum of the even-valued terms. def solution(limit): a = 1 b = 2 s = 0
python
bin edges, including the rightmost edge, allowing for non-uniform bin widths. (default: None, use Freedman-Diaconis rule) """)
python
[{'params': model_registrar.get_all_but_name_match('map_encoder').parameters()}, {'params': model_registrar.get_name_match('map_encoder').parameters(), 'lr': 0.0008}], lr=hyperparams['learning_rate']) # Set Learning Rate if hyperparams['learning_rate_style'] == 'cons...
python
def logged_check_call(*args, **kwargs): try: subprocess.check_call(*args, **kwargs) except subprocess.CalledProcessError as e: logger.error('Command `{}` exited with return value {}\nOutput:\n{}'.format(e.cmd, e.returncode, e.output))
python
def gen_crl(): with _workdir() as workdir: with open(os.path.join(workdir, 'crlnumber'), 'w') as f: f.write('{:02x}'.format(Certificate.get_crlnumber()))
python
# from json import dumps # api_addr = 'http://127.0.0.1:8000/api/' # def save_message(data: dict): # # data = {'message': '你好', 'customData': {'user_id': 7}, 'session_id': 'b9c6bb643e194746b278f0438215daba'} # tail = "testSaveChat/" # record = { # "content": data["message"], # "from_user...
python
for option in self.options: if option.name == name or option.alias == name and name: return option.value return None def set(self, name, value): name = name.upper() for option in self.options: if option.name == name or option.alias == name a...
python
dhi = self.tmy["DHI"] albedo = 0.16 # Urban environement is 0.14 - 0.22 # POA Beam component df_poa["E_b_poa"] = dni * np.cos(np.radians(aoi)) # POA Ground component df_poa["E_g_poa"] = ( ghi * albedo * ((1 - np.cos(np.radians(self.surface_tilt))) / 2) ...
python
# template matching res = cv2.matchTemplate(src, templ, cv2.TM_CCOEFF_NORMED) res_norm = cv2.normalize(res, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U) _, maxv, _, maxloc = cv2.minMaxLoc(res) print('maxv', maxv) print('maxloc', maxloc) # 매칭 결과를 빨간 사각형으로 표시 th, tw = templ.shape[:2] dst = cv2.cvtColor(src, cv2.COLOR_G...
python
""" PyDMD init """ __all__ = ['dmdbase', 'dmd', 'fbdmd', 'mrdmd', 'cdmd', 'hodmd', 'dmdc', 'optdmd', 'hankeldmd'] from .meta import * from .dmdbase import DMDBase from .dmd import DMD from .fbdmd import FbDMD from .mrdmd import MrDMD from .cdmd import CDMD from .hankeldmd import HankelDMD
python
# will be logged to log.error in the thrown exception log.status.Print(error) if 'errorDetail' in log_record: error_detail = log_record['errorDetail']['message'].strip() log.status.Print(error_detail)
python
def quit_wrapper(webdriver, current_webdriver_list): for not_closed_webdriver in current_webdriver_list: not_closed_webdriver.close() webdriver.quit()
python
from rest_framework import serializers from .models import ItemModel class ItemModelSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ItemModel fields = ['url', 'name', 'description', 'image']
python
OPENAI_GPT_CONFIG = "" convert_openai_checkpoint_to_pytorch(OPENAI_GPT_CHECKPOINT_FOLDER_PATH, OPENAI_GPT_CONFIG, PYTORCH_DUMP_OUTPUT) elif sys.argv[1] == "transfo_xl": ...
python
if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_repo_mirror_config" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'reposit...
python
return self.db.lookup_id(n3 + " ") def count(self, triple): s, p, o = triple vs = (s is None) or isinstance(s, rdflib.Variable) vp = (p is None) or isinstance(p, rdflib.Variable)
python
Returns ------- hrf: array of shape(length / tr * oversampling, float), hrf sampling on the oversampled time grid """ dt = tr / oversampling time_stamps = np.linspace(0, time_length, float(time_length) / dt) time_stamps -= onset / dt
python
def start(self, from_run=False): self._lock.acquire() if from_run or self._stopped: if not self.next_call: self.next_call = time.time() self.next_call += self.interval self._timer = Timer(self.next_call - time.time(), self._run) self....
python
pass else: response = requests.get(f'https://api.pubg.com/shards/steam/matches/{matchId}', headers=header) r = response.json() participantList = r["included"] for participant in p...
python
TypeError: 'module' object is not callable >>> RESTART: Z:/Coding Classes/Python Text Adventures/wwif/students/simone/kjf dlscvniuekdfs.py Warning (from warnings module): File "C:\Users\wwclc\AppData\Local\Programs\Python\Python35\lib\getpass.py", line 101 return fallback_getpass(prompt, stream) GetPassWarnin...
python
""" calculates the non-living equations for DOM, POM, and nutrients """ # State variables o2o = conc[0] # Dissolved oxygen (mg O_2 m^-3) n3n = conc[2] # Nitrate (mmol N m^-3) n4n = conc[3] # Ammonium (mmol N m^-3)
python
transparent_canvas = Image.new('RGBA', bg.size, color=(0, 0, 0, 0)) transparent_canvas.paste(cutout, offset, cutout) offset_decal = transparent_canvas displaced = ImageChops.multiply(offset_decal, source) product = ImageChops.composite(displaced, source, displaced) bg.paste(product, ((bg.width...
python
def test_channel_not_configured(): assert not is_channel_configured( MagicMock(client_id=123, client_secret="secret", pool_address=None))
python
from keras.engine.topology import Layer from keras import regularizers from keras import constraints from keras import activations from keras import initializations
python
shutil.copy(file_path, file_name) except Exception: raise Exception('Failed to prepare file for upload.') try: file_handler = open(file_name, 'rb') fname = os.path.basename(file_handler.name) encoded_file_name = base64.b64encode(fname.encode()) file_data = file_h...
python
from pydantic import BaseModel class Auth(BaseModel): auth_type: str class NewUser(BaseModel): email: str first_name: str last_name: str
python
# Define loss functions def gram_matrix(x): assert K.ndim(x) == 3 features = K.batch_flatten(x) gram = K.dot(features, K.transpose(features)) return gram def region_style_loss(style_image, target_image, style_mask, target_mask): '''Calculate style loss between style_image and target_image, for...