ngram
listlengths
0
67.8k
[ "verb = models.CharField(max_length=255, db_index=True) description = models.TextField(blank=True, null=True) target_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, blank=True,", "the rest for field in ('verb', 'description', 'timestamp', 'extra'): data[field] = kwargs[field] return", ...
[ "# python 3.5 以降であれば以下のようにして # 2つのディクショナリをマージできる。(いくつでも可能) # ------------------------------------------------------------ dict_a = {'a': 1, 'b':", "<filename>trypython/basic/dict_/dict02.py<gh_stars>1-10 \"\"\" ディクショナリについてのサンプルです。 dict の マージ について (Python 3.5 以降で有効) \"\"\" from trypython.common.commoncls", "# --...
[ "save_json(file_path, self) @classmethod def load(cls, file_path: Path): data = parse_json(file_path) return cls(data) @classmethod", "@classmethod def load(cls, file_path: Path): data = parse_json(file_path) return cls(data) @classmethod def fromcounter(cls,", "import Counter, OrderedDict from pathlib import P...
[ "# Copyright 2016 NXP # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause #", "# All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause # # Generated by erpcgen", "23 13:00:45 2019. # # AUTOGENERATED - DO NOT EDIT # import erpc", "Iremote_control_app_1(object): SERVICE_ID = 2 BUTTON_PRESS...
[ "self.df.at[i, 'Class'] if self.nmax is not None and self.counts[label] >= self.nmax: continue else:", "+ '.wav' print('\\n', file) try: sr, wav_data = wavfile.read(os.path.join(self.root, 'Train', file)) except Exception", "file) continue print(type(wav_data), 'original sample rate: ', sr) print(np.min(wav_dat...
[ "return self.__get_first_value('config', 'Entrypoint') def get_exposed_ports(self): return self.__get_first_value('config', 'ExposedPorts') def get_layer_ids(self): layer_ids = []", "NotImplementedError def get_exposed_ports(self): raise NotImplementedError def get_docker_version(self): raise NotImplementedError ...
[ "= ' + str(ref_id)): has_result = True print_highlight(row[1] + ': ') print '\\t\\t\\t'", "True: # ref_id = -1 # continue has_result = False print '' caused_id", "\"\"\"Print in color.\"\"\" # print \"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\" #def writec(text, color): # \"\"\"Write to stdout", "False:...
[ "< 0: return 'Invalid input. Must be a value greater than 0' if", "* factorial(input - 1) # smart factorial that doesn't perform the full operation", "else: result = n ** k print(f'Result: {result}') if __name__ == '__main__': main()", "'(C)': result = combination(n, k) elif operation == '(P)': result = permu...
[ "from .models import Branch,Product,Transfer,Vendor,Model # Register your models here. admin.site.register(Branch) admin.site.register(Product) admin.site.register(Transfer) admin.site.register(Vendor)", "<reponame>rishthas/ProdTracker from django.contrib import admin from .models import Branch,Product,Transfer,V...
[ "models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ('id_pais', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='afiliados.paises')), ], ), migrations.CreateModel(", "('estado', models.BooleanField(...
[ "import Flask from flask_bootstrap import Bootstrap from flask_mail import Mail from flask_moment import", "Flask from flask_bootstrap import Bootstrap from flask_mail import Mail from flask_moment import Moment", "config from flask_debugtoolbar import DebugToolbarExtension from flask.ext.login import LoginMana...
[ "'').strip()) elif line.startswith('STARTTLS'): self._STARTTLS() elif line.startswith('MAIL FROM'): self._MAIL_FROM() elif line.startswith('RCPT TO'): self._RCPT_TO() elif", "param=None): resp = '250 Hello {}\\r\\n250 STARTTLS\\r\\n'.format(param) self.send_response(resp.encode()) def _STARTTLS(self): self.send_r...
[ "\"\"\" Takes 1000 documents at a time and batch queries all of the", "pmids = [pmid.strip() for pmid in pmids.split(',')] # fixes issue where pmid numbers", "from .date import add_date from Bio import Entrez from Bio import Medline from", "pmids.split(',')] # fixes issue where pmid numbers under 10 is read a...
[ "non-ascii-name checker. \"\"\" áéíóú = 4444 # [non-ascii-name] def úóíéá(): # [non-ascii-name] \"\"\"yo\"\"\"", "for non-ascii-name checker. \"\"\" áéíóú = 4444 # [non-ascii-name] def úóíéá(): # [non-ascii-name]", "\"\"\" Tests for non-ascii-name checker. \"\"\" áéíóú = 4444 # [non-ascii-name] def úóíéá():", ...
[ "notifications are rendered even if user # killed the app printer_name = token[\"printerName\"]", "if camera_url and camera_url.strip(): image = self.image(camera_url, hflip, vflip, rotate) except: self._logger.info(\"Could not", "apns_token = token[\"apnsToken\"] printerID = token[\"printerID\"] # Ignore token...
[ "api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) user.token = token", "('id', 'password', 'password2', 'access_token') extra_kwargs = { 'password': { 'write_only': True, 'min_length': 8,", "write_only=T...
[ "app = Flask(__name__) app.config['SECRET_KEY'] = 'random string' app.debug = True app.register_blueprint(ling_blueprint) app.register_blueprint(wff_blueprint) @app.route(\"/\")", "return '<p><a href=\"/MrLing\">Ling</a></p><p><a href=\"/MrWff\">Wff</a></p>' if __name__ == '__main__': app.run(host = '0.0.0.0', po...
[ "y = np.array([3, 4]) result = foo(x, y) assert((result[0] == x).all() and (result[1]", "at http://www.boost.org/LICENSE_1_0.txt) from phylanx import Phylanx import numpy as np @Phylanx def foo(x,", "(c) 2018 <NAME> # # Distributed under the Boost Software License, Version 1.0.", "# Copyright (c) 2018 <NAME> ...
[ "raise metadata = { 'uuid': metadata['sessionID'], 'age_range': metadata['age'], 'request': metadata['nativeLanguage'], 'gender': metadata['gender'] }", "if not bearer_token.startswith(PREFIX): return None return bearer_token[len(PREFIX):] @app.route('/xyz', methods=['GET']) def generic(): return {'msg':'hello", ...
[ "of command with '-i' argument to keep processing jobs even if a job", "from django_future.models import ScheduledJob class RunScheduledJobsCommandTest(TestCase): def setUp(self): self.schedule_at = timezone.now() - timedelta(days=1)", "processing jobs even if a job fails. Ensure the non-failing jobs are marked...
[ "to # of validation examples /batch size (i.e. figure out num validation examples)", "KIND, either express or implied. # See the License for the specific language", "tf.image.resize(tf.reshape(image, [example['image/height'], example['image/width'], 3]), [299, 299]) image = tf.cast(image, tf.uint8) image = tf.r...
[ "Documentation', author, 'dotapatch', 'Parses Dota 2 text patches to html format.', 'Miscellaneous'), ]", "sys import path import sphinx_rtd_theme path.insert(0, abspath('..')) needs_sphinx = '1.6.5' extensions = [", "sphinx_rtd_theme path.insert(0, abspath('..')) needs_sphinx = '1.6.5' extensions = [ 'sphinx.e...
[ "# Generated by Django 3.0.9 on 2020-08-23 12:27 from django.db import migrations class", "3.0.9 on 2020-08-23 12:27 from django.db import migrations class Migration(migrations.Migration): dependencies = [", "Migration(migrations.Migration): dependencies = [ ('home', '0007_auto_20200823_1340'), ] operations = [...
[ "energy.\") print(f\"Current energy: {energy}.\") elif order == \"order\": if energy >= 30: energy", "coins > 0: print(f\"You bought {order}.\") else: print(f\"Closed! Cannot afford {order}.\") break if", "> 0: print(f\"You bought {order}.\") else: print(f\"Closed! Cannot afford {order}.\") break if coins", "...
[ "string.ascii_lowercase + string.digits)for i in range(N)) return gen_password def create_credential(user_name,site_name,account_name,password): ''' function that", "print('Enter the name of site to be deleted') delete_account = input() if find_by_site_name(delete_account):", "Welcome to Password-locker.') whil...
[ "arg == '-h': return 1 elif arg == '-c': self.context = True if", "self.func = False self.depth = 0 self.path = None self.pattern = None self.regexp", "PythonLexer from pygments import highlight from pygments.formatters.terminal import TerminalFormatter import shutil import re", "== '-cl': self.cl = True args...
[ "# See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy class PlumaItem(scrapy.Item): # define the", "# https://docs.scrapy.org/en/latest/topics/items.html import scrapy class PlumaItem(scrapy.Item): # define the fields for your item", "for your item here like: # name = scra...
[ "(inputs['frameid'] < pool_start_frm + span_frms)] dnn_scores = np.array(pool_images['prediction_proba'].tolist())[:, 1] assert dnn_scores.ndim == 1", "otherwise passthrough; training set is ever expanding; svm_cutoff=0.3): if not isinstance(svm_cutoff, list): svm_cutoff", "assert y_jit.shape[0] == np.count_non...
[ "num_clients self.device = device # update global model def update(self): raise NotImplementedError def", "global model def update(self): raise NotImplementedError def get_model(self): return copy.deepcopy(self.model) \"\"\"This implements a", "base class for client.\"\"\" class BaseClient: def __init__(self, i...
[ "len(a) if(aux==0): print(0) return canta = 0 for i in a: if(i[0]=='a'): canta+=1", "= [] for i in range(n): if(a[i]!=b[i]): newa.append((a[i],i)) newb.append((b[i],i)) a,b = newa,newb aux", "print(len(a)//2) lastA,lastB = -1,-1 for i in range(aux): if(a[i][0]=='a'): if(lastA==-1): lastA=a[i][1] else: print(las...
[ "#datetime.time(h,m,s,ms) #datetime.datetime(y,m,d,h,m,s,ms) hour_delta = datetime.timedelta(hours=10) print(datetime.datetime.now() + hour_delta) datetime_today=datetime.datetime.now(tz=pytz.utc) print(datetime_today.astimezone(pytz.timezone('US/Pacific'))) datetime_pacific = datetime_today.astimezone(pytz.timezon...
[]
[ "\"\"\" if 'match_id' in kwargs and kwargs['match_id'] in match_library: return match_library[kwargs['match_id']] match =", "else RaceInfo(), ranked=bool(row[9]), is_best_of=bool(row[10]), max_races=int(row[11]) ) sheet_info = MatchGSheetInfo() sheet_info.wks_id = row[14] sheet_info.row", "display_text async de...
[ "# Keras won't let us multiply floats by booleans, so we explicitly cast", "2 Conv1D then 2 Fully def build_model(model_path, learning_rate=0.01): if os.path.exists(model_path): # model =", "huber_loss}) model = load_model(model_path) print('Load existing model.') else: model = Sequential() model.add(Dense(Inpu...
[ "from periphery import GPIO, PWM, GPIOError def initPWM(pin): pwm = PWM(pin, 0) pwm.frequency", "= PWM(pin, 0) pwm.frequency = 1e3 pwm.duty_cycle = 0 pwm.enable() return pwm try:", "initPWM(1), initPWM(0), GPIO(77 , \"out\"), ] except GPIOError as e: print(\"Unable to access", "__del__(self): if hasattr(self,...
[ "ConventionManager() class Meta: verbose_name = _('Convention') verbose_name_plural = _('Conventions') def __str__(self): return self.name", "range(days)] return dates def ticket_sales_has_started(self): return timezone.now() > self.ticket_sales_opens def ticket_sales_has_ended(self): return timezone.now()", "c...
[ "from string import ascii_lowercase from amqp import connect_get_channel_declare_exchange_and_return_channel, EXCHANGE_NAME APPS = [\"foo\", \"bar\",", "in range(1, 1000): routing_key = \"%s.%s\" % (choice(APPS), choice(LEVELS)) body = \"%03d Some", "#!/usr/bin/env python import time from random import choice f...
[ "to 50)```**\\n**```kekw!emojis```**\", inline=False) embed.set_footer(text=\"Requested by: \" + str(ctx.author), icon_url=str(ctx.author.avatar_url)) await ctx.message.delete() await ctx.send(embed=embed,", "help(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def help(self, ctx)...
[ "''' Twilio keys for send_text.py: account_sid_key auth_token ''' class TwilioKey: def __init__(self): #", "account_sid_key auth_token ''' class TwilioKey: def __init__(self): # https://www.twilio.com/try-twilio self.account_sid_key = \"your_sid\" self.auth_token_key", "__init__(self): # https://www.twilio.com/...
[ "doing computation using spark streaming # store back to kafka producer in another", "5) logging.basicConfig() self.logger = logging.getLogger() self.logger.setLevel(logging.INFO) def process(self, timeobj, rdd): def group(record): data", "topic to send processed data to kafka broker\") parser.add_argument(\"ka...
[ "start_urls = ['https://api.wallstcn.com/apiv1/content/information-flow?channel=global&accept=article&limit=20&action=upglide'] category_id = get_category_by_name(name) def parse(self, response): json_data = response.json() res_list", "item = WallstreetcnItem() resource = res[\"resource\"] title = resource[\"titl...
[ "end <= max: break else: print(f'Please enter a number between {min} and {max}')", "print(f'Please enter a number between {min} and {max}') while True: end = get_num_int('Enter", "a list in a cleaner way\"\"\" string = '' for i in range(len(lst)):", "get_num_int(prompt: str) -> int: \"\"\"Function to check if...
[ "from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.views.decorators.http import", "HttpResponse(status=404) FormFieldQueryset=PDFFormField.objects.filter(pdf=pdfid).prefetch_related('field') context={ \"formFields\":FormFieldQueryset,...
[ "'Zoo', 'Credit'], key=str.lower, reverse=True) print(s) L = [('Bob', 75), ('Adam', 92), ('Bart', 66),", "return t[0].lower() def by_score(t): return t[1] if __name__ == '__main__': print(sorted([36, 5, -12,", "L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] s2 = sorted(L,", "92), ('Bart', 66), ('...
[ "distributed in the hope that it will be useful, # but WITHOUT ANY", "not, see <http://www.gnu.org/licenses/>. import sys import fontforge if __name__ == \"__main__\": font =", "either version 3 of the License, or # (at your option) any later", "#!/usr/bin/python # Copyright (C) 2012, <NAME> <<EMAIL>> # http:...
[ "* 1 if x is not None else None, alpha=alpha if alpha is", "not None else None ) super(BLModel, self).__init__() self._set_parents(self.bernoulli, self.lognormal) def prod(args): return np.prod(args,", "<reponame>i1bgv/abtools # -*- coding: utf-8 -*- import numpy as np from .base import", "k_b=None, k_l=None)...
[ "from pydantic import BaseModel, Field class URL(BaseModel): \"\"\" FastAPI uses pydantic to validate", "\"\"\" Simulate get from db like in sqlalchemy, where u can .get by", "typing.List[URL]: \"\"\" To work with large collections of data better use generators, to", "URL: \"\"\" DB create simulation. Better ...
[ "simplified_params = module.get_graph_json(), module.get_lib(), module.get_params() repo_root = \"/home/ubuntu/workspace/tvm\" project_dir = os.path.join(repo_root, \"apps\", \"microtvm\",", "= \"float32\" with tvm.micro.Session(binary=micro_bin, flasher=compiler.flasher()) as sess: m_ = tvm.micro.create_local_gr...
[ "# First check if the data has been generated # If not prompt", "looks like no processed data has been generated.\\n', 'Please run the \\'data_generation.py\\' file", "directory\\ in order to run these scripts. Type \\'pwd\\' in the command line\\", "filepath.endswith('myersBriggsNLPAnalysis'): print('\\nYou ...
[ "k):>6}|{scm(i, k):>6}|{(i * k):>6}\") # gcd(a, b) * scm(a, b) = |a *", "return a def gcd_recursive(a: int, b: int): return gcd_recursive(b, a % b) if", "int: while True: r = a % b a = b b =", "else a def scm(a: int, b: int) -> int: # gcd(a, b) *", "def parse_args(): parser = argparse.ArgumentParser(descrip...
[ "= [graph['accuracy'], graph['merged_summary_op']] accuracy_test, test_summary = sess.run(test_opts, feed_dict=feed_dict) test_writer.add_summary(test_summary, step) print('===============Eval a batch=======================')", "[graph['train_op'], graph['loss'], graph['merged_summary_op'], graph['global_step']] ...
[ "huffman.Node.from_binary(lorem_tree) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes == lorem_codes)", "ad minim veniam, quis nostrud exercitation \" b\"ullamco laboris nisi ut aliquip ex", "deserunt \" b\"mollit anim id est laborum.\") lorem_codes = { \" \"...
[ "if not action: action = self.try_merge() #if not action: # action = self.try_dependent()", "alignment empty (or singleton) if len(tok_alignment) <= 1: return None # check if", "+ 1) if not cur_alignment or not nxt_alignment: return None # If both", "action is PRED, COPY_LEMMA, COPY_SENSE01. If 1) the current...
[ "'publish') @patch('urllib2.urlopen') def test_graceful_failure_on_http_error(self, urlopen_mock, publish_mock): urlopen_mock.side_effect = HTTPError( Mock(), Mock(), Mock(), Mock(),", "CollectorTestCase from test import get_collector_config from test import unittest from urllib2 import HTTPError", "2692, 'hach...
[ "'weights.pth') if os.path.isfile(model_path): print('Loading %s' % model_path) model.load_state_dict(torch.load(model_path)) self.dataset = self.create_dataset(model.deconv_cell_size) self.optimizer =", "= 'train', **kwargs): assert mode == 'train' # Single epoch metric_context = MetricContext()", "range(30): ...
[ "self.hlay_inner_opacity.addWidget(self.slide_inner_opacity) self.gridLayout.addLayout(self.hlay_inner_opacity, 13, 1, 1, 2) self.btn_outline_on = QPushButton(self.gridLayoutWidget) self.btn_outline_on.setObjectName(u\"btn_outline_on\") self.btn_outline_on.setCheckable(True) self.btn_outline_on.setChecked(True) sel...
[ "dbc.Checklist( id=\"spdx_recursive\", options=[ {\"label\": \"Recursive (Projects in Projects)\", \"value\": 1}, ], value=[], switch=True,", "value=[], switch=True, ) ], className=\"mr-3\", ), dbc.Button(\"Export SPDX\", id=\"buttons_export_spdx\", color=\"primary\"), ], # inline=True,", "+= 1 print(\"{}: mark...
[ "np import unittest import os import tempfile import sys class TestConversion(unittest.TestCase): def test_imread(self):", "for fname in expected_files] found_paths, found_files = phathom.utils.tifs_in_dir(file_test_dir) self.assertEqual(found_files, expected_files, msg='found incorrect tif", "= np.random.rando...
[ "a match. ''' teamMatchId = db.Column(db.Integer, primary_key=True) #tuid matchNo = db.Column(db.Integer, db.ForeignKey('Match.matchNo'), nullable=False)", "easier autoLow = db.Column(db.Integer) autoHigh = db.Column(db.Integer) autoPickedUp = db.Column(db.Integer) autoNotes = db.Column(db.String(255))", "db.Fo...
[ "TableService(account_name,accoun_key) def get_table_service(): return ts.exists(table_name,10) ts = set_table_service() if get_table_service() == False: ts.create_table(table_name)", "= csv.DictReader(csvFile) rows = [row for row in reader] for row in rows:", "'projectx' file_name = 'C:\\\\Users\\\\admin\\\\Do...
[ "from tests.base import RDMATestCase from pyverbs.mr import MR import pyverbs.enums as e class", "create_mr(self): self.mr = MR(self.pd, self.msg_size, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoXRC(XRCResources): def create_mr(self): self.mr", "client.pre_run(server.psns, server.qps_num)...
[ "document import preprocess import argparse import pdb def get_summary(input_text): pr = preprocess.Preprocess() original_text", "pr = preprocess.Preprocess() original_text = input_text preprocessed_text = pr.get_clean_article(input_text) sentences = pr.get_article_sentences(preprocessed_text) original_sentences"...
[ "Copyright (c) 2016, 2017, 2018, 2019 Sqreen. All rights reserved. # Please refer", "= logging.Formatter(LOG_FORMAT) handlers = [] # Configure the stderr handler configured on CRITICAL", "\\t%(message)s\" ) def configure_root_logger(log_level, log_location=None, root=ROOT_LOGGER_NAME): \"\"\" Configure the sqre...
[ "<reponame>kevinkissi/basic-tech-tips-webapp from django.contrib import admin from django.apps import apps questions = apps.get_app_config('questions') for", "from django.contrib import admin from django.apps import apps questions = apps.get_app_config('questions') for model_name,", "from django.apps import app...
[]
[ "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "writing, software # distributed under the License is distributed on an \"AS IS\"", "KIND, either express or implied. # See the License for the specific language", "language governing permissions and # limitations under the License...
[ "import Runnable class showMultiPlayerBoard(Runnable): def __init__(self,vue, sec): Runnable.__init__(self,vue) self.sec = sec def run(self):", "view.runnable.Runnable import Runnable class showMultiPlayerBoard(Runnable): def __init__(self,vue, sec): Runnable.__init__(self,vue) self.sec = sec def", "Runnable cl...
[ "'v2' def __init__(self, api_key, api_secret, base_api_uri=None, api_version=None, debug=False): if not api_key: raise ValueError('Missing", "market = market, timeframe = timeframe ) if page is not None: params[\"page\"]", "= 0.0 page = 0 n_entries = 100 while True: book_page = self.get_book(market,", "temp =...
[ "version='1.1', description='assembly and variant calling for stlfr and hybrid assembler for linked-reads', author='XinZhou',", "setuptools import setup, find_packages, Extension setup(name='aquila_stlfr', version='1.1', description='assembly and variant calling for stlfr", "from setuptools import setup, find_p...
[ "observer.on_next, on_error, observer.on_completed, scheduler ) return subscription return Observable(subscribe) def _catch(handler: Union[Observable, Callable[[Exception,", "or an exception handler function that returns an observable sequence given the error", "Union[Observable, Callable[[Exception, Observable...
[ "path_list)) self.assertEqual( \"Documents\", get_best_match(\"dos\", path_list)) self.assertEqual( \"Downloads\", get_best_match(\"dol\", path_list)) # Case insensitive self.assertEqual(", "filter_paths, get_print_directories, get_best_match) TEST_DIR = \"fixtures\" def touch(path): with open(path, 'a'): os.utim...
[ "# -*- coding: utf-8 -*- class classproperty(property): def __get__(self, cls, owner): return classmethod(self.fget).__get__(None,", "-*- coding: utf-8 -*- class classproperty(property): def __get__(self, cls, owner): return classmethod(self.fget).__get__(None, owner)()" ]
[ "!!! ''' ################################# # import PyMbs & Lib. # ################################# from PyMbs.Input import", "Zyl_stange_4.addFrame('Zyl_stange_4_cs', p=[0,0,0]) Zyl_stange_4.addFrame('Zyl_stange_4_cs_2', p=[0,0,0]) Zyl_stange_5 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inerti...
[ "this world wr = width/3.0 # wr width of reward area wwalls =", "/ Sorbonne Université 02/2018 This file allows to build worlds TODO : replace", "square world \"\"\" ## first build default world texture_paths, world_info = _build_square_default_world(model, texture,", "if distractors: # add visual distractors...
[ "supplied cache type name cannot be found. \"\"\" def get_cache(cfg): \"\"\" Attempt to", "implement correctly. __slots__ = (\"cache\", \"max_age\", \"max_size\", \"queue\") clock = staticmethod(time.time) def __init__(self,", "if cache_name == \"null\": logger.info(\"Caching deactivated\") return None for ep i...
[ "settings given some environment variables. :param monkeypatch: The pytest monkeypatch fixture \"\"\" settings", ") def test_full(settings_env_var_to_full): \"\"\"Test the source of effective settings given a full config.", "given some cli parameters.\"\"\" settings = deepcopy(NavigatorConfiguration) settings.i...
[ "def validate_user(self): if True: self.auth = True if __name__ == '__main__': app =", "if True: self.auth = True if __name__ == '__main__': app = QApplication(sys.argv) w", "import os, sys sys.path.append(os.getcwd()) from PyQt5.QtWidgets import QApplication from src.view.widgets.buttons_cch import ButtonsCCHV...
[ "The preprocessor module. ''' # CS 267 specific imports from preprocessor.build_tables import read_input_files", "the words extracted from the PDFs. The preprocessor module. ''' # CS 267", "imports from preprocessor.build_tables import read_input_files from preprocessor.build_tables import determine_word_positi...
[ "<gh_stars>1-10 # Generated by Django 4.0.1 on 2022-03-16 14:58 import base.models from django.db", "Generated by Django 4.0.1 on 2022-03-16 14:58 import base.models from django.db import migrations,", "= [ ('base', '0031_alter_profile_picture_delete_weeklychallenge'), ] operations = [ migrations.AlterField( mo...
[ "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "writing, software # distributed under the License is distributed on an \"AS IS\"", "def _histogram_model(): return histogram_model.HistogramModelBroadcastProcess( _test_weights_type_struct_float_tensor, _mn, _mx, _nbins) class Histo...
[ "** zoom xtile = int((lon_deg + 180.0) / 360.0 * n) ytile =", "cur = conn.cursor() bboxStr = \"-180,-85,180,85\" if BBOX is None else \",\".join(map(str, BBOX))", "for y in range(ystart, yend+1): download_url(zoom, x, y, cur) conn.commit() cur.close() conn.close() main(argv)", "or \"overlay\" LAYERNAME = \"OS...
[ "txt in txts[-10:]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt) as f: text=f.readline().strip() eval_set.append((iid, text))", "txt) with open(txt) as f: text=f.readline().strip() train_set.append((iid, text)) for txt in txts[-20:-10]: iid=os.path.basename(txt).split('.')...
[ "\"\"\"Retain the K most recent scores, and replace the rest with zeros\"\"\" for", "scores def select(self, choice_scores): \"\"\"Use the top k learner's scores for usage in", "self.choices: continue choice_rewards[choice] = reward_func(scores) return self.bandit(choice_rewards) class RecentKVelocity(RecentKRe...
[ "p.raw) self.assertEqual(indicator, p.indicator) self.assertEqual(value, p.value) def test_valid_altimeter(self): self._test_valid(\"A2992\", \"A\", 29.92) def test_valid_QNH(self): self._test_valid(\"Q1013\",", "indicator, value): p = Pressure(raw) self.assertEqual(raw, p.raw) self.assertEqual(indicator, p.indic...
[ "design = models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True) content = models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True) usability = models.PositiveSmallIntegerField( choices=RATE_CHOICES, null=True)", "self.save() RATE_CHOICES = [ (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5,", "im...
[ "data_service.append(\"\") data_service.extend([ f\"{TAB}#{'-' * 40}\", f\"{TAB}# END '{service.name}'\", f\"{TAB}#{'-' * 40}\" ]) return", "parser.add_parser(\"docker-compose\", help=\"build a docker-compose\") sub_parser.add_argument(\"-v\", \"--compose-version\", default=\"3.7\", help=\"minimum docker-compose ...
[ "return len(list(([e for e in nums if len(str(e))%2 == 0]))) if __name__ ==", "int: return len(list(([e for e in nums if len(str(e))%2 == 0]))) if __name__", "len(list(([e for e in nums if len(str(e))%2 == 0]))) if __name__ == '__main__':", "for e in nums if len(str(e))%2 == 0]))) if __name__ == '__main__': p...
[ "(event.key == K_SPACE or event.key == K_UP): playerEvent = event # move pipes", "+ 10 return [ {'x': pipeX, 'y': gapY - PIPEHEIGHT}, # upper pipe", "0}) for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN", "crash here crashTest = checkCrash(player, upperPipes, lowerPipes) if cra...
[ "redirect('lab_reports') @login_required def lab_reports(request): reports = Report.objects.filter(user = request.user) if reports: return render(request,", "if appointments: return render(request, \"appointments_list.html\", {'appointments': appointments}) else: message = \"No records Found\"", "\"No records F...
[ "{ \"_index\": \"blog\", \"_type\": \"_doc\", \"_id\": \"1\", \"_score\": \"10.114\", \"_source\": { \"title\": \"Test", "elasticsearch_dsl.connections import add_connection @fixture def mock_client(dummy_response): \"\"\"Returns elasticsearch mock client\"\"\" client = MagicMock()", "względów doszli potem się ...
[ "here char_line = 0 char = {} elif char_line == 1: char['font'] =", "parse_font_dat(self): self._fonts = [] float_pattern = '[+-]?[0-9]+\\.[0-9]+' string = '' char_line = 9999", "self.parse_font_dat() return self._string def parse_font_dat(self): self._fonts = [] float_pattern = '[+-]?[0-9]+\\.[0-9]+' string ="...
[ "build_argv(positional=self.positional) with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v1-json.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using", "with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fiel...
[ "stdin. Args: stdin (str): The output of sys.stdin.read() \"\"\" print stdin def _cat_file(self,", "import sys class Cat(object): def __init__(self, fname=None, stdin=None): \"\"\" Constructor Args: fname (str):", "for f in self.fname: self._validate_file(f) self._cat_file(f) else: self._validate_file(self.fnam...
[ "in ipid_map.iteritems(): # f.write(\"ip: \"+ip+\" id: \"+str(id_list)+\"\\n\") #f.close() if __name__ == \"__main__\": main()", "and (sum(result)/len(result))>0 and (sum(result)/len(result)) < 6: reflector_candidate[ip] = lists[0] f4.write(\"respond to ip: \"+ip)", "<= 29 and len(result) >20 and (sum(result)/l...
[ "from ralph.accounts.tests.factories import RegionFactory, UserFactory from ralph.back_office.tests.factories import BackOfficeAssetFactory from ralph.lib.transitions.tests import TransitionTestCase", "ValidationError from django.core.urlresolvers import reverse from ralph.accounts.tests.factories import RegionFa...
[ "the same row-traversing order as they were. If the reshape operation with given", "of the original matrix in the same row-traversing order as they were. If", "new reshaped matrix; Otherwise, output the original matrix. Example 1: Input: mat =", "1 <= r, c <= 300 Solution-: class Solution: def matrixReshape(s...
[ "'Variable Categories') cat_ids = var_categories['CategoryId'].unique().tolist() cat_ids = [int(x) for x in cat_ids] current_cat_id", "1 entities = [] variables = pd.read_excel(xlsx, 'Variables') for idx, row in variables.iterrows():", "local_id = str(row['VariableName']).strip() if '%' in local_id: local_id = ...
[ "platform, api=None): \"\"\"Retrieve information about an influencer. Args: project_id (int): id of the", "= api.router.influencer['find'].format(project_id=project_id) params = dict( uid=influencer_id, platform=platform ) res_data = api.get(url, params=params) return", "\"\"\" api = api or RadarlyApi.get_defau...
[ "<= 0: raise ZDBPathNotFound(\"all storagepools are already used by a zerodb\") return free_path[0]", "import config from zerorobot.template.base import TemplateBase from zerorobot.template.decorator import retry, timeout from zerorobot.template.state", "hostname, \"node_id:%s\" % node_id, \"interface:%s\" % mg...
[ "django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('authorization', '0004_auto_20200207_2147'), ] operations = [ migrations.AlterField(", "from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('authorizat...