text stringlengths 232 16.3k | domain stringclasses 1
value | difficulty stringclasses 3
values | meta dict |
|---|---|---|---|
<|fim_suffix|>
class ImmutableMetadataFormat(model.TextFileFormat):
def _validate_(self, level):
try:
Metadata.load(str(self))
except (MetadataFileError,) as e:
raise ValidationError(str(e))
ImmutableMetadataDirectoryFormat = model.SingleFileDirectoryFormat(
'ImmutableM... | code_fim | medium | {
"lang": "python",
"repo": "gregcaporaso/q2-types",
"path": "/q2_types/metadata/_format.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> embedded_premise = seq2vec_seq_aggregate(embedded_premise, premise_mask, self._premise_aggregate,
self._premise_encoder.is_bidirectional(), 1)
if self._hypothesis_encoder:
embedded_hypothesis = self._hypothesis_encoder(embedded_... | code_fim | hard | {
"lang": "python",
"repo": "dianags/OpenBookQA",
"path": "/obqa/models/entailment/stacked_nn_aggregate_custom.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: dianags/OpenBookQA path: /obqa/models/entailment/stacked_nn_aggregate_custom.py
from typing import Dict, Optional, AnyStr
import torch
from allennlp.common import Params
from allennlp.common.checks import ConfigurationError
from allennlp.data import Vocabulary
from allennlp.models.model import M... | code_fim | hard | {
"lang": "python",
"repo": "dianags/OpenBookQA",
"path": "/obqa/models/entailment/stacked_nn_aggregate_custom.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> if premise_output_dim * 4 != \
aggregate_feedforward.get_input_dim():
raise ConfigurationError("The output of aggregate_feedforward input dim ({2}) "
"should be {3} = 4 x {0} ({1} = premise_output_dim == hypothesis_output_dim)!"
... | code_fim | hard | {
"lang": "python",
"repo": "dianags/OpenBookQA",
"path": "/obqa/models/entailment/stacked_nn_aggregate_custom.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: toschmidt/pg-cv path: /src/python/view_generator/parsesql_helper.py
from typing import Type
from sqlparse import sql
from sqlparse.tokens import Name
# find first token of the given type in the parsed query (using depth-first-search)
def find_first_instance(token: sql.Token, instancetype: Type... | code_fim | hard | {
"lang": "python",
"repo": "toschmidt/pg-cv",
"path": "/src/python/view_generator/parsesql_helper.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # check if type is identical and both have the same attributes
equal = isinstance(token1, type(token2)) and isinstance(token2, type(token2)) and (
token1.is_group == token2.is_group) and (token1.is_keyword == token2.is_keyword) and (
token1.is_whitespace == token2.i... | code_fim | hard | {
"lang": "python",
"repo": "toschmidt/pg-cv",
"path": "/src/python/view_generator/parsesql_helper.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: AdityaTewari/first_expts path: /caffeModels/testCaffe.py
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import numpy as np
import matplotlib.pyplot as plt
caffe_root = "../libraries/caffe-master"
<|fim_suffix|>caffe.set_phase_test()
net = caffe.Classifier(MODEL_F... | code_fim | hard | {
"lang": "python",
"repo": "AdityaTewari/first_expts",
"path": "/caffeModels/testCaffe.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>caffe.set_phase_test()
net = caffe.Classifier(MODEL_FILE, PRETRAINED,
mean=np.load(caffe_root + '/python/caffe/imagenet/ilsvrc_2012_mean.npy'),
channel_swap=(2,1,0),
raw_scale=255,
image_dims=(256, 256))
input_imag... | code_fim | hard | {
"lang": "python",
"repo": "AdityaTewari/first_expts",
"path": "/caffeModels/testCaffe.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Randomneo/python_game path: /game/loader/load_map.py
'''
defend blocks with `--`
in next lines describe game object:
name (hero, bullet, platform, plattfrom_map, platfrom_list, etc.)
path to file with spritesheet description (rows and posotions of frames)
path to spritesheet
'''
from ..obje... | code_fim | medium | {
"lang": "python",
"repo": "Randomneo/python_game",
"path": "/game/loader/load_map.py",
"mode": "psm",
"license": "WTFPL",
"source": "the-stack-v2"
} |
<|fim_suffix|> for entity in self.level_text.split('--')[1:]:
obj = [t for t in entity.split('\n') if t and not t.isspace()]
if obj[0] == 'hero':
hero = Hero()
hero.load(*obj[1:])
object_manager.camera.center_obj = hero
objec... | code_fim | medium | {
"lang": "python",
"repo": "Randomneo/python_game",
"path": "/game/loader/load_map.py",
"mode": "spm",
"license": "WTFPL",
"source": "the-stack-v2"
} |
<|fim_suffix|> def load(self, object_manager):
for entity in self.level_text.split('--')[1:]:
obj = [t for t in entity.split('\n') if t and not t.isspace()]
if obj[0] == 'hero':
hero = Hero()
hero.load(*obj[1:])
object_manager.camera.cen... | code_fim | medium | {
"lang": "python",
"repo": "Randomneo/python_game",
"path": "/game/loader/load_map.py",
"mode": "spm",
"license": "WTFPL",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: betafcc/dataclass-util path: /dataclass_util/meta/predicates.py
from types import SimpleNamespace
from operator import eq
def make_module(*, asdict):
def is_key_submap(a, b):
return is_submap_by(lambda _a, _b: True, a, b)
def is_submap(a, b):
return is_submap_by(eq, a,... | code_fim | medium | {
"lang": "python",
"repo": "betafcc/dataclass-util",
"path": "/dataclass_util/meta/predicates.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def is_submap_by(f, a, b):
da, db = asdict(a), asdict(b)
return all(
key in db and f(da[key], db[key])
for key in da
)
def has_common_keys(a, b):
try:
a, b = asdict(a), asdict(b)
except TypeError:
return Fa... | code_fim | medium | {
"lang": "python",
"repo": "betafcc/dataclass-util",
"path": "/dataclass_util/meta/predicates.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> return Dinner.query.order_by(Dinner.timestamp.asc())
def hosting_dinners(self):
return self.get_dinners() is not None
def get_reset_password_token(self, expires_in=600):
return jwt.encode(
{'reset_password': self.id, 'exp': time() + expires_in},
app.config['SECRET_KEY'], algorithm='HS256')... | code_fim | hard | {
"lang": "python",
"repo": "naomipohl/dinner-project-app",
"path": "/app/models.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> return jwt.encode(
{'register': self.id, 'exp': time() + expires_in},
app.config['SECRET_KEY'], algorithm='HS256').decode('utf-8')
@staticmethod
def verify_register_token(token):
try:
id = jwt.decode(token, app.config['SECRET_KEY'],
algorithms=['HS256'])['register']
except:
return... | code_fim | hard | {
"lang": "python",
"repo": "naomipohl/dinner-project-app",
"path": "/app/models.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: naomipohl/dinner-project-app path: /app/models.py
from datetime import datetime
from hashlib import md5
from app import db, login, app
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from time import time
import jwt
import cloudinary
cl... | code_fim | hard | {
"lang": "python",
"repo": "naomipohl/dinner-project-app",
"path": "/app/models.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: pazhik/cspcapp path: /cspcapp/globals.py
from .models import Course, CourseElement, A<|fim_suffix|>ll()
teachers: AuthUserXPerson.objects.all()<|fim_middle|>uthUserXPerson
courses = Course.objects.all()
course_elements = CourseElement.objects.a | code_fim | medium | {
"lang": "python",
"repo": "pazhik/cspcapp",
"path": "/cspcapp/globals.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>()
course_elements = CourseElement.objects.all()
teachers: AuthUserXPerson.objects.all()<|fim_prefix|># repo: pazhik/cspcapp path: /cspcapp/globals.py
from .models import Course, CourseElement, A<|fim_middle|>uthUserXPerson
courses = Course.objects.all | code_fim | easy | {
"lang": "python",
"repo": "pazhik/cspcapp",
"path": "/cspcapp/globals.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> assert get_encoding(font) == encoding<|fim_prefix|># repo: alphagov-mirror/notifications-template-preview path: /tests/test_pdf_redactor.py
from unittest.mock import Mock
import pytest
from app.pdf_redactor import get_encoding
<|fim_middle|>
@pytest.mark.parametrize(['font', 'encoding'], [
(Mo... | code_fim | hard | {
"lang": "python",
"repo": "alphagov-mirror/notifications-template-preview",
"path": "/tests/test_pdf_redactor.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: alphagov-mirror/notifications-template-preview path: /tests/test_pdf_redactor.py
from unittest.mock import Mock
import pytest
<|fim_suffix|>@pytest.mark.parametrize(['font', 'encoding'], [
(Mock(Encoding='SomeFont'), 'SomeFont'),
(Mock(Encoding=Mock(BaseEncoding='SomeFont')), 'SomeFont'... | code_fim | easy | {
"lang": "python",
"repo": "alphagov-mirror/notifications-template-preview",
"path": "/tests/test_pdf_redactor.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> #======================== private =========================================<|fim_prefix|># repo: ssciancalepore/BitTransfer path: /openwsn-sw/software/openEndPoint/injector/Injector.py
import logging
class NullHandler(logging.Handler):
def emit(self, record):
pass
log = logging.getLogger(... | code_fim | medium | {
"lang": "python",
"repo": "ssciancalepore/BitTransfer",
"path": "/openwsn-sw/software/openEndPoint/injector/Injector.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ssciancalepore/BitTransfer path: /openwsn-sw/software/openEndPoint/injector/Injector.py
import logging
class NullHandler(logging.Handler):
def emit(self, record):
pass
log = logging.getLogger('Injector')
log.setLevel(logging.ERROR)
log.addHandler(NullHandler())
class Injector(object)... | code_fim | medium | {
"lang": "python",
"repo": "ssciancalepore/BitTransfer",
"path": "/openwsn-sw/software/openEndPoint/injector/Injector.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> , triggerMatchers = None
, triggerProducer = None
, path = None
, hltProcess = None
, outputModule = None
, postfix = None
):
if triggerMatchers is None:
... | code_fim | hard | {
"lang": "python",
"repo": "cms-sw/cmssw",
"path": "/PhysicsTools/PatAlgos/python/tools/trigTools.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Switch on PAT trigger matching if needed
dictConfig = {}
if not hasattr( process, triggerProducer ):
if exampleMatchers:
print('%s():'%( self._label ))
print(' PAT trigger matching switched on automatically using')
pr... | code_fim | hard | {
"lang": "python",
"repo": "cms-sw/cmssw",
"path": "/PhysicsTools/PatAlgos/python/tools/trigTools.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: cms-sw/cmssw path: /PhysicsTools/PatAlgos/python/tools/trigTools.py
if triggerProducer is None:
triggerProducer = self._defaultParameters[ 'triggerProducer' ].value
if triggerEventProducer is None:
triggerEventProducer = self._defaultParameters[ 'triggerEventProd... | code_fim | hard | {
"lang": "python",
"repo": "cms-sw/cmssw",
"path": "/PhysicsTools/PatAlgos/python/tools/trigTools.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> def process_request(self, request):
'''
Same as the typical request handling for agents but uses the network to sample decisions
and writes game information to the buffer using store_in_buffer
'''
self.request_update(request.message)
message = request.me... | code_fim | hard | {
"lang": "python",
"repo": "SSussexGit/deepikachu",
"path": "/training.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> '''
stores a state in buffer recursively
'''
for field in state_buffer:
if (isinstance(state_buffer[field], dict)):
state_buffer[field] = self.recurse_index_state(state_buffer[field], idxs)
else:
state_buffer[field] = ... | code_fim | hard | {
"lang": "python",
"repo": "SSussexGit/deepikachu",
"path": "/training.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: SSussexGit/deepikachu path: /training.py
zeros(self.buffer_size, dtype=np.float32) #the rewards-to-go
self.val_buffer = np.zeros(self.buffer_size, dtype=np.float32) #save in np because we recompute value a bunch anyway
self.logp_buffer = np.zeros(self.buffer_size, dtype=np.float32... | code_fim | hard | {
"lang": "python",
"repo": "SSussexGit/deepikachu",
"path": "/training.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> with open(pubPath, 'r') as f:
pubkey = rsa.PublicKey.load_pkcs1(f.read().encode())
with open(priPath, 'r') as f:
priKey = rsa.PublicKey.load_pkcs1(f.read().encode())
return pubkey,priKey
def encrypt_rsa(msg, pubkey):
return rsa.encrypt(msg.encode(),pubkey)
def decrypt_rsa... | code_fim | hard | {
"lang": "python",
"repo": "FengxiangZhao/Code-Collaboration-Tool",
"path": "/server.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: FengxiangZhao/Code-Collaboration-Tool path: /server.py
import socket
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES
from Crypto import Random
import base64,string,random,rsa
#AES-demo
def gen_key(length):
publicKey, privateKey = rsa.newkeys(length)
# with open("public.pe... | code_fim | hard | {
"lang": "python",
"repo": "FengxiangZhao/Code-Collaboration-Tool",
"path": "/server.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> if not data:
break
if data.startswith('-----BEGIN RSA PUBLIC KEY-----'):
pubkey = rsa.PublicKey.load_pkcs1(data.encode())
data = encrypt_rsa(aeskey,pubkey)
print ("sending: " + str(data))
conn.send(... | code_fim | hard | {
"lang": "python",
"repo": "FengxiangZhao/Code-Collaboration-Tool",
"path": "/server.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: aaronnewcomb/PyDagg path: /pydagg.py
#!/usr/bin/python3
import pygame
import re
pygame.init()
white = (255,255,255)
black = (0,0,0)
cursor_x = 36
cursor_y = 668
text = '.'
running = True
line_pos = 630
text_line = {}
n = 0
heart_large = True
heart_rate = 800 #1000
screen = pygame.display.set_... | code_fim | hard | {
"lang": "python",
"repo": "aaronnewcomb/PyDagg",
"path": "/pydagg.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> text_width, text_height = game_font.size(text)
screen.blit(game_font.render(text, True, black), (1024 - text_width,596))
pygame.display.update()
def evaluate(text):
# Evaluate the syntax
return True
# Initialize the game elements
update_lh("EMPTY")
update_rh("EMPTY")
while running:
... | code_fim | hard | {
"lang": "python",
"repo": "aaronnewcomb/PyDagg",
"path": "/pydagg.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: opensafely/post-covid-kidney-outcomes path: /analysis/study_definition_covid_2017_additional.py
from cohortextractor import (
StudyDefinition,
patients,
codelist_from_csv,
codelist,
filter_codes_by_category,
combine_codelists
)
<|fim_suffix|>study = StudyDefinition(
d... | code_fim | hard | {
"lang": "python",
"repo": "opensafely/post-covid-kidney-outcomes",
"path": "/analysis/study_definition_covid_2017_additional.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>from variables_outcomes_2020 import generate_outcomes_2020
variables_outcomes_2020= generate_outcomes_2020(index_date_variable="case_index_date")
study = StudyDefinition(
default_expectations={
"date": {"earliest": "1900-01-01", "latest": "today"},
"rate": "uniform",
"incidenc... | code_fim | hard | {
"lang": "python",
"repo": "opensafely/post-covid-kidney-outcomes",
"path": "/analysis/study_definition_covid_2017_additional.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ruibinch/sg-calculator path: /tests/cpf/test_projection.py
etime as dt
from typing import Tuple
from logic.cpf.main import calc_cpf_projection
from logic.cpf import constants, cpfhelpers, genhelpers
from utils import strings
class TestCpfCalculateAnnualChange1(object):
"""Tests the `calc_an... | code_fim | hard | {
"lang": "python",
"repo": "ruibinch/sg-calculator",
"path": "/tests/cpf/test_projection.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> oa, sa, ma = (6000, 2000, 3000)
cont_oa_under45, cont_sa_under45, cont_ma_under45 = (840.21, 279.86, 359.93)
cont_oa_over45, cont_sa_over45, cont_ma_over45 = (760.14, 319.97, 399.89)
# calcd based on age=46
cont_oa_bonus, cont_sa_bonus, cont_ma_bonus = (2660.46, 111... | code_fim | hard | {
"lang": "python",
"repo": "ruibinch/sg-calculator",
"path": "/tests/cpf/test_projection.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ruibinch/sg-calculator path: /tests/cpf/test_projection.py
cont_oa, cont_sa, cont_ma = (920.13, 239.9, 319.97)
cont_oa_bonus, cont_sa_bonus, cont_ma_bonus = (3220.42, 839.67, 1119.91)
if month == 12: # month is December
oa += cont_oa_bonus
sa +... | code_fim | hard | {
"lang": "python",
"repo": "ruibinch/sg-calculator",
"path": "/tests/cpf/test_projection.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: gary-pickens/HouseMonitor path: /housemonitor/lib/test/hmscheduler_Test.py
'''
Created on May 5 2013
@author: Gary
'''
from apscheduler.scheduler import Scheduler
from datetime import timedelta
from housemonitor.inputs.dataenvelope import DataEnvelope
from housemonitor.lib.constants import Const... | code_fim | hard | {
"lang": "python",
"repo": "gary-pickens/HouseMonitor",
"path": "/housemonitor/lib/test/hmscheduler_Test.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def test_deleteJob( self, ):
que = MagicMock()
self.sched = HMScheduler( que )
self.sched.start()
self.sched.scheduler = MagicMock( spec=Scheduler )
self.sched.scheduler.add_date_job.return_value = 55
name = 'test1'
device = 'a'
port = ... | code_fim | hard | {
"lang": "python",
"repo": "gary-pickens/HouseMonitor",
"path": "/housemonitor/lib/test/hmscheduler_Test.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def process_arguments(argv):
if len(argv) != 2:
help()
else:
iteration_num = argv[1]
return iteration_num
def help():
print('Usage: python test_model.py ITERATION_NUM\n'
'ITERATION_NUM denotes iteration number of model which shall be tested.'
, file=... | code_fim | hard | {
"lang": "python",
"repo": "yotammarton/animals_image_classification",
"path": "/train_CRF-RNN/test_model.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: yotammarton/animals_image_classification path: /train_CRF-RNN/test_model.py
#!/usr/bin/env python
# Martin Kersner, 2016/01/28
from __future__ import print_function
import sys
import os
import caffe
import numpy as np
from skimage.io import imread
from py_img_seg_eval.eval_segm import *
from ut... | code_fim | hard | {
"lang": "python",
"repo": "yotammarton/animals_image_classification",
"path": "/train_CRF-RNN/test_model.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Metadata route
mapper.connect(
self.PATH_PREFIX+'/intra_extensions/{intra_extension_id}/subject_categories',
controller=intra_ext_controller,
action='get_subject_categories',
conditions=dict(method=['GET']))
mapper.connect(
... | code_fim | hard | {
"lang": "python",
"repo": "hashnfv/hashnfv-moon",
"path": "/keystone-moon/keystone/contrib/moon/routers.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: hashnfv/hashnfv-moon path: /keystone-moon/keystone/contrib/moon/routers.py
_k_id}/{object_name}/{action_name}',
controller=authz_controller,
action='get_authz',
conditions=dict(method=['GET']))
# IntraExtensions/Admin route
mapper.connect(
... | code_fim | hard | {
"lang": "python",
"repo": "hashnfv/hashnfv-moon",
"path": "/keystone-moon/keystone/contrib/moon/routers.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Metarule route
mapper.connect(
self.PATH_PREFIX+'/intra_extensions/{intra_extension_id}/aggregation_algorithm',
controller=intra_ext_controller,
action='get_aggregation_algorithm',
conditions=dict(method=['GET']))
mapper.connect(
... | code_fim | hard | {
"lang": "python",
"repo": "hashnfv/hashnfv-moon",
"path": "/keystone-moon/keystone/contrib/moon/routers.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: drvinceknight/sal path: /main.py
"""
Script to generate `main.csv` which contains the transition matrix for snakes
and ladders.
"""
import numpy as np
snakes_and_ladders = {
3: 19,
15: 37,
22: 42,
25: 64,
41: 73,
53: 74,
63: 86,
76: 91,
84: 98,
11: 7,
... | code_fim | medium | {
"lang": "python",
"repo": "drvinceknight/sal",
"path": "/main.py",
"mode": "psm",
"license": "CC0-1.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>for i, row in enumerate(P):
# Apply snakes and ladders
for square, target in snakes_and_ladders.items():
if row[square] > 0:
row[square], row[target] = 0, row[target] + row[square]
# If you do not land on 100 you stay where you are
if (row_sum := np.sum(row)) < 1:
... | code_fim | medium | {
"lang": "python",
"repo": "drvinceknight/sal",
"path": "/main.py",
"mode": "spm",
"license": "CC0-1.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: tussanakorn/flask-google-sheets path: /app.py
import os
from flask import Flask, render_template
import googleapiclient.discovery
from google.oauth2 import service_account
def get_credentials():
scopes = ["https://www.googleapis.com/auth/spreadsheets.readonly"]
GOOGLE_PRIVATE_KEY = os.e... | code_fim | medium | {
"lang": "python",
"repo": "tussanakorn/flask-google-sheets",
"path": "/app.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
app = Flask(__name__)
@app.route('/', methods=['GET'])
def homepage():
service = get_service()
spreadsheet_id = os.environ["GOOGLE_SPREADSHEET_ID"]
range_name = os.environ["GOOGLE_CELL_RANGE"]
result = service.spreadsheets().values().get(
spreadsheetId=spreadsheet_id, range=ran... | code_fim | hard | {
"lang": "python",
"repo": "tussanakorn/flask-google-sheets",
"path": "/app.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> service = get_service()
spreadsheet_id = os.environ["GOOGLE_SPREADSHEET_ID"]
range_name = os.environ["GOOGLE_CELL_RANGE"]
result = service.spreadsheets().values().get(
spreadsheetId=spreadsheet_id, range=range_name).execute()
values = result.get('values', [])
return rende... | code_fim | hard | {
"lang": "python",
"repo": "tussanakorn/flask-google-sheets",
"path": "/app.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
if __name__ == "__main__":
mpl.rcParams['font.sans-serif'] = ['simHei']
mpl.rcParams['axes.unicode_minus'] = False
np.set_printoptions(suppress=True)
x = np.linspace(0, 2*np.pi, 16, endpoint=False)
print('时域采样值:', x)
y = np.sin(2*x) + np.sin(3*x + np.pi/4) + np.sin(5*x)
# y =... | code_fim | hard | {
"lang": "python",
"repo": "lsieun/learn-AI",
"path": "/ML_Chinahadoop/05/code/lesson/5.7.FFT.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> plt.figure(facecolor='w')
plt.subplot(211)
plt.plot(x, y, 'go-', lw=2)
plt.title('时域信号', fontsize=15)
plt.grid(True)
plt.subplot(212)
w = np.arange(N) * 2*np.pi / N
print('频率采样值:', w)
plt.stem(w, a, linefmt='r-', markerfmt='ro')
plt.title('频域信号', fontsize=15)
pl... | code_fim | hard | {
"lang": "python",
"repo": "lsieun/learn-AI",
"path": "/ML_Chinahadoop/05/code/lesson/5.7.FFT.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: lsieun/learn-AI path: /ML_Chinahadoop/05/code/lesson/5.7.FFT.py
# !/usr/bin/python
# -*- coding:utf-8 -*-
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
def triangle_wave(size, T):
t = np.linspace(-1, 1, size, endpoint=False)
# where
# y = np.where(t < ... | code_fim | hard | {
"lang": "python",
"repo": "lsieun/learn-AI",
"path": "/ML_Chinahadoop/05/code/lesson/5.7.FFT.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: les-tallman/cloudbolt-forge path: /blueprints/aws_rds_instance/delete.py
from common.methods import set_progress
from infrastructure.models import Environment
from resourcehandlers.aws.models import AWSHandler
def run(job, logger=None, **kwargs):
resource = kwargs.pop('resources').first()
... | code_fim | hard | {
"lang": "python",
"repo": "les-tallman/cloudbolt-forge",
"path": "/blueprints/aws_rds_instance/delete.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> # The Environment ID and RDS Instance data dict were stored as attributes on
# this service by a build action.
aws_id = resource.aws_rh_id
env_id_cfv = resource.attributes.filter(field__name__startswith='aws_environment').first()
region = resource.aws_region
aws = None
if aws_... | code_fim | medium | {
"lang": "python",
"repo": "les-tallman/cloudbolt-forge",
"path": "/blueprints/aws_rds_instance/delete.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> resource = property(fget=get_resource)
def get_parent_resource_nodes(self):
"""Gets the parents of this resource.
return: (osid.resource.ResourceNodeList) - the parents of the
resource
*compliance: mandatory -- This method must be implemented.*
... | code_fim | hard | {
"lang": "python",
"repo": "birdland/dlkit-doc",
"path": "/dlkit/mongo/resource/objects.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: birdland/dlkit-doc path: /dlkit/mongo/resource/objects.py
s = self._get_registry('RESOURCE_RECORD_TYPES')
self._records = dict()
self._load_records(osid_object_map['recordTypeIds'])
self._catalog_name = 'bin'
def is_group(self):
"""Tests if this resource is a... | code_fim | hard | {
"lang": "python",
"repo": "birdland/dlkit-doc",
"path": "/dlkit/mongo/resource/objects.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def __init__(self, osid_catalog_map=None, record_types=None, runtime=None, **kwargs):
osid_objects.OsidForm.__init__(self, runtime=runtime)
self._record_type_data_sets = self._get_registry('BIN_RECORD_TYPES')
self._kwargs = kwargs
self._init_metadata(**kwargs)
... | code_fim | hard | {
"lang": "python",
"repo": "birdland/dlkit-doc",
"path": "/dlkit/mongo/resource/objects.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: zamazaljiri/django-pyston path: /example/dj/apps/app/tests/serializer.py
from __future__ import unicode_literals
import json
import xml.dom.minidom
from germanium.tools import assert_true, assert_equal
from unittest.case import TestCase
<|fim_suffix|> def test_serialization(self):
... | code_fim | medium | {
"lang": "python",
"repo": "zamazaljiri/django-pyston",
"path": "/example/dj/apps/app/tests/serializer.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def test_serialization(self):
for i in range(10):
User.objects.create(is_superuser=True, email='test{}@test.cz'.format(i))
assert_true(isinstance(json.loads((serialize(User.objects.all()))), list))
assert_true(isinstance(json.loads((serialize(User.objects.first()))... | code_fim | medium | {
"lang": "python",
"repo": "zamazaljiri/django-pyston",
"path": "/example/dj/apps/app/tests/serializer.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> if index >= 0 and index < self.numItems:
return self.items[index]
raise IndexError("Pylist index out of range")
def __setitem__(self,index,val):
if index >= 0 and index < self.numItems:
self.items[index] = val
return
... | code_fim | medium | {
"lang": "python",
"repo": "sidhu177/pythonprog",
"path": "/PyList.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def __getitem__(self,index):
if index >= 0 and index < self.numItems:
return self.items[index]
raise IndexError("Pylist index out of range")
def __setitem__(self,index,val):
if index >= 0 and index < self.numItems:
self.items[index] =... | code_fim | medium | {
"lang": "python",
"repo": "sidhu177/pythonprog",
"path": "/PyList.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: sidhu177/pythonprog path: /PyList.py
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 24 22:17:16 2019
<|fim_suffix|> raise IndexError("Pylist assignment index out of range")<|fim_middle|>taken from Data Structures and Algorithms using Python, Lee and Hubbard, Springer
"""
class P... | code_fim | hard | {
"lang": "python",
"repo": "sidhu177/pythonprog",
"path": "/PyList.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ashawkey/uuunet path: /uuunet/training/loss_functions/GDL.py
import torch
from uuunet.training.loss_functions.dice_loss import get_tp_fp_fn
from uuunet.utilities.tensor_utilities import sum_tensor
from torch import nn
class GDL(nn.Module):
def __init__(self, apply_nonlin=None, batch_dice=Fa... | code_fim | hard | {
"lang": "python",
"repo": "ashawkey/uuunet",
"path": "/uuunet/training/loss_functions/GDL.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> return (prefixes, first_part, last_part, suffixes)
_namecase = {'ii': 'II', 'iii': 'III', 'iv': 'IV', 'vi': 'VI', 'vii': 'vii'}
def namecase(name):
"""
>>> namecase('michael stephens')
'Michael Stephens'
>>> namecase('m. stephens')
'M. Stephens'
>>> namecase('m.j. stephens'... | code_fim | hard | {
"lang": "python",
"repo": "mikejs/name_tools",
"path": "/name_tools/split.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Look for compound last name
prefixes, name_na = split_prefixes(name_ns)
m = _compound_pattern.search(name_na)
if m and m.start() != 0:
first_part = name_na[0:m.start()]
last_part = m.group(0)
else:
words = name_na.split()
first_part = ' '.join(words[0:... | code_fim | hard | {
"lang": "python",
"repo": "mikejs/name_tools",
"path": "/name_tools/split.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: mikejs/name_tools path: /name_tools/split.py
from affixes import split_prefixes, split_suffixes
import re
# List of compound prefixes adapted from
# http://code.google.com/p/php-name-parser/
_compound_prefixes = ['vere', 'von', 'van', 'de', 'del', 'della', 'di', 'da',
'piet... | code_fim | hard | {
"lang": "python",
"repo": "mikejs/name_tools",
"path": "/name_tools/split.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>
BASE = ["A", "B", "C", "D", "E", "F"]
TO_DELETE = ["\r", ""]
COMBINATIONS = []
for perm in itertools.permutations(TO_DELETE):
COMBINATIONS.append(BASE + list(perm))
@pytest.mark.strings
@pytest.mark.parametrize("args", COMBINATIONS)
def test_clean_tail_empty_strings(args):
assert clean_tail_emp... | code_fim | hard | {
"lang": "python",
"repo": "lopz82/pyldt",
"path": "/tests/test_pyldt.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: lopz82/pyldt path: /tests/test_pyldt.py
import itertools
import pathlib
import numpy as np
import pytest
from pandas.core.frame import DataFrame
from pyldt._ldt import (
get_data_from_string,
clean_tail_empty_strings,
numerical_conversion,
LDT,
)
EXPECTED_SHAPE = (181, 361)
@... | code_fim | hard | {
"lang": "python",
"repo": "lopz82/pyldt",
"path": "/tests/test_pyldt.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: llol111/Website path: /src/app/cfg.py
import yaml
WEBSITE = yaml.load(open("app/config/website.yml"), Loader=yaml.<|fim_suffix|>r)
PRIVATE = yaml.load(open("app/config/private.yml"), Loader=yaml.SafeLoader)<|fim_middle|>SafeLoader)
SERVERS = yaml.load(open("app/config/servers.yml"), Loader=yaml.... | code_fim | medium | {
"lang": "python",
"repo": "llol111/Website",
"path": "/src/app/cfg.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>r)
PRIVATE = yaml.load(open("app/config/private.yml"), Loader=yaml.SafeLoader)<|fim_prefix|># repo: llol111/Website path: /src/app/cfg.py
import yaml
WEBSITE = yaml.load(open("app/config/website.yml"), Loader=yaml.SafeLoader)
SERVERS = yaml.load(open("app/config/servers.yml"), Loader=yaml.Sa<|fim_middle... | code_fim | medium | {
"lang": "python",
"repo": "llol111/Website",
"path": "/src/app/cfg.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>
## Първи мой вариант:
# words = input()
#
# new_list = {}
#
# for word in words:
# count = 0
# index_chr = 0
# index = word[index_chr]
# if index == " ":
# continue
# if word == index:
# count +=1
# index_chr += 1
# if word not in new_list:
# new... | code_fim | hard | {
"lang": "python",
"repo": "eclipse-ib/Software-University-Fundamentals_Module",
"path": "/09-Dictionaries/Exercises/1-Count_Chars_in_a_String.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: eclipse-ib/Software-University-Fundamentals_Module path: /09-Dictionaries/Exercises/1-Count_Chars_in_a_String.py
words = input()
new_list = {}
for word in words:
if word == " ":
continue
if word not in new_list:
new_list[word] = 1
else:
new_list[word] += 1
f... | code_fim | hard | {
"lang": "python",
"repo": "eclipse-ib/Software-University-Fundamentals_Module",
"path": "/09-Dictionaries/Exercises/1-Count_Chars_in_a_String.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Octoberr/letcode path: /easy/numbercomplement.py
"""
给定一个正整数,输出它的补数。补数是对该数的二进制表示取反。
注意:
给定的整数保证在32位带符号整数的范围内。
你可以假定二进制数不包含前导零位。
示例 1:
输入: 5
输出: 2
解释: 5的二进制表示为101(没有前导零位),其补数为010。所以你需要输出2。
示例 2:
<|fim_suffix|>
class Solution:
def findComplement(self, num):
for i in range(32):
... | code_fim | easy | {
"lang": "python",
"repo": "Octoberr/letcode",
"path": "/easy/numbercomplement.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> for i in range(32):
if num < 2 ** i:
return 2 ** i - 1 - num
if __name__ == '__main__':
s = Solution()
res = s.findComplement(5)
print(res)<|fim_prefix|># repo: Octoberr/letcode path: /easy/numbercomplement.py
"""
给定一个正整数,输出它的补数。补数是对该数的二进制表示取反。
注意:
给定的整... | code_fim | easy | {
"lang": "python",
"repo": "Octoberr/letcode",
"path": "/easy/numbercomplement.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> # raise NotImplementedError
if data_name == 'VOC':
train_dataset = Pascal_VOC_dataset(devkit_path = 'VOCdevkit', dataset_list = ['2007_trainval'], just_car=config.just_car) # Remember to change the path!
val_dataset = Pascal_VOC_dataset(devkit_path = 'VOCdevkit', dataset_list = ['2007_test'], just_c... | code_fim | medium | {
"lang": "python",
"repo": "ChillingDream/cv_project_rfcn",
"path": "/train.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def get_dataloader(data_name):
# raise NotImplementedError
if data_name == 'VOC':
train_dataset = Pascal_VOC_dataset(devkit_path = 'VOCdevkit', dataset_list = ['2007_trainval'], just_car=config.just_car) # Remember to change the path!
val_dataset = Pascal_VOC_dataset(devkit_path = 'VOCdevkit', data... | code_fim | hard | {
"lang": "python",
"repo": "ChillingDream/cv_project_rfcn",
"path": "/train.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ChillingDream/cv_project_rfcn path: /train.py
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import numpy as np
from tqdm import tqdm
from models.rfcn import RFCN
from trainer import Trainer
from config import config
from Pascal_VOC_dataset import Pascal_VOC_dataset
from BDD100K_dataset imp... | code_fim | hard | {
"lang": "python",
"repo": "ChillingDream/cv_project_rfcn",
"path": "/train.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> assert add_elevation_data_to_coordinates(
coordinates=[[8, 49], [9, 50], [10, 51]],
elevation=[248, 249, 250],
) == [[8, 49, 248], [9, 50, 249], [10, 51, 250]]
def test_turn_coordinates_into_list_of_distances():
assert turn_coordinates_into_list_of_distances([(99, 16), (98, 1... | code_fim | hard | {
"lang": "python",
"repo": "paturiku-p/workoutizer",
"path": "/wizer/tests/unit_tests/gis/test_gis.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: paturiku-p/workoutizer path: /wizer/tests/unit_tests/gis/test_gis.py
from wizer.gis.gis import add_elevation_data_to_coordinates, calc_distance_of_points, \
turn_coordinates_into_list_of_distances
def test_calc_distance_of_points():
assert calc_distance_of_points([(48, 8), (48, 9)]) == ... | code_fim | medium | {
"lang": "python",
"repo": "paturiku-p/workoutizer",
"path": "/wizer/tests/unit_tests/gis/test_gis.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> assert turn_coordinates_into_list_of_distances([(99, 16), (98, 16), (97, 16)]) == [0.0, 106.8875, 213.775]
assert turn_coordinates_into_list_of_distances([(99, 16), (99, 16)]) == [0.0, 0.0]<|fim_prefix|># repo: paturiku-p/workoutizer path: /wizer/tests/unit_tests/gis/test_gis.py
from wizer.gis.gi... | code_fim | hard | {
"lang": "python",
"repo": "paturiku-p/workoutizer",
"path": "/wizer/tests/unit_tests/gis/test_gis.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> print "Create"
def setUp(self, pc):
A, P = pc.getOperators()
print A.size
self.Ct = A.getSubMatrix(self.u_is,self.b_is)
self.C = A.getSubMatrix(self.b_is,self.u_is)
self.D = A.getSubMatrix(self.r_is,self.b_is)
self.Bt = A.getSubMatrix(self.u_i... | code_fim | hard | {
"lang": "python",
"repo": "wathen/UBC",
"path": "/MHD/FEniCS/MHD/Stabilised/SaddlePointForm/Test/MHDpreconditioner.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: wathen/UBC path: /MHD/FEniCS/MHD/Stabilised/SaddlePointForm/Test/MHDpreconditioner.py
self.kspQ.solve(y3,xp)
bb = x.getSubVector(self.b_is)
xb, its, self.HiptmairTime = HiptmairSetup.HiptmairApply(self.A, bb, self.kspScalar, self.kspVector, self.G, self.P, self.tol)
b... | code_fim | hard | {
"lang": "python",
"repo": "wathen/UBC",
"path": "/MHD/FEniCS/MHD/Stabilised/SaddlePointForm/Test/MHDpreconditioner.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> self.W = W
self.kspF = kspF
self.kspA = kspA
self.kspQ = kspQ
self.Fp = Fp
self.kspScalar = kspScalar
self.kspCGScalar = kspCGScalar
self.kspVector = kspVector
# self.Bt = Bt
self.HiptmairIts = 0
self.CGits = 0
... | code_fim | hard | {
"lang": "python",
"repo": "wathen/UBC",
"path": "/MHD/FEniCS/MHD/Stabilised/SaddlePointForm/Test/MHDpreconditioner.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>(True),
# Resolution power for distinguishing between 2 muon seeds (suppression of combinatorics)
# this means 1/20th of MB0
maxEtaResolutionDT = cms.double(0.02),
maxDeltaEtaDT = cms.double(0.3),
# this is a 5th of a chamber width
maxPhiResolutionCSC = cms.double(0.03),
maxDe... | code_fim | hard | {
"lang": "python",
"repo": "cms-sw/cmssw",
"path": "/RecoMuon/MuonSeedGenerator/python/MuonSeed_cfi.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: cms-sw/cmssw path: /RecoMuon/MuonSeedGenerator/python/MuonSeed_cfi.py
import FWCore.ParameterSet.Config as cms
from RecoMuon.TrackingTools.MuonServiceProxy_cff import *
from RecoMuon.MuonSeedGenerator.ptSeedParameterization_cfi import *
from RecoMuon.MuonSeedGenerator.MuonSeedPtScale_cfi import ... | code_fim | hard | {
"lang": "python",
"repo": "cms-sw/cmssw",
"path": "/RecoMuon/MuonSeedGenerator/python/MuonSeed_cfi.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: darkshloser/web3.py path: /tests/core/utilities/test_encoding.py
# encoding: utf-8
from __future__ import unicode_literals
import pytest
import re
import sys
from eth_utils import (
is_hex,
)
from hypothesis import (
example,
given,
strategies as st,
)
from web3.utils.encodin... | code_fim | hard | {
"lang": "python",
"repo": "darkshloser/web3.py",
"path": "/tests/core/utilities/test_encoding.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>@only_python3
@given(st.text())
def test_hexstr_if_str_on_invalid_hex(val):
try:
is_hexstr = (is_hex(val) or val == '')
except ValueError:
is_hexstr = False
if not is_hexstr:
with pytest.raises(ValueError):
hexstr_if_str(Mock(), val)
@only_python3
@given(... | code_fim | hard | {
"lang": "python",
"repo": "darkshloser/web3.py",
"path": "/tests/core/utilities/test_encoding.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
class Cat(Pet):
def make_voice(self):
print('%s: 喵喵喵' % self._nick_name)
def main():
pets = [Dog('旺财'), Cat('Katty'), Dog('Tom')]
for pet in pets:
pet.make_voice()
if __name__ == '__main__':
main()
"""
在上面的代码中,我们将Pet类处理成了一个抽象类,
所谓抽象类就是不能够创建对象的类,这种类的存在就是专门为了让其他类去继承它。
... | code_fim | medium | {
"lang": "python",
"repo": "Zzz-ww/Python-prac",
"path": "/python_Project/Day_09/test_6.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Zzz-ww/Python-prac path: /python_Project/Day_09/test_6.py
"""
子类在继承了父类的方法后,可以对父类已有的方法给出新的实现版本,这个动作称之为方法重写(override。
通过方法重写我们可以让父类的同一个行为在子类中拥有不同的实现版本,
当我们调用这个经过子类重写的方法时,不同的子类对象会表现出不同的行为,
这个就是多态(poly-morphism)。
"""
from abc import ABCMeta, abstractmethod
<|fim_suffix|>def main():
pets = [Dog(... | code_fim | hard | {
"lang": "python",
"repo": "Zzz-ww/Python-prac",
"path": "/python_Project/Day_09/test_6.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>>>> print(s.info_es())
index_pattern: flights
Index:
index_field: _id
is_source_field: False
Mappings:
capabilities:
es_field_name is_source es_dtype es_date_format pd_dtype is_searchable is_aggregatable is_scripted aggregatable_es_field_name
NaN script_field_None False double ... | code_fim | hard | {
"lang": "python",
"repo": "alphax777/eland",
"path": "/setup.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: alphax777/eland path: /setup.py
# Licensed to Elasticsearch B.V under one or more agreements.
# Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information
# flake8: noqa
from codecs import open
from os import path
f... | code_fim | hard | {
"lang": "python",
"repo": "alphax777/eland",
"path": "/setup.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>[5 rows x 27 columns]
```
See [docs](https://eland.readthedocs.io/en/latest) and [demo_notebook.ipynb](https://eland.readthedocs.io/en/latest/examples/demo_notebook.html) for more examples.
## Where to get it
The source code is currently hosted on GitHub at:
https://github.com/elastic/eland
Binary inst... | code_fim | hard | {
"lang": "python",
"repo": "alphax777/eland",
"path": "/setup.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: kvikshaug/btc.kvikshaug.no path: /priceticker/priceticker/workers.py
from datetime import datetime, timedelta
import decimal
import json
import logging
import sys
import threading
import pusherclient
import requests
from .models import Price
logger = logging.getLogger(__name__)
class USDNOKWo... | code_fim | hard | {
"lang": "python",
"repo": "kvikshaug/btc.kvikshaug.no",
"path": "/priceticker/priceticker/workers.py",
"mode": "psm",
"license": "Unlicense",
"source": "the-stack-v2"
} |
<|fim_suffix|> while not self.stop_event.is_set():
session = self.Session()
date_limit = datetime.now() - DBCleaner.HISTORY
logger.debug("DBCleaner: Purging prices from before %s" % date_limit)
count = session.query(Price).filter(Price.datetime < date_limit).delete... | code_fim | hard | {
"lang": "python",
"repo": "kvikshaug/btc.kvikshaug.no",
"path": "/priceticker/priceticker/workers.py",
"mode": "spm",
"license": "Unlicense",
"source": "the-stack-v2"
} |
<|fim_suffix|> def handle_trade(self, data):
btcusd = json.loads(data, parse_float=decimal.Decimal)['price']
logger.debug("New BTCUSD rate: %s" % btcusd)
self.ticker.set_btcusd(btcusd)
def stop(self):
logger.debug("BTCUSDWorker: Disconnecting from Pusher")
self.pusher.dis... | code_fim | hard | {
"lang": "python",
"repo": "kvikshaug/btc.kvikshaug.no",
"path": "/priceticker/priceticker/workers.py",
"mode": "spm",
"license": "Unlicense",
"source": "the-stack-v2"
} |
<|fim_suffix|> for i in tqdm(range(n_annotations)):
annotation_frame = annotation_df.iloc[i]
program_id = int(annotation_frame['ID'])
targets = [int(annotation_frame[ix_to_label[ix]])
for ix in xrange(label_dim)]
ast = ast_programs[program_id]
removeColors(... | code_fim | hard | {
"lang": "python",
"repo": "masterofcs/rubric-sampling-public",
"path": "/rubric_sampling/experiments/preprocess.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: masterofcs/rubric-sampling-public path: /rubric_sampling/experiments/preprocess.py
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import os
import sys
import json
import cPickle
import numpy as np
import pandas as pd
from tqdm import ... | code_fim | hard | {
"lang": "python",
"repo": "masterofcs/rubric-sampling-public",
"path": "/rubric_sampling/experiments/preprocess.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>"""
a helper function to convert 1-d index to 2-d position
"""
def idx2pos(theta, d):
return d % len(theta), d / len(theta);
"""
calculate partial derivative of loss function to d-th parameter theta[d]
@theta: parameter matrix
@d: index of the parameter
@X: training sample matrix
@Y: ... | code_fim | hard | {
"lang": "python",
"repo": "AshuAkshi0708/Data-Science-Projects",
"path": "/Wine Dataset - Coordinate Descent/src/softmax.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: AshuAkshi0708/Data-Science-Projects path: /Wine Dataset - Coordinate Descent/src/softmax.py
#!/usr/bin/env python
import random
import numpy as np
from sklearn.metrics import log_loss
from numpy.linalg import norm
from config import *
"""
calculate regularized cross-entropy loss
input:
@th... | code_fim | hard | {
"lang": "python",
"repo": "AshuAkshi0708/Data-Science-Projects",
"path": "/Wine Dataset - Coordinate Descent/src/softmax.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.