text stringlengths 232 16.3k | domain stringclasses 1
value | difficulty stringclasses 3
values | meta dict |
|---|---|---|---|
<|fim_prefix|># repo: wesleyvieiraa/CRUD_MM path: /App.py
l(self.container_main,
text="ID de Usuário:",
font=font,
bg="#EBF4FC")
self.text_id.place(x=50, y=25)
self.id = Entry(self.container_main, width=5, justify="... | code_fim | hard | {
"lang": "python",
"repo": "wesleyvieiraa/CRUD_MM",
"path": "/App.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> email = self.email.get()
tel = self.tel.get()
validator_object = Validate()
if self.validator() == True:
user = Users()
user.name = self.name.get()
user.email = validator_object.validate_email(email)
user.email = validator_ob... | code_fim | hard | {
"lang": "python",
"repo": "wesleyvieiraa/CRUD_MM",
"path": "/App.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: wesleyvieiraa/CRUD_MM path: /App.py
=1045, bg="#EBF4FC")
self.container_main.pack(after=self.container_header, side=TOP)
font = tkFont.Font(family="open-sans", size=11)
self.text_id = Label(self.container_main,
text="ID de Usuário:",
... | code_fim | hard | {
"lang": "python",
"repo": "wesleyvieiraa/CRUD_MM",
"path": "/App.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>if __name__ == '__main__':
if len(sys.argv) != 2:
usg = '\nusage: python echo_client.py "this is my message"\n'
print >>sys.stderr, usg
sys.exit(1)
msg = sys.argv[1]
client(msg)<|fim_prefix|># repo: openwonk/echo path: /python/echo_client.py
#!/usr/bin/python
import ... | code_fim | hard | {
"lang": "python",
"repo": "openwonk/echo",
"path": "/python/echo_client.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: openwonk/echo path: /python/echo_client.py
#!/usr/bin/python
import socket, sys
HOST = "127.0.0.1"
PORT = 8080
def client(msg, log_buffer=sys.stderr):
server_address = (HOST, PORT)
sock = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
... | code_fim | medium | {
"lang": "python",
"repo": "openwonk/echo",
"path": "/python/echo_client.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ucl-cssb/ROCC path: /examples/Figure_3/PI_comp_example.py
import os
import sys
os.environ['KMP_DUPLICATE_LIB_OK']='True'
from ROCC import *
from reward_func import *
def entry():
'''
Entry point for command line application handle the parsing of arguments and runs the relevant agent
... | code_fim | hard | {
"lang": "python",
"repo": "ucl-cssb/ROCC",
"path": "/examples/Figure_3/PI_comp_example.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> env.plot_trajectory([0,1])
plt.savefig(save_path + '/final_trajectory' + str(SSE)+'.png')
np.save(save_path + '/final_trajectory' + str(SSE)+'.npy', env.sSol)
plt.figure()
plt.plot(train_rs)
plt.savefig(save_path + '/train_returns.png')
if __name__ == '__m... | code_fim | hard | {
"lang": "python",
"repo": "ucl-cssb/ROCC",
"path": "/examples/Figure_3/PI_comp_example.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> if self.has_asterisk(item):
return True
return False
def has_asterisk(self, string):
"""
Whether string has asterisk
:param string:
:return:
"""
if self.debug:
print('... | code_fim | hard | {
"lang": "python",
"repo": "rubelw/cloudformation-validator",
"path": "/cfn_model/model/Principal.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: rubelw/cloudformation-validator path: /cfn_model/model/Principal.py
from __future__ import absolute_import, division, print_function
import inspect
import sys
def lineno():
"""Returns the current line number in our program."""
return str(' - Principal - line number: '+str(inspect.curren... | code_fim | hard | {
"lang": "python",
"repo": "rubelw/cloudformation-validator",
"path": "/cfn_model/model/Principal.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>sm.showFadeTransition(0, 1000, 3000)
sm.sendDelay(500)
sm.removeOverlapScreen(1000)
sm.sendDelay(500)
sm.setFieldFloating(331005110, 1, 5, 200)
sm.setIntroBoxChat(JAY)
sm.sendNext("#face1#K? Kinesis? What's going on?")
sm.setIntroBoxChat(KINESIS)
sm.sendSay("#face0#Aaah... It's... My head!")
sm.setI... | code_fim | hard | {
"lang": "python",
"repo": "Bratah123/v203.4",
"path": "/scripts/field/enter_331005110.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
sm.setIntroBoxChat(KINESIS)
sm.sendSay("#face0#Argghhh!")
sm.setFieldFloating(331005110, 20, 20, 100)
sm.showFadeTransition(0, 1000, 3000)
sm.sendDelay(500)
sm.removeOverlapScreen(1000)
sm.sendDelay(500)
sm.showFadeTransition(0, 1000, 3000)
sm.sendDelay(500)
sm.removeOverlapScreen(1000)
sm.sendDelay(... | code_fim | hard | {
"lang": "python",
"repo": "Bratah123/v203.4",
"path": "/scripts/field/enter_331005110.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Bratah123/v203.4 path: /scripts/field/enter_331005110.py
# Created by MechAviv
# Kinesis Introduction
# Map ID :: 331005110
# Unnamed
KINESIS = 1531000
JAY = 1531001
WHITE_MAGE = 1531005
sm.lockForIntro()
sm.changeBGM("Bgm00.img/Silence", 0, 0)
sm.blind(1, 255, 0, 0)
sm.setSpineObjectEffectAddPl... | code_fim | hard | {
"lang": "python",
"repo": "Bratah123/v203.4",
"path": "/scripts/field/enter_331005110.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> body = request.get_body()
headers[constant.X_CA_NONCE] = utils.get_uuid()
if request.get_content_type():
headers[constant.HTTP_HEADER_CONTENT_TYPE] = request.get_content_type()
else:
headers[constant.HTTP_HEADER_CONTENT_TYPE] = constant.CONTENT_TYP... | code_fim | hard | {
"lang": "python",
"repo": "royalwang/pyframework",
"path": "/vendor/aliyun/feiyan/client.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: royalwang/pyframework path: /vendor/aliyun/feiyan/client.py
# coding: utf-8
import requests
from vendor.aliyun.feiyan import constant
from vendor.aliyun.feiyan import utils
class DefaultClient:
def __init__(self, app_key=None, app_secret=None, time_out=None):
self.__app_key = app_k... | code_fim | hard | {
"lang": "python",
"repo": "royalwang/pyframework",
"path": "/vendor/aliyun/feiyan/client.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> """Decode data in jwt token."""
return jwt.decode(token, app.config["JWT_SECRET"], algorithms=["HS256"])<|fim_prefix|># repo: ONSdigital/ras-frontstage path: /frontstage/jwt.py
"""
Module to create jwt token.
"""
from jose import jwt
from frontstage import app
<|fim_middle|>def encode(data):
... | code_fim | medium | {
"lang": "python",
"repo": "ONSdigital/ras-frontstage",
"path": "/frontstage/jwt.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ONSdigital/ras-frontstage path: /frontstage/jwt.py
"""
Module to create jwt token.
"""
from jose import jwt
from frontstage import app
<|fim_suffix|> """Encode data in jwt token."""
return jwt.encode(data, app.config["JWT_SECRET"], algorithm="HS256")
def decode(token):
"""Decode d... | code_fim | easy | {
"lang": "python",
"repo": "ONSdigital/ras-frontstage",
"path": "/frontstage/jwt.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: quant-ops/azul path: /tests/test_sp500_wikipedia_symbol_fetcher.py
import unittest
from azul import symbol_fetcher_registry
<|fim_suffix|>
def test_returns_the_right_symbols(self):
sym_fetcher = symbol_fetcher_registry.get('sp500_wikipedia')
actual = sym_fetcher.symbols()
... | code_fim | easy | {
"lang": "python",
"repo": "quant-ops/azul",
"path": "/tests/test_sp500_wikipedia_symbol_fetcher.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def test_returns_the_right_symbols(self):
sym_fetcher = symbol_fetcher_registry.get('sp500_wikipedia')
actual = sym_fetcher.symbols()
self.assertEqual(505, len(actual))
expected = ['BK', 'CI', 'JPM', 'DD-B', 'CL', 'HIG']
self.assertFalse(set(expected).isdisjoin... | code_fim | easy | {
"lang": "python",
"repo": "quant-ops/azul",
"path": "/tests/test_sp500_wikipedia_symbol_fetcher.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> if x[feature_id] == left_value:
return self._find_leaf_node(x, left_node)
elif x[feature_id] == right_value:
return self._find_leaf_node(x, right_node)
def find_leaf_node(self, x):
if not self.root:
raise ModelNotFittedError
return s... | code_fim | hard | {
"lang": "python",
"repo": "gitter-badger/simple_ml",
"path": "/simple_ml/ensemble.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: gitter-badger/simple_ml path: /simple_ml/ensemble.py
# -*- coding:utf-8 -*-
from simple_ml.base.base_enum import ClassifierType, LabelType
from simple_ml.base.base_error import *
from simple_ml.score import *
from simple_ml.base.base import BaseClassifier, BaseFeatureSelect
class BaseAdaBoost(... | code_fim | hard | {
"lang": "python",
"repo": "gitter-badger/simple_ml",
"path": "/simple_ml/ensemble.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> self._init(x, y)
self._init_f0()
temp = []
for m in range(self.nums):
y_residual = self._get_residual(m)
tree = self.Trees[m]
tree.fit(x, y_residual)
self._update_f(tree)
temp.append(tree.importance)
self.i... | code_fim | hard | {
"lang": "python",
"repo": "gitter-badger/simple_ml",
"path": "/simple_ml/ensemble.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: em4n0n/datamine_python path: /datamine/loaders/telluslabs.py
from . import Loader
import pandas as pd
class TellusLabsLoader(Loader):
dataset = 'TELLUSLABS'
fileglob = 'TELLUSLABS_*.csv'
index = 'metric_date'
columns = ['crop', 'country_iso', 'geo_level', 'geo_id',
... | code_fim | medium | {
"lang": "python",
"repo": "em4n0n/datamine_python",
"path": "/datamine/loaders/telluslabs.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Assumption: the header from the value column provides
# the name of the measure for that CSV file.
df = pd.read_csv(file, low_memory=False)
df['measure'] = df.columns[-1]
return df
tellusLabsLoader = TellusLabsLoader()<|fim_prefix|># repo: em4n0n/datamine_python ... | code_fim | medium | {
"lang": "python",
"repo": "em4n0n/datamine_python",
"path": "/datamine/loaders/telluslabs.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> 'keypoints', 'Level', 'Mode', 'set_mode', 'set_level', 'set_path', 'set_rotate_log']<|fim_prefix|># repo: Gasol/opencv-log path: /cvlog/__init__.py
from .log import image, edges, threshold, hough_circles, hough_lines, contours, keypoints
from .config import Level, Mode, set_mode, set_level, set_path, se... | code_fim | medium | {
"lang": "python",
"repo": "Gasol/opencv-log",
"path": "/cvlog/__init__.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Gasol/opencv-log path: /cvlog/__init__.py
from .log import image, edges, threshold, hough_circles, hough_lines, contours, keypo<|fim_suffix|> 'keypoints', 'Level', 'Mode', 'set_mode', 'set_level', 'set_path', 'set_rotate_log']<|fim_middle|>ints
from .config import Level, Mode, set_mode, set_level... | code_fim | medium | {
"lang": "python",
"repo": "Gasol/opencv-log",
"path": "/cvlog/__init__.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: somewayin/MyComputerCollegeCourses path: /CS116课后题/06/a06_interface/a06q1.py
large_number = \
33644764876431783266621612005107543310302148460680063906564769974680081442166662368155595513633734025582065332680836159373734790483865268263040892463056431887354544369559827491606602099884183933864652731... | code_fim | medium | {
"lang": "python",
"repo": "somewayin/MyComputerCollegeCourses",
"path": "/CS116课后题/06/a06_interface/a06q1.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> if n in f:return f[n]
else:
if n%2==0:
f[n]=get_f(n//2,f)*(2*get_f((n//2)+1,f)-get_f(n//2,f))
return f[n]
else:
f[n]=get_f((n-1)//2,f)**2+get_f((n+1)//2,f)**2
return f[n]
def large_fibonacci(n):
f={}
f[0]=0
f[1]=1
f[2]=1
f[3]=2
ans=get_f(n,f)
# print(f... | code_fim | medium | {
"lang": "python",
"repo": "somewayin/MyComputerCollegeCourses",
"path": "/CS116课后题/06/a06_interface/a06q1.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Asafgendler/Thesis path: /code/arc/arc/coverage.py
import numpy as np
from sklearn.model_selection import train_test_split
from tqdm import tqdm
def wsc(X, y, S, delta=0.1, M=1000, verbose=False):
def wsc_v(X, y, S, delta, v):
n = len(y)
cover = np.array([y[i] in S[i] for i ... | code_fim | hard | {
"lang": "python",
"repo": "Asafgendler/Thesis",
"path": "/code/arc/arc/coverage.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def wsc_vab(X, y, S, v, a, b):
n = len(y)
cover = np.array([y[i] in S[i] for i in range(n)])
z = np.dot(X,v)
idx = np.where((z>=a)*(z<=b))
coverage = np.mean(cover[idx])
return coverage
X_train, X_test, y_train, y_test, S_train, S_test = train_test_... | code_fim | hard | {
"lang": "python",
"repo": "Asafgendler/Thesis",
"path": "/code/arc/arc/coverage.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def test_logged_in_GET(self):
self.c.login(**self.login_data)
r = self.c.get(reverse('Submit'))
self.assertIsInstance(r.context['form'], SubmissionForm)
def test_making_a_submission(self):
self.c.login(**self.login_data)
test_data = {
'title': '... | code_fim | hard | {
"lang": "python",
"repo": "avinassh/django_reddit",
"path": "/reddit/tests/test_submission.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>class TestSubmissionRequests(TestCase):
def setUp(self):
self.c = Client()
self.login_data = {
'username': 'submissiontest',
'password': 'password'
}
RedditUser.objects.create(
user=User.objects.create_user(**self.login_data)
... | code_fim | hard | {
"lang": "python",
"repo": "avinassh/django_reddit",
"path": "/reddit/tests/test_submission.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: avinassh/django_reddit path: /reddit/tests/test_submission.py
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase, Client
from reddit.forms import SubmissionForm
from reddit.models import RedditUser, Submission
class TestSubm... | code_fim | hard | {
"lang": "python",
"repo": "avinassh/django_reddit",
"path": "/reddit/tests/test_submission.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: c137digital/unv_web path: /src/unv/web/settings.py
import copy
import jinja2
from unv.app.settings import ComponentSettings, SETTINGS as APP_SETTINGS
from unv.deploy.components.redis import SETTINGS as REDIS_DEPLOY_SETTINGS
from unv.deploy.settings import SETTINGS as DEPLOY_SETTINGS
class Web... | code_fim | hard | {
"lang": "python",
"repo": "c137digital/unv_web",
"path": "/src/unv/web/settings.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> return self._data['redis']['enabled']
@property
def redis_database(self):
return self._data['redis']['database']
@property
def redis_min_connections(self):
return self._data['redis']['connections']['min']
@property
def redis_max_connections(self):
... | code_fim | hard | {
"lang": "python",
"repo": "c137digital/unv_web",
"path": "/src/unv/web/settings.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|># 返回的是一个三元tupple(dirpath, dirnames, filenames),
# 其中第一个为起始路径,第二个为起始路径下的文件夹,第三个是起始路径下的文件。
# dirpath是一个string,代表目录的路径,
# dirnames是一个list,包含了dirpath下所有子目录的名字,
# filenames是一个list,包含了非目录文件的名字,这些名字不包含路径信息。如果需要得到全路径,需要使用 os.path.join(dirpath, name)。
Lname = ""
if __name__ == '__main__':
argus = ... | code_fim | medium | {
"lang": "python",
"repo": "Garretming/csb2csd",
"path": "/getFiles.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Garretming/csb2csd path: /getFiles.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: clark
"""
import os, re, plistlib
import sys
def parseArgument():
argus = []
for i in range(0,len(sys.argv)):
# print(sys.argv[i])
argus.append(sys.argv[i])
return a... | code_fim | hard | {
"lang": "python",
"repo": "Garretming/csb2csd",
"path": "/getFiles.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def test(path):
for fpathe,dirs,fs in os.walk(path):
for f in fs:
print(os.path.join(fpathe,f))
# 返回的是一个三元tupple(dirpath, dirnames, filenames),
# 其中第一个为起始路径,第二个为起始路径下的文件夹,第三个是起始路径下的文件。
# dirpath是一个string,代表目录的路径,
# dirnames是一个list,包含了dirpath下所有子目录的名字,
# filenames是一个li... | code_fim | hard | {
"lang": "python",
"repo": "Garretming/csb2csd",
"path": "/getFiles.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Kwentar/ospa path: /test_ospa.py
import os
import unittest
from ospa import listdir
from ospa import OspaException
class TestOspaListDir(unittest.TestCase):
"""
Test class for ospa.listdir function
"""
@staticmethod
def get_dummy_folder() -> str:
"""
Get du... | code_fim | hard | {
"lang": "python",
"repo": "Kwentar/ospa",
"path": "/test_ospa.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def test_double_dot(self):
result = listdir(os.path.join('..', 'ospa', 'dummy_test_folder'), full_path=False)
need_result = ['memes',
'txt_files',
'antigravity.png',
'egg.png',
'empty.txt',
... | code_fim | hard | {
"lang": "python",
"repo": "Kwentar/ospa",
"path": "/test_ospa.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: oxwhirl/smac path: /smac/examples/rllib/__init__.py
from smac.examples.rllib.env import RLlib<|fim_suffix|>RLlibStarCraft2Env", "MaskedActionsModel"]<|fim_middle|>StarCraft2Env
from smac.examples.rllib.model import MaskedActionsModel
__all__ = [" | code_fim | medium | {
"lang": "python",
"repo": "oxwhirl/smac",
"path": "/smac/examples/rllib/__init__.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>el import MaskedActionsModel
__all__ = ["RLlibStarCraft2Env", "MaskedActionsModel"]<|fim_prefix|># repo: oxwhirl/smac path: /smac/examples/rllib/__init__.py
from smac.examples.rllib.env import RLlib<|fim_middle|>StarCraft2Env
from smac.examples.rllib.mod | code_fim | easy | {
"lang": "python",
"repo": "oxwhirl/smac",
"path": "/smac/examples/rllib/__init__.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: fvictorio/abed path: /scripts/format_checker.py
#! /usr/bin/env python
import argparse
import re
class FormatCheckerError:
NO_ERROR = 0
EMPTY_FILE = 1
BAD_HEADER = 2
BAD_LINE = 3
BAD_LABEL = 4
MISSING_LABEL = 5
class FormatCheckerType:
SSV = 0
CSV = 1
ssv_header... | code_fim | hard | {
"lang": "python",
"repo": "fvictorio/abed",
"path": "/scripts/format_checker.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>def ssv_line_pattern(d):
return r"^\s*(?:\s*%s\s*){%i}\s*(?:(\d+)\s*)?$" % (float_pattern, d)
def csv_line_pattern(d):
return r"^(?:\s*%s\s*,){%d}\s*%s\s*(?:\s*,\s*(\d+))?\s*$" % (float_pattern, d-1, float_pattern)
# Check that the file from
# file handler f has the
# proper format.
def check_fo... | code_fim | hard | {
"lang": "python",
"repo": "fvictorio/abed",
"path": "/scripts/format_checker.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> """Adds a given item/items to this flow."""
@abc.abstractmethod
def __len__(self):
"""Returns how many items are in this flow."""
@abc.abstractmethod
def __iter__(self):
"""Iterates over the children of the flow."""
@abc.abstractmethod
def iter_links(self... | code_fim | hard | {
"lang": "python",
"repo": "openstack/taskflow",
"path": "/taskflow/flow.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> """Iterate over nodes of the flow.
Iterates over 2-tuples ``(A, meta)``, where
* ``A`` is a child (atom or subflow) of current flow;
* ``meta`` is link metadata, a dictionary.
"""
def __str__(self):
cls_name = reflection.get_class_name(self)
... | code_fim | hard | {
"lang": "python",
"repo": "openstack/taskflow",
"path": "/taskflow/flow.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: openstack/taskflow path: /taskflow/flow.py
# -*- coding: utf-8 -*-
# Copyright (C) 2012 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of t... | code_fim | hard | {
"lang": "python",
"repo": "openstack/taskflow",
"path": "/taskflow/flow.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: DamonDeng/thetago path: /robot/mxnet_robot.py
import mxnet as mx
import numpy as np
from data_loader.sgf_iter import SimulatorIter, SGFIter
import logging
from go_core.goboard import GoBoard
from go_core.array_goboard import ArrayGoBoard
import copy
from data_loader.original_processor import Or... | code_fim | hard | {
"lang": "python",
"repo": "DamonDeng/thetago",
"path": "/robot/mxnet_robot.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> self.go_board.stop_simulating()
def select_move(self, color):
data,label = self.processor_class.feature_and_label(color, (0,0), self.go_board)
(input_data_label, input_data_shape) = self.processor_class.get_single_data_shape()[0]
input_data = np.zeros(input_data_shape)
... | code_fim | hard | {
"lang": "python",
"repo": "DamonDeng/thetago",
"path": "/robot/mxnet_robot.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
resp = self.client.api.exec_create(
self.id, cmd, stdout=stdout, stderr=stderr, stdin=stdin, tty=tty,
privileged=privileged, user=user, environment=env... | code_fim | hard | {
"lang": "python",
"repo": "samuel-phan/mssh-copy-id",
"path": "/tests/func-tests/dockertest.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: samuel-phan/mssh-copy-id path: /tests/func-tests/dockertest.py
from contextlib import contextmanager
import datetime
import logging
import os
import shlex
import shutil
import subprocess
import uuid
import docker
import pytest
import conf
import constantstest
import filetest
from logtest import... | code_fim | hard | {
"lang": "python",
"repo": "samuel-phan/mssh-copy-id",
"path": "/tests/func-tests/dockertest.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: wangqi1996/njunmt path: /src/optim/lr_scheduler.py
from collections import OrderedDict
from src.optim import Optimizer
from src.utils.common_utils import register
SCHEDULERS = {}
def register_sheduler(name: str):
return register(name, SCHEDULERS)
class LearningRateScheduler(object):
... | code_fim | hard | {
"lang": "python",
"repo": "wangqi1996/njunmt",
"path": "/src/optim/lr_scheduler.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> super(NoamScheduler, self).__init__(optimizer=optimizer, min_lr=min_lr)
self.d_model = d_model
self.warmup_steps = warmup_steps
# Update learning at first step
self.step(global_step=1)
def update_lr(self, old_lr, global_step, **kwargs):
opt_corr = 0.00... | code_fim | hard | {
"lang": "python",
"repo": "wangqi1996/njunmt",
"path": "/src/optim/lr_scheduler.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: adeepH/kan_hope path: /Dual Channel models/get_predictions.py
import torch
device = 'cuda' if torch.cuda.is_available() else 'cpu'
def get_predictions(model, data_loader):
model = model.eval()
sentence = []
predictions = []
prediction_probs = []
real_values = []
with to... | code_fim | hard | {
"lang": "python",
"repo": "adeepH/kan_hope",
"path": "/Dual Channel models/get_predictions.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>dictions.extend(preds)
prediction_probs.extend(outputs)
real_values.extend(labels)
predictions = torch.stack(predictions).cpu()
prediction_probs = torch.stack(prediction_probs).cpu()
real_values = torch.stack(real_values).cpu()
return sentence, predictions, predicti... | code_fim | hard | {
"lang": "python",
"repo": "adeepH/kan_hope",
"path": "/Dual Channel models/get_predictions.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: lovejavaee/a-week-in-wild-ai path: /ML-week/regression/tensorflow/decomposition_method/linear_reg_decomposition_method.py
# coding: utf-8
# # Linear Regression: Using a Decomposition (Cholesky Method)
# --------------------------------
#
# This script will use TensorFlow's function, `tf.choles... | code_fim | hard | {
"lang": "python",
"repo": "lovejavaee/a-week-in-wild-ai",
"path": "/ML-week/regression/tensorflow/decomposition_method/linear_reg_decomposition_method.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
# Extract coefficients
slope = solution_eval[0][0]
y_intercept = solution_eval[1][0]
print('slope: ' + str(slope))
print('y_intercept: ' + str(y_intercept))
# Get best fit line
best_fit = []
for i in x_vals:
best_fit.append(slope*i+y_intercept)
# Finally, we plot the fit with Matplotlib.
# In[12]:... | code_fim | hard | {
"lang": "python",
"repo": "lovejavaee/a-week-in-wild-ai",
"path": "/ML-week/regression/tensorflow/decomposition_method/linear_reg_decomposition_method.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> self.configuration_store = ConfigurationStore()
self.configuration = self.configuration_store.get()
self.key_generator = KeyGenerator()
def initialize_configuration(self, maker_id):
Logger.info(LOCATION, 'Initializing configuration...')
public_key, private_key ... | code_fim | hard | {
"lang": "python",
"repo": "BankingofThings/BoT-Python-SDK",
"path": "/showqr.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: BankingofThings/BoT-Python-SDK path: /showqr.py
# if you have the issue “warning: setlocale: LC_ALL: cannot change locale (en_US.UTF-8)”, you can solve it with the command “sudo dpkg-reconfigure locales”, select en_US.UTF-8 as default
import json
import qrcode
from bot_python_sdk.configuratio... | code_fim | hard | {
"lang": "python",
"repo": "BankingofThings/BoT-Python-SDK",
"path": "/showqr.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>print(" int64_t ntest = {};".format(n))
print("")
print(" double theta[{}] = {{".format(n))
for i in range(n):
print(" {},".format(theta[i]))
print(" };")
print("")
print(" double phi[{}] = {{".format(n))
for i in range(n):
print(" {},".format(phi[i]))
print(" };")
p... | code_fim | medium | {
"lang": "python",
"repo": "giuspugl/toast",
"path": "/src/libtoast/tests/gen_healpix_data.py",
"mode": "spm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: giuspugl/toast path: /src/libtoast/tests/gen_healpix_data.py
# This generates a small dataset with healpy
# that can be inserted into the unit tests.
# To update test data, do:
#
# %> python gen_healpix_data.py > data_healpix.cpp
#
import numpy as np
import healpy as hp
nside = 16384
angperri... | code_fim | hard | {
"lang": "python",
"repo": "giuspugl/toast",
"path": "/src/libtoast/tests/gen_healpix_data.py",
"mode": "psm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: arkhn/fhir-river path: /django/river/common/analyzer/attribute.py
import logging
from typing import List
from common.normalizers import normalize_to_bool, normalize_to_str
from .input_group import InputGroup
logger = logging.getLogger(__name__)
type_to_normalizer = {
"integer": int,
... | code_fim | hard | {
"lang": "python",
"repo": "arkhn/fhir-river",
"path": "/django/river/common/analyzer/attribute.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> self.input_groups.append(new_group)
def cast_type(self, value):
if value is None:
return None
try:
return self.normalizer(value)
except Exception as e:
logger.warning(
f"Could not cast value {value} to type {self.typ... | code_fim | medium | {
"lang": "python",
"repo": "arkhn/fhir-river",
"path": "/django/river/common/analyzer/attribute.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> def add_input_group(self, new_group):
self.input_groups.append(new_group)
def cast_type(self, value):
if value is None:
return None
try:
return self.normalizer(value)
except Exception as e:
logger.warning(
f"Coul... | code_fim | hard | {
"lang": "python",
"repo": "arkhn/fhir-river",
"path": "/django/river/common/analyzer/attribute.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> >>> ctrl_points = np.arange(9).reshape(3, 3)
>>> ut.write_points_in_vtp(ctrl_points, 'example_points.vtp', color=(255, 0, 0))
"""
if color is None:
color = (0, 0, 255)
# setup points and vertices
Points = vtk.vtkPoints()
Vertices = vtk.vtkCellArray()
Colors = vtk.v... | code_fim | hard | {
"lang": "python",
"repo": "mahgadalla/PyGeM",
"path": "/pygem/utils.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: mahgadalla/PyGeM path: /pygem/utils.py
"""
Auxiliary utilities for PyGeM.
"""
import vtk
import numpy as np
import matplotlib.pyplot as plt
def write_bounding_box(parameters, outfile, write_deformed=True):
"""
Method that writes a vtk file containing the FFD lattice. This method allows
... | code_fim | hard | {
"lang": "python",
"repo": "mahgadalla/PyGeM",
"path": "/pygem/utils.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> :param numpy.ndarray box_points: coordinates of the FFD control points.
:param string filename: name of the output file.
:param list dimensions: dimension of the lattice in (x, y, z) directions.
.. warning::
If you want to visualize in paraview the inner points,
... | code_fim | hard | {
"lang": "python",
"repo": "mahgadalla/PyGeM",
"path": "/pygem/utils.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Define controls
problem.control('hdg','rad')
# Define Cost Functional
problem.cost['path'] = Expression('(1-w)+w*V*conv*elev*terrain(x,y)', 's')
#Define constraints
problem.constraints().initial('x-x_0','m') \
.initial('y-y_0','m') \
... | code_fim | hard | {
"lang": "python",
"repo": "thomasantony/beluga",
"path": "/examples/Mansell/Hannibal_HPAdemo.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: thomasantony/beluga path: /examples/Mansell/Hannibal_HPAdemo.py
#==================================================================================
# PROGRAM: "Hannibal_HPAdemo.py"
# LOCATION: beluga>examples>Mansell
# Author: Justin Mansell (2016)
#
# Description: Preliminary test of a track pat... | code_fim | hard | {
"lang": "python",
"repo": "thomasantony/beluga",
"path": "/examples/Mansell/Hannibal_HPAdemo.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> terr=(-0.3*np.exp(-0.5*((x-2.7)**2+1.5*(y-2.1)**2))+2.6*np.exp(-0.55*(0.87*(x-6.7)**2+(y-2.2)**2))+2.1*np.exp(-0.27*(0.2*(x-5.5)**2+(y-7.2)**2))+ \
1.6*(np.cos(0.8*y))**2*(np.sin(0.796*x))**2)*0.21509729918970577/0.772319886055
return terr
#print(terrain1(4.0,4.0))
#print(terrain2(4.0,4.0))
... | code_fim | hard | {
"lang": "python",
"repo": "thomasantony/beluga",
"path": "/examples/Mansell/Hannibal_HPAdemo.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: fancent/CSC311 path: /A2/q2_materials/Q2.py
import numpy as np
import matplotlib.pyplot as plt
from utils import load_train, load_valid
from run_knn import run_knn
trainData = load_train()
validData = load_valid()
<|fim_suffix|>def classificationRate(validSet, trainResult):
return np.sum(va... | code_fim | medium | {
"lang": "python",
"repo": "fancent/CSC311",
"path": "/A2/q2_materials/Q2.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>classificationRateResults = [classificationRate(validData[1], i) for i in results]
fig, graph = plt.subplots()
graph.plot(kRange, classificationRateResults, 'x')
graph.plot(kRange, classificationRateResults)
graph.set(xlabel='k value', ylabel='classification rate',
title='classification rate as a ... | code_fim | medium | {
"lang": "python",
"repo": "fancent/CSC311",
"path": "/A2/q2_materials/Q2.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: f-morera19/tec-big-data path: /homework_one/transactions/data_aggregation.py
"""
NAME
data_aggregation.py
DESCRIPTION
Logic for data aggregation.
Student: Fabian Morera Gutierrez.
Course: Big Data.
Instituto Tecnologico de Costa Rica.
2021
"""
from pyspark.sql import SparkSession
... | code_fim | hard | {
"lang": "python",
"repo": "f-morera19/tec-big-data",
"path": "/homework_one/transactions/data_aggregation.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Create new dataframe by grouping the data by province
# using the sum function.
agg_total_dist = src_df.na.drop().groupBy("province").sum("distance").orderBy("province")
return agg_total_dist
def aggregateByDate(src_df):
# Create new dataframe by grouping the data by date
# us... | code_fim | medium | {
"lang": "python",
"repo": "f-morera19/tec-big-data",
"path": "/homework_one/transactions/data_aggregation.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: lyft/cartography path: /tests/integration/cartography/intel/gcp/test_compute.py
import cartography.intel.gcp.compute
import tests.data.gcp.compute
TEST_UPDATE_TAG = 123456789
def _ensure_local_neo4j_has_test_instance_data(neo4j_session):
cartography.intel.gcp.compute.load_gcp_instances(
... | code_fim | hard | {
"lang": "python",
"repo": "lyft/cartography",
"path": "/tests/integration/cartography/intel/gcp/test_compute.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def test_nic_to_subnets(neo4j_session):
"""
Ensure that network interfaces are attached to subnets
"""
_ensure_local_neo4j_has_test_subnet_data(neo4j_session)
_ensure_local_neo4j_has_test_instance_data(neo4j_session)
subnet_query = """
MATCH (nic:GCPNetworkInterface{id:$NicId}... | code_fim | hard | {
"lang": "python",
"repo": "lyft/cartography",
"path": "/tests/integration/cartography/intel/gcp/test_compute.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> self.cur.execute("CREATE TYPE status AS ENUM ('normal', 'atrasado', 'adiantado', 'garagem', 'indeterminado');")
self.assertEqual(self.cur.statusmessage, "CREATE TYPE")<|fim_prefix|># repo: matheussampaio/sig path: /src/tests/OnibusTest.py
import psycopg2
import unittest
import sys
import os
class ... | code_fim | hard | {
"lang": "python",
"repo": "matheussampaio/sig",
"path": "/src/tests/OnibusTest.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> for self.dadosFalhos in self.falhos:
try:
self.cur.execute(self.dadosFalhos)
except:
self.assertFalse(False)
def testCCreateEnum(self):
self.cur.execute("CREATE TYPE status AS ENUM ('normal', 'atrasado', 'adiantado', 'garagem', 'indeterminado');")
self.assertEqual(self.cur... | code_fim | hard | {
"lang": "python",
"repo": "matheussampaio/sig",
"path": "/src/tests/OnibusTest.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: matheussampaio/sig path: /src/tests/OnibusTest.py
import psycopg2
import unittest
import sys
import os
class DOnibusTest(unittest.TestCase):
def setUp(self):
self.table = open(os.path.abspath('../') + '/sql/createsTable/Onibus.sql', 'r')
self.constraints = open(os.path.abspath('../') +... | code_fim | hard | {
"lang": "python",
"repo": "matheussampaio/sig",
"path": "/src/tests/OnibusTest.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>tions': 'processingInstructions',
'reportGroup': '',
'surchargeAmount': ''},
'registerTokenRequest': {'accountNumber': '',
'applepay': 'applepayType',
'cardValidationNum': '',
... | code_fim | hard | {
"lang": "python",
"repo": "Vantiv/vantiv-sdk-for-python",
"path": "/vantivsdk/dictmap.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Vantiv/vantiv-sdk-for-python path: /vantivsdk/dictmap.py
'paypal': 'payPal',
'pin': '',
'pos': 'pos',
'processingInstructions': 'processingInstructions',
'reportGroup': '',
'secondaryAmount': '',
'surchargeAmount': '',
... | code_fim | hard | {
"lang": "python",
"repo": "Vantiv/vantiv-sdk-for-python",
"path": "/vantivsdk/dictmap.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Vantiv/vantiv-sdk-for-python path: /vantivsdk/dictmap.py
s',
'secondaryAmount': '',
'sellerInfo': 'sellerInfo',
'sepaDirectDebit': 'sepaDirectDebitType',
'shipToAddress': 'shipToAddress',
'skipRealtimeAU': '',
'sofort': 'sofortType',
'surcha... | code_fim | hard | {
"lang": "python",
"repo": "Vantiv/vantiv-sdk-for-python",
"path": "/vantivsdk/dictmap.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> #save without cloth image
class face_object:
def __init__(self, face_image, name, coordinate):
self.face = face_image
self.name = name
x, y, h, w = coordinate
self.x = x
self.y = y
self.h = h
self.w = w
def showface(self):
cv.imshow("Output", self.face)
cv.waitKey(0)
... | code_fim | hard | {
"lang": "python",
"repo": "ishaan95/202-project3",
"path": "/Main/face_replacer.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> cv.imshow("Output", self.face)
cv.waitKey(0)
cwd = os.getcwd()
anime_image_path = r'\output'
main_image_path = r'\input\input.jpg'
temp_path = r'\temp\\'
top_image = r'\mask.png'
predictor_path = r'shape_predictor_68_face_landmarks.dat'
face_cascade = cv.CascadeClassifier(cwd + r'\lbpcas... | code_fim | hard | {
"lang": "python",
"repo": "ishaan95/202-project3",
"path": "/Main/face_replacer.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ishaan95/202-project3 path: /Main/face_replacer.py
import cv2 as cv
import numpy as np
import glob
import os
import numpy
from PIL import Image
import keyboard
from Human_face_detector import human_face_detector
class anime_face_crop:
#get the image without clothings
def __init_... | code_fim | hard | {
"lang": "python",
"repo": "ishaan95/202-project3",
"path": "/Main/face_replacer.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: karahbit/radical.pilot path: /old_tests/test_da_scheduler/test_agent_rm_slurm.py
import os
import shutil
import errno
import unittest
import json
import radical.utils as ru
import radical.pilot as rp
from radical.pilot.agent.rm.slurm import Slurm
import hostlist
try:
import mock
except Imp... | code_fim | hard | {
"lang": "python",
"repo": "karahbit/radical.pilot",
"path": "/old_tests/test_da_scheduler/test_agent_rm_slurm.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> """
Test Slurm with xsede_comet_orte
"""
# Set environment variables
os.environ['SLURM_NODELIST'] = 'nodes[1-2]'
os.environ['SLURM_NPROCS'] = '24'
os.environ['SLURM_NNODES'] = '2'
os.environ['SLURM_CPUS_ON_NODE'] = '24'
# Run compon... | code_fim | hard | {
"lang": "python",
"repo": "karahbit/radical.pilot",
"path": "/old_tests/test_da_scheduler/test_agent_rm_slurm.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Run component with desired configuration
self.component._cfg = self.cfg_xsede_supermic_ssh
self.component._configure()
# Verify configured correctly
self.assertEqual(self.component.cores_per_node, 20)
self.assertEqual(self.component.gpus_per_node, 0)
... | code_fim | hard | {
"lang": "python",
"repo": "karahbit/radical.pilot",
"path": "/old_tests/test_da_scheduler/test_agent_rm_slurm.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|># 1+i factor
a = 1
c = 2
ac = 2
while(ac <= N):
total += math.floor(N/ac)*2*a
ac += c
a += 1
# 1+ni and n+i factor
ilim = math.floor(math.sqrt(N-1))+1
for i in range(2,ilim):
c = i*i+1
ac = c
ai = i+1
while(ac <= N):
total += math.floor(N/ac)*2*ai
ac += c
... | code_fim | medium | {
"lang": "python",
"repo": "Adamssss/projectEuler",
"path": "/pb153.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Adamssss/projectEuler path: /pb153.py
import math
import time
t1 = time.time()
N = 100000000
def gcd(x,y):
if x < y:
temp = x
x = y
y = temp
while y > 0:
temp = x%y
x = y
y = temp
<|fim_suffix|># 1+ni and n+i factor
ilim = math.floor... | code_fim | hard | {
"lang": "python",
"repo": "Adamssss/projectEuler",
"path": "/pb153.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: aniketk21/crawler path: /es.py
# -*- coding: utf-8 -*-
import requests
def insert_url(url, checksum):
'''
insert the `url` and its `checksum` in ES
'''
base = "http://localhost:9200/duplicate_urls/url"
payload = '{"link": "'+url+'", ' + '"checksum": "'+checksum+'"}'
... | code_fim | hard | {
"lang": "python",
"repo": "aniketk21/crawler",
"path": "/es.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> payload = '{' + link + title + body + '}'
#print(payload
headers = {'content-type': 'application/json'}
r = requests.post(url=base, data=payload, headers=headers)
if r.status_code == 201: # 201 Created
return True
print... | code_fim | hard | {
"lang": "python",
"repo": "aniketk21/crawler",
"path": "/es.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def search_url(url):
'''
search the `url` in ES
'''
base = "http://localhost:9200/duplicate_urls/url/_search"
payload = '{"query": {"constant_score": {"filter": {"term": {"link": "' + url + '"}}}}}'
headers = {'content-type': 'application/json'}
res = requests.get(url=... | code_fim | hard | {
"lang": "python",
"repo": "aniketk21/crawler",
"path": "/es.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def test_merge_failure(self):
with self.assertRaises(ValueError):
conf.merge({"a": 1}, {"a": 2})
with self.assertRaises(ValueError):
conf.merge(1, "a")
def test_resolve(self):
self.assertEqual(
conf.resolve_function("unittest.TestCase"),... | code_fim | hard | {
"lang": "python",
"repo": "Mailu/Mailu",
"path": "/core/base/libs/socrate/test.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> for result, *parts in TestConf.MERGE_EXPECTATIONS:
self.assertEqual(result, conf.merge(*parts))
def test_merge_failure(self):
with self.assertRaises(ValueError):
conf.merge({"a": 1}, {"a": 2})
with self.assertRaises(ValueError):
conf.merge(1... | code_fim | hard | {
"lang": "python",
"repo": "Mailu/Mailu",
"path": "/core/base/libs/socrate/test.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Mailu/Mailu path: /core/base/libs/socrate/test.py
import unittest
import io
import os
from socrate import conf, system
class TestConf(unittest.TestCase):
""" Test configuration functions
"""
MERGE_EXPECTATIONS = [
({"a": "1", "b": "2", "c": "3", "d": "4"},
{"a": "... | code_fim | hard | {
"lang": "python",
"repo": "Mailu/Mailu",
"path": "/core/base/libs/socrate/test.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: psu-inversion/LPDM-postprocessing path: /carsurf_loop.py
(wrf_out["wrf_lat"][1])
lon_var.setncatts(wrf_out["wrf_lon"][1])
return grid_mapping
def set_coord_values(ds, wrf_out, footprint_nbins):
"""Set the coordinate variables from wrf_out.
Parameters
----------
ds: net... | code_fim | hard | {
"lang": "python",
"repo": "psu-inversion/LPDM-postprocessing",
"path": "/carsurf_loop.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> # alternate: netCDF4.numtodate(sec_since_start, lpdm_obs_time_unit)
# - simulation_unit
# // datetime.timedelta(hours=OBS_WINDOW)
# use time at the end of the window, not the start
return n_obs_bins - bin_num
print("Bin index for last rel... | code_fim | hard | {
"lang": "python",
"repo": "psu-inversion/LPDM-postprocessing",
"path": "/carsurf_loop.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>def netcdf_compatible_array(arry):
"""Get an array compatible with netCDF dtypes from arry.
Return an array whose dtype is not object.
Assumes object arrays contain a single array.
Parameters
----------
arry: np.ndarray
The array processed
Returns
-------
np.... | code_fim | hard | {
"lang": "python",
"repo": "psu-inversion/LPDM-postprocessing",
"path": "/carsurf_loop.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: PsychedelicPasta/pyFrets path: /guitarfretboard.py
import argparse
from itertools import cycle,dropwhile,islice,product
from prettytable import PrettyTable
from sys import exit
notes = ['A','A#','B','C','C#','D','D#','E','F','F#','G','G#']
cycled_notes = cycle(notes)
def generateScale(rootNote,... | code_fim | hard | {
"lang": "python",
"repo": "PsychedelicPasta/pyFrets",
"path": "/guitarfretboard.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> len_scale = len(scale_notes)
steps = 2
chord_triads = []
for i in range(len_scale):
rootNote = scale_notes[i]
thirdNote = scale_notes[(i+steps)%len_scale]
fifthNote = scale_notes[(i+steps+steps)%len_scale]
chordType = getChordType(rootNote,thirdNote,fifthNote)
chord_triads.append([(rootNote,... | code_fim | hard | {
"lang": "python",
"repo": "PsychedelicPasta/pyFrets",
"path": "/guitarfretboard.py",
"mode": "spm",
"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.