ngram
listlengths
0
67.8k
[ "ConfigParser def configLoader(filename): if os.path.exists(filename): _config = ConfigParser() _config.read(filename) return _config._sections else: return", "os import sys from ConfigParser import ConfigParser def configLoader(filename): if os.path.exists(filename): _config =", "import ConfigParser def config...
[ "self.shuffle() def shuffle(self): counter = self.mines for idx1 in range(self.size): for idx2 in", "epoch -= 1 def checking(self): idx1 = 0 idx2 = 0 # searching", "0: if idx2 - 1 >= 0: neighbours.append([idx1-1, idx2-1]) if idx2 + 1", "epoch = 1000 while epoch > 0: idx1, idx2, idx3, idx4 = sample([num", "i...
[]
[ "import DynamixelMotor from .fan import Fan from .force_sensor import ForceSensor from .joint import", ".joint import Joint from .orbita import OrbitaActuator Device = Union[Fan, Joint, DynamixelMotor, ForceSensor,", "from .force_sensor import ForceSensor from .joint import Joint from .orbita import OrbitaActua...
[ "\"\"\" # O(n) time # O(n) memory from typing import Optional # Definition", "head visitedNodes = {} while currentNode is not None: if visitedNodes.get(currentNode) is not", "Cycle https://leetcode.com/problems/linked-list-cycle/ \"\"\" # O(n) time # O(n) memory from typing import Optional", "= None class Sol...
[ "as f: long_desc = f.read() setup( name=\"pyumlgen\", version=\"0.1.6\", description=\"Generate UML diagrams with type", "type information from python modules\", author=\"<NAME>\", packages=find_packages(), entry_points={ \"console_scripts\": [ \"pyumlgen=pyumlgen:main\" ] }", "path.abspath(path.dirname(__file_...
[ "self.assertEqual( self.method.charge_excl_tax_before_discount, D('10.00')) self.assertEqual(self.method.code, self.base_method.code) self.assertEqual(self.method.name, self.base_method.name) self.assertEqual(self.method.description, self.base_method.description) def test_discounts_charge(self): self.assertEqual(se...
[ "in data: commentCurr = { \"author\": obj.user_id, \"text\": urllib2.unquote(obj.comment.replace('+', ' ')), \"post_id\": obj.post_id,", "'GET': return render_to_response('index.html') elif request.method == 'POST': queryDict = QueryDict() queryDict = request.POST", "= Comments.objects.all() comments = [] for o...
[ "3 - Recovered = 4 - Dead = 5 \"\"\" # Copia degli", "contaggiosi = np.concatenate((n_exp,n_inf,n_g_inf), axis=None) for x in contaggiosi: for n in self.g.neighbors(x): Rand", "t_inc: {}; t_inf: {}\\n alpha: {}; beta: {}; gamma: {}'.format(simulator.p_link, simulator.exp0,simulator.t_exp,simulator.t_inf,simulat...
[ "django.contrib import admin # Register your models here. from .models import shortenedUrl admin.site.register(shortenedUrl)", "from django.contrib import admin # Register your models here. from .models import shortenedUrl" ]
[ "actually accounted for. The rest are absolutely trashed. ''' res = subprocess.run( [DIALOG_NAME,", "= (0,0,) # Try to get the primary screen resolution from xrandr. try:", "join def _fix_output(output): ''' Removes miscelanous stdout output that can happen with Mesa", "to jump into the except block. raise Va...
[ "import division from __future__ import absolute_import from future import standard_library import twitter_scraper as", "division from __future__ import absolute_import from future import standard_library import twitter_scraper as twitter_scraper", "tweets = twitter_scraper.scraper.Scraper.get_tweets(search_par...
[ "get_banned_users( active_only, ban_type, limit, offset, namespace, doc, login_as, ): login_as_internal(login_as) if doc: click.echo(admin_get_banned_users_v3.__doc__)", "type=int) @click.option(\"--namespace\") @click.option(\"--doc\", type=bool) @click.option(\"--login_as\", type=click.Choice([\"client\", \"use...
[ "return sum(len(l.encode('unicode_escape').decode('utf-8').replace('\"', '\\\\\"')) - len(l) + 2 for l in a) if __name__", "2 for l in a) def part2(a): return sum(len(l.encode('unicode_escape').decode('utf-8').replace('\"', '\\\\\"')) - len(l) +", "a) if __name__ == '__main__': data = get_data(day=8, year=2015)...
[ "grid_object.height) self._fb = adafruit_framebuf.FrameBuffer(self._buffer, grid_object.width, grid_object.height, buf_format=adafruit_framebuf.MVLSB) super().__init__(grid_object, speed, color, name=name) on_cycle_complete_supported =", "on the display self.cycle_complete = True self._frame = 0 def reset(self): ...
[ "self.fc1 = layers.Dense(128) self.fc2 = layers.Dense(4) def call(self, x, training=False): x,_ = self.encoder(x)", "CNN() ip_dims = self.cnn.compute_output_shape((None,None,None,5))[-1] self.encoder = Encoder(self.cnn,ip_dims) self.flatten = layers.Flatten() self.drop = layers.Dropout(0.3)", "layers.Dense(4) d...
[ "import re from os import environ # URL to the Groupme API endpoint", "endpoint API_URL = 'https://api.groupme.com/v3/bots/post' # URL to the Google Sheets JSON API endpoint", "API_URL = 'https://api.groupme.com/v3/bots/post' # URL to the Google Sheets JSON API endpoint SHEET_BASE_URL", "re from os import env...
[]
[ "ConfigManager config_data = ConfigManager() f2g_session = Face2Gene(config=config_data) s_list = f2g_session.browse_all_syndromes() with open(\"f2g_library_dump.json\", \"w\")", "pprint import json from lib.api.face2gene import Face2Gene from lib.model.config import ConfigManager config_data =", "from lib.mode...
[ "as system class TestShadowMayaSystem(MayaBaseTestCase): def test_system(self): \"\"\"Test system in some fashion\"\"\" return True", "from maya import cmds from base import MayaBaseTestCase import shadow_maya.shadow_maya_system as system class", "base import MayaBaseTestCase import shadow_maya.shadow_maya_syst...
[ "async def linguas(message, _): msg = \"```\\n\" for k in LANGUAGES.keys(): msg +=", "cod2 in list(LANGUAGES.values())): for k in LANGUAGES.keys(): if LANGUAGES[k] == cod2: cod2 =", "= k elif (len(cod1) == 2 and cod1 not in list(LANGUAGES.keys())): return Exception", "for k in LANGUAGES.keys(): msg += str(k)+...
[ "self._inject_provider(account) return account raise IndexError(f\"No account with alias '{alias}'.\") @singledispatchmethod def __getitem__(self, account_id)", "import ConfigManager from .converters import ConversionManager from .networks import NetworkManager @dataclass class AccountManager:", "section of the...
[ "number # ------------------------------------------------- # # Return triangle number, return number of factors. #", "if sqrt*sqrt==n: t -=1 return t result,d,num,_tau=0,0,0,0 while _tau < 500: _t=t(d) _tau=tau(_t)", "-=1 return t result,d,num,_tau=0,0,0,0 while _tau < 500: _t=t(d) _tau=tau(_t) if result <", ...
[ "repository}, # howpublished = {\\url{https://github.com/AntixK/PyTorch-VAE}} # } from torch import nn from abc", "= {PyTorch-VAE}, # year = {2020}, # publisher = {GitHub}, # journal =", "= {GitHub}, # journal = {GitHub repository}, # howpublished = {\\url{https://github.com/AntixK/PyTorch-VAE}} # }", "# } fr...
[ "deviation (FSTDEV)** The sample variance of the forecasts is defined as .. math::", "@property def BAGSS(self): \"\"\"Bias Adjusted Gilbert Skill Score (BAGSS)\"\"\" return self.bias_adjusted_gilbert_skill_score(self._f, self._o) @staticmethod", "A perfect forecast would have MSE = RMSE = 0. MSE can be", "is...
[ "SIR(t, X): #The main set of equations Y = np.zeros((3)) Y[0] = -b", "their contacts contacts = randint(N, size=b) for j in contacts: if not pop[j].is_removed():", "2 = removed \"\"\" def __init__(self,startpos=None): self.status = 0 if startpos==None: self.pos =", "* X[2] - (k * X[2]) + r * X[1] return Y t_e...
[ "self._map_object = map_object self._part = part def flip(self): self._map_object.invalidate_geometry() with self._undo_stack.property_change( \"Sprite/Wall Flip\",", "self._part, \"xflip\", \"yflip\" ): if self._stat.xflip and self._stat.yflip: self._stat.xflip = 0 elif self._stat.xflip:", "__init__( self, und...
[ "the second number:\") s_num = int(input()) subtraction = f_num - s_num print (\"The", "second number:\") s_num = int(input()) subtraction = f_num - s_num print (\"The value", "f_num = int(input()) print(\"Enter the second number:\") s_num = int(input()) subtraction = f_num", "the first number:\") f_num = int...
[ "\"\"\" count = 0 for i in range(0, 32): if num & 1:", "countOnes(self, num): # write your code here \"\"\" count=0 while num!=0: num =", "if num & 1: count = count + 1 num = num >>", "in range(0, 32): if num & 1: count = count + 1 num", "Solution: \"\"\" @param: num: An integer @return: An integer \"\"\" d...
[ "web.args['name'], float(web.args['lat']), float(web.args['lon']) location[i].name, location[i].lat, location[i].lon = args location[i].flush() except Exception as e:", "int(web.args['idx']) args = web.args['name'], float(web.args['lat']), float(web.args['lon']) location[i].name, location[i].lat, location[i].lon ...
[ "wait for input from user. Each queue has a number associated with it,", "instance, which will be used to manipulate queues. Other attributes, that may be", "inside of script's help (run with -h argument); * client_method_name (str) - name", "(seperated by space) / ' '\"all\" to choose all queues.', 'nargs': ...
[ "= [ ] operations = [ migrations.CreateModel( name='Portfolio', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,", "models.CharField(max_length=255, verbose_name='title')), ('slug', models.SlugField(help_text=\"Used to build the category's URL.\", max_length=255, unique=True,...
[ ") # the furthest i can go with current i if ( i", "limit if i < len(steps) - 1: step_num += 1 # each switch", "values in this problem 1. current furthest distance 2. current index 3. current", "i, means i can never reach i return None furthest = max( furthest,", "> len(steps) - 1: return step_num for i in ...
[ "list_of_squares(num): i = 1 squares = [] while i**2 <= num: squares.append(i**2) i", "squares = [] while i**2 <= num: squares.append(i**2) i += 1 return squares", "<= num: squares.append(i**2) i += 1 return squares if __name__ == '__main__': num", "квадратов def list_of_squares(num): i = 1 squares = [] while...
[]
[ ": float recall : float \"\"\" if position == 0: precision = 1.0", "fig, ax = plt.subplots(1, 1, figsize=(7, 4)) plot_axes(ax, p, r, legend_text='IAP', **kwargs) plt.show()", "side-by-side for two different sets of scores, against the same true observations. Parameters", "on a weighted sum of the data. Parame...
[ "(i + l < len(B)) and (j - l > 0) right =", "i: B[k][down] -= 1 # diagonal downwards queen line of sight for l", "args[1] n = 0 try: n = int(ns) except ValueError: print(usage) return #", "True ns = args[1] n = 0 try: n = int(ns) except ValueError:", "if not args[0] == \"-v\": print(usage) return v = True n...
[ "models extendable at runtime.\"\"\" # shortcut to main used class from .main import", "pydantic models extendable at runtime.\"\"\" # shortcut to main used class from .main", "\"\"\"A lib to define pydantic models extendable at runtime.\"\"\" # shortcut to main", "to define pydantic models extendable at runt...
[ "arg +'\" &') serial.write('n'.encode()) else: print('Unknown Command') class ScratchServer(socketserver.ThreadingTCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,", "+'\" &') serial.write('n'.encode()) else: print('Unknown Command') class ScratchServer(socketserver...
[ "show, warn, error from basemessage import WireMessage from nullsink import NullSink class Sink:", "len(msg) > _max: _max = len(msg) if not _min or _min > len(msg):", "= average message size\" % int(s/n)) show(\"%d = minimum message size\" % _min)", "WireMessage from nullsink import NullSink class Sink: def _...
[ "connection=dynamodb_connection, global_indexes=[index_job_id]) etl_records = ETLRecords(persistence_object=table, avro_schema_object=avro_schema) for job in SAMPLE_RECORD_JOBS: assert etl_records.put(**job) yield", "None, } class TestRunActions(object): @pytest.yield_fixture(scope='module') # noqa def etl_record...
[ "= forms.CharField( label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('email',", "form for creating new users. Includes all the required fields, plus a repeated", "plus a repeated password.\"\"\" password1 = forms.CharField(label='Password', widget=forms.PasswordInput...
[ "thermostat_devices(self): \"\"\" :return: Thermostat devices associated to the Raspberry Pi. \"\"\" residence =", "= ('datetime',) def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() assert (self.pk == self.datetime) pks.append(self.datetime.isoformat()) return", "future work. \"\"\" class M...
[ "to manage a frozen lake from gym lib and make an agent play.", "game_setting : Dict() Dictionnary of all game setting ai_setting : Dict() Dictionnary of", "is_done, _ = self.env.step(action) reward = 0 is_win = new_state == self.cell_count -", ": Env() Object that store all the gym environment Methods ------...
[ "0.1, # variance of location on x-axis 0.1, # variance of location on", "jacfwd, jit import matplotlib.pyplot as plt from src.environments import DiffDriveRobot from util import", "https://github.com/AtsushiSakai/PythonRobotics \"\"\" from functools import partial from estimation import ExtendedKalmanFilter, Ka...
[ "setuptools setuptools.setup( name=\"uniqpy\", version=\"0.1.3\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"UNIQUAC-based tool for multicomponent VLEs\", long_description=\"uniqpy\", long_description_content_type=\"\",", "multicomponent VLEs\", long_description=\"uniqpy\", long_description_conten...
[ "y = fetch_libsvm(\"news20.binary\") C_min = 2 / norm(X.T @ y, ord=np.inf) C =", "converge\") warnings.filterwarnings(\"ignore\", message=\"Liblinear failed to converge\") X, y = fetch_libsvm(\"news20.binary\") C_min = 2", "= linear_model.LogisticRegression( C=C, solver=\"liblinear\", penalty='l1', fit_intercep...
[ "+ '_2' self.samweb.modifyDefinition(defname,defname=defname2) d = self.samweb.descDefinitionDict(defname2) assert defname2 == d[\"defname\"] self.samweb.deleteDefinition(defname2) class TestDefinitionCommands(testbase.SAMWebCmdTest):", "assert defname in d d = self.samweb.descDefinitionDict(defname) assert defna...
[ "index(int): Index. batch_size(int): Batch Size. max_len_src(int): Max length for resource. max_len_trg(int): Max length", "* (max_src_len - len(line)) for line in sorted_src_lines ] input_lines_trg = [ [", "self.src[idx][\"data\"] = [] self.trg[idx][\"data\"] = [] # Populate buffer for src, trg in", "] sent1...
[]
[ "def before_request(): g.db = sqlite3.connect(app.config['DATABASE']) @app.teardown_request def teardown_request(exception): db = getattr(g, 'db', None)", "methods=['POST', 'GET']) def login(): if request.method == 'POST': name = request.form['user'] password =", "g.db.execute('select * from users where name=? ...
[ "print('Invalid parts') return False if parts[0] != 'Bearer': print('No bearer') return False try:", "<filename>backend/src/auth.py from flask import request import jwt import os JWT_SECRET = os.getenv('JWT_SECRET') JWT_AUDIENCE", "authorization.split(' ') if len(parts) != 2: print('Invalid parts') return False...
[ "License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "writing, software # distributed under the License is distributed on an \"AS IS\"", "# under the License. from tempest.common import utils from tempest.lib import decorators from", "Unless required by applicable law or agreed ...
[ "no # digit is exceeded by the digit to its right it is", "to its left # it is called an increasing number; for example, 134468.", "by the digit to its left # it is called an increasing number;", "http://github.com/lcsm29/project-euler import timed def dummy(n): pass if __name__ == '__main__': n = 1000", "f...
[ "= await get_firebolt_tables(connection) logger.info(f\"Found {len(tables)} available tables.\") return await gather(*[get_table_stream(connection, table) for table", "logger: Logging object to display debug/info/error to the logs (logs will not be", "\"\"\" try: with establish_connection(config, logger) as con...
[ "self.translate_collection if not word: return word for write in translate_list: if isinstance(write, dict)", "value in v.items(): return cast(value_type, value) fdict = {} for key in thsort:", "for i, value in enumerate(search_obj): new_d_path = None if d_path: new_d_path = f'{d_path}[{i}]'", "import os impo...
[ "import bot if __name__ == '__main__': zonbot = bot.Bot('!', pm_help = True) zonbot.run(zonbot.token)" ]
[ "= { 'type': 'intention', 'function': eq2, } yaml_dict['constraints'] = constraints # agents agents", "as f: yaml.dump(scenarios, f) print(f'Simulation scenario file saved: {yaml_file}') if __name__ == '__main__':", "}) exported_file = args.file.split('/')[-1] + '-scenario.yaml' yaml_file = os.path.join('./yaml...
[ "'_gdp'].sum() dec_base[perc] = dec_gdp_tot/dec_pop_tot ind_ctry = dec.index imtrx_dec = imtrx_gdp[:,ind_ctry,:] imtrx_dec_sum = dec_gdp_tot-(imtrx_dec.data).sum(axis=1)", "_env.mkdirs(odir_summary) for scen in scens: writer = pd.ExcelWriter(odir_summary + 'Deciles_and_Quintile_ratio_changes_'+ds+'_'+scen+'_Burke...
[ "from typing import List mylist: list[int] = [1, 2, 3, 4] print(mylist) mylist", "# from typing import List mylist: list[int] = [1, 2, 3, 4] print(mylist)", "import List mylist: list[int] = [1, 2, 3, 4] print(mylist) mylist = '1234'", "typing import List mylist: list[int] = [1, 2, 3, 4] print(mylist) mylist =...
[ "self.terminal = self.protocol.terminal def do_help(self): public_methods = [function_name for function_name in dir( self)", "class CommandsHandler: def __init__(self, protocol): self.protocol = protocol self.terminal = self.protocol.terminal def do_help(self):", "'.join(commands)) def do_echo(self, *args): sel...
[ "self.__relationships relationships[statistic] = dict() for row in ws.iter_rows(values_only=True): if row[0] in relationships[statistic]: for", "not None and i not in relationships[statistic][row[0]]: relationships[statistic][row[0]].append(i) else: relationships[statistic][row[0]] = [i for", "row in ws.iter_ro...
[ "rect4, title='RectCent: [1,-0.5], W: [0.5,1.0]', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) # Show Unions savedict[\"savename\"]=\"sphere_union_2d.jpg\"", "2D Value zero - set as cyan contour. Author: <NAME>, October 29, 2021", "-2*np.ones((2, 1),dtype=np.float64) g...
[ "clean_invite_embed(msg): \"\"\"Prevents invites from embedding\"\"\" return msg.replace(\"discord.gg/\", \"discord.gg/\\u200b\") def clean_backticks(msg): \"\"\"Prevents backticks from", "from embedding\"\"\" return msg.replace(\"discord.gg/\", \"discord.gg/\\u200b\") def clean_backticks(msg): \"\"\"Prevents bac...
[ "list(legend1.keys()) # Plot the results (= shape of the data points cloud) plt.figure(1)", "yy1, Z1, levels=[0], linewidths=2, colors=colors[i]) legend1_values_list = list(legend1.values()) legend1_keys_list = list(legend1.keys()) # Plot", "be able to run ML algorithms json_to_python = json.loads(data) per_siz...
[ "= time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq if time == last_time and switched_onepps: print \"Correcting delayed", "last_seconds > seconds0: # print \"Wrong event order\",seconds0,line # continue last_seconds = seconds0", "= True time_ch0 = seconds0 if time_ch0 - seconds0 > 50e-9: wa...
[ "default = Label(\"//tools/bzldoc:bzl2yaml\"), doc = \"The path to the bzl2yaml tool itself.\", ),", "), \"out\": attr.output( mandatory = True, doc = \"YAML file to generate.\", ),", "\"src\": attr.label( allow_files = [\".bzl\"], doc = \"BZL file to parse.\", ), \"out\":", "% name], visibility = [\"//visibi...
[ "KerasModel def main(): logging.basicConfig( level=logging.INFO, format=\"%(asctime)s : \" + \"%(module)s (%(lineno)s) - %(levelname)s", "wordsim.nn.utils import evaluate from wordsim.nn.data import create_datasets from wordsim.nn.model import KerasModel def main():", "conf = ConfigParser(os.environ) conf.read(...
[ "API. See api_version in realms.proto. API_VERSION = 1 def merge(permissions, realms, out=None): \"\"\"Merges", "the index in the final merged proto (or None if undefined). old_to_new =", "# Add the relabeled realm to the output. assert old_realm.name.startswith(proj_id+':'), old_realm.name new_realm =", "Aut...
[ "ContextManager() cm.fallback_context = \"m\" cm.initial_contexts = [\"m\"] cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) c1 = cm.create_context(\"t1\")", "constructor\"\"\" c = Context(\"test_context\", lambda *a, **k: True) self.assertIsNotNone(c) def test_threading(self): \"\"\"Tests whe...
[ "a partire da matrice di sostituzione aminoacid = file.readline().split() ami = aminoacid[3] #indicizzato", "le righe a partire dalla prima con un solo elemento print col #print(col)", "anche mettere int(col[i][:-1]) che mi consente di rimuovere il punto #che altrimenti da", "dict[k]=float(scores[row][col]) c...
[ "if jdata.get('errcode') == 0: print('开始好友对战...') else: print(jdata) except: print(resp.text) def findQuiz(quizNum): params =", "resp = session.post(url=chooseUrl,data=params,headers=headers) try : jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print(player", "tempParams = sorted(tempParams.items()...
[ "adc0 = ADC(Pin(26)) # create ADC object on ADC pin adc1 = ADC(Pin(27))", "adc1 = ADC(Pin(27)) # create ADC object on ADC pin #adc=None, Vref=3.3, R=10000,", ") ntc0=NTC(adc=ADC(Pin(26)), R=3300, Ro=47000, beta=3740) ntc1=NTC(adc=ADC(Pin(27)), R=3300, Ro=47000, beta=3740) print (\"{} V\".format(ntc0.in_volt()))...
[ "Bank Transfer \"\"\" k = int(input()) fee = 25 + k * 0.01", "> 2000 else fee fee = 100 if fee < 100 else fee", "2000 if fee > 2000 else fee fee = 100 if fee <", "fee = 25 + k * 0.01 fee = 2000 if fee >", "= 2000 if fee > 2000 else fee fee = 100 if fee", "\"\"\" 백준 21633번 : Bank Transfer \"\"\" k = int(in...
[ "dice_result = [] for i in range(0,1000): dice1 = random.randint(1,6) dice2 = random.randint(1,6)", "= [] for i in range(0,1000): dice1 = random.randint(1,6) dice2 = random.randint(1,6) dice_result.append(dice1+dice2)", "random.randint(1,6) dice2 = random.randint(1,6) dice_result.append(dice1+dice2) mean = sum(...
[ "+ len(self.cert_data) uefi_subreg_authen_hdr = struct.pack( self._StructAuthInfoFormat, self.w_name, self.vendor_guid.bytes_le, self.w_revision, self.dw_length, self.cert_type.bytes_le, ) self._valid", "typedef struct { # SUB_REGION_HEADER Hdr; // Certificate Header # UINT8 CertData[1]; //", "# typedef struct ...
[ "<gh_stars>1-10 # -*- coding: utf-8 -*- from django import template from django.conf import", "import settings from vvcatalog.conf import CURRENCY, PAGINATION register = template.Library() @register.simple_tag def get_currency():", "vvcatalog.conf import CURRENCY, PAGINATION register = template.Library() @regis...
[ "str \"\"\" return self._url @url.setter def url(self, url: str): \"\"\"Sets the url of", "accuracy: The accuracy of this DataUtility. :type accuracy: float \"\"\" if accuracy is", "completeness @property def timeliness(self) -> float: \"\"\"Gets the timeliness of this DataUtility. :return:", "completeness: f...
[ "torch.cuda.manual_seed_all(int(seed)) torch.backends.cudnn.deterministic = True def set_py_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for python", "elif not isinstance(int(seed), int): raise ValueError(f\"seed={seed} should be str or int\") random.seed(int(seed)) def", "torch process's rand seed The...
[ "socket.TCP_KEEPINTVL, 75) ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60) ftp = FTP_TLS() ftp.set_pasv(True) connect() ftp.voidcmd('TYPE I') dst_filesize", "= True t.start() return stop return wrap return outer_wrap class PyFTPclient: def __init__(self,", "ftp.voidcmd('TYPE I') dst_filesize = ...
[ "logging.getLogger(\"Ingest\") logger.info(\"Ingesting data\") try: columns = getattr(column_constants, \"column_constants\") schema = StructType([StructField(columns[\"GENDER\"], StringType(), True),", "input JSON file \"\"\" logger = logging.getLogger(\"Ingest\") logger.info(\"Ingesting data\") try: columns = g...
[ "self.handler # ValueError becomes exceptions.Gone handler.kwargs = {'id': 'string'} self.assertRaises( exceptions.Gone, handler.get_data_item, )", "users = mommy.make(User, 10) def test_get_data_item_single_field_selection(self): handler = self.handler self.assertEquals( handler.get_data_item(), None, )", "han...
[ "(str): path+name of the tiff file we want to convert destination_geojson_path (str): path+name", "\"__main__\": for file in os.listdir(\"asset/tiff\"): print(\"Conversion of \" + file + \" starting", "(str): path+name of the targeted geojson band (int): tiff band you want to", "geopandas as gpd def convert_t...
[ "while respecting the deadlines. Please refer to documentation for appropriate setup of solving", "range(NB_WORKERS): if t.skills[w] > 0: wt = mdl.interval_var(optional=True, name=\"H{}-{}({})\".format(loc, t.name, WORKER_NAMES[w])) worker_tasks[w].append(wt) allocs.append(wt)", "# Maximize total of skills mdl....
[ "Script que identifica si un numero ingresado por el usuario es PAR. '''", "un numero Entero: \") num = int(input()) if num % 2 == 0", ": print (\"El Numero es Par: \") else: print (\"El Numero es Impar:", "ingresado por el usuario es PAR. ''' N = 0 print (\"Ingrese un", "0 print (\"Ingrese un numero Entero...
[ "for idx, ch in enumerate(S): if ch == '(': stack.append(idx) elif ch ==", "idx, ch in enumerate(S): if ch == '(': stack.append(idx) elif ch == ')':", "S: str) -> int: stack = [] violations = 0 if S ==", "0 if S == '': return 0 for idx, ch in enumerate(S): if", "elif ch == ')': if len(stack) == 0: violation...
[]
[ "\"\"\" This module tests the creation of pipeline nodes from various different types", "( \"function_single_nodes\", 4, \"\"\"\\ from kedro.pipeline import Pipeline, node node_a_b = node(lambda x:", "4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline = [ node(lambda x: x, \"a\",", "x, \"a\", \"b\", n...
[ "'value': 'RUN: ls -lash', 'op': 'replace'}], expect_errors=True, context=self.context) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message'])", "self.dbapi.create_configfile(cdict) data = self.get_json('/configfiles/%...
[ "'.join('{:02x}'.format(c) for c in r) l2 = ''.join(chr(c) if 32 <= c <", "hexDump(data): size, over = divmod(len(data), 16) if over: size += 1 offsets =", "for c in r) return l1, l2 def hexDump(data): size, over = divmod(len(data),", "return l1, l2 def hexDump(data): size, over = divmod(len(data), 16) if ove...
[ "amet, consectetur adipiscing elit. # Morbi non lorem porttitor neque feugiat blandit. Ut", "ipsum eget quam lacinia accumsan. # Etiam sed turpis ac ipsum condimentum fringilla.", "adipiscing elit. # Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum", "rhoncus gravida arcu. from PyQt5.QtWidgets ...
[ "= session['email'] author_nickname = User.find_by_email(author_email).nick_name note_for_save = Note(title=title, content=content, author_email=author_email, shared=share, author_nickname=author_nickname ,share_only_with_users=share_only_with_users)", "note.author_email == session['email']: author_email_is_sessi...
[ "version = version.replace(\"^\", \"~=\") return version # ~=X.X else: # Allow exact version", "updates version = version.replace(\"^\", \"\") major, minor, patch = version.split(\".\") return \"~={}.{}\".format(major, minor)", "= version.replace(\"^\", \"\") major, minor, patch = version.split(\".\") return \"...
[ "game = form.save(commit=False) game.game = gamelication if 'icon' not in request.POST: game.icon =", "GameCategory.objects.all() if request.method == 'POST': form = UploadGameForm(request.POST) gamelication = request.FILES['game'] if form.is_valid():", "= GameCommentForm() subForm = SubGCommentForm() c = game....
[ "script to replace numactl in testing environment # import argparse import subprocess print(\"Using", "in testing environment # import argparse import subprocess print(\"Using dummy numactl\") parser =", "numactl in testing environment # import argparse import subprocess print(\"Using dummy numactl\") parser", ...
[ "not yet annotated if not annotation['annotations']: continue for tweet_id, tweet in tweet_dict.items(): if", "= Path(os.path.join(default_raw_path, anno_data_file)) agree_path = Path(os.path.join(default_raw_path, agree_file)) disagree_path = Path(os.path.join(default_raw_path, disagree_file)) with anno_data_pat...
[ "= 1 # nums_to_select 的设定 new_nums_to_select = min(math.ceil(len(u_data) * math.pow((step + 1), args.q)", "type=str, metavar='PATH',default=os.path.join(working_dir, 'logs')) # 保持日志根目录 parser.add_argument('--exp_name',type=str,default=\"nlvm-b1\") parser.add_argument('--exp_order',type=str,default=\"1\") parser.a...
[ "- start} secs; msg len = {len(msg)}\") def transmit(): while True: # global", "start = time.time() def process_message(msg): print(msg) # print(f\"Time passed: {time.time() - start} secs;", "from Raspberry Pi!\\n\") time.sleep(1) def receive(): while True: line = port.readline().decode('utf-8').rstrip() proces...
[ "returns False. Otherwise, returns the new board state with the locked piece. Args:", "<= 4): return False elif board_state['tetromino'] == 'I': i_offset = I_OFFSETS[i_rotate*5 + k]", "(4 + new_rotation_idx - current_rotation_idx) % 4 assert(iterations != 2) dim = int(len(tetromino)**0.5)", "List[int], List[i...
[ "only published posts, and order by descending date \"\"\" return Post.objects.filter( published_at__lte=timezone.now(), status=\"P\"", "PostDetailView(generic.DetailView): model = Post queryset = Post.objects.exclude(status='D') template_name = 'blog/detail.html' class PostView(generic.ListView): template_name",...