ngram
listlengths
0
67.8k
[ "<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- import pkg_resources __version__ = pkg_resources.get_distribution('g-pypi').version.replace('dev',", "#!/usr/bin/env python # -*- coding: utf-8 -*- import pkg_resources __version__ = pkg_resources.get_distribution('g-pypi').version.replace('dev', '')" ...
[ "scale = np.stack([scaleX, scaleY, scaleZ], axis=0).T scale = scale.reshape(1, -1) return [offset, scale]", "X[0] / 2 offY[i] = X[1] / (2 * X[3]) offZ[i] = X[2]", "* offY[i]**2 + X[4] * offZ[i] ** 2 scaleX[i] = np.sqrt(temp) scaleY[i] =", "= np.array([mag[:, 0], mag[:, 1], mag[:, 2], - mag[:, 1] ** 2, -", "...
[]
[ "from setuptools import setup, find_packages long_description = \"\"\"tcapy is a transaction cost analysis", "transaction cost analysis library for determining calculating your trading costs\"\"\" setup(name='tcapy', version='0.1.0', description='Tranasction", "determining calculating your trading costs\"\"\" s...
[ "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,", "project_report['generalData']['documentation']['completeness'] self.apis = comp['apis'] self.examples = comp['examples'] self.explanations = comp['explanations'] def __gather_interface_level(self, project_report):", "MERCHANTA...
[ "self.selection = selection self.combination = combination self.mutation = mutation self.solution = solution self.goal_error", "# Template method population = self.population_generation() min_error = self.solution(population).error for i in range(self.num_iter):", "num_iter self.selection = selection self.combi...
[]
[ "body=message, to=to_number, from_=self.phone_number ) except twilio.TwilioRestException as e: print e def send_message(self, to_number,", "import twilio import twilio.rest class Notify(object): def __init__(self, account_sid, auth_token, phone_number): self.account_sid =", "account_sid, auth_token, phone_numbe...
[ "self._is_on = self.hass.async_add_executor_job(self.fritzbox_tools.fritzstatus.is_connected) self._is_available = True status = self.fritzbox_tools.fritzstatus uptime_seconds = await self.hass.async_add_executor_job(lambda:", "-> dict: return self._attributes async def _async_fetch_update(self): self._is_on = Tr...
[ "1, right - 1, i + 1 else: while i<n: res[i], left, i", "\"\"\" left, right, res = 0, n+1, [None]*n for i in range(n): if", "int :type k: int :rtype: List[int] \"\"\" left, right, res = 0, n+1,", "right, i = right - 1, right - 1, i + 1 else:", "left + 1, left + 1, i + 1 return res else: if", "- 1, i + 1 e...
[ "in ['fc', 'conv'] self.layer_type = layer_type self.epsilon = 1e-6 self.dim = dim self.mem", "dimension, for conv layers, shape is the number of feature maps ''' assert", "name='beta') self.params = [self.gamma, self.beta] self.moving_mean = 0 self.moving_var = 1 def _train_fprop(self,", "sq = T.sqr(state_be...
[ "len(row) grad = [0.0 for _ in range(m + 1)] diff = compute_y(model,", "fold_actual, learning_rate, iterations_count) fold_pred = [compute_y(model, row) for row in fold] test_pred =", "\"R2 (train)\", \"RMSE (test)\", \"R2 (test)\"] + [\"f\" + str(i) for i in", "in range(m): y += row[i] * model[i] return y + ...
[ "b1 = 1/m1 sum21+=b1 m1 = m1-1 Ns.append(N1) error1 = (sum11 - sum21)/(np.absolute(sum11)+np.absolute(sum21))", "summation is more precise because the error of the number is proportional to", "error = (sum1 - sum2)/(np.absolute(sum1)+np.absolute(sum2)) print(\"For N = :\",N,\", the error is: \",error)", "temp...
[ "__init__(self, **kwargs): super().__init__() args = kwargs['params'] freeze_base = args['freeze_base'] training_head_type = args['training_head_type'] self.device", "data['image_dim'].unsqueeze(-1) assert len(params['image_dim'].size()) == len(image_mask.size()) image_mask = image_mask < params['image_dim'] para...
[ "as EC from selenium.common.exceptions import NoSuchElementException import sys,os options = webdriver.ChromeOptions() options.add_argument('--ignore-certificate-errors') options.add_argument('--headless')", "selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import NoSuch...
[ "migrations.AddField( model_name='pic', name='classification152', field=models.TextField(blank=True), ), migrations.AddField( model_name='pic', name='classification18', field=models.TextField(blank=True), ), migrations.AddField( model_name='pic', name='transfer',", "2.2.4 on 2019-09-11 14:12 from django.db import...
[ "{} Q = prio_dict.PriorityDictionary() Q[src] = 0 for v in Q: D[v] =", "path = [] while True: path.append(dst) if dst == src: break dst =", "or len(temp) < len(shortest_path): shortest_path = temp return shortest_path def is_connected(self, visited=None, src=None):", "src, dst): D,P = self.Dijkstra(G, src, ds...
[ "live_neighbors > 3): board[row][col] = 0 if copy_board[row][col] == 0 and live_neighbors ==", "(-1,-1), (-1,0), (-1,1), (0,1), (1,1)] rows = len(board) cols = len(board[0]) copy_board =", "neighbors: r = (row + neighbor[0]) c = (col + neighbor[1]) if (rows", "c = (col + neighbor[1]) if (rows > r >= 0) and (c...
[ "Table from typing import List from pathlib import Path from dbxdeploy.package.Dependency import Dependency", "dependencies def __load_main_dependencies(self) -> list: requirements_config = RequirementsConfig() requirements_config.exclude_index_info() requirements_txt = self.__requirements_generator.generate(requ...
[ "0 def initialize_policies_and_distributions(self): \"\"\" Initialize policies and corresponding distributions. \"\"\" if self._oracle_type ==", "KIND, either express or implied. # See the License for the specific language", "Unless required by applicable law or agreed to in writing, software # distributed", ...
[]
[ "{'name'.encode(): name.encode(), 'attrs'.encode(): lcmeta.encode(), 'header'.encode(): header.encode()} lcs = lcs.replace_schema_metadata(meta) pq.write_table(lcs, wpath + name", "lcs of the simulation. \"\"\" file_path, file_ext = os.path.splitext(file_path) if file_ext == '.pkl':", "name : str Simulation nam...
[ "i, (idx, row) in enumerate(timestamps.iterrows()): uids[i] = str(idx) dump_scores_to_json(results, uids, args.submission_json / (test_set", "verb_scores = verb_scores.mean(axis=(1, 2)) noun_scores = results['scores']['noun'] if len(noun_scores.shape) == 4: noun_scores =", "entries def compute_score_dicts(resul...
[ "placement['Company_name'] = item['Company_name'] placement['title'] = item['title'] placement['description'] = item['description'] placement['category'] = item['category'] placement['contact_info']", "in response['Items']: Placement_ID = item['ID'] #we got placement id placement = {} #####################", "=...
[ "imgpos: str, facenum=120): # 该函数的作用是提取图中人脸 message = {} # client_id 为官网获取的AK, client_secret 为官网获取的SK", "# print(params['image']) request_url = request_url + \"?access_token=\" + access_token headers = {'content-type': 'application/json'}", "base64 def fetchImageFromHttp(image_url, timeout_s=1): # 该函数是读取url图片 i...
[ "# P = 1000 r = 2.5 # % n = 4 #", "*= (1 + r/100/n) # r/100 since r is in % print('Amount (", "4 # quarterly y = 5 amount = P print('Amount (Starting):', amount) for", "principal # r - annual rate (%) # n - compounding frequency #", "** (ny) # P = 1000 r = 2.5 # % n =", "= 1000 r = 2.5 # % n = 4 # quarter...
[ "identifying 'cache_key' property. \"\"\" item = kwargs.get('instance') cache.set(item.cache_key, item, CACHE_TIMEOUT) def cache_evict(sender, **kwargs):", "CACHE_TIMEOUT def cache_update(sender, **kwargs): \"\"\" signal for updating a model instance in the", "from django.core.cache import cache from .settings ...
[ "'SHOW'} {setting};\" prefix = '' suffix = '' try: res = await conn.fetchval(q)", "} key_len = max((len(v) for v in settings)) for setting, validator in settings.items():", "prefix, suffix = COLOR.RED, COLOR.RESET print(f\"* {setting:{key_len}} = {prefix}{res}{suffix}\") results[setting] = res return", "for v...
[ "17, 19) for i in range(3, len(dims)): run = build_simple_run({\"ccd\": numpy.random.random(dims[:i])}) model =", "AxesSpec() model = Images(\"ccd\", axes=axes) assert model.figure is None figure = FigureSpec((axes,), title=\"\")", "= AxesSpec() model = Images(\"ccd\", axes=axes) assert model.figure is None fig...
[ "distance pair is {pair}\".format(pair = indices[0])) print(\"Pivot is piont {piv}\".format(piv = indices[0][0])) pivot.append(indices[0])", "\"compute\", \"coward\",\"forward\",\"interaction\",\"activity\",\"odor\",\"order\",\"international\"] WORDS = [] data_file_name = \"fastmap-data.txt\" words_file_name = 'f...
[ "wave.open(sys.argv[1], 'rb') depth = waveReader.getnframes() width = 16 # wav is 16 bits", "= wave.open(sys.argv[1], 'rb') depth = waveReader.getnframes() width = 16 # wav is 16", "16 bits radix = \"HEX\" # address and data in hex print(\"DEPTH =\",", "str(depth)+\";\") print(\"WIDTH =\", str(width)+\";\") p...
[ "https://leetcode.com/problems/unique-paths/description/ \"\"\" class Solution(object): def uniquePaths(self, m, n): \"\"\" :type m: int :type", "\"\"\" A robot is located at the top-left corner of a m x", "num *= i for i in range(m - 1, 0, -1): den *=", "below). The robot can only move either down or right a...
[ "numpy from sympy import Symbol, lambdify, sin, pprint a = numpy.arange(10) x =", "from sympy import Symbol, lambdify, sin, pprint a = numpy.arange(10) x = Symbol('x')", "Symbol, lambdify, sin, pprint a = numpy.arange(10) x = Symbol('x') expr = sin(x)", "sympy import Symbol, lambdify, sin, pprint a = numpy.ar...
[ "os import glob from app.backend.core.utils import getDirectorySizeInBytes, humanReadableSize if __name__ == '__main__': path='../../../data/datasets'", "getDirectorySizeInBytes(pp) tsizeHuman = humanReadableSize(tsize) print ('[%d] %s : %s (%d)' % (ii, tbn,", "import getDirectorySizeInBytes, humanReadableSize ...
[ "# import pytest import subprocess from ._subprocess import run_cli_tool def _unittest_trivial() -> None:", "_unittest_trivial() -> None: run_cli_tool('show-transport', timeout=2.0) with pytest.raises(subprocess.CalledProcessError): run_cli_tool(timeout=2.0) with pytest.raises(subprocess.CalledProcessError): run_...
[ "< self.num_train_steps: try: batch = batch_queue.get_nowait() except queue.Empty: continue self._update_step(batch, replay_priority_queue, update_step) update_step.value", "# Predict next actions with target policy network next_action = self.target_policy_net(next_state) # Predict", "-policy_loss.mean() self.p...
[ "= pywintypes.TimeType self._client = OpenOPC.client() self._client.connect(opc_server_name) self._print('connected to OPC server ' + opc_server_name)", "continue to use for name, value, quality, timeRecord in self._client.iread(self._param_list, group='Group0', update=1): param_array.append(self._get_dict_from_o...
[ "<gh_stars>0 import unittest import si7021 class Si7021SensorTests(unittest.TestCase): def setUp(self): # TODO: checks for", "os if os.name == 'Windows': raise OSError self._sensor = si7021.Si7021Sensor() def _assert_in_range(self, action,", "be less or equal to {max}.') def test_read_humidity(self): self._asse...
[ "import * logger = logging.getLogger(__name__) # noinspection PyUnusedLocal def get_user(url='', key='', timeout=60, **kwargs):", "get(url + '/user', headers={'Authorization': \"Bearer \" + key}, timeout=timeout).json() # noinspection PyUnusedLocal def", "+ '/user/tokens', headers={'Authorization': \"Bearer \" ...
[ "except ImportError: from lwr.lwr_client.manager import ObjectStoreClientManager class LwrObjectStore(ObjectStore): \"\"\" Object store implementation that", "None) manager_options = dict(transport=transport) client_options = dict(url=url, private_token=private_token) lwr_client = ObjectStoreClientManager(**manag...
[ "s, t): dic1, dic2 = [0]*26, [0]*26 for item in s: dic1[ord(item)-ord('a')] +=", "s, t): dic1, dic2 = {}, {} for item in s: dic1[item] =", "= dic2.get(item, 0) + 1 return dic1 == dic2 def isAnagram2(self, s, t):", "for item in s: dic1[ord(item)-ord('a')] += 1 for item in t: dic2[ord(item)-ord('a')] +=", "di...
[ "on Geophysics, 2nd ed., Vol. 10, pp. 153-193). ' 'Oxford, Elsevier-Pergamon, doi:10.1016/B978-0-444-53802-4.00169-X.') density_mars", "Planets, 106, 1-13, ' 'doi:10.1007/s11038-009-9342-7.') b_mars = _Constant( abbrev='b_mars', name='Semiminor axis of the", "_Constant( abbrev='density_mars', name='Mean density...
[ "elif nested_fields: check_required_fields(data[field], requirements.get('fields', {})) check_required_fields(request.json, required_fields) for validation_field, validation_message, validation_func in validations:", "}), follow_redirects=True, content_type='application/json') response_dict = json.loads(response....
[ "y.t(), z.t(), -p.t()), dim=1), torch.tensor([[0, 0, 0, 1]], dtype=torch.float, device=self.device)), dim=0) return M", "representing the camera extrinsic properties Attributes ---------- position : Tensor the camera position", "(3,) position tensor Returns ------- CameraExtrinsic the extrinsic itself \"\"\" se...
[ "= feature var colors = ['#636EFA', '#EF553B', '#00CC96', '#AB63FA', '#FFA15A', '#19D3F3', '#FF6692', '#B6E880',", "updateChart function with this selected option update(selectedOption) }); } }) </script> ''')).substitute({ 'chart_id':", "color: #2A3F5E; } .selection { margin-bottom: 20px; } .dot { stroke: #fff...
[ ":return: Dataframe ''' length = len(df) if num < 1: num = int(length", "get_subdirs * 获取当前目录下所有该类型的文件名 - get_files * 获取当前目录和所有子目录下所有该类型的文件名 - get_files_all * 数据表随机长度的抽样 - random_dataframe_sample", "sub_dirs.append(abs_path) return sub_dirs def random_dataframe_sample(df, num): ''' 返回dataframe的随机数量的样本,不放回。 如果出现...
[ "from yardstick.common import openstack_utils from yardstick.common import exceptions LOG = logging.getLogger(__name__) class CreateImage(base.Scenario):", "= self.options.get(\"disk_format\") self.container_format = self.options.get(\"container_format\",) self.disable_vendor_agent = self.options.get(\"disable_ve...
[ "Exception\")): response = self.client.get(f\"/ipip/{self._test_ip}\") self.assertEqual(response.status_code, 404) _json_body = response.json self.assertIn(\"not found\", _json_body[\"message\"]) self.assertEqual(_json_body[\"status\"],", "self.client.get(\"/ipip/FAKE_IP\") self.assertEqual(response.status_code, ...
[ "ABC, abstractmethod class AbstractDbOps(ABC): @abstractmethod def __init__(self): '''初始化 eg: Initialize db instance '''", "class AbstractDbOps(ABC): @abstractmethod def __init__(self): '''初始化 eg: Initialize db instance ''' raise NotImplementedError", "@author: <EMAIL> @last_modified: 2019.6.20 ''' from abc imp...
[ "and hand[0].is_ace() and hand[1].is_ten(): return True if len(hand) == 2 and hand[1].is_ace() and", "human-readable string representation.\"\"\" return '{}{} '.format(Card.rank_names[self.rank], Card.suit_names[self.suit]) def __repr__(self): return self.__str__() def value(self):", "self.__str__() def value(s...
[ "pessoa[3] == 'f': mulher.append(pessoa) contador_mulher = contador_mulher + 1 # break arquivo =", "arquivo.close() maior_idade = [] contador_maior = 0 for pessoa in lista_cadastro: if int(pessoa[2])", "in lista_cadastro: # if pessoa[0].upper() == '300': # print(pessoa) # break # for", "for pessoa in lista_ca...
[ "reduction, channel), nn.Sigmoid() ) def forward(self, x): b, c, _, _ = x.size()", "__init__(self, block, layers, use_se=True, im_size=112): self.inplanes = 64 self.use_se = use_se super(ResNet, self).__init__()", "use_se=self.use_se)) return nn.Sequential(*layers) def forward(self, x): x = self.conv1(x) x = se...
[ "* from data_pipe_test.verify_index import * def test_log2(): print() assert integer_log2(1) == 0 assert", "test_log2(): print() assert integer_log2(1) == 0 assert integer_log2(2) == 1 assert integer_log2(4) ==", "assert integer_log2(4) == 2 assert integer_log2(8) == 3 def test_index_store(): index_store = Basi...
[ "}) return results def station(self, id): station = self._query('station/%s' % id) if station", "r.status_code != 204: return r.json() else: sleep(0.25) except Exception as e: logger.info('RadioWorld API", "self._base_uri % (\"station/{}/image\".format(id)) def search(self, q, location_id): results = [] search ...
[ "getopt.getopt(sys.argv[1:],'ldh') try: target=args[0] except: usage() try: ip_range=IPNetwork(target) for ip in ip_range: if str(ip_range.cidr)", "exit() if(len(sys.argv)>1): opts, args = getopt.getopt(sys.argv[1:],'ldh') try: target=args[0] except: usage() try: ip_range=IPNetwork(target) for", "if(len(sys.arg...
[ "KIND, either express or implied. # See the License for the specific language", "Unless required by applicable law or agreed to in writing, software # distributed", "cxx = toolchain / \"bin\" / \"aarch64-linux-android{}-clang++\".format(args.api) elif args.arch == \"arm\": cc =", "\"-GNinja\", \"-B {}\".forma...
[ "_preprocess_data(): data_df = pd.read_csv(\"/opt/airflow/data/raw/{{ ds }}/data.csv\") target_df = pd.read_csv(\"/opt/airflow/data/raw/{{ ds }}/target.csv\") print(f\"data before", "}}/data.csv\" print(f\"saving processed data to {processed_path}\") data_df.to_csv(processed_path, index=False) def _train_val_spli...
[ "with open(path, 'r') as f: config = json.load(f) return config def make_config(paths): configs", "process pool and getting results as completed. Not necessarily in order. # async", "math.ceil(8/workers) due to process overhead. # # # Output: # # (1, -2)", "cpu_bound_func, list(range(8)), b=2)): # result = aw...
[ "id {0.id}, groupID: {0.group}'.format(self.request)) pipe = subprocess.PIPE with subprocess.Popen(job.run_context.command, shell=True, encoding='utf-8', # Avoid", "else job.run_context.job_options['cwd'], stdout=pipe, stderr=pipe) as process: for line in process.stdout: print(line, end='') process.wait()", "ht...
[]
[ "= tuple([int(coord) for coord in pos_str.replace(' ', '').split('<')[1].split(',')]) velo = tuple([int(velo) for velo", "INPUT_FILE_NAME = 'input.txt' def parseSpotInput(text): tmp_split = text.split('>') pos_str, velo_str = tmp_split[0], tmp_split[1]", "velo_str = tmp_split[0], tmp_split[1] pos = tuple([int(c...
[ "from rest_framework.response import Response from rest_framework.views import APIView, View from .models import Bug", ".serializers import BugReadSerializer, BugWriteSerializer, UserReadSerializer class BugList(APIView): def get(self, request): bug = Bug.objects.all()", "import Http404 from django.contrib.auth...
[ "PAL error.\\n{str(err)}\") except (KeyError, ValueError) as err: logging.critical(f\"Finished with an error.\\n{repr(err)}\") finally: if", "KIND, either express or implied. # See the License for the specific language", "clean_environment from specification_parser import Specification from input_data_parser im...
[ "n_classes): \"\"\"Calculates the logaritm of the probability of belonging to each class. Arguments:", "k-nearest neighbors. Arguments: X {DataFrame} -- Independent variables. X_train {DataFrame} -- Independent training", "variables. \"\"\" try: X = X.values except AttributeError: pass try: X_train = X_train.va...
[ "is # distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF", "its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version", "to validate aws_encryption_sdk.key_providers.raw.RawMasterKeyConfig\"\"\" import pytest import six from aws_encryption_sdk.identifiers import Enc...
[ "output_field = FloatField() class XMin(Func): \"\"\"Returns the X minima of a 2D or", "3D bounding box or a geometry.\"\"\" function = \"ST_YMax\" output_field = FloatField() class", "2D or 3D bounding box or a geometry.\"\"\" function = \"ST_YMax\" output_field =", "\"ST_ZMax\" output_field = FloatField() c...
[ "timeseries.shape[0] == 8760: return timeseries elif timeseries.shape[0] == 8784: times = pd.date_range(\"01-01-2000 00:00:00\",", "pandas as pd from . import ResError def remove_leap_day(timeseries): \"\"\"Removes leap days from", "array_like is given, the length must be 8784 * If a pandas DataFrame", "from ...
[ "name='Article', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=1000)), ('desc', models.CharField(max_length=1000)), ], ),", "('type_usr', models.IntegerField()), ('phone', models.CharField(max_length=15)), ], ), mi...
[]
[ "path( 'memory/<int:quid>/detail/', memory.questionnaire_detail, name='memory_questionnaire_detail', ), path( 'memory/<str:campaign>/', memory.questionnaire_form, name='memory_questionnaire_promo_form', ), path( 'memory/', memory.questionnaire_form,", "django.views.generic import TemplateView from djforms.alumni....
[ "arguments') print('Usage: create_welsh_messages.py [CSV file name] [output file name]\\n') print('Note: output file name", "1: output_file.write(key + '===================================================\\n') else: output_file.write(key + '\\n') elif len(welsh) > 0: output_file.write('{}={}\\n'.format(key,", "...
[ "psycopg2 from ..config import AppConfig from ..designpatterns import singleton config = AppConfig() @singleton", "..config import AppConfig from ..designpatterns import singleton config = AppConfig() @singleton class MyApplicationDatabase(object):", "PostgreSQL database, but can be modified for any other. ''' ...
[ "def setParams(self): a = np.array( [-2.95553, 8.48252, -9.48291, 4.74052, -1.24984, 0.15021, 0.66]) b", "FWHM &= \\sqrt{2^{2/3}-1}g\"\"\" def __init__(self, fwhm=None, mu=None, amp=None, **kwargs): super(Irrational, self).__init__(fwhm=fwhm, mu=mu, amp=amp,", "self.rho * self.wG) self.wL = s * (1 - (1 - self.r...
[ "tdmap_setup_json, tdmapsDBPath, tdmapsDBSchema): inserted_key = None sqlite3_conn = create_or_open_db(tdmapsDBPath, tdmapsDBSchema) sql = '''insert", "return inserted_key def get_tdmaps_data( id, tdmapsDBPath, tdmapsDBSchema ): result = None inserted_key =", "tdmapsDBSchema) if data is None: result = { \"apiVe...
[ "Ss = [] for m in range(depth): U = Us[m] S = np.sum(U,", "den, N): omegas = np.array(range(N)) return gauss(omegas - center, den) def gauss(omega, den):", "phi[0] = 1.0 filterbank[:, 0, -1] = phi for m in range(dim): filterbank", "np.expand_dims(filterbank, axis=2) return filterbank def gabor(center, den, N)...
[ "response.code == 200 body = tornado.escape.to_unicode(response.body) assert \"<title>Error</title>\" in body response = self.fetch(", "method=\"GET\") assert response.code == 200 response = self.fetch(\"/?url=https%3A%2F%2Fgoogle.com%2F\", method=\"GET\") assert response.code == 200", "def get_app(self): exten...
[ "* mats = UnwrapElement(IN[0]) colorlist = list() glowlist = list() classlist = list()", "glowlist = list() classlist = list() shinylist = list() smoothlist = list() translist", "mat in mats: colorlist.append(mat.Color) if mat.Glow: glowlist.append(True) else: glowlist.append(False) classlist.append(mat.Materia...
[]
[ "## The generated population may already be vaccinated. def generate(self, n_individuals): \"\"\"Generate a", "if (np.random.uniform() < r[k]): result[i, k] = 0 else: result[i, k] = self.X[t,", "import numpy as np import pickle class Person: def __init__(self, pop): self.genes =", "self.comorbidities[0] = pop...
[ "#! /usr/bin/env python import sys sys.path.append('..') from vec2d import vec2d v = vec2d(-1,", "/usr/bin/env python import sys sys.path.append('..') from vec2d import vec2d v = vec2d(-1, 1)", "import sys sys.path.append('..') from vec2d import vec2d v = vec2d(-1, 1) print (v.angle)", "python import sys sys....
[ "*args, **kwargs) except ( aioredis.ConnectionClosedError, aioredis.PoolClosedError, ConnectionRefusedError, ) as e: log.debug( f\"Command {command}", "**kwargs) except ( aioredis.ConnectionClosedError, aioredis.PoolClosedError, ConnectionRefusedError, ) as e: log.debug( f\"Command {command} failed,", "getLogge...
[ "1, 100)) Y = X # prepare pytorch dataloader dataset = TensorDataset(torch.tensor(X), torch.tensor(Y))", "= ConvAutoencoder() model = model.double() # tackles a type error # define loss", "for an autoencoder. import torch import numpy as np import torch.optim as optim", "Y = X # prepare pytorch dataloader dat...
[ "times = []double() for i in range(4): t0 = clock() res = copy_list(addr(a),", "for i in range(n): b = a[:] for j in range(10): b.push_back( j", "i in range(4): t0 = clock() res = copy_list(addr(a), 10000) tk = clock()", "def test(): a = range(1000) times = []double() for i in range(4): t0", "t0 = clock() r...
[ "guild_id is the id of the guild that has the message to expand.", "function returns True, allow the message to be expanded to another guild. pass", "simple. bot.load_extension(\"discord.ext.utils.cogs.minimal_expander\") # Expand all. # self.load_extension(\"discord.ext.utils.cogs.expander\") # Expand all and ...
[]
[ "subplot fig.subplots_adjust(0.05,0.05,0.95,0.95) # get rid of unnecessary padding therm1 = ax.imshow(np.zeros(mlx_interp_shape),interpolation='none', cmap=plt.cm.bwr,vmin=25,vmax=45) #", "args.imageMirror if(imageMirror == 'false'): print('Mirror mode: false') else: imageMirror = 'true' print('Mirror mode:", "...
[ "..bases import Event from .bases import ApplicationObject from .parameters import ParameterGroup, ParameterObject class", "_application_perform_callback(self, clock_context, midi_message): await self.application.perform( [midi_message], moment=clock_context.current_moment ) @classmethod async def _deserialize(cl...
[ "import admin from .models import Hivernant, Phone, Email class PhoneInline(admin.TabularInline): model = Phone", "42 default_zoom = 2 list_display = ('names', 'fulladdress', 'comments') inlines = [PhoneInline, EmailInline]", "Email class PhoneInline(admin.TabularInline): model = Phone extra = 1 class EmailInli...
[ "json import blueprints_pb2_grpc import blueprints_pb2 from sagas.ofbiz.blackboard import Blackboard, BlackboardReceiver _ONE_DAY_IN_SECONDS = 60", "start as # or: python -m sagas.ofbiz.rpc_artifacts \"\"\" #$ ./query.py talk \"hi\" #$", "context): rs=talk(request.sender, request.message) recips = [] for r in r...
[ "- Beginner/1789.py # URI Online Judge 1789 while True: try: N = int(input())", "# URI Online Judge 1789 while True: try: N = int(input()) entrada =", "i in input().split()] if max(entrada) < 10: print(1) elif max(entrada) >= 10 and", "Online Judge 1789 while True: try: N = int(input()) entrada = [int(i) for"...
[ "logging import psycopg2 from tasks import DatabaseInterface def get_database_name(): return os.environ[\"POSTGRES_DB\"] def get_database_user():", "\"territory_name\": data[13], \"state_code\": data[14], } def get_pending_gazettes(self) -> Generator: with self._connection.cursor() as cursor:", "def __init__(se...
[ "# # require: # https://github.com/edburnett/twitter-text-python # # download csv file from: # https://github.com/bpb27/political_twitter_archive/tree/master/realdonaldtrump", "parser as date_parser # read csv to Dict with open('realdonaldtrump.csv', 'r') as f:", "f: reader = csv.DictReader(f, delimiter = ',') ...
[ "return jsonResponse['data']['attributes']['user']['id'] def getBotResponse(UserID, input): url = \"https://api.thebotplatform.com/v1.0/interaction\" headers = { \"Content-Type\": \"application/json\",", "json=payloaddict) jsonResponse = response.json() formatJsonresp = json.dumps(jsonResponse, indent=4, sort_key...
[ "input(\"Enter first number: \") b = input(\"Enter first number: \") sum_numbers = sum(int(a),int(b))", "number: \") b = input(\"Enter first number: \") sum_numbers = sum(int(a),int(b)) print(\"Sum: \",", "return a+b a = input(\"Enter first number: \") b = input(\"Enter first number:", "sum(a,b): return a+b a...
[ "== ( height, width), (image.shape[:2], (height, width)) print('verify ' + ifile) self._batch_generator =", "[] @property def n_samples(self): return len(self._input_files) def __next__(self): self._batch = next(self._batch_generator) return self._batch", "+ ifile) self._batch_generator = self.__get_batch_gener...
[ "os.path.extsep + options.backup_suffix) with open(path, 'r+b', buffering=0) as f: f.seek(offset) f.write(bytes(chr(value))) parser =", "help=\"create a backup of the uncorrupted original\" \" [default: %default]\") parser.add_option(\"\", \"--no-backup\", action=\"store_false\",", "os.access(bkup, os.R_OK): sh...
[ "# # Permission is hereby granted, free of charge, to any person #", "parse_date(m.group(2).strip())}) def parse_end(m, statements): statements.append({'type': 'end', 'date': parse_date(m.group(2).strip())}) def parse_resolution(m, statements): m_ =", "+ txt + \":\" return d def parse_activity(m, statements): d...
[ "# Copyright 2017 <NAME>. See LICENSE.md file for terms. import socket import threading", "thing'], 'port': TCP_PORT}} sim = usersim.UserSim(True) task_id = api.validate_config(telnet_config) def start_server(): s =", "s.bind((TCP_IP, TCP_PORT)) s.listen(1) conn, addr = s.accept() print('Connection Address: ' +...
[ "<filename>polichart/api/views.py # -*- coding: utf-8 -*- from flask import Blueprint, current_app, request, jsonify", "flask.ext.login import login_user, current_user, logout_user from ..extensions import db from polichart import models", "from ..extensions import db from polichart import models api = Blueprin...
[ "desc = self.get_data(service_def.get(\"description\", \"\")) swagger_conf = service_def.get(\"swagger\", {}) if swagger_conf.get(\"display_permission\", True): if desc:", "desc += f\"permission: {service_def['permission']}\" api_def[path or \"/\"][method.lower()] = { \"tags\": swagger_conf.get(\"tags\", [\"\"]) ...