ngram
listlengths
0
82k
[ "nn.ModuleList( [TransformerEncoderLayer(d_model, heads, d_ff, dropout) for _ in range(num_inter_layers)]) self.dropout", "1, 0) memory_bank, _ = self.rnn(x1) memory_bank = self.dropout(memory_bank) +", "nn.ReLU() self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, b...
[ "% (token.token,)}, ) response.raise_for_status() return self.get_provider().sociallogin_from_response(request, response.json()) oauth_login = OAuth2LoginView.adapter_view(DropboxOAuth2Adapter)", ") from .provider import DropboxOAuth2Provider class DropboxOAuth2Adapter(OAuth2Adapter): provider_id = DropboxOAuth2P...
[ "# region Path setup sys.path.insert(0, os.path.abspath('..')) # endregion # region", "# region Options for HTML output # The theme to", "# so a file named \"default.css\" will overwrite the builtin", "configuration # Add any Sphinx extension module names here, as", "for # a list of builtin themes. html_the...
[ "path[path.rfind(\":\") + 1:] if not any(path in type_ for type_", "for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP: if type_ in param[\"type\"]: keep =", "\"pcl\": a(\"using namespace %s;\" % namespace) a(\"\\n\") for class_ in", "= list(dependency_tree.leaf_iterator()) def index_for_class(class_): return c...
[ "winrm_wrapper.writeLog(\"loading script\") f = codecs.open(os.environ[\"script\"], encoding='utf-8', mode='r') command = f.read()", "is stored in environment and you can get them by", "for importing file winrm_wrapper from parent dir sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import", "wi...
[ "in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension], dict(a=True, b=1, c=2)) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in", "class Extension4(object): pass def test_enum_registry(self): ExtensibleEnumeration.register('c') self.assertTrue(ExtensibleE...
[ "for fut in self.futs: if not fut.done(): fut.set_result(None) async def", "start(self): self.server = await asyncio.start_server(self.on_connect, host=\"127.0.0.1\") @property def port(self): return", "for i in s.split(\"\\n\") if i] async def close(self): if", "s.split(\"\\n\") if i] async def close(self): ...
[ "before int as python says a bool is an int", "None: self.log.warning('The key is None.') return None # get variable", "Array.\"\"\" for d in data: if not self._is_tc_entity(d): return False", "in ['key', 'value']) def _is_key_value_array(self, data): \"\"\"Return True if provided", "not isinstance(value, b...
[ "and # limitations under the License. \"\"\"BERT finetuning runner.\"\"\" from", "None, \"The vocabulary file that the BERT model was trained", "2.0 (the \"License\"); # you may not use this file", "When false, uses TF32 on A100 and FP32 on V100", "master_process = True training_hooks = [] global_batch_size...
[ "no, # profile picture, about me etc of a student", "ans.append(k) ans.sort() output = BytesIO() book = Workbook(output,{'in_memory':True}) title =", "if request.method == 'POST': programme = request.POST['programme'] now = datetime.datetime.now()", "entry.course_type=course_type entry.save() curriculum = Cur...
[ "' 'compare az1:9292 az2:9292 --debug' % (sys.executable,)) exitcode, out, err", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "may obtain # a copy of the License at #", "limitations # under the License. ...
[ "dt = date(year, 1, 1) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1),", "4, 2), date(2000, 4, 21), date(2010, 4, 2), date(2018, 3,", "<<EMAIL>> # Website: https://github.com/OmoMicheal/trading_days # License: MIT (see LICENSE file)", "11, 27), date(2015, 11, 26), date(20...
[ "d = generate_distutils_setup( packages=['rosmsg'], package_dir={'': 'src'}, scripts=['scripts/rosmsg', 'scripts/rosmsg-proto', 'scripts/rossrv'], requires=['genmsg',", "catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup( packages=['rosmsg'], package_dir={'': 'src'}, scripts=['sc...
[ "result.append(iter.value) iter = self.next_iter(iter) if not iter: break return result", "True: result.append(iter.value) iter = self.next_iter(iter) if not iter: break return", "self.assertEqual(iter.value, 2) iter = d.next_iter(iter) self.assertEqual(iter.value, 1) self.assertEqual(d.tolist(), [2, 1])", "i...
[ "Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, r=r, p=p, b=b,", "self.model._initialize_bcs(bcs=\"mask\") self.geometry = geometry self.space_order = space_order self.kernel = kernel", "TimeFunction(name=\"p\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_ord...
[ "') itemSetList.append(list(map(int, cates))) def myApriori(): te = TransactionEncoder() te_ary =", "import TransactionEncoder from mlxtend.frequent_patterns import apriori dataPath = \"data/static\" itemSetList", "apriori dataPath = \"data/static\" itemSetList = [] def loadDataSet(): with", "itemSetList.appe...
[ "= request.get_json() name = 'World' if request_json and 'name' in", "name = request_json['name'] headers = { 'Access-Control-Allow-Origin': 'https://furikuri.net', 'Access-Control-Allow-Methods': 'GET,", "+ name + '! From GCP + Python', 200, headers)", "request_json['name'] headers = { 'Access-Control-Allow-...
[ "Signer, ClientConfig, \\ ParamsOfEncodeMessage, ParamsOfProcessMessage BASE_DIR = os.path.dirname(__file__) SAMPLES_DIR =", "abi=giver_abi, signer=Signer.NoSigner(), address=GIVER_ADDRESS, call_set=call_set) process_params = ParamsOfProcessMessage( message_encode_params=encode_params, send_events=False) async_co...
[ "import i18n from flask import request from flask_kajiki import render_template", "request.path == '/test_i18n': return s.upper() return s i18n.gettext = gettext", "so we test for request path that only functions from", "DOCTYPE; see also render_args expected = '<p>HELLO!</p>' assert rendered ==", "render_t...
[ "(None if self.upsample_method == 'nearest' else False) upsample_cfg_.update( scale_factor=self.scale_factor, mode=self.upsample_method,", "x = self.upsample(x) if self.upsample_method == 'deconv': x = self.relu(x)", "im_mask[(inds, ) + spatial_inds] = masks_chunk for i in range(N):", "== 'cpu') if threshold ...
[ "= \"DB\" cfg.det_model_dir = \"./inference/ch_ppocr_mobile_v2.0_det_infer/\" cfg.det_limit_side_len = 960 cfg.det_limit_type =", "False # #EAST parmas # cfg.det_east_score_thresh = 0.8 # cfg.det_east_cover_thresh", "0.3 cfg.det_db_box_thresh = 0.5 cfg.det_db_unclip_ratio = 1.6 cfg.use_dilation = False", "cfg...
[ "m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def", "torch.cat( [out,skip_x], 1 ) out = self.res(out) return out class", "32->16 self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.num...
[ "num_training_steps = args.max_steps if args.max_steps > 0 else len( train_data_loader)", "overlaps a bit the context of the previous feature. #", "range(len(examples))] tokenized_examples = tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # Let's", "args import parse_a...
[ "noise, it is epsilon-greedy with epsilon decreasing over time #", "every a available at a state Qout = tf.matmul(input1, W)", "axis=1) # Feature vector for next state representation nextQ =", "s:s+1: \", np.identity(env.observation_space.n)[s:s+1]) # s = 0 --> Identity s:", "# TRAIN THE NETWORK init = tf.g...
[ "prf from tink import signature from tink import streaming_aead from", "tink import signature from tink import streaming_aead from tink.proto import", "2.0 (the \"License\"); # you may not use this file", "languages that are supported by a KeyType SUPPORTED_LANGUAGES = {", "# For each KeyType, a list of all...
[ "os import path import logging logging.basicConfig(filename='./remote-signer.log', format='%(asctime)s %(message)s', level=logging.INFO) app", "@app.route('/keys/<key_hash>', methods=['POST']) def sign(key_hash): response = None try: data =", "except Exception as e: data = {'error': str(e)} logging.error('Excep...
[ "unwind_info['Version'] == 1: unwind_codes = [ ] for i in", "in unwind_info: continue funcs.add(start_address) if not thread.cancelled: thread.progress = 'Creating", "0x2 UNW_FLAG_FHANDLER = 0x3 UNW_FLAG_CHAININFO = 0x4 def read_unwind_info(view, address):", "= ('VersionAndFlags', 'SizeOfProlog', 'CountOfCode...
[ "3) Call `fig.show()` to render the figure. \"\"\" import plotly.graph_objects", "render the figure. \"\"\" import plotly.graph_objects as go import numpy", "as np from ..pixlib.geometry.utils import to_homogeneous def init_figure(height=800): \"\"\"Initialize a", "powerful library like Open3D. Plotly however...
[ "-> None: checked_grids[np.where(grids == number)] = True def check_victory(check_grids: np.ndarray)", "np.ndarray, number: int) -> None: checked_grids[np.where(grids == number)] = True", "= [int(n) for n in lines[0].split(\",\")] grids = np.array([read_bingo_grid(lines[i :", "list[list[int]]: return [[int(n)...
[ "pop = data.population.url slider = alt.binding_range(min=1850, max=2000, step=10) select_year =", "of age groups within a population. It uses a slider", "alt from altair.expr import datum, if_ from vega_datasets import data", "slider = alt.binding_range(min=1850, max=2000, step=10) select_year = alt.selectio...
[ "('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', models.CharField(max_length=20,", "class Migrat...
[ "= db.Column(db.DateTime) # # def __init__(self, uuid, payload, datetime): #", "datetime): # self.uuid = uuid # self.payload = payload #", "= db.Column(db.Text) datetime = db.Column(db.DateTime) def __init__(self, uuid, response, datetime):", "# class Logs(db.Model): # id = db.Column(db.Integer, primary_key=T...
[ "format *args @functools.wraps(func) def workaround(*args, **kwargs): args = args[0] if", "self.pre_iface_state != 'UP' and self.rollback: command_util('ifconfig', self.iface, 'down') self.post_iface_state =", "returned. This helper filter them out @functools.wraps(func) def wrapper(*args, **kwargs):", "dupli...
[ "ma from models.johnson_scanner_data import JohnsonScannerDataModel from schemas.brand import BrandSchema from", "BrandSchema from schemas.category import CategorySchema from schemas.facts_in_data import FactsInDataSchema from", "from schemas.category import CategorySchema from schemas.facts_in_data import Fact...
[ "################################################################################ # PyTorch and neural network imports import torch from", "the class predictions #TODO: apply an activition function to 'batch'", "Fill in the remaining initializations replacing each '_' with #", "the outputs of conv1 self.conv1...
[ "import credentials from datetime import datetime, timedelta class NewsAPI: def", "except: raise RuntimeError('Failed to retrive New York Times data.') if", "def get_nyt_last_week_articles(self, topic, today): delta = timedelta(weeks = 1) last_week", "= urllib.request.urlopen(url) articles = json.loads(json_u...
[ "str(i), display_name=\"C\" + str(i), source_arn=\"D\" + str(i), status=api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"E\" +", "api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"D\") == obj.status assert {\"E\": 1.0, \"F\": \"G\"} ==", "source_arn=\"K\", timestamp=...
[ "the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._update_oligo:", "# emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # 3. install the Xover", "oligo to the 3' strand new_olg3p.removeFromPart() for strand in stran...
[ "sensor.get_temperature(W1ThermSensor.DEGREES_F) temperature_in_all_units = sensor.get_temperatures([W1ThermSensor.DEGREES_C, W1ThermSensor.DEGREES_F, W1ThermSensor.KELVIN]) print(\"Sensor id:\" + sensor.id)", "temperature_in_fahrenheit = sensor.get_temperature(W1ThermSensor.DEGREES_F) temperature_in_all_units = ...
[ "migrations, models class Migration(migrations.Migration): dependencies = [ ('tables', '0003_exposure_category'), ]", "17:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies =", "'0003_exposure_category'), ] operations = [ migrations.AlterField( model_name='exposure',...
[ "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", "2000-2016 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportla...
[ "= list(client.list(scope, \"roleName eq '{}'\".format(role))) if not role_defs: raise CLIError(\"Role", "check_existence, get_target_network_api, get_storage_blob_uri from azure.cli.command_modules.vm._template_builder import StorageProfile import azure.cli.core.keys as", "identities if x != MSI_LOCAL_ID] if u...
[ "FAQ_LINKS, COLLECTION_NAME def cleanQuestions(questions): questionList = [] for question in", ": ', answer[i].isspace()) if text[i].isspace(): whitespaceCount = whitespaceCount + 1", "for i in range(0, len(text)): # print(answer[i], ' isSpace :", "print(soup1) answer = soup1.getText().lstrip() answer = clean...
[ "\"\"\"Presents a yes/no prompt to the user and handles replies.", "readline.set_auto_history(False) try: yield finally: readline.set_auto_history(True) def confirm(text): \"\"\"Presents a yes/no", "text, esc(sgr(0))) @contextmanager def readline_disabled(): \"\"\"Context manager to temporarily disable", "= d...
[ "tests[1], tests[2]]) class TestSUBPIXEL(unittest.TestCase): @parameterized.expand(TEST_CASE_SUBPIXEL) def test_subpixel_shape(self, input_param, input_shape, expected_shape):", "limitations under the License. import unittest import torch import torch.nn", "W and D (2, 1, 32, 16, 8), ] conv_block", "the pad/p...
[ "auctionCfg = CFGBuilder().build_from_file('auction.py','./auction/auction.py') #auctionEventCfg = CFGBuilder().build_from_file('auction_event.py','./auction/auction_event.py') bidCfg.build_visual('bidCfg', 'pdf') auctionCfg.build_visual('auctionCfg', 'pdf')", "'./auction/user.py') bidCfg = CFGBuilder().build_fro...
[ "<filename>CodeForces/A2OJ Ladder/softuni_problem.py total_budget = 0 while True: destination = input()", "if command == \"End\": break money = float(command) total_budget +=", "Ladder/softuni_problem.py total_budget = 0 while True: destination = input() if", "== \"End\": break minimal_budget = float(input())...
[ "from footmark.regioninfo import RegionInfo class RAMRegionInfo(RegionInfo): \"\"\" Represents an ram", "an ram Region \"\"\" def __init__(self, connection=None, name=None, id=None, connection_cls=None):", "id=None, connection_cls=None): from footmark.ram.connection import RAMConnection super(RAMRegionInfo, sel...
[ "if not os.path.exists(path): os.mkdir(path) data = application.session.data_collection[0] subsets = stage_subsets(application)", "\"\"\" Convert a single histogram to a D3PO plot :param", "os.chdir(path) while True: try: PORT = randrange(8000, 9000) server =", "pass print('Serving D3PO on port 0.0.0.0:%i' % ...
[ "a razão: ')) termo = n1 c = 1 print('A", "é (', end='') while c <= 10: print('{}'.format(termo), end='') print(',", "end='') while c <= 10: print('{}'.format(termo), end='') print(', ' if", "')) termo = n1 c = 1 print('A P.A. é", "print('{}'.format(termo), end='') print(', ' if c < 10 else '',", "10 else...
[ "= location.port self._connection = self._init_connection() response = self._retry_request(method, uri, body=body,", "provide transaction support. \"\"\" pass def cursor(self, factory=None): \"\"\"Return a", "is called). The connection will be unusable from this point", "host='localhost', port=4001, user=None...
[ "* 8.2 price_trucks = trucks * 2 total_price = price_puzzles", "price_minions + price_trucks if total_toys >= 50: total_price = total_price", "total_price = total_price - rent if total_price >= price: print(f\"Yes!", "left.\") else: print(f\"Not enough money! {(price - total_price):.2f} lv needed.\")", "(to...
[ "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "get(self, key): dt = datetime.datetime.now() + datetime.timedelta(minutes=5) return json.dumps((self._cache.get(key), dt.strftime('%s')))", "may obtain # a cop...
[ "ReviewForm(FlaskForm): rating = HiddenField(\"Rating\", validators=[DataRequired()]) review_title = StringField(\"Headline\") review_content =", "StringField, TextAreaField, DateTimeField, HiddenField, PasswordField, ) from wtforms.validators import DataRequired,", "class EditProfileForm(FlaskForm): display_na...
[ "normalizate #tipul de normalizare este setat implicit la l2 scaler", "definim modelul model_svm.fit(norm_train, train_labels) # procesul de invatare test_predictions =", "normalizare este setat implicit la l2 scaler = None if", "by Colaboratory. Original file is located at https://colab.research.google.com/d...
[]
[ "function's signature, workflows need to run through the function itself", "track of workflow inputs that you've declared with add_workflow_input but", "def add_workflow_output( self, output_name: str, p: Union[Promise, List[Promise], Dict[str, Promise]],", "None and ctx.execution_state.mode == ExecutionState...
[ "acoustic sequence. glen: Length vector of the target sequence. blank:", "2.0 (the \"License\"); # you may not use this file", "tuple of the backward variable probabilities - beta of shape", "t in range(0, T): # for u in range(0, U", "forward variable probabilities - alpha of shape [T, U] and", "__init__(...
[ "self.name = \"swirls\" self.n_samples = { \"train\": 2000, \"val\": 1000,", "class SwirlsSet(Dataset): def __init__(self): super().__init__() self.name = \"swirls\" self.n_samples =", "numpy as np import math from dataset_specifications.dataset import Dataset class", "model with 2 components def sample_ys(se...
[ "import summarize_jsons from package.util.setting import TestPlatform def report_coverage() -> None:", "#!/usr/bin/env python import time from package.oss.cov_json import get_json_report from package.oss.init", "# collect coverage data from json profiles if options.need_summary: summarize_jsons(", "python imp...
[ "np.array([tweet.vect for tweet in user1.tweets]) user2_vect = np.array([tweet.vect for tweet", "LogisticRegression().fit(vects, labels) # We've done the model fitting, now to", "user2 = User.query.filter(User.name == user2_name).one() user1_vect = np.array([tweet.vect for tweet", "a given Tweet. Example: pre...
[ "work worldwide through the CC0 1.0 # Universal public domain", "1.0 # Universal public domain dedication. __version__ = '1.0.0' #", "waives # copyright and related rights in the work worldwide", "through the CC0 1.0 # Universal public domain dedication. __version__", "part of groupthink. # https://github.c...
[ "at the begining or end of sequence random_move: If true,", "sequence debug: If true, only use the first 100 samples", "json.load(f) # fill data_numpy data_numpy = np.zeros((self.C, self.T, self.V, self.num_person_in))", "sample_name) with open(sample_path, 'r') as f: video_info = json.load(f) #", "If true,...
[ "'Sexual Content'), ('OTHER', 'Other')], max_length=50)), ('description', models.TextField()), ('date', models.DateTimeField(auto_now_add=True)), ('to_vit',", "('link', 'Purple'), ('primary', 'Turquoise'), ('warning', 'Yellow'), ('danger', 'Red'), ('dark', 'Black'),", "Generated by Django 4.0.2 on 2022-03-02 03...
[ "time.sleep(3) return self def stop(self): self.svc.kill() def create_schema(self, name, destination,", "self.initial_schema = initial_schema self.svc = None def start(self): env =", "name, destination, query, body, schema_type): with grpc.insecure_channel(f\"localhost:{self.input_port}\") as channel: stub", ...
[ "noqa # pylint: disable=unused-import from testsuite.echoed_request import EchoedRequest pytestmark =", "loaded correctly and should route all the requests to a", "asserts, that the routing policy is active and the requests", "import Version # noqa # pylint: disable=unused-import from testsuite import", "fr...
[ "It is defining the exchange and topics to be connected", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "] cfg.CONF.register_opts(OPTS) SERVICE = 'sahara' class DataProcessing(plugin.NotificationBase): resource_name = '%s.cluster'", "# # Licensed under the Apache Lice...
[ "import pwd from reuse_func import GetData class All_records_download(): def __init__(self,driver):", "') self.data.page_loading(self.driver) self.driver.find_element_by_id(Data.Download).click() time.sleep(4) self.filename = self.p.get_download_dir() + '/collectionType_all_data.csv' time.sleep(2)", "self.p.get...
[ "cursor.fetchall() total_cookie_count = len(table) for i, (host, name, value, path,", "= {'brave', 'chrome', 'chromium', 'edge', 'opera', 'vivaldi'} SUPPORTED_BROWSERS = CHROMIUM_BASED_BROWSERS", "= raw_ciphertext[nonce_length:-authentication_tag_length] authentication_tag = raw_ciphertext[-authentication_tag_l...
[ "os import pytest from hgtools import managers def _ensure_present(mgr): try:", "def _ensure_present(mgr): try: mgr.version() except Exception: pytest.skip() @pytest.fixture def tmpdir_as_cwd(tmpdir):", "hgtools import managers def _ensure_present(mgr): try: mgr.version() except Exception: pytest.skip()", "'c...
[ "foo SET age = %s, name = %s, created =", "q.query() 'INSERT INTO foo (age, name, created) VALUES (%s, %s,", "\"bar\", \"email\": \"<EMAIL>\"}] >>> db.multiple_insert('person', values=values, _test=True) <sql: \"INSERT INTO", "= ' + sqlquote(val) else: nout = SQLQuery(val) elif isinstance(val,", "('SELECT',...
[ "production secret! SECRET_KEY = '<KEY> # SECURITY WARNING: don't run", "'pw_name', 'USER': 'pw_name', 'USERNAME': 'pw_name', 'UID': 'pw_uid', 'GID': 'pw_gid', 'HOME':", "For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the", "os.environ.get('DJANGO_DATABASE_PA...
[ "System :: POSIX :: Linux\", \"Environment :: Console\", \"Programming Language", "around iwlist and /etc/network/interfaces. \"\"\" def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read()", "long_description=read('README.rst'), packages=['wifi'], scripts=['bin/wifi'], test_suite='te...
[ "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "this action'}, \\ http_status.HTTP_401_UNAUTHORIZED else: response, status = {'subscriptions': ProductSubscriptionSchema().dump(subscriptions,", "# # Licensed under the Apache License, Version 2.0 (the", "compliance with ...
[ "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(), }", "pending app queryset, along # with a count of how", "dictionary with the three s...
[ "2*np.pi, thetamin = 0, thetamax = np.pi, spacing=20): super(RadialSource, self).__init__()", "0 self.source_id = \"PointSource_\" + str(id(self)) def photon(self): photon =", "isotropic vectors is taken from GNU Scientific Library LOOP =", "photon.wavelength = self.wavelength return photon class CylindricalS...
[ "and isinstance(b2, input_two): return input_two elif isinstance(b1, (input_one, input_two)) and", ">>> all(results) True \"\"\" return bit.operation(op.imp_, self, other) def nand(self,", "[b.value for b in bs] [0, 0, 0, 1, 1,", "bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\" return bit.operati...
[ "plt.title('msg sent by author in the server.') plt.xlabel('Author') plt.ylabel('Message_count') plt.savefig('output2.png')", "= {} for i in author: if i in message_counter:", "# for not mentioning the bot in the line graph.", "= df['author'].to_list() message_counter = {} for i in author: if", "list(messag...
[ "open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=\"fastnode2vec\", version=\"0.0.5\", author=\"<NAME>\", license=\"MIT\", author_email=\"<EMAIL>\", description=\"Fast implementation", "of node2vec\", long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", url...
[ "DEBUG = False class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI =", "SQLALCHEMY_TRACK_MODIFICATIONS = False class TestingConfig(Config): DEBUG = True TESTING =", "class TestingConfig(Config): DEBUG = True TESTING = True SQLALCHEMY_DATABASE_URI =", "= True SQLALCHEMY_DATABASE_URI = 'sqlite...
[ "= chkusr.check_if_user_exists() # Error handling and JSON return if success:", "% self.user return success, ret_msg def main(): # Parsing argument", "chkusr = User(user) success, ret_msg = chkusr.check_if_user_exists() # Error handling", "# Error handling and JSON return if success: module.exit_json(msg=ret_...
[ "[https://www.ebi.ac.uk/ols/docs/api] url = f\"{OLS_API_ROOT}/{method}?q={quote_plus(label)}&ontology={ontology.lower()}\" response = requests.get(url) if not response.ok:", "lookup failed, got status code {response.status_code}: {response.text}\" ) return [(r[\"obo_id\"],", "of the curie, 0000001 from CL:00000...
[ "}] } \"\"\" serializer_class = get_account_serializer() class QuestionListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered", "\"metric\": { \"slug\": \"all-questions\", \"title\": \"All questions\", \"predicates\": [] },", "aggregate_scores(self, metric, cohorts, cut=None, accounts=None): #pylint:disable...
[ "(label['id'], label['name'])) \"\"\" return labels except errors.HttpError as error: print", "def main(): credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service =", "completed to obtain the new credentials. Returns: Credentials, the obtained", "'https://www.googleapis.com/auth/...
[ "## halogalaxystruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32),", "obj.galaxies == 0: if obj.format_revision == 0: print('OUTDATED ROCKSTAR, PLEASE", "('mgrav',np.float32), ('vmax',n...
[ "from dateutil.tz import tzlocal BOTWARNING = \"\"\" <!-- This text", "\"\\n\" + LINE_SEPARATOR + str(event) ) else: past_events.append(event) append_past_events(past_events, wiki['user'],", "dest=\"ics_url\", help=\"The URL under which the ICS-file can be retrieved\",", "hier manuell editiert, hinzugefügt wi...
[ "= list(a) b = alist[d:]+alist[:d] return b if __name__ ==", "sys # Complete the rotLeft function below. def rotLeft(a, d):", "list(a) b = alist[d:]+alist[:d] return b if __name__ == '__main__':", "import random import re import sys # Complete the rotLeft", "= int(nd[0]) d = int(nd[1]) a = list(map(int, inp...
[ "cflearn import platform import unittest from cfdata.tabular import TabularDataset num_jobs", "= \"__test_zoo__\" class TestZoo(unittest.TestCase): @staticmethod def _test_zoo_core(model: str) -> None:", "y, pipelines=m) cflearn._rmtree(logging_folder) def test_fcnn_zoo(self) -> None: self._test_zoo_core(\"fcnn...
[ "right.head # Iterate over left and right until we reach", "the tail node from left to merged linked list elif", "left to set loop condition to False left_head = left_head.next_node", "current to left node if left_data < right_data: current.next_node =", "if linked_list == None or linked_list.head == None: ...
[ "# Add rbp as child hash of permutations hash permutations.add_child_hash(rbp_perm,", "LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A", "dists = CosineDistance().distance(matrix,query) dists = dists.reshape((-1,)) dists = sorted(dists) print(dists[:10])", "HashPermutationMapper('permut2') # Cre...
[ "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()", "q=str(q) if q==\"0\": count+=1 if count>0: p=conn.srem(global_ch,\"0\") if p==True: print(\"正常起動\")", ...
[ "= px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_cols') # Getting a reference to the main", "cluster_utils.plot_cluster_h5_group(h5_kmeans_grp) ##################################################################################### # 3. Non-negative Matrix Factorization (NMF) # ======================================...
[ "self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_save_to(self, urlopen): mock_response =", "test_with_ext(self): url = 'http://example.com/sub/myfile.txt' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') def", "shutil.rmtree...
[ "# 「/box」が頭についたメッセージならオウム返しする if message.content.startswith('/box'): # 文字から「/box」を抜く question = message.content[len('/box'):].strip() #", "# 指定カテゴリに属する場合だけ対象チャンネル候補とみなす if str(channel.category) == target_category_name: # positionが小さいほうを「より対象チャンネルに近い」として交換 # 初期値はpositionが大きい(99999999)ので,必ず入れ替わる想定", "# 指定したサーバにある...
[ "= np.argwhere(k_abs == k_abs_t) num = num[0,0] # generate timecourse", "exp_info.slopes exp_folders.reverse() k_abs = np.flip(k_abs) fig,ax = plt.subplots(nrows=2,ncols=2,figsize=(4,4)) pop =", "= exp_info.slopes exp_folders.reverse() k_abs = np.flip(k_abs) fig,ax = plt.subplots(nrows=2,ncols=2,figsize=(4,4)) ...
[ "are problematic (but will hopefully be solved # later by", "s_newarg) == s_oldarg else: assert not self.frozen if block not", "that have blocked blocks # --- end of debugging information", "set of links that have ever been followed self.notify =", "map {block: graph-containing-it} self.annotated = {} # set...
[ "= url class WorkItemStateResultModel(Model): \"\"\"WorkItemStateResultModel. :param color: :type color: str", "combiner. :type inherited: bool :param is_contribution: A value indicating if", "inherits: :type inherits: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>`...
[ "'year' in obj: obj['year'] = int(obj['year']) response.append(obj) return response def", "ids): \"\"\" hydrate relevant ids with data \"\"\" return class", "DEFAULT_FIELDS = ['title', 'year', 'genres'] def __init__(self, **kwargs): super().__init__() for", "'year', 'genres'] def __init__(self, **kwargs): sup...
[ "py_grpc_compile( name = name_pb, deps = deps, visibility = visibility,", "srcs = [name_pb], deps = all_requirements, # This magically adds", "\"all_requirements\") def py_proto_library(**kwargs): name = kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose", "native.py_library( name = name, srcs = [name_p...
[ "else: ident = self.type_ast.ident return set((\"%s.hh\" % ident, \"%s.cc\" %", "USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED", "slicc.ast.DeclAST import DeclAST from slicc.symbols.Type import Type class TypeDeclAST(DeclAST): def", "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY O...