ngram
listlengths
0
67.8k
[ "__init__(self, d_model, heads, d_ff, dropout): super(TransformerDecoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads, d_model, dropout=dropout)", "emb): return self.pe[:, :emb.size(1)] class TransformerEncoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff, dropout): super(Transf...
[ "= \"https\" def complete_login(self, request, app, token, **kwargs): response = requests.post( self.profile_url, headers={\"Authorization\":", "= \"https://api.dropbox.com/2/users/get_current_account\" redirect_uri_protocol = \"https\" def complete_login(self, request, app, token, **kwargs): response =", "toke...
[ "= '1.2.7' # The full version, including alpha/beta/rc tags release = f'v{version}' #", "tags release = f'v{version}' # endregion # region General configuration # Add any", "sys.path.insert(0, os.path.abspath('..')) # endregion # region Project information project = 'Upkeep' copyright =", "contain templates h...
[ "variables def get_enums(header): enums = [e for e in header.enums if e.get(\"name\")] #", "return enums def read_header(header_path, skip_macros=None): # I tried to do this in multiple", "main_classes[(module, header)] methods_defined_outside = get_methods_defined_outside(header_functions) class_definitions = ...
[ "= codecs.open(os.environ[\"script\"], encoding='utf-8', mode='r') command = f.read() command = command.replace(\"$uid\", uid) # Call", "and replace params winrm_wrapper.writeLog(\"loading script\") f = codecs.open(os.environ[\"script\"], encoding='utf-8', mode='r') command = f.read()", "stored in environment a...
[ "@registry.extensible_enum class ExtensibleEnumeration(Enum): a = auto() b = auto() class RegistryTests(unittest.TestCase): def test_class_registry(self):", "@registry.autoregister class Extension4(object): pass def test_enum_registry(self): ExtensibleEnumeration.register('c') self.assertTrue(ExtensibleEnumeratio...
[ "handler.wait_closed() await finalize() @pytest.fixture async def setup_logger(make_tcp_handler): async def go(*args, **kwargs): handler, server", "[loads(i) for i in s.split(\"\\n\") if i] async def close(self): if self.server is", "yield go async def finalize(): for server in servers: await server.close() awa...
[ "(not isinstance(value, dict) or not self._is_tc_entity(value)): raise RuntimeError('Invalid data provided for TcEntity.') #", "proper structure for Key Value.\"\"\" if data is None: return False return all(x", "self._output_variables_by_name = {} self._output_variables_by_type = {} for ov in self._output_varia...
[ "dtype=tf.int32), }) if is_training: if hvd is not None: d = d.shard(hvd.size(), hvd.rank())", "\"Whether to enable AMP ops. When false, uses TF32 on A100 and FP32", "Unless required by applicable law or agreed to in writing, software # distributed", "is_training, drop_remainder, hvd=None): \"\"\"Creates an `...
[ "| Student.objects.filter(programme = \"PhD\") assistant_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(acad_approval =", "no in excel file roll_no - details of student from file first_name -", "def get_context(requ...
[ "License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "writing, software # distributed under the License is distributed on an \"AS IS\"", "Unless required by applicable law or agreed to in writing, software # distributed", "subject.cmd.replicator ' 'compare az1:9292 az2:9292 --de...
[ "date(1970, 5, 30), date(1971, 5, 31), date(1997, 5, 26), date(1999, 5, 31), date(2000,", "4, 15), self.markettradingdayss.BtwDates(current_date, future_date)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.BtwDates(current_date, future_date)) # if __name__ ==", "nc_marketholidayss) nc_marketholida...
[ "#!/usr/bin/env python from distutils.core import setup from catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup(", "import setup from catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup( packages=['rosmsg'], package_dir={'': 'src'}, scripts=['scri...
[ "= None def insert(self, value): self.list = Node(value, self.list) def start_iter(self): return self.list", "\"\"\" Main execution function \"\"\" if test: return ############################################################################### # Executable code ####################################################...
[ "of the spatial stencil discretisation. Defaults to 4. kernel : selects a visco-acoustic", "return rec, p, v, summary def adjoint(self, rec, srca=None, va=None, pa=None, vp=None, qp=None,", "or array-like The receiver data. Please note that these act as the source", "= r or TimeFunction(name=\"r\", grid=self....
[ "') itemSetList.append(list(map(int, cates))) def myApriori(): te = TransactionEncoder() te_ary = te.fit(itemSetList).transform(itemSetList) df =", "TransactionEncoder() te_ary = te.fit(itemSetList).transform(itemSetList) df = pd.DataFrame(te_ary, columns=te.columns_) return df def dataInit(): if", "= line.repl...
[ "= request_json['name'] headers = { 'Access-Control-Allow-Origin': 'https://furikuri.net', 'Access-Control-Allow-Methods': 'GET, POST', 'Access-Control-Allow-Headers': 'Content-Type' }", "<reponame>FuriKuri/faas-playground def hello_world(request): request_json = request.get_json() name = 'World' if request_json ...
[ "from tonclient.client import TonClient from tonclient.types import Abi, CallSet, Signer, ClientConfig, \\ ParamsOfEncodeMessage,", "signer=Signer.NoSigner(), address=GIVER_ADDRESS, call_set=call_set) process_params = ParamsOfProcessMessage( message_encode_params=encode_params, send_events=False) async_core_clien...
[ "'/test_i18n': return s.upper() return s i18n.gettext = gettext def test_does_translations(app): \"\"\"Callback interface is", "we test for request path that only functions from this module could set", "# so we test for request path that only functions from this module", "== '/test_i18n': return s.upper() ret...
[ "else: w_scale, h_scale = scale_factor[0], scale_factor[1] img_h = np.round(ori_shape[0] * h_scale.item()).astype( np.int32) img_w", "- y0) * 2 - 1 img_x = (img_x - x0) / (x1", "shape (n, 4/5) det_labels (Tensor): shape (n, ) img_shape (Tensor): shape (3, )", "mask_targets @force_fp32(apply_to=('mask_pred', )...
[ "= Config() #params for text detector cfg.det_algorithm = \"DB\" cfg.det_model_dir = \"./inference/ch_ppocr_mobile_v2.0_det_infer/\" cfg.det_limit_side_len", "1.6 cfg.use_dilation = False # #EAST parmas # cfg.det_east_score_thresh = 0.8 # cfg.det_east_cover_thresh", "cfg.det_db_unclip_ratio = 1.6 cfg.use_dilati...
[ ") self.res = DoubleResNet(BasicBlock,deconv_outplanes+skip_inplanes,res_outplanes,stride=1) def forward(self,x,skip_x): out = self.deconv(x,output_size=skip_x.size()) # concat skip connections", "self.inplanes, kernel_size=7, stride=1, padding=3, bias=True) # initial conv layer self.bn1 = nn.BatchNorm2d(self.inp...
[ "in range(len(examples))] questions = [examples[i]['question'] for i in range(len(examples))] tokenized_examples = tokenizer( questions,", "import paddle from paddle.io import DataLoader from args import parse_args import paddlenlp as", "Stack(dtype=\"int64\") }): fn(samples) train_data_loader = DataLoader( dat...
[ "# env.render() # # # Update Q table with new knowledge # Q[s,", "--> Identity s: s + 1: [[1. 0. 0. 0. 0. 0. 0.", "Q = np.zeros([env.observation_space.n, env.action_space.n]) # # # List of reward and steps per", "greedy # print(\"s = \", s,\" --> Identity s:s+1: \", np.identity(env.observation_space.n)[s:s+1]...
[ "'RsaSsaPkcs1PrivateKey': [ 'RSA_SSA_PKCS1_3072_SHA256_F4', 'RSA_SSA_PKCS1_4096_SHA512_F4' ], 'RsaSsaPssPrivateKey': [ 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4', 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4' ], 'AesCmacPrfKey': ['AES_CMAC_PRF'], 'HmacPrfKey':", "'ECDSA_P256_IEEE_P1363': signature.signature_key_templates.EC...
[ "key hash {}'.format(key['public_key'], key_hash)) else: logging.warning(\"Couldn't public key for key hash {}\".format(key_hash)) response", "level=logging.INFO) app = Flask(__name__) # sample config used for testing config = {", "= None try: if key_hash in config['keys']: key = config['keys'][key_hash] respon...
[ "0x1 UNW_FLAG_UHANDLER = 0x2 UNW_FLAG_FHANDLER = 0x3 UNW_FLAG_CHAININFO = 0x4 def read_unwind_info(view, address):", "None: runtime_function['BeginAddress'] += view.start runtime_function['EndAddress'] += view.start runtime_function['UnwindData'] += view.start return runtime_function, address", "is None: contin...
[ "fig.add_trace(traces[0]) idx = len(fig.data) - 1 for i, tr in enumerate(traces): frames.append(go.Frame(name=str(i), traces=[idx],", "z = corners.T tr = go.Scatter3d( x=x, y=y, z=z, line=dict(color='rgba(0, 0, 0, .5)'),", "def plot_camera(fig, R, t, K, color='rgb(0, 0, 255)'): \"\"\"Plot a camera as a", "z=[...
[ "= True def check_victory(check_grids: np.ndarray) -> set[int]: \"\"\"return empty set if no victory,", "set if no victory, else set of id of the wining grids\"\"\" return", "<filename>day04/c.py import numpy as np GRID_SIZE = 5 def read_bingo_grid(lines: list[str]) -> list[list[int]]:", "np.ndarray, number: ...
[ "alt.selection_single(name='year', fields=['year'], bind=slider) base = alt.Chart(pop).add_selection( select_year ).transform_filter( select_year ).transform_calculate( gender=if_(datum.sex == 1,", "# category: case studies import altair as alt from altair.expr import datum, if_", "select_year ).transform_calcu...
[ "[ migrations.CreateModel( name='Token', fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('name',"...
[ "= db.Column(db.DateTime) # # def __init__(self, uuid, payload, datetime): # self.uuid = uuid", "self.uuid = uuid # self.payload = payload # self.datetime = datetime # #", "payload # self.datetime = datetime # # def __repr__(self): # return '<Data %r>'", "= db.Column(db.Integer, primary_key=True) uuid = db.Co...
[ "= iface self.pre_iface_state = _iface_state(iface) self.iface_state = self.pre_iface_state self.post_iface_state = '' def iface_up(self):", "state returns UP, DOWN, UNKNOWN \"\"\" state = command_util('ip', 'link', 'show', iface).stdout.read() search_result", "range_start[i] < 255: yield '.'.join([str(item) fo...
[ "schemas.category import CategorySchema from schemas.facts_in_data import FactsInDataSchema from schemas.market import MarketSchema from schemas.period", "from schemas.brand import BrandSchema from schemas.category import CategorySchema from schemas.facts_in_data import FactsInDataSchema from", "import FactsInD...
[ "and compare the results of with your # improved architecture. # # Be", "pass to fully-connected layer batch = batch.view(-1, self.num_flat_features(batch)) # Connect the reshaped features", "an activition function to 'batch' #batch = func.sigmoid(batch) return batch def num_flat_features(self, inputs):", "Pa...
[ "= timedelta(weeks = 1) last_week = today - delta begin_date = last_week.strftime('%Y%m%d') url", "= json.loads(json_url.read()) except: raise RuntimeError('Failed to retrive New York Times data.') if articles['status']", "= today - delta begin_date = last_week.strftime('%Y%m%d') url = 'https://api.nytimes.com/...
[ "str(i), status=api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"E\" + str(i)), start_time=start_time + datetime.timedelta(hours=i), end_time=end_time + datetime.timedelta(hours=i), creation_time=creation_time +", "} for i in range(10) ], \"NextToken\": \"100\", }, { \"TrialComponentSummari...
[ "# 1. update preserved oligo length olg5p.incrementLength(new_olg3p.length()) # 2. Remove the old oligo", "oligo length olg5p.incrementLength(old_olg3p.length()) # 2. Remove the old oligo and apply the 5'", "2. install the crossover 3. update the oligo length 4. apply the new", "def def undo(self): part = sel...
[ "temperature_in_celsius = sensor.get_temperature() temperature_in_fahrenheit = sensor.get_temperature(W1ThermSensor.DEGREES_F) temperature_in_all_units = sensor.get_temperatures([W1ThermSensor.DEGREES_C, W1ThermSensor.DEGREES_F, W1ThermSensor.KELVIN]) print(\"Sensor id:\"", "temperature_in_fahrenheit = sensor.get...
[ "Generated by Django 3.1.1 on 2020-09-01 17:04 from django.db import migrations, models class", "('tables', '0003_exposure_category'), ] operations = [ migrations.AlterField( model_name='exposure', name='location', field=models.CharField(blank=True, default='', max_length=200), ),", "2020-09-01 17:04 from djang...
[ "#Copyright ReportLab Europe Ltd. 2000-2016 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/graphics/charts/__init__.py __version__='3.3.0'", "Europe Ltd. 2000-2016 #see license.txt for license details #history http://www.reportlab.co.u...
[ "requirements, but is specifically disallowed for this image. Please try a different value.\".format(username))", "_validate_vm_create_nsg(cmd, namespace): if namespace.nsg: if check_existence(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'Microsoft.Network', 'networkSecurityGroups'): namespace.nsg_t...
[ "# print(0 + i - 3) return answer[0 : 0 + i -", "+ len(questions[i]) end = bodyText.index(questions[i + 1], start, -1) print(\"Start : \", start", "print(bodyText) questionCount = len(questions) answerList = [] for i in range(0, questionCount): print('Q:", "\"https://transportation.oregonstate.edu/aabc/freque...
[ "\"bright_cyan\", \"bright_white\", ), range(90, 98)))) BG_COLORS = dict((f\"on_{key}\", val + 10) for key,", "invisibles (for readline); else False. Returns: A string with the original text wrapped", "def readline_disabled(): \"\"\"Context manager to temporarily disable readline features. \"\"\" readline.set_a...
[ "kernel_size=3, stride=1, padding=1) ) TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA = [ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2,", "writing, software # distributed under the License is distributed on an \"AS IS\"", "1, 16, 8, 4), # different size for H, W and D (2,", "nn from parameterized import p...
[ "CFGBuilder userCfg = CFGBuilder().build_from_file('user.py', './auction/user.py') bidCfg = CFGBuilder().build_from_file('bid.py', './auction/bid.py') auctionCfg = CFGBuilder().build_from_file('auction.py','./auction/auction.py') #auctionEventCfg", "userCfg = CFGBuilder().build_from_file('user.py', './auction/use...
[ "= float(input()) while True: command = input() if command == \"End\": break money", "minimal_budget = float(input()) while True: command = input() if command == \"End\": break", "money = float(command) total_budget += money if total_budget >= minimal_budget: print(f\"Going to {destination}!\")", "= float(com...
[ "from footmark.regioninfo import RegionInfo class RAMRegionInfo(RegionInfo): \"\"\" Represents an ram Region \"\"\" def", "def __init__(self, connection=None, name=None, id=None, connection_cls=None): from footmark.ram.connection import RAMConnection super(RAMRegionInfo, self).__init__(connection, name,", "impo...
[ "a single histogram to a D3PO plot :param plot: Glue histogram :type plot:", "plot :class:`~glue.viewers.scatter.qt.ScatterViewer` :param index: 1D index of plot on the page :type index:", "- The Glue session must have only one dataset open, and 0 or", "save_page(page, page_number, label, subset): \"\"\" Conv...
[ "P.A. é (', end='') while c <= 10: print('{}'.format(termo), end='') print(', ' if", "(', end='') while c <= 10: print('{}'.format(termo), end='') print(', ' if c <", "print(', ' if c < 10 else '', end='') termo += r c", "termo da P.A.: ')) r = int(input('Digite a razão: ')) termo = n1", "n1 c = 1 print('A ...
[ "a connection without committing the changes first will cause an implicit rollback to", ".extensions import PARSE_DECLTYPES, PARSE_COLNAMES class Connection(object): from .exceptions import ( Warning, Error, InterfaceError,", "self._connection.request(method, uri, body=body, headers=dict(self._headers, **header...
[ "rent = total_price * 0.1 total_price = total_price - rent if total_price >=", "rent if total_price >= price: print(f\"Yes! {(total_price - price):.2f} lv left.\") else: print(f\"Not", "minions = int(input()) trucks = int(input()) total_toys = puzzles + dolls + bears", "= int(input()) trucks = int(input()) to...
[ "License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "writing, software # distributed under the License is distributed on an \"AS IS\"", "return json.dumps((self._cache.get(key), dt.strftime('%s'))) def set(self, key, value, timeout=None): self.set_value = value self.set_key =", ...
[ "EqualTo class NullableDateTimeField(DateTimeField): \"\"\"Modify DateField to allow for Null values\"\"\" def process_formdata(self, valuelist):", "import DataRequired, ValidationError, Email, EqualTo class NullableDateTimeField(DateTimeField): \"\"\"Modify DateField to allow for Null", "ValidationError, Email...
[ "header=None, engine='python') train_labels = train_labels.to_numpy() # convertim data frame-ul intr-un vector train_labels =", "_ = normalize_data(validation_features, validation_features) # Aplicam modelul SVM model_svm = svm.SVC(kernel='linear', C=23, gamma=110)", "return scaled_train_data, scaled_test_data ...
[]
[ "from flytekit.core.promise import ( NodeOutput, Promise, VoidPromise, binding_from_python_std, create_and_link_node, create_native_named_tuple, create_task_output, translate_inputs_to_literals, )", "a Python native value. for k, v in kwargs.items(): if not isinstance(v, Promise):", "need to run through the fun...
[ "+ betas[T - 1, U - 1]) # The above is also equivalent", "Unless required by applicable law or agreed to in writing, software # distributed", "if T != max_T: raise ValueError(f\"Input length mismatch! Given T: {T}, Expected max", "- 1] # // grad to last blank transition grads[T - 1, U", "Unused. Tensor of s...
[ "as np import math from dataset_specifications.dataset import Dataset class SwirlsSet(Dataset): def __init__(self): super().__init__()", "= means + std*noise return ys def sample(self, n): xs = np.random.uniform(low=0., high=2.,", "math from dataset_specifications.dataset import Dataset class SwirlsSet(Dataset)...
[ "initialization() # run cpp tests get_json_report(test_list, options) # collect coverage data from json", "run cpp tests get_json_report(test_list, options) # collect coverage data from json profiles if", "= time.time() (options, test_list, interested_folders) = initialization() # run cpp tests get_json_report(...
[ "a given Tweet. Example: predict_user('ausen', 'elonmusk', 'Lambda School Rocks!') Returns 1 corresponding to", "'elonmusk', 'Lambda School Rocks!') Returns 1 corresponding to 1st user passed in, or", "to 1st user passed in, or 0 for second. \"\"\" user1 = User.query.filter(User.name", "np from sklearn.linear...
[ "States. # Additionally, the Government of the District of Columbia waives # copyright", "worldwide through the CC0 1.0 # Universal public domain dedication. __version__ = '1.0.0'", "python # -*- coding: utf-8 -*- # This file is part of groupthink.", "-*- coding: utf-8 -*- # This file is part of groupthink. #...
[ "[l in rank[i, -top_k:] for i, l in enumerate(self.label)] return sum(hit_top_k) * 1.0", "= score.argsort() hit_top_k = [l in rank[i, -top_k:] for i, l in enumerate(self.label)]", "self.sample_name = os.listdir(self.data_path) if self.debug: self.sample_name = self.sample_name[0:2] # load label label_path =", ...
[ "'Sexual Content'), ('OTHER', 'Other')], max_length=50)), ('description', models.TextField()), ('date', models.DateTimeField(auto_now_add=True)), ('to_vit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vit.vit')), ('user',", "options={ 'ordering': ['name'], }, ), migrations.CreateModel( name...
[ "schema_type): with grpc.insecure_channel(f\"localhost:{self.input_port}\") as channel: stub = pb2_grpc.SchemaRegistryStub(channel) resp = stub.AddSchema( pb2.NewSchema( definition=bytes(body,", "if self.initial_schema is not None: env.update(SCHEMA_REGISTRY_IMPORT_FILE=self.initial_schema) self.svc = subprocess....
[ "a routing policy is set with an empty condition, it should be loaded", "EchoedRequest pytestmark = [ pytest.mark.skipif(\"TESTED_VERSION < Version('2.11')\"), pytest.mark.issue(\"https://issues.redhat.com/browse/THREESCALE-6415\")] @pytest.fixture(scope=\"module\") def service_proxy_settings(private_base_url): \...
[ "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "writing, software # distributed under the License is distributed on an \"AS IS\"", "[ '%s.create' % self.resource_name, '%s.update' % self.resource_name, '%s.delete' % self.resource_name, ] @staticmethod def", "or # implied. # See...
[ "Select from Data.parameters import Data from get_dir import pwd from reuse_func import GetData", "def __init__(self,driver): self.driver = driver self.filename ='' def test_download_csv(self): self.data = GetData() self.p", "import Data from get_dir import pwd from reuse_func import GetData class All_records_d...
[ "= compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=host, domain_specified=bool(host), domain_initial_dot=host.startswith('.'), path=path, path_specified=bool(path), secure=is_secure,", "--enable-logging=stderr --v=1 2>&1 | grep key_storage_ # Chromium supports a...
[ "managers def _ensure_present(mgr): try: mgr.version() except Exception: pytest.skip() @pytest.fixture def tmpdir_as_cwd(tmpdir): with tmpdir.as_cwd():", "managers.GitManager() _ensure_present(mgr) mgr._invoke('init') mgr._invoke('config', 'user.email', '<EMAIL>') mgr._invoke('config', 'user.name', 'HGTools') os....
[ "isinstance(other, SQLQuery): self.items.extend(other.items) else: return NotImplemented return self def __len__(self): return len(self.query()) def", "def query(self, paramstyle=None): \"\"\" Returns the query part of the sql query. >>>", "and `offset`. Uses vars to interpolate. Otherwise, each clause can be a...
[ "'<KEY> # SECURITY WARNING: don't run with debug turned on in production! DEBUG", "= [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dddp', 'dddp.server', 'dddp.accounts', 'dddppp.slides', ]", "'...
[ "python from setuptools import setup import os __doc__ = \"\"\" Command line tool", "#!/usr/bin/env python from setuptools import setup import os __doc__ = \"\"\" Command line", ":: BSD License\", \"Topic :: System :: Networking\", \"Operating System :: POSIX ::", "return open(os.path.join(os.path.dirname(__f...
[ "auth_api.utils.util import cors_preflight API = Namespace('products', description='Endpoints for products management') TRACER = Tracer.get_instance()", "endpoints for managing an Org resource.\"\"\" from flask import request from flask_restplus import", "Namespace('products', description='Endpoints for product...
[ ").count(), Application.QUESTION: all_apps.filter( status=Application.QUESTION, partner__coordinator__editor=coordinator[0], ).count(), Application.APPROVED: all_apps.filter( status=Application.APPROVED, partner__coordinator__editor=coordinator[0], ).count(), } editor", "import Application from TWLight.resources....
[ "wavelength=555, polarisation=None): super(Laser, self).__init__() self.position = np.array(position) self.direction = np.array(direction) self.wavelength = wavelength", "photon.active = True return photon class RadialSource(object): \"\"\" A point source that emits", "Laser is not set.\" self.polarisation = np...
[ "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) @ input(y)) ... results.append(int(b)", "other)]) def nand_(self: bits, other) -> bits: \"\"\" >>> results = [] >>>", "== c.evaluate([x, x, x, y, y, y])) >>> all(results) True \"\"\" return bits([x.imp_(y)", "of logic circuits and synthesizing c...
[ "author = df['author'].to_list() message_counter = {} for i in author: if i in", "# for not mentioning the bot in the line graph. message_counter.pop('ninza_bot_test') authors_in_discord =", "graph. message_counter.pop('ninza_bot_test') authors_in_discord = list(message_counter.keys()) no_of_messages = list(mes...
[ "#!/usr/bin/env python3 import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read()", "\"tqdm\"], python_requires=\">=3.6\", entry_points={\"console_scripts\": [\"fastnode2vec = fastnode2vec.cli:node2vec\"]}, classifiers=[\"Topic :: Scientific/Enginee...
[ "os basedir = os.path.abspath(os.path.dirname(__file__)) class Config: SECRET_KEY = os.getenv('SECRET_KEY', '') DEBUG = False", "True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db') PRESERVE_CONTEXT_ON_EXCEPTION = False SQLALCHEMY_TRACK_MODIFICATIONS = False", "= False class Prod...
[ "exists' % self.user except KeyError: success = False ret_msg = 'User %s does", "True ret_msg = 'User %s exists' % self.user except KeyError: success = False", "chkusr.check_if_user_exists() # Error handling and JSON return if success: module.exit_json(msg=ret_msg) else: module.fail_json(msg=ret_msg) if", "= ...
[ "an appropriate ontology term. Args: label: the label to find ontology terms for", "a given curie like 'CL:1000413', get the label like 'endothelial cell of artery'\"\"\"", "and you want to find an appropriate ontology term. Args: label: the label", "f\"http://purl.obolibrary.org/obo/{_ontology_name(curie)}_{...
[ "\"operator\": \"\", \"operand\": \"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } \"\"\"", "TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE", "'cut': EditableFilterSerializer().to_representation(cut), 'cohorts': cohort_serializer(many=True).to_representation(cohor...
[ "or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials =", "'client_secret.json' APPLICATION_NAME = 'Inbox Organize' def get_credentials(): \"\"\"Gets valid user credentials from storage.", "with Python 2.6 credentials ...
[ "halogalaxystruct1') return halogalaxystruct1 else: print('found HALO_FORMAT_REVISION=%d, if this is >1 email me!' %", "('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err'...
[ "def location(self): \"\"\" Retrieve the location of an event :return: location :rtype: str", "describing the event :rtype: str \"\"\" return (\"| \" + self.begin_date + self.end_date", "= self.event.location if location.lower() in locations.keys(): location = locations[location.lower()] return location @proper...
[ "os import random import re import sys # Complete the rotLeft function below.", "rotLeft(a, d): alist = list(a) b = alist[d:]+alist[:d] return b if __name__ ==", "= list(a) b = alist[d:]+alist[:d] return b if __name__ == '__main__': fptr =", "= int(nd[0]) d = int(nd[1]) a = list(map(int, input().rstrip().spli...
[ "import cflearn import platform import unittest from cfdata.tabular import TabularDataset num_jobs = 0", "TabularDataset.iris().xy zoo_folder = os.path.join(logging_folder, f\"__{model}__\") zoo = cflearn.Zoo(model) for key, config in zoo.benchmarks.items():", "= \"__test_zoo__\" class TestZoo(unittest.TestCase...
[ "the unsorted list at the midpoint into sublists. Takes O(k log n) quasilinear", "the linked list into sublists containing a single node - Repeatedly merge the", "right_head.next_node # Move current to next node current = current.next_node # Discard fake", "set loop condition to False right_head = right_head....
[ "TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.", "k, 10)) # Create engine engine_rbps = Engine(DIM, lshashes=hashes, distance=CosineDistance()) # First index", "EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "= numpy.rand...
[ "print(discord.__version__) # discord.pyのバージョン print('----------------') print('Hello World !!') await self.change_presence(status=discord.Status.idle,activity=discord.Game(name=f'Ping:{self.ws.latency * 1000:.0f}ms')) conn=r.connect() ky=conn.keys()", "discord.pyのバージョン print('----------------') print('Hello Worl...
[ "# The package used for creating and manipulating HDF5 files: import h5py #", "# Import packages # Ensure that this code works on both python 2", "files: # finally import pycroscopy: try: import pycroscopy as px except ImportError: print('pycroscopy", "method to determine the types of spectral responses prese...
[ "TestCase from unittest.mock import Mock from unittest.mock import patch from foliant.config.downloadfile import download_file", "= get_file_ext_from_url(url) self.assertEqual(ext, '.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile' ext = get_file_ext_from_url(url) self.assertEqual(ext,", "unit...
[ "idが0以外なら匿名質問する if target_channel_id == 0: dm = await message.author.create_dm() # 質問者へDM作成 await dm.send(", "チャンネルに質問メッセージ送信 await target_channel.send(question) # 匿名質問させたいチャンネルのidを取得 # 指定したカテゴリにある最初のTextチャンネル=質問させたいチャンネルとみなす # ただしカテゴリにチャンネルが無い時は0を返す def getTargetChannelId() -> int:", "discord.Client() # 接続に使用す...
[ "max cell count if any(data_t >= 1): survive_count += 1 if counts_total is", "at least 10% of the max cell count if any(data_t >= 1): survive_count", "exp_info.populations[0] ax = ax.reshape((len(k_abs),)) axnum = 0 tc_axes=[] drug_axes=[] for exp in exp_folders:", "== k_abs_t) num = num[0,0] # generate timec...
[ "about the specific entry point.\"\"\" assert isinstance(function, types.FunctionType), \"fix that!\" from rpython.annotator.policy import", "i)): new_ops = op.transform(self) if new_ops is not None: block.operations[i:i+1] = new_ops if", "for # which it is fine to always raise an exception. We then", "= self...
[ "'type': '{object}'}, 'show_on_deleted_work_item': {'key': 'showOnDeletedWorkItem', 'type': 'bool'} } def __init__(self, contribution_id=None, height=None, inputs=None,", "inherited=None, is_contribution=None, label=None, order=None, overridden=None, visible=None): super(Group, self).__init__() self.contribution ...
[ "from utils import LogMixin class Reponse(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def redis(self): \"\"\"", "= self.redis.mget(('inverse:index:movie:{}'.format(idx) for idx in movies)) response = [] for movie in movies:", "@abc.abstractmethod def fetch(self, ids): \"\"\" hydrate relevant ids wi...
[ "# This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH imports = [name_pb], visibility = visibility,", "kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose = kwargs.get(\"verbose\") visibility = kwargs.get(\"visibility\") name_pb = name", "name + \"_pb\" py_grpc_compile( name = name_pb...
[ "the copyright holders nor the names of its # contributors may be used", "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A", "machine: machine.addType(new_type) self.symtab.newSymbol(new_type) self.symtab.pushFrame() # Add all of the fields of the type", "ANY # THEORY OF LIABILITY, ...