text
stringlengths
232
16.3k
domain
stringclasses
1 value
difficulty
stringclasses
3 values
meta
dict
<|fim_suffix|> def pip_sync(requirements_file, venv_path, module, proxy): pip = venv_path / "bin/pip" pip_args = ["--timeout=60"] if proxy: pip_args.append(f"--proxy={quote(proxy)}") module.run_command( [pip, "install", "--quiet", "--upgrade", *pip_args, "pip-tools"], check_rc=Tr...
code_fim
hard
{ "lang": "python", "repo": "dimagi/commcare-cloud", "path": "/src/commcare_cloud/ansible/library/setup_virtualenv.py", "mode": "spm", "license": "BSD-3-Clause", "source": "the-stack-v2" }
<|fim_suffix|> kty: COSEKTY alg: COSEAlgorithmIdentifier n: bytes e: bytes def decode_credential_public_key( key: bytes, ) -> Union[DecodedOKPPublicKey, DecodedEC2PublicKey, DecodedRSAPublicKey]: """ Decode a CBOR-encoded public key and turn it into a data structure. Supports OKP, EC2,...
code_fim
hard
{ "lang": "python", "repo": "duo-labs/py_webauthn", "path": "/webauthn/helpers/decode_credential_public_key.py", "mode": "spm", "license": "BSD-3-Clause", "source": "the-stack-v2" }
<|fim_suffix|> decoded_key: dict = decoder.loads(key) kty = decoded_key[COSEKey.KTY] alg = decoded_key[COSEKey.ALG] if not kty: raise InvalidPublicKeyStructure("Credential public key missing kty") if not alg: raise InvalidPublicKeyStructure("Credential public key missing alg") ...
code_fim
hard
{ "lang": "python", "repo": "duo-labs/py_webauthn", "path": "/webauthn/helpers/decode_credential_public_key.py", "mode": "spm", "license": "BSD-3-Clause", "source": "the-stack-v2" }
<|fim_prefix|># repo: duo-labs/py_webauthn path: /webauthn/helpers/decode_credential_public_key.py from typing import Union from cbor2 import decoder from pydantic import BaseModel from .cose import COSECRV, COSEKTY, COSEAlgorithmIdentifier, COSEKey from .exceptions import InvalidPublicKeyStructure, UnsupportedPubli...
code_fim
hard
{ "lang": "python", "repo": "duo-labs/py_webauthn", "path": "/webauthn/helpers/decode_credential_public_key.py", "mode": "psm", "license": "BSD-3-Clause", "source": "the-stack-v2" }
<|fim_prefix|># repo: anxuae/pih2o path: /pih2o/controls/pump.py # -*- coding: utf-8 -*- """Pih2o pump / electro-valve management. """ import threading from RPi import GPIO from pih2o.utils import LOGGER class Pump(object): def __init__(self, pin): self._running = threading.Event() self.pin =...
code_fim
hard
{ "lang": "python", "repo": "anxuae/pih2o", "path": "/pih2o/controls/pump.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> def is_running(self): """ Return True if the pump is started. """ return self._running.is_set() def start(self): """ Start the pump. """ if self.is_running(): # Avoid starting several times to prevent concurent access ...
code_fim
medium
{ "lang": "python", "repo": "anxuae/pih2o", "path": "/pih2o/controls/pump.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> def get_attr(self, server, attribute): """ Public method to get the value of some given attribute in cfg associated with given server. :param server: Takes server object ot just server id string :param attribute: Takes string with attribute name :return: Value of given attribute if exist, els...
code_fim
hard
{ "lang": "python", "repo": "dzenX/music_bot", "path": "/settings.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: dzenX/music_bot path: /settings.py import os import yaml from utils import get_dict, silent_remove, valid_server class Settings: """ Class to stoge and control settings for different servers. """ Settings = {} # Store in servers setting def __init__(self, settings_folder): """ ...
code_fim
hard
{ "lang": "python", "repo": "dzenX/music_bot", "path": "/settings.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> progress = round(100 / goal * i, 2) print(f"Progress: {progress}%")<|fim_prefix|># repo: MHartveit/lcm path: /api/util/utils.py def print_progress(i: int, goal: int):<|fim_middle|> if i != 0 and i % 100 == 0:
code_fim
easy
{ "lang": "python", "repo": "MHartveit/lcm", "path": "/api/util/utils.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: MHartveit/lcm path: /api/util/utils.py def print_progress(i: int, goal: int):<|fim_suffix|> progress = round(100 / goal * i, 2) print(f"Progress: {progress}%")<|fim_middle|> if i != 0 and i % 100 == 0:
code_fim
easy
{ "lang": "python", "repo": "MHartveit/lcm", "path": "/api/util/utils.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: scrapinghub/spidermon path: /tests/contrib/actions/slack/test_slack_message_manager.py import pytest from scrapy.utils.test import get_crawler from slack_sdk.errors import SlackApiError from spidermon.contrib.actions.slack import SlackMessageManager, SendSlackMessage @pytest.fixture def logge...
code_fim
hard
{ "lang": "python", "repo": "scrapinghub/spidermon", "path": "/tests/contrib/actions/slack/test_slack_message_manager.py", "mode": "psm", "license": "BSD-3-Clause", "source": "the-stack-v2" }
<|fim_suffix|> fake_error = SlackApiError("mocked error", FakeResponse()) mock_webclient().users_list.side_effect = fake_error manager = SlackMessageManager(sender_token="Fake", sender_name="test_invalid_bot") with pytest.raises(SlackApiError) as excinfo: manager._get_icon_url() assert excinf...
code_fim
hard
{ "lang": "python", "repo": "scrapinghub/spidermon", "path": "/tests/contrib/actions/slack/test_slack_message_manager.py", "mode": "spm", "license": "BSD-3-Clause", "source": "the-stack-v2" }
<|fim_prefix|># repo: hylin-work/quality-assessment-protocol path: /qap/cli.py '%d:00:00' % hrs_limit config_dict["time_limit"] = time_limit env_arr_idx = '$SLURM_ARRAY_TASK_ID' batch_file_contents = cluster_templates.slurm_template confirm_str = '(?<=Submitted batch job...
code_fim
hard
{ "lang": "python", "repo": "hylin-work/quality-assessment-protocol", "path": "/qap/cli.py", "mode": "psm", "license": "BSD-3-Clause", "source": "the-stack-v2" }
<|fim_suffix|> # Start the magic if not self._platform and not self._bundle_idx: # not a cluster/grid run for idx in range(1, num_bundles+1): results.append(self.run_one_bundle(idx)) elif not self._bundle_idx: # there is a self._bundle_idx only...
code_fim
hard
{ "lang": "python", "repo": "hylin-work/quality-assessment-protocol", "path": "/qap/cli.py", "mode": "spm", "license": "BSD-3-Clause", "source": "the-stack-v2" }
<|fim_suffix|> # flatten the participant dictionary self._sub_dict = self.create_session_dict(subdict) # create the list of bundles self._bundles_list = self.create_bundles() num_bundles = len(self._bundles_list) if not self._bundle_idx: # want to initialize ...
code_fim
hard
{ "lang": "python", "repo": "hylin-work/quality-assessment-protocol", "path": "/qap/cli.py", "mode": "spm", "license": "BSD-3-Clause", "source": "the-stack-v2" }
<|fim_suffix|> exercise_name = Label(exercise_details_content, text="Exercise") exercise_name.grid(row=1, column=1) exercise_sets = Label(exercise_details_content, text="Set") exercise_sets.grid(row=1, column=2) exercise_reps = Label(exercise_details_content, text="Reps") ...
code_fim
hard
{ "lang": "python", "repo": "delereyus/ProLog", "path": "/exercise_details_page.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: delereyus/ProLog path: /exercise_details_page.py from tkinter import * from back_end import Database import edit_workout_page import config database = Database("py_project.db") class ExerciseDetailsPage: def __init__(self, content, exercise, workout_id, workout_date, username): sel...
code_fim
hard
{ "lang": "python", "repo": "delereyus/ProLog", "path": "/exercise_details_page.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: zjhdota/practice path: /numpy/sample_numpy.py import numpy as np a = np.array([[1,2,3], [4,5,6]], dtype=np.int) print(a.ndim) print(a.shape) print(a.dtype) # 生成0矩阵 a = np.zeros((3,4), dtype=np.int16) print(a) # 生成随机数矩阵 a = np.empty((2,3)) print(a) # 类似range a = np.arange(12...
code_fim
hard
{ "lang": "python", "repo": "zjhdota/practice", "path": "/numpy/sample_numpy.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> # 合并矩阵 a = np.array([1, 1, 1]) b = np.array([2, 2, 2]) # 上下合并 c = np.vstack((a,b)) print(c) print(c.shape) # 左右合并 d = np.hstack((a,b)) print(d) print(d.shape) # 横向数列变为纵向数列 print(a.reshape(a.size,1)) print(a[:, np.newaxis]) a = a[:, np.newaxis] b = b[:, np.newaxis] print(a, b) # c = np.concatenate((a,...
code_fim
hard
{ "lang": "python", "repo": "zjhdota/practice", "path": "/numpy/sample_numpy.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> usuario_google = users.get_current_user() if usuario_google: google_id = usuario_google.user_id() query = Usuario.query_by_google(google_id) usuario_logado = query.get() if not usuario_logado: usuario_logado = Usuario(nome=usuario_google.nickname(), ...
code_fim
hard
{ "lang": "python", "repo": "kaiocesar/portalcursos", "path": "/backend/src/usuario/middleware.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: kaiocesar/portalcursos path: /backend/src/usuario/middleware.py # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from google.appengine.api import users from usuario.model import Usuario import tmpl <|fim_suffix|> usuario_google = users.get_current_user() if...
code_fim
hard
{ "lang": "python", "repo": "kaiocesar/portalcursos", "path": "/backend/src/usuario/middleware.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> try: index = self._names.index(name) except ValueError: return self.__dict__[name] return self._chars[index] @property def kind(self): return self._kind @kind.setter def kind(self, value): self._kind = value self._ch...
code_fim
hard
{ "lang": "python", "repo": "pji/blackjack", "path": "/blackjack/utility.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: pji/blackjack path: /blackjack/utility.py """ utility ~~~~~~~ Miscellaneous objects for the blackjack module. """ splash_title = ( '╔╗ ║ ╔═╗ ╔═╗ ║ ║', '║║ ║ ║ ║ ║ ╠═╝', '╠╩╗ ║ ╠═╣ ║ ╠═╗', '║ ║ ║ ║ ║ ║ ║ ║', '╚═╝ ╚══ ║ ║ ╚═╝ ║ ║', '', ' ║ ╔═╗ ╔═╗ ║ ║...
code_fim
hard
{ "lang": "python", "repo": "pji/blackjack", "path": "/blackjack/utility.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> @property def custom(self): return self._custom @custom.setter def custom(self, value): strvalue = str(value) if len(strvalue) == 14: self._custom = str(strvalue) self._kind = 'custom' else: reason = 'The custom string mu...
code_fim
hard
{ "lang": "python", "repo": "pji/blackjack", "path": "/blackjack/utility.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: rattletat/covid-register.eu path: /covidregister/register/migrations/0013_auto_20200525_2239.py # Generated by Django 3.0.6 on 2020-05-25 22:39 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('register', '0012_auto_20200525_1954'),...
code_fim
hard
{ "lang": "python", "repo": "rattletat/covid-register.eu", "path": "/covidregister/register/migrations/0013_auto_20200525_2239.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|>dication', name='count', field=models.PositiveSmallIntegerField(blank=True, null=True, verbose_name='Quantity'), ), migrations.AlterField( model_name='preexistingmedication', name='dosage_form', field=models.PositiveSmallIntegerFi...
code_fim
hard
{ "lang": "python", "repo": "rattletat/covid-register.eu", "path": "/covidregister/register/migrations/0013_auto_20200525_2239.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: DDMAL/cantus path: /app/public/cantusdata/views/folio.py from cantusdata.models.folio import Folio from cantusdata.serializers.folio import FolioSerializer from django.http import Http404 from rest_framework import generics class FolioList(generics.ListAPIView): model = Folio serializer...
code_fim
hard
{ "lang": "python", "repo": "DDMAL/cantus", "path": "/app/public/cantusdata/views/folio.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> if len(queryset) == 0: raise Http404("No data for a folio with that number") else: return queryset[:1] # Make sure we return only one element class FolioDetail(generics.RetrieveAPIView): model = Folio queryset = Folio.objects.all() serializer_class = ...
code_fim
hard
{ "lang": "python", "repo": "DDMAL/cantus", "path": "/app/public/cantusdata/views/folio.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> assert all([rule(i).is_valid() for i in tests])<|fim_prefix|># repo: Nikita-Boyarskikh/bnf path: /bnf/test/utils.py from typing import Iterator <|fim_middle|>from bnf.rule import Rule def assert_all_tests_is_valid(rule: Rule, tests: Iterator[str]):
code_fim
medium
{ "lang": "python", "repo": "Nikita-Boyarskikh/bnf", "path": "/bnf/test/utils.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: Nikita-Boyarskikh/bnf path: /bnf/test/utils.py from typing import Iterator <|fim_suffix|> assert all([rule(i).is_valid() for i in tests])<|fim_middle|>from bnf.rule import Rule def assert_all_tests_is_valid(rule: Rule, tests: Iterator[str]):
code_fim
medium
{ "lang": "python", "repo": "Nikita-Boyarskikh/bnf", "path": "/bnf/test/utils.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> self.client.set('key', 'value') self.assertEqual(self.client._client, self.client._cache) class TestWithEnvironmentAuth(TestWithExplicitAuth): def setUp(self): os.environ['MEMCACHE_SERVERS'] = '127.0.0.1' os.environ['MEMCACHE_USERNAME'] = 'user' os.environ['ME...
code_fim
hard
{ "lang": "python", "repo": "waenwj/django-bmemcached", "path": "/tests/__init__.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: waenwj/django-bmemcached path: /tests/__init__.py import os import unittest import django_bmemcached class TestWithExplicitAuth(unittest.TestCase): def setUp(self): self.client = django_bmemcached.BMemcached(('127.0.0.1:11211', ), {'OPTIONS': {'username': 'user', 'passw...
code_fim
medium
{ "lang": "python", "repo": "waenwj/django-bmemcached", "path": "/tests/__init__.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> def testPropertyCacheRetunsAwaysSameServer(self): self.client.set('key', 'value') self.assertEqual(self.client._client, self.client._cache) class TestWithEnvironmentAuth(TestWithExplicitAuth): def setUp(self): os.environ['MEMCACHE_SERVERS'] = '127.0.0.1' os.enviro...
code_fim
hard
{ "lang": "python", "repo": "waenwj/django-bmemcached", "path": "/tests/__init__.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: biolearning-stadius/rdkit path: /rdkit/ML/Data/test_data/populate.py import RDConfig from Dbase import DbUtils from io import StringIO basic_2class = """ID,VAL,ACT id-1,1.0,0 id-2,23.0,1 id-3,4.0,0 id-4,6.0,1 id-5,321.0,0 id-6,885.0,1 id-7,252.0,0 id-8,1351.1,1 id-9,3215.0,0 id-10,2585.0,1 id-11...
code_fim
medium
{ "lang": "python", "repo": "biolearning-stadius/rdkit", "path": "/rdkit/ML/Data/test_data/populate.py", "mode": "psm", "license": "BSD-3-Clause", "source": "the-stack-v2" }
<|fim_suffix|>ils.TextFileToDatabase(RDConfig.RDTestDatabase, 'basic_2class', io) io = StringIO(float_2class) DbUtils.TextFileToDatabase(RDConfig.RDTestDatabase, 'float_2class', io)<|fim_prefix|># repo: biolearning-stadius/rdkit path: /rdkit/ML/Data/test_data/populate.py import RDConfig from Dbase import DbUtils from ...
code_fim
hard
{ "lang": "python", "repo": "biolearning-stadius/rdkit", "path": "/rdkit/ML/Data/test_data/populate.py", "mode": "spm", "license": "BSD-3-Clause", "source": "the-stack-v2" }
<|fim_prefix|># repo: heyitsmine/FewRel path: /models/proto_plain.py import sys sys.path.append('..') import fewshot_re_kit import torch from torch import autograd, optim, nn class ProtoPlain(fewshot_re_kit.framework.FewShotREModel): def __init__(self, sentence_encoder): fewshot_re_kit.framework.FewShot...
code_fim
hard
{ "lang": "python", "repo": "heyitsmine/FewRel", "path": "/models/proto_plain.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> support = support.view(-1, N, K, self.hidden_size) # (B, N, K, D) query = query.view(-1, total_Q, self.hidden_size) # (B, total_Q, D) # Prototypical Networks support = torch.mean(support, 2) # Calculate prototype for each class, (B, N, D) logits = -self.__batch_...
code_fim
hard
{ "lang": "python", "repo": "heyitsmine/FewRel", "path": "/models/proto_plain.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: hpagseddy/ZPUI path: /apps/example_apps/test_hanging/main.py menu_name = "Test hangup" from ui import Printer from time import sleep i = None o = None <|fim_suffix|>def callback(): Printer("Hangup", None, o, 0) while True: sleep(1)<|fim_middle|>def init_app(input, output): ...
code_fim
medium
{ "lang": "python", "repo": "hpagseddy/ZPUI", "path": "/apps/example_apps/test_hanging/main.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|>def callback(): Printer("Hangup", None, o, 0) while True: sleep(1)<|fim_prefix|># repo: hpagseddy/ZPUI path: /apps/example_apps/test_hanging/main.py menu_name = "Test hangup" from ui import Printer from time import sleep i = None o = None def init_app(input, output): <|fim_middle|> ...
code_fim
easy
{ "lang": "python", "repo": "hpagseddy/ZPUI", "path": "/apps/example_apps/test_hanging/main.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> Printer("Hangup", None, o, 0) while True: sleep(1)<|fim_prefix|># repo: hpagseddy/ZPUI path: /apps/example_apps/test_hanging/main.py menu_name = "Test hangup" <|fim_middle|>from ui import Printer from time import sleep i = None o = None def init_app(input, output): global i, o ...
code_fim
medium
{ "lang": "python", "repo": "hpagseddy/ZPUI", "path": "/apps/example_apps/test_hanging/main.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: ajb254/BehavioralDataAnalysis path: /Chapter 10 - Cluster Randomization and Hierarchical Modeling/chap 10 - analyzing data.py # -*- coding: utf-8 -*- """ Created on Sun May 10 11:44:30 2020 @author: Florent """ import os import pandas as pd import numpy as np import statsmodels.formula.api as s...
code_fim
hard
{ "lang": "python", "repo": "ajb254/BehavioralDataAnalysis", "path": "/Chapter 10 - Cluster Randomization and Hierarchical Modeling/chap 10 - analyzing data.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> vcf = {"rep_ID": "0+C(rep_ID)"} h_mod = sm.mixedlm("call_CSAT ~ reason + age + group", data = dat_df, groups = dat_df["center_ID"], re_formula='1', vc_formula=vcf) coeff = h_mod.fit().fe_params.values[2] retu...
code_fim
hard
{ "lang": "python", "repo": "ajb254/BehavioralDataAnalysis", "path": "/Chapter 10 - Cluster Randomization and Hierarchical Modeling/chap 10 - analyzing data.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> center_ID, data_np = strat_prep_fun(dat_df) N = len(data_np) #Calculate distance matrix from scipy.spatial import distance_matrix d_mat = distance_matrix(data_np, data_np) np.fill_diagonal(d_mat,N+1) # Set up variables available = [i for i in range(N)] available_te...
code_fim
hard
{ "lang": "python", "repo": "ajb254/BehavioralDataAnalysis", "path": "/Chapter 10 - Cluster Randomization and Hierarchical Modeling/chap 10 - analyzing data.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: FelipeDreissig/Prog-em-Py---CursoEmVideo path: /Mundo 3/02 - Listas - p1/Ex078 - Maior e menor.py ### maior e menor em uma LISTA posicoes = [] n1 = int(input('Digite um valor:\n')) n2 = int(input('Digite outro valor:\n')) n3 = int(input('Digite mais um valor:\n')) n4 = int(input('Este é o penúlti...
code_fim
medium
{ "lang": "python", "repo": "FelipeDreissig/Prog-em-Py---CursoEmVideo", "path": "/Mundo 3/02 - Listas - p1/Ex078 - Maior e menor.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|>1) print(f'O maior valor é o {maior} e ele está na {posicoes[0]}ª posição.') print(f'O menor valor é o {menor} e ele está na {posicoes[1]}ª posição.')<|fim_prefix|># repo: FelipeDreissig/Prog-em-Py---CursoEmVideo path: /Mundo 3/02 - Listas - p1/Ex078 - Maior e menor.py ### maior e menor em uma LISTA posi...
code_fim
medium
{ "lang": "python", "repo": "FelipeDreissig/Prog-em-Py---CursoEmVideo", "path": "/Mundo 3/02 - Listas - p1/Ex078 - Maior e menor.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> @json_response @swagger_auto_schema( auto_schema=XcodeAutoSchema, operation_summary='Device logout', operation_description='Removes the api token of a device that has already logged in. If the device is a desktop client, also remove all sync tokens of repos synced on that c...
code_fim
hard
{ "lang": "python", "repo": "syncwerk/syncwerk-server-restapi", "path": "/fhs/usr/share/python/syncwerk/restapi/restapi/api3/custom/views_auth.py", "mode": "spm", "license": "Apache-2.0", "source": "the-stack-v2" }
<|fim_suffix|>class LogoutDeviceView(APIView): """Removes the api token of a device that has already logged in. If the device is a desktop client, also remove all sync tokens of repos synced on that client . """ authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticate...
code_fim
medium
{ "lang": "python", "repo": "syncwerk/syncwerk-server-restapi", "path": "/fhs/usr/share/python/syncwerk/restapi/restapi/api3/custom/views_auth.py", "mode": "spm", "license": "Apache-2.0", "source": "the-stack-v2" }
<|fim_prefix|># repo: syncwerk/syncwerk-server-restapi path: /fhs/usr/share/python/syncwerk/restapi/restapi/api3/custom/views_auth.py from rest_framework import status from rest_framework.permissions import IsAuthenticated from synserv import syncwerk_api from restapi import settings from restapi.api3.base import API...
code_fim
hard
{ "lang": "python", "repo": "syncwerk/syncwerk-server-restapi", "path": "/fhs/usr/share/python/syncwerk/restapi/restapi/api3/custom/views_auth.py", "mode": "psm", "license": "Apache-2.0", "source": "the-stack-v2" }
<|fim_suffix|> async def async_image(self) -> bytes | None: """Return bytes of image.""" image_path = Path(__file__).parent / self._image_filename return await self.hass.async_add_executor_job(image_path.read_bytes)<|fim_prefix|># repo: home-assistant/core path: /homeassistant/components/kit...
code_fim
hard
{ "lang": "python", "repo": "home-assistant/core", "path": "/homeassistant/components/kitchen_sink/image.py", "mode": "spm", "license": "Apache-2.0", "source": "the-stack-v2" }
<|fim_prefix|># repo: home-assistant/core path: /homeassistant/components/kitchen_sink/image.py """Demo image platform.""" from __future__ import annotations from pathlib import Path from homeassistant.components.image import ImageEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core im...
code_fim
hard
{ "lang": "python", "repo": "home-assistant/core", "path": "/homeassistant/components/kitchen_sink/image.py", "mode": "psm", "license": "Apache-2.0", "source": "the-stack-v2" }
<|fim_suffix|> async def async_added_to_hass(self): """Set the update time.""" self._attr_image_last_updated = dt_util.utcnow() async def async_image(self) -> bytes | None: """Return bytes of image.""" image_path = Path(__file__).parent / self._image_filename return await...
code_fim
hard
{ "lang": "python", "repo": "home-assistant/core", "path": "/homeassistant/components/kitchen_sink/image.py", "mode": "spm", "license": "Apache-2.0", "source": "the-stack-v2" }
<|fim_prefix|># repo: dccastro/Morpho-MNIST path: /scripts/interleave.py import os import shutil import numpy as np import pandas as pd from morphomnist import io def interleave_dfs(dfs, indices, keys): df = pd.concat(dfs, axis=0, keys=keys) df = df.swaplevel(0, 1) df = df.loc[list(enumerate(indices))]...
code_fim
hard
{ "lang": "python", "repo": "dccastro/Morpho-MNIST", "path": "/scripts/interleave.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> data_dirs = [os.path.join(data_root, dataset_names[i]) for i in pairing] imgs_paths = [os.path.join(data_dir, images_filename) for data_dir in data_dirs] metrics_paths = [os.path.join(data_dir, metrics_filename) for data_dir in data_dirs] all_images = np.arr...
code_fim
hard
{ "lang": "python", "repo": "dccastro/Morpho-MNIST", "path": "/scripts/interleave.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> if __name__ == "__main__": parser = argparse.ArgumentParser(description="A tool script to record schedule.") # type参数理论上可以是任何合法的类型, 但有些参数传入格式比较麻烦,例如list, # 一般使用bool, int, str, float这些基本类型,更复杂的需求可以通过str传入,然后手动解析。 # bool类型的解析比较特殊,传入任何值都会被解析成True,传入空值时才为False parser.add_argument("--mode"...
code_fim
hard
{ "lang": "python", "repo": "lartpang/PySchedule", "path": "/main.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: lartpang/PySchedule path: /main.py import argparse from utils.file_funcs import read_json, save_table from utils.operator_funcs import append_record, delete_record, display_all, update_record from utils.print_funcs import disp_msg from utils.tool_funcs import read_data def main(args): <|fim_su...
code_fim
hard
{ "lang": "python", "repo": "lartpang/PySchedule", "path": "/main.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> translator: sockeye.inference.Translator, chunk_id: int = 0) -> float: """ Translates each line from source_data, calling output handler after translating a batch. :param output_handler: A handler that will be called once with the output of each translation. :param sou...
code_fim
hard
{ "lang": "python", "repo": "zz1559152814/my-notebook", "path": "/paper:sockeye亚马逊翻译模型(2017业内最佳)/sockeye-master/sockeye/translate.py", "mode": "spm", "license": "Apache-2.0", "source": "the-stack-v2" }
<|fim_prefix|># repo: zz1559152814/my-notebook path: /paper:sockeye亚马逊翻译模型(2017业内最佳)/sockeye-master/sockeye/translate.py # Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You may not # use this file except in compliance with th...
code_fim
hard
{ "lang": "python", "repo": "zz1559152814/my-notebook", "path": "/paper:sockeye亚马逊翻译模型(2017业内最佳)/sockeye-master/sockeye/translate.py", "mode": "psm", "license": "Apache-2.0", "source": "the-stack-v2" }
<|fim_prefix|># repo: araschermer/python-code path: /algorithms_and_data_structures/linked_lists/shift_elements.py from linked_lists_util import print_linked_list, insert_list, Node class LinkedList: def __init__(self): self.head = None def shift_elements(self, shifts): """Shift the elements...
code_fim
hard
{ "lang": "python", "repo": "araschermer/python-code", "path": "/algorithms_and_data_structures/linked_lists/shift_elements.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> def remove_tail(self): """removes the last element from the linked list""" pointer = self.head while pointer.next_node.next_node: pointer = pointer.next_node pointer.next_node = None return self def shift_elements2(self, num_shifts: int): ...
code_fim
hard
{ "lang": "python", "repo": "araschermer/python-code", "path": "/algorithms_and_data_structures/linked_lists/shift_elements.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> def get_length(self): """Returns length of the linked list.""" pointer = self.head counter = 0 while pointer: counter += 1 pointer = pointer.next_node return counter if __name__ == '__main__': linked_list2 = LinkedList() insert_...
code_fim
hard
{ "lang": "python", "repo": "araschermer/python-code", "path": "/algorithms_and_data_structures/linked_lists/shift_elements.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|>def favorite_number(): number = stored_number() if number: print("I know your favorite number! It's " + number) else: number = survey_number() print("Enter") favorite_number()<|fim_prefix|># repo: ikamilov/Python path: /Exercise/10.11.Favoritenumber.py import json def stored_number(): filename...
code_fim
medium
{ "lang": "python", "repo": "ikamilov/Python", "path": "/Exercise/10.11.Favoritenumber.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: ikamilov/Python path: /Exercise/10.11.Favoritenumber.py import json def stored_number(): filename = 'numbers.json' try: with open(filename) as file_object: number = json.load(file_object) except FileNotFoundError: return None else: return number def survey_number(): <|fim_suffix|>...
code_fim
medium
{ "lang": "python", "repo": "ikamilov/Python", "path": "/Exercise/10.11.Favoritenumber.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: TheAlgorithms/Python path: /maths/segmented_sieve.py """Segmented Sieve.""" import math def sieve(n: int) -> list[int]: """Segmented Sieve.""" in_prime = [] start = 2 end = int(math.sqrt(n)) # Size of every segment temp = [True] * (end + 1) prime = [] ...
code_fim
medium
{ "lang": "python", "repo": "TheAlgorithms/Python", "path": "/maths/segmented_sieve.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> low = end + 1 high = min(2 * end, n) while low <= n: temp = [True] * (high - low + 1) for each in in_prime: t = math.floor(low / each) * each if t < low: t += each for j in range(t, high + 1, each): ...
code_fim
hard
{ "lang": "python", "repo": "TheAlgorithms/Python", "path": "/maths/segmented_sieve.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> mapper = FormProcessMapperService.create_mapper(dict_data) response, status = mapper_schema.dump(mapper), HTTPStatus.CREATED except ValidationError as form_err: response, status = {'systemErrors': form_err.messages}, \ HTTPStatus.BAD_REQUEST ...
code_fim
hard
{ "lang": "python", "repo": "olukunle-abolade/forms-flow-ai", "path": "/forms-flow-api/src/api/resources/form_process_mapper.py", "mode": "spm", "license": "Apache-2.0", "source": "the-stack-v2" }
<|fim_prefix|># repo: olukunle-abolade/forms-flow-ai path: /forms-flow-api/src/api/resources/form_process_mapper.py """API endpoints for managing form resource.""" from http import HTTPStatus from flask import g, jsonify, request from flask_restx import Namespace, Resource, cors from marshmallow import ValidationErr...
code_fim
hard
{ "lang": "python", "repo": "olukunle-abolade/forms-flow-ai", "path": "/forms-flow-api/src/api/resources/form_process_mapper.py", "mode": "psm", "license": "Apache-2.0", "source": "the-stack-v2" }
<|fim_suffix|> mapper = FormProcessMapperService.create_mapper(dict_data) response, status = mapper_schema.dump(mapper), HTTPStatus.CREATED except ValidationError as form_err: response, status = {'systemErrors': form_err.messages}, \ HTTPStatus.BAD_REQUEST ...
code_fim
hard
{ "lang": "python", "repo": "olukunle-abolade/forms-flow-ai", "path": "/forms-flow-api/src/api/resources/form_process_mapper.py", "mode": "spm", "license": "Apache-2.0", "source": "the-stack-v2" }
<|fim_suffix|> a_lat = np.where((lat_array < latitude))[0][0] b_lat = np.where((lat_array >= latitude))[0][-1] # Compute geo extent around the point : # => extent definition : LR,LL,UL,UR extent = [lon_array[a_lon], lat_array[a_lat], lon_array[b_lon], lat_array[...
code_fim
hard
{ "lang": "python", "repo": "hulaba/sen2like", "path": "/sen2like/sen2like/atmcor/atmospheric_parameters.py", "mode": "spm", "license": "Apache-2.0", "source": "the-stack-v2" }
<|fim_suffix|> """ v1 = (A[extent_index[7], extent_index[6]]) # UL v2 = (A[extent_index[5], extent_index[4]]) # UR v3 = (A[extent_index[1], extent_index[0]]) # LL estimate_v = v1 + (v2 - v1) * beta_longitude + (v3 - v1) * beta_latitude return estimate_v @classmet...
code_fim
hard
{ "lang": "python", "repo": "hulaba/sen2like", "path": "/sen2like/sen2like/atmcor/atmospheric_parameters.py", "mode": "spm", "license": "Apache-2.0", "source": "the-stack-v2" }
<|fim_prefix|># repo: hulaba/sen2like path: /sen2like/sen2like/atmcor/atmospheric_parameters.py import logging import numpy as np log = logging.getLogger("Sen2Like") class ATMO_parameter: """ Related to Atmospheric properties of a given geolocation Used cams_data as property Return with getValues, ...
code_fim
hard
{ "lang": "python", "repo": "hulaba/sen2like", "path": "/sen2like/sen2like/atmcor/atmospheric_parameters.py", "mode": "psm", "license": "Apache-2.0", "source": "the-stack-v2" }
<|fim_prefix|># repo: madisoncooney/HPR_Titan path: /NoFAT/Python Code/NF_serialcapture.py from bitstring import BitArray, BitStream import base64 import datetime <|fim_suffix|># Open port and start writing data ser.open() # this needs to be in a loop packet = ser.read_until(255,6) output = NF_rawToDatum(packet) #...
code_fim
medium
{ "lang": "python", "repo": "madisoncooney/HPR_Titan", "path": "/NoFAT/Python Code/NF_serialcapture.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|># Open port and start writing data ser.open() # this needs to be in a loop packet = ser.read_until(255,6) output = NF_rawToDatum(packet) #Testing purposes print(output.sensor) print(output.feed) print(output.time) print(output.channel) print(output.data)<|fim_prefix|># repo: madisoncooney/HPR_Titan pa...
code_fim
medium
{ "lang": "python", "repo": "madisoncooney/HPR_Titan", "path": "/NoFAT/Python Code/NF_serialcapture.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> leg_terms = [ {"term": "2009-2010", "chamber": "upper", "district": "1"}, {"term": "2011-2012", "chamber": "upper", "district": "1"}, # redistricting {"term": "2013-2014", "chamber": "upper", "district": "2"}, # lost election, then came back {"term": "20...
code_fim
medium
{ "lang": "python", "repo": "compwright/people", "path": "/scripts/one-off/test_migrate_people.py", "mode": "spm", "license": "CC0-1.0", "source": "the-stack-v2" }
<|fim_prefix|># repo: compwright/people path: /scripts/one-off/test_migrate_people.py from migrate_people import terms_to_roles nc_terms = [ {"end_year": 2010, "start_year": 2009, "name": "2009-2010", "sessions": ["2009"]}, {"end_year": 2012, "start_year": 2011, "name": "2011-2012", "sessions": ["2011"]}, ...
code_fim
medium
{ "lang": "python", "repo": "compwright/people", "path": "/scripts/one-off/test_migrate_people.py", "mode": "psm", "license": "CC0-1.0", "source": "the-stack-v2" }
<|fim_suffix|> def get_command(self, ctx: Context, cmd_name: str) -> Optional[Command]: try: mod = __import__( f"cos.commands.cmd_{cmd_name}", None, None, ["cli"]) except ImportError: return return mod.cli @click.command(cls=Commands) def cli(): "...
code_fim
hard
{ "lang": "python", "repo": "Adwaith-Rajesh/cospy", "path": "/cos/cli.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: Adwaith-Rajesh/cospy path: /cos/cli.py import os from typing import Iterable from typing import Optional import click from click import Command from click import Context <|fim_suffix|> def get_command(self, ctx: Context, cmd_name: str) -> Optional[Command]: try: mod = __...
code_fim
hard
{ "lang": "python", "repo": "Adwaith-Rajesh/cospy", "path": "/cos/cli.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: vveitch/causal-network-embeddings path: /src/relational_ERM/effect_estimates/exogeneity_plotting.py import os import seaborn as sns import matplotlib.pyplot as plt import relational_ERM.effect_estimates.compute_ate as ate import pandas as pd def make_reddit_prop_plt(): <|fim_suffix|> prop_ex...
code_fim
hard
{ "lang": "python", "repo": "vveitch/causal-network-embeddings", "path": "/src/relational_ERM/effect_estimates/exogeneity_plotting.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> plt.figure(figsize=(4.75, 3.5)) # plt.figure(figsize=(2.37, 1.5)) sns.scatterplot(data=prop_expt, legend='brief', s=75) plt.xlabel("Exogeneity", fontfamily='monospace') plt.ylabel("ATE Estimate", fontfamily='monospace') plt.tight_layout() fig_dir = '../output/figures' os.m...
code_fim
hard
{ "lang": "python", "repo": "vveitch/causal-network-embeddings", "path": "/src/relational_ERM/effect_estimates/exogeneity_plotting.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|># Links to the cpu_temp.py script if command == "2": exec(open("./src/cpu_temp.py").read())<|fim_prefix|># repo: eding42/pycpu path: /pycpu.py #!/usr/bin/python3 print("-------------- Welcome to PyCPU v1.05 --------------") command = input("Choose a function:\n1. CPU Frequency (MHz)\n2. CPU Temper...
code_fim
medium
{ "lang": "python", "repo": "eding42/pycpu", "path": "/pycpu.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|># Links to the cpu_freq.py script if command == "1": exec(open("./src/cpu_freq.py").read()) # Links to the cpu_temp.py script if command == "2": exec(open("./src/cpu_temp.py").read())<|fim_prefix|># repo: eding42/pycpu path: /pycpu.py #!/usr/bin/python3 print("-------------- Welcome to PyCPU ...
code_fim
medium
{ "lang": "python", "repo": "eding42/pycpu", "path": "/pycpu.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: eding42/pycpu path: /pycpu.py #!/usr/bin/python3 print("-------------- Welcome to PyCPU v1.05 --------------") command = input("Choose a function:\n1. CPU Frequency (MHz)\n2. CPU Temperature (UNDER DEVELOPEMENT)\n") # Links to the cpu_freq.py script <|fim_suffix|>if command == "2": exec(o...
code_fim
medium
{ "lang": "python", "repo": "eding42/pycpu", "path": "/pycpu.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> if not (mkl_controller and expected_layer): pytest.skip("requires MKL and the environment variable MKL_THREADING_LAYER set") actual_layer = mkl_controller.lib_controllers[0].threading_layer assert actual_layer == expected_layer.lower() def test_blis_threading_layer(): # Check th...
code_fim
hard
{ "lang": "python", "repo": "joblib/threadpoolctl", "path": "/tests/test_threadpoolctl.py", "mode": "spm", "license": "BSD-3-Clause", "source": "the-stack-v2" }
<|fim_suffix|> # Trigger the import of numpy to potentially import Intel OpenMP via MKL pytest.importorskip("numpy.linalg") # Check that a warning is raised when both libomp and libiomp are loaded # It should happen in one CI job (pylatest_conda_mkl_clang_gcc). controller = ThreadpoolController() ...
code_fim
hard
{ "lang": "python", "repo": "joblib/threadpoolctl", "path": "/tests/test_threadpoolctl.py", "mode": "spm", "license": "BSD-3-Clause", "source": "the-stack-v2" }
<|fim_prefix|># repo: joblib/threadpoolctl path: /tests/test_threadpoolctl.py as_openmp() blas_controller = ThreadpoolController().select(user_api="blas") original_openmp_info = ThreadpoolController().select(user_api="openmp").info() with blas_controller.limit(limits=1): blas_controller = Threadp...
code_fim
hard
{ "lang": "python", "repo": "joblib/threadpoolctl", "path": "/tests/test_threadpoolctl.py", "mode": "psm", "license": "BSD-3-Clause", "source": "the-stack-v2" }
<|fim_prefix|># repo: HusseinElsherbini/Chixculub-Impactor path: /terminal.py t_13.setSpacing(0) self.verticalLayout_13.setObjectName("verticalLayout_13") self.pauseBtn = QtWidgets.QPushButton(self.frame_18) self.pauseBtn.setStyleSheet("QPushButton{\n" "b...
code_fim
hard
{ "lang": "python", "repo": "HusseinElsherbini/Chixculub-Impactor", "path": "/terminal.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> def __init__(self, objectName, VID_PID): super().__init__() self.setObjectName(objectName) self.VID_PID = VID_PID self.gridLayout_3 = QtWidgets.QGridLayout(self) self.gridLayout_3.setContentsMargins(0, 0, 0, 0) self.gridLayout_3.setObjectName("gridLayou...
code_fim
hard
{ "lang": "python", "repo": "HusseinElsherbini/Chixculub-Impactor", "path": "/terminal.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: HusseinElsherbini/Chixculub-Impactor path: /terminal.py -color: rgb(242,242,242,90); } QScrollBar::add-line:vertical { height: 0px; } QScrollBar::sub-line:vertical { height: 0px; } ...
code_fim
hard
{ "lang": "python", "repo": "HusseinElsherbini/Chixculub-Impactor", "path": "/terminal.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> input: torch.Tensor, target: torch.Tensor, alpha: float = -1, lmd: float = 0.5, reduction: Optional[str] = 'sum', ) -> torch.Tensor: lhs = gs_div(input, target, alpha=alpha, lmd=lmd, reduction=reduction) rhs = gs_div(target, input, alpha=alpha, lmd=lmd, reduction=reduction) ...
code_fim
easy
{ "lang": "python", "repo": "ISMHinoLab/geodesical_skew_divergence", "path": "/gs_divergence/symmetrized_geodesical_skew_divergence.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: ISMHinoLab/geodesical_skew_divergence path: /gs_divergence/symmetrized_geodesical_skew_divergence.py from typing import Optional import torch from gs_divergence import gs_div <|fim_suffix|> input: torch.Tensor, target: torch.Tensor, alpha: float = -1, lmd: float = 0.5, reduct...
code_fim
easy
{ "lang": "python", "repo": "ISMHinoLab/geodesical_skew_divergence", "path": "/gs_divergence/symmetrized_geodesical_skew_divergence.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> random.random() print "End of program. Bye!"<|fim_prefix|># repo: authman/Python201609 path: /Guerrero_Melissa/Assignments/coin_tosses.py heads_count = 0 tails_count = 0 for count in range (0, 5001): import random random_num = random.random() x = random_num x_rounded = round(x) if (0 <= x_rounde...
code_fim
medium
{ "lang": "python", "repo": "authman/Python201609", "path": "/Guerrero_Melissa/Assignments/coin_tosses.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: authman/Python201609 path: /Guerrero_Melissa/Assignments/coin_tosses.py heads_count = 0 tails_count = 0 for count in range (0, 5001): import random random_num = random.random() x = random_num x_rounded = round(x) <|fim_suffix|> random.random() print "End of program. Bye!"<|fim_middle|> if ...
code_fim
hard
{ "lang": "python", "repo": "authman/Python201609", "path": "/Guerrero_Melissa/Assignments/coin_tosses.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: YisusJe/Todolist path: /backend/todolist/api/controllers/__init__.py from flask import make_response, jsonify def format_response(message, status, message_type="error"): <|fim_suffix|> """ return make_response( jsonify({message_type: message}), status ) from .user imp...
code_fim
medium
{ "lang": "python", "repo": "YisusJe/Todolist", "path": "/backend/todolist/api/controllers/__init__.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> """ return make_response( jsonify({message_type: message}), status ) from .user import UserController<|fim_prefix|># repo: YisusJe/Todolist path: /backend/todolist/api/controllers/__init__.py from flask import make_response, jsonify <|fim_middle|>def format_response(message,...
code_fim
hard
{ "lang": "python", "repo": "YisusJe/Todolist", "path": "/backend/todolist/api/controllers/__init__.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: chrisburr/lhcb-talky path: /talky/database_events.py import os from os.path import join import secrets from sqlalchemy.event import listens_for from sqlalchemy import inspect from .talky import app from .schema import db, Submission, Talk, Comment from . import messages @listens_for(Submissio...
code_fim
hard
{ "lang": "python", "repo": "chrisburr/lhcb-talky", "path": "/talky/database_events.py", "mode": "psm", "license": "BSD-3-Clause", "source": "the-stack-v2" }
<|fim_suffix|> @listens_for(db.session, 'after_flush') def monitor_db_after_flush(session, flush_context): """Monitor for changes in the database""" changed_objects = session.new.union(session.dirty) for obj in changed_objects: if isinstance(obj, Talk): talk_changed(obj) if isins...
code_fim
hard
{ "lang": "python", "repo": "chrisburr/lhcb-talky", "path": "/talky/database_events.py", "mode": "spm", "license": "BSD-3-Clause", "source": "the-stack-v2" }
<|fim_suffix|> N = 400 m = 2 graf = np.zeros((N,N), dtype=int) for k in s.keys(): x, y = k graf[m*x+N//2,m*y+N//2] = s[k] + 4000 for e in g.edges(): a, b = e c = graf[m*a[0]+N//2, m*a[1]+N//2] x, y = (m*a[0]+N//2+m*b[0]+N//2)//2, (m*a[1]+N//2+m*b[1]+N//2)//2 ...
code_fim
hard
{ "lang": "python", "repo": "orrinjelo/AdventOfCode2018", "path": "/20/part1/main.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|>def plot_course(s,g): N = 400 m = 2 graf = np.zeros((N,N), dtype=int) for k in s.keys(): x, y = k graf[m*x+N//2,m*y+N//2] = s[k] + 4000 for e in g.edges(): a, b = e c = graf[m*a[0]+N//2, m*a[1]+N//2] x, y = (m*a[0]+N//2+m*b[0]+N//2)//2, (m*a[1]...
code_fim
hard
{ "lang": "python", "repo": "orrinjelo/AdventOfCode2018", "path": "/20/part1/main.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: orrinjelo/AdventOfCode2018 path: /20/part1/main.py #!/usr/bin/env python3 import os, sys import numpy as np from pprint import pprint import time # from operator import itemgetter import matplotlib.pyplot as plt import re import networkx def traverse(msg): maze = networkx.Graph() stack...
code_fim
hard
{ "lang": "python", "repo": "orrinjelo/AdventOfCode2018", "path": "/20/part1/main.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }
<|fim_suffix|> """Penalize the weight of the embedding such that two similar words in the corpus embedding spaced trained using gensim stay similar in the new emebedding space""" shape = weight_matrix.shape #Sample at random nb_rand_sample of words pairs z1 = tf.random_uniform([nb_rand_sample], minval =...
code_fim
hard
{ "lang": "python", "repo": "cgallay/KaggleDathena", "path": "/sentiment_analyzer.py", "mode": "spm", "license": "MIT", "source": "the-stack-v2" }
<|fim_prefix|># repo: cgallay/KaggleDathena path: /sentiment_analyzer.py # LSTM for sequence classification in the IMDB dataset import keras import tensorflow as tf from keras import backend as K from keras.datasets import imdb from keras.models import Sequential, Model from keras.layers import Dense, Lambda, Input fr...
code_fim
hard
{ "lang": "python", "repo": "cgallay/KaggleDathena", "path": "/sentiment_analyzer.py", "mode": "psm", "license": "MIT", "source": "the-stack-v2" }