text stringlengths 232 16.3k | domain stringclasses 1
value | difficulty stringclasses 3
values | meta dict |
|---|---|---|---|
<|fim_suffix|> env = jinja2.Environment(loader=loader)
template = loader.load(env, 'index.md')
rendered = template.render({
'data': preprocess_data(read_input(args.input_file))
})
write_output(args.output_file, rendered, force_stdout=args.e or not args.output_file)
if __name__ == '__main_... | code_fim | hard | {
"lang": "python",
"repo": "ihadgraft/lighthouse-reporter",
"path": "/lighthouse2md.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ihadgraft/lighthouse-reporter path: /lighthouse2md.py
from __future__ import print_function
import argparse
import jinja2
import os
import io
import json
import sys
SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__))
def get_args():
example_text = '''
examples:
python %... | code_fim | hard | {
"lang": "python",
"repo": "ihadgraft/lighthouse-reporter",
"path": "/lighthouse2md.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> def should_not_be_item_cart(self):
assert self.is_not_element_present(*BasketPageLocators.BASKET_ITEMS), \
"The basket is not empty"
def should_be_text_item_cart(self):
assert self.is_element_present(*BasketPageLocators.TEXT_NOT_ITEM_BASKET), \
"Success tex... | code_fim | medium | {
"lang": "python",
"repo": "Egor754/autotests_final_project",
"path": "/pages/basket_page.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> def should_be_text_item_cart(self):
assert self.is_element_present(*BasketPageLocators.TEXT_NOT_ITEM_BASKET), \
"Success text is presented, but should not be"<|fim_prefix|># repo: Egor754/autotests_final_project path: /pages/basket_page.py
from .base_page import BasePage
from .loc... | code_fim | hard | {
"lang": "python",
"repo": "Egor754/autotests_final_project",
"path": "/pages/basket_page.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Egor754/autotests_final_project path: /pages/basket_page.py
from .base_page import BasePage
from .locators import BasePageLocators, BasketPageLocators
<|fim_suffix|> def should_be_cart_button(self):
assert self.is_element_present(*BasePageLocators.CART_LINK), "Cart button is not pres... | code_fim | medium | {
"lang": "python",
"repo": "Egor754/autotests_final_project",
"path": "/pages/basket_page.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|>quest',
fields=[
('accept', models.BooleanField(default=False)),
('uuid', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('userFrom', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, relate... | code_fim | hard | {
"lang": "python",
"repo": "Damidara16/Social-Media-React-Native-Django-Example-Api",
"path": "/backend/moji/account/migrations/0001_initial.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Damidara16/Social-Media-React-Native-Django-Example-Api path: /backend/moji/account/migrations/0001_initial.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.23 on 2020-01-09 03:36
from __future__ import unicode_literals
from django.conf import settings
import django.contrib.auth.validators
... | code_fim | hard | {
"lang": "python",
"repo": "Damidara16/Social-Media-React-Native-Django-Example-Api",
"path": "/backend/moji/account/migrations/0001_initial.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|>arField(blank=True, max_length=255, null=True)),
('link1', models.URLField(blank=True, null=True)),
('link2', models.URLField(blank=True, null=True)),
('location', models.CharField(blank=True, max_length=150, null=True)),
('pic', models.FileF... | code_fim | hard | {
"lang": "python",
"repo": "Damidara16/Social-Media-React-Native-Django-Example-Api",
"path": "/backend/moji/account/migrations/0001_initial.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> if not A:
return []
# first word
cur_dict = collections.Counter(c for c in A[0])
# the rest words
for i in range(1, len(A)):
new_dict = collections.Counter(c for c in A[i])
for c in cur_dict:
if c in new_dict:
... | code_fim | hard | {
"lang": "python",
"repo": "xzguy/LeetCode",
"path": "/Problem 1001 - 1100/P1002.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: xzguy/LeetCode path: /Problem 1001 - 1100/P1002.py
import collections
class Solution:
def commonChars(self, A: [str]) -> [str]:
if not A:
return []
# first word
cur_dict = self.get_char_count(A[0])
# the rest words
for i in range(1, len(A))... | code_fim | hard | {
"lang": "python",
"repo": "xzguy/LeetCode",
"path": "/Problem 1001 - 1100/P1002.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> # use counter, same logic
def commonChars_1(self, A: [str]) -> [str]:
if not A:
return []
# first word
cur_dict = collections.Counter(c for c in A[0])
# the rest words
for i in range(1, len(A)):
new_dict = collections.Counter(c for c ... | code_fim | hard | {
"lang": "python",
"repo": "xzguy/LeetCode",
"path": "/Problem 1001 - 1100/P1002.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Key with None are not cached
if key is None:
obj = cls_obj.__new__(cls_obj, key, *args, **kwargs)
old_init(obj, key, *args, **kwargs)
return obj
cached_key = mcs.SENTINEL_KEY if key == sentinel else key
# I... | code_fim | hard | {
"lang": "python",
"repo": "pereirfe/toggl-cli",
"path": "/toggl/utils/metas.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: adeak/AoC2019 path: /day03.py
import numpy as np
def print_wires(origin, wires):
out = np.full(wires.shape[1:], fill_value='.')
for i,layer in enumerate(wires, 1):
out[layer] = str(i)
out[origin[0], origin[1]] = 'o'
print('\n'.join([''.join([c for c in row]) for row in o... | code_fim | hard | {
"lang": "python",
"repo": "adeak/AoC2019",
"path": "/day03.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|>def day03(inp):
origin,wires = get_wires(inp)
#print_wires(origin, wires)
# wires is ~ 700 MB for real input
# mask out origin, find crossings
wires[:, origin[0], origin[1]] = False
crosses = wires.all(0).nonzero()
dists = abs(crosses[0] - origin[0]) + abs(crosses[1] - origin[... | code_fim | hard | {
"lang": "python",
"repo": "adeak/AoC2019",
"path": "/day03.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> # mask out origin, find crossings
wires[:, origin[0], origin[1]] = False
crosses = wires.all(0).nonzero()
dists = abs(crosses[0] - origin[0]) + abs(crosses[1] - origin[1])
closest = dists.argmin()
part1 = dists[closest]
# brute force solver: MemoryError due to floats
#path... | code_fim | hard | {
"lang": "python",
"repo": "adeak/AoC2019",
"path": "/day03.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> http_client = Mock()
http_client.request.return_value = json.dumps({"id": "985ae50937a94c64b392531ea87a0263",
"url": "https://example.com/webhook",
"channelId": "853eeb5348e541a595... | code_fim | hard | {
"lang": "python",
"repo": "messagebird/python-rest-api",
"path": "/tests/test_conversation_webhook.py",
"mode": "spm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> http_client.request.assert_called_once_with('webhooks/webhook-id', 'GET', None)
self.assertEqual(datetime(2019, 4, 3, 8, 41, 37, tzinfo=tzutc()), web_hook.createdDatetime)
self.assertEqual(None, web_hook.updatedDatetime)
self.assertEqual(['conversation.created', 'conversati... | code_fim | hard | {
"lang": "python",
"repo": "messagebird/python-rest-api",
"path": "/tests/test_conversation_webhook.py",
"mode": "spm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: messagebird/python-rest-api path: /tests/test_conversation_webhook.py
import json
import unittest
from datetime import datetime
from unittest.mock import Mock
from dateutil.tz import tzutc
from messagebird import Client
from messagebird.conversation_webhook import \
CONVERSATION_WEBHOOK_EVE... | code_fim | hard | {
"lang": "python",
"repo": "messagebird/python-rest-api",
"path": "/tests/test_conversation_webhook.py",
"mode": "psm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> for state in t.states:
for arc in state.arcs:
print('{} -> {} / {}:{} / {}'.format(state.stateid,
arc.nextstate,
t.isyms.find(arc.ilabel),
t.osyms.find... | code_fim | hard | {
"lang": "python",
"repo": "vagrawal/gsoc-progress",
"path": "/mshah1/ctc.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> t2[x].final=True
return t2
def gen_parents_dict(graph):
parents={}
for state in graph.states:
for arc in state.arcs:
if arc.nextstate in parents:
parents[arc.nextstate].append(state.stateid)
else:
parents[arc.nextst... | code_fim | hard | {
"lang": "python",
"repo": "vagrawal/gsoc-progress",
"path": "/mshah1/ctc.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: vagrawal/gsoc-progress path: /mshah1/ctc.py
import sys
import fst
import random
import math
import numpy as np
from scipy.sparse import bsr_matrix
reload(sys)
sys.setdefaultencoding('utf8')
def ran_lab_prob(n_samps):
r = [random.random() for i in range(138)]
s = sum(r)
... | code_fim | hard | {
"lang": "python",
"repo": "vagrawal/gsoc-progress",
"path": "/mshah1/ctc.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: entirelymagic/Design_Algorithms_in_Python path: /Chapter3/stack_class.py
class Stack:
"""A stack class.
push: add the item to the last level of the stack.
pop: get the last item from the top of the stack.
its_empty: test if the stack is empty.
height: return th... | code_fim | hard | {
"lang": "python",
"repo": "entirelymagic/Design_Algorithms_in_Python",
"path": "/Chapter3/stack_class.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> """:return: the top element from the stack if not empty, else return None."""
if len(self.items) > 0:
return self.items[len(self.items)-1]
else:
return None<|fim_prefix|># repo: entirelymagic/Design_Algorithms_in_Python path: /Chapter3/stack_class.py
class ... | code_fim | hard | {
"lang": "python",
"repo": "entirelymagic/Design_Algorithms_in_Python",
"path": "/Chapter3/stack_class.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> def top_stack(self) -> object or None:
""":return: the top element from the stack if not empty, else return None."""
if len(self.items) > 0:
return self.items[len(self.items)-1]
else:
return None<|fim_prefix|># repo: entirelymagic/Design_Algorithms_in_Py... | code_fim | hard | {
"lang": "python",
"repo": "entirelymagic/Design_Algorithms_in_Python",
"path": "/Chapter3/stack_class.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|>class OverallInsightsEnqueue(webapp.RequestHandler):
"""
Enqueues Overall Insights calculation for a given kind.
"""
def get(self, kind):
taskqueue.add(
target='backend-tasks-b2',
url='/backend-tasks-b2/math/do/overallinsights/{}'.format(kind),
m... | code_fim | hard | {
"lang": "python",
"repo": "the-blue-alliance/the-blue-alliance",
"path": "/old_py2/controllers/cron_controller.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> path = os.path.join(os.path.dirname(__file__), '../templates/math/year_insights_do.html')
self.response.out.write(template.render(path, template_values))
def post(self):
self.get()
class OverallInsightsEnqueue(webapp.RequestHandler):
"""
Enqueues Overall Insights cal... | code_fim | hard | {
"lang": "python",
"repo": "the-blue-alliance/the-blue-alliance",
"path": "/old_py2/controllers/cron_controller.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: the-blue-alliance/the-blue-alliance path: /old_py2/controllers/cron_controller.py
import datetime
import logging
import os
import json
from google.appengine.api import taskqueue
from google.appengine.ext import ndb
from google.appengine.ext import webapp
from google.appengine.ext.webapp import... | code_fim | hard | {
"lang": "python",
"repo": "the-blue-alliance/the-blue-alliance",
"path": "/old_py2/controllers/cron_controller.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: jukim20/Python_Practice path: /Day23/player1.py
import pygame
class Player(ImgBase):
def __init__(self, x, y, w, h, speed):
super().__init__("plane.png", x, y, w, h, speed)
self.isLeft = False
self.isRight = False
self.bullets = []
def keyDown(self, key):... | code_fim | hard | {
"lang": "python",
"repo": "jukim20/Python_Practice",
"path": "/Day23/player1.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> self.key = key
if self.key == pygame.K_d:
self.isRight = False
if self.key == pygame.K_a:
self.isLeft = False
def move(self):
if self.isRight == True:
self.x += self.speed
if self.isLeft == True:
self.x -= self.speed... | code_fim | hard | {
"lang": "python",
"repo": "jukim20/Python_Practice",
"path": "/Day23/player1.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def search(self):
"""searches facts after substituting
with bindings
"""
term = self.substitute()
##print ("searching:",term)
##print ("in facts",self.facts)
##input()
bindings = deepcopy(self.bindings)
found = False
... | code_fim | hard | {
"lang": "python",
"repo": "kauroy1994/Top-down-induction-of-logical-decision-tree",
"path": "/Prover.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: kauroy1994/Top-down-induction-of-logical-decision-tree path: /Prover.py
import string
from copy import deepcopy
class Proof_node(object):
def __init__(self,literal,bindings,facts):
"""proof node during backtracking
"""
self.literal = literal
self.bindings = ... | code_fim | hard | {
"lang": "python",
"repo": "kauroy1994/Top-down-induction-of-logical-decision-tree",
"path": "/Prover.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> #if no rule body then trivially true
if not rule.split(':-')[1]:
return True
#assume example is true
proved = True
#collect head variables and bind to example atoms
bindings = {}
head = rule.split(':-')[0].strip()
... | code_fim | hard | {
"lang": "python",
"repo": "kauroy1994/Top-down-induction-of-logical-decision-tree",
"path": "/Prover.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|>all_schools_df = pd.DataFrame(filtered_schools)
all_schools_df.fillna(value='', inplace=True)
all_schools_df = all_schools_df[['****']]
all_schools_df.rename(
columns={'****'},
inplace=True
)
##########################################################################################
#Initialize v... | code_fim | hard | {
"lang": "python",
"repo": "Arvind-Bala/Arvind-Work-Samples",
"path": "/data_etl.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|>##########################################################################################
#Initialize variables for Upswing API Call
upswing_api_secret = '****'
url = '****'
headers = {
'Content-Type': 'application/json',
'****': upswing_api_secret,
'Accept': 'application/json'
}
... | code_fim | hard | {
"lang": "python",
"repo": "Arvind-Bala/Arvind-Work-Samples",
"path": "/data_etl.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Arvind-Bala/Arvind-Work-Samples path: /data_etl.py
import requests
import pandas as pd
import json
import datetime
import pprint
pp = pprint.PrettyPrinter(indent=4)
streak_api_key = '****'
pipeline_url = '****'
call_headers = {'content-type' : 'application/json'}
upswing_pipeline_key = ''****''
... | code_fim | hard | {
"lang": "python",
"repo": "Arvind-Bala/Arvind-Work-Samples",
"path": "/data_etl.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: erezhuri/erez-py path: /fromFluent/Telnet_Basic_Test.py
#!/usr/bin/env python
import sys, os, telnetlib, pyodbc, re, logging #, math, commands, cPickle, datetime, shutil, _mssql,
#sys.path.append("/mobileye/shared/scripts/QA_Bundle_scripts/lib/")
from E_lib import *
color = paintText()
def sta... | code_fim | hard | {
"lang": "python",
"repo": "erezhuri/erez-py",
"path": "/fromFluent/Telnet_Basic_Test.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> # set up logging to file - see previous section for more details
logging.basicConfig(level=logging.INFO,#level=logging.DEBUG
format='%(asctime)s,%(levelname)-8s,%(message)s',
#format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M',
filename=logFileName,
... | code_fim | hard | {
"lang": "python",
"repo": "erezhuri/erez-py",
"path": "/fromFluent/Telnet_Basic_Test.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Ledoux/ShareYourSystem path: /Pythonlogy/draft/Noders/Parenter/__init__.py
# -*- coding: utf-8 -*-
"""
<DefineSource>
@Date : Fri Nov 14 13:20:38 2014 \n
@Author : Erwan Ledoux \n\n
</DefineSource>
A Parenter completes the list of grand-parent nodes that
a child node could have. It acts only... | code_fim | hard | {
"lang": "python",
"repo": "Ledoux/ShareYourSystem",
"path": "/Pythonlogy/draft/Noders/Parenter/__init__.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> #Check
if len(self.ParentedDeriveParentersList)>0:
self.ParentedTopDeriveParenterVariable=self.ParentedDeriveParentersList[-1]
else:
self.ParentedTopDeriveParenterVariable=self
#Link
self.update(
zip(
self.ParentingTopPickVariablesList,
self.ParentedTopDerive... | code_fim | hard | {
"lang": "python",
"repo": "Ledoux/ShareYourSystem",
"path": "/Pythonlogy/draft/Noders/Parenter/__init__.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Look for subscriptions(s1) that ended on 'threshold_day' (having length > 5)
# and join them with the same user|type future subscriptions (s2) (having length > 5)
# that start within 'self.churn_threshold_in_days'
sql = '''
SELECT s1.user_id AS user_id, s1.end_tim... | code_fim | hard | {
"lang": "python",
"repo": "remp2020/pythia-tools",
"path": "/aggregate/utils/subscriptions_churn_events.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: remp2020/pythia-tools path: /aggregate/utils/subscriptions_churn_events.py
from __future__ import print_function
from datetime import timedelta
import pandas
class Event:
def __init__(self, user_id, time, type):
self.user_id = user_id
self.time = time
self.type = typ... | code_fim | hard | {
"lang": "python",
"repo": "remp2020/pythia-tools",
"path": "/aggregate/utils/subscriptions_churn_events.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: KenleyArai/python-algorithms path: /tests/test_linkedlist.py
from Datastructures import LinkedList
class TestLinkedList:
def test_init(self):
ll = LinkedList()
assert ll.head.val is None
assert ll.head.next is None
def test_insert(self):
ll = LinkedLis... | code_fim | hard | {
"lang": "python",
"repo": "KenleyArai/python-algorithms",
"path": "/tests/test_linkedlist.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> ptr = ptr.next
assert ptr.val == 5
def test_search(self):
ll = LinkedList()
ll.insert(5)
ll.insert(25)
ll.insert("k")
ll.insert(98)
ll.insert("String")
test_node = ll.search("k")
assert test_node.val == "k"
t... | code_fim | medium | {
"lang": "python",
"repo": "KenleyArai/python-algorithms",
"path": "/tests/test_linkedlist.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> test_node = ll.search("k")
assert test_node.val == "k"
test_node = ll.search("Not there")
assert test_node is None
def test_delete_node(self):
ll = LinkedList()
ll.insert(25)
ll.insert(98)
ll.insert(105)
ll.delete_node(25)
... | code_fim | hard | {
"lang": "python",
"repo": "KenleyArai/python-algorithms",
"path": "/tests/test_linkedlist.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> # 3.1 根据n1_high和n2_low来定义买入卖出的信号序列
# 注意,是当天的收盘价,高于昨天以前的n1值,就买入,不能包括今天的,因为今天的收盘价,怎么也不会高于今天的最高值
buy_signal=kl_pd[kl_pd.close > kl_pd.n1_high.shift(1)].index
kl_pd.loc[buy_signal,'signal']=1
# 3.2 n2_low的卖出信号同理
sell_signal=kl_pd[kl_pd.close < kl_pd.n2_low.shift(1)].index
kl_pd.loc... | code_fim | hard | {
"lang": "python",
"repo": "JillWang777/QuantantiveSystem",
"path": "/Section7/Section7_1_3.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> # 5. 基准收益,是指我从一开始就持有,然后一直到最后才卖的收益
# 5.1 计算每天基准收益
kl_pd['benchmark_profit']=kl_pd['close']/kl_pd['close'].shift(1)-1
# 5.2 计算策略每天收益
kl_pd['trend_profit']=kl_pd['keep']*kl_pd['benchmark_profit']
# 5.3 计算累加基准收益和策略收益
kl_pd['benchmark_profit_accum']=kl_pd['benchmark_profit'].cumsum(... | code_fim | hard | {
"lang": "python",
"repo": "JillWang777/QuantantiveSystem",
"path": "/Section7/Section7_1_3.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: JillWang777/QuantantiveSystem path: /Section7/Section7_1_3.py
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from abupy import ABuSymbolPd
if __name__ == '__main__':
kl_pd=ABuSymbolPd.make_kl_df('TSLA',n_folds=2)
# 1、这里采用N日趋势突破,即超过N1天内的最高价,就买入,低于N2天内的最低价,就卖出
N... | code_fim | hard | {
"lang": "python",
"repo": "JillWang777/QuantantiveSystem",
"path": "/Section7/Section7_1_3.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: taoualiw/Data-Science-Basics path: /Data-Visualization/.ipynb_checkpoints/figconfig-checkpoint.py
import matplotlib.pyplot as plt
from matplotlib import rc
import numpy as np
# Set the global font to be DejaVu Sans, size 10 (or any other sans-serif font of your choice!)
rc('font',**{'family':'san... | code_fim | hard | {
"lang": "python",
"repo": "taoualiw/Data-Science-Basics",
"path": "/Data-Visualization/.ipynb_checkpoints/figconfig-checkpoint.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> return ax
def custom_boxplot(ax, x, y, error, xlims, ylims, mediancolor='magenta'):
"""Customized boxplot with solid black lines for box, whiskers, caps, and outliers."""
medianprops = {'color': mediancolor, 'linewidth': 2}
boxprops = {'color': 'black', 'linestyle': '-'}
whiskerprops... | code_fim | hard | {
"lang": "python",
"repo": "taoualiw/Data-Science-Basics",
"path": "/Data-Visualization/.ipynb_checkpoints/figconfig-checkpoint.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> """Initializes the database."""
init_db()
print('Initialized the database.')
@app.teardown_appcontext
def close_db(error):
"""Closes the database again at the end of the request."""
if hasattr(g, 'sqlite_db'):
g.sqlite_db.close()
if __name__ == '__main__':
app.run()<|fi... | code_fim | hard | {
"lang": "python",
"repo": "geegog/app",
"path": "/app.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: geegog/app path: /app.py
import os
from flask import Flask, g
from services import dao
from controllers import user, auth
app = Flask(__name__)
app.config.from_object(__name__)
app.register_blueprint(user.get_user)
app.register_blueprint(user.user_page)
app.register_blueprint(user.register_us... | code_fim | hard | {
"lang": "python",
"repo": "geegog/app",
"path": "/app.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ryan81120/-Noise-reduction path: /CuDNNLSTM.py
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from keras.models import Sequential, model_from_json, load_model
from keras.... | code_fim | hard | {
"lang": "python",
"repo": "ryan81120/-Noise-reduction",
"path": "/CuDNNLSTM.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> noisy=np.reshape(noisy,(1,np.shape(noisy)[0],1))
rate, clean = wavfile.read(clean_path[index])
clean=clean.astype('float32')
if len(clean.shape)==2:
clean=(clean[:,0]+clean[:,1])/2
clean=clean/2**15
clean=np.reshape(clean,(1,np.shap... | code_fim | hard | {
"lang": "python",
"repo": "ryan81120/-Noise-reduction",
"path": "/CuDNNLSTM.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|>##建立模型
start_time = time.time()
model = Sequential()
model.add(CuDNNLSTM(32,return_sequences=True,input_shape=(None,1)))
model.add(CuDNNLSTM(32,return_sequences=True)) # 返回维度为 32 的向量序列
model.add(Dense(1,activation='tanh'))
model.summary()
##訓練開始
epoch=5
batch_size=1
model.compile(loss='mse', optimizer='... | code_fim | hard | {
"lang": "python",
"repo": "ryan81120/-Noise-reduction",
"path": "/CuDNNLSTM.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|>## TODO: The following two methods needs to be generalized
## given a scan, offer analyses options
def getScanView(self, scan):
# this is a shortcut for now, in the future the view would be
# an overview of the entry with ability to open different analyses
if isinstance(scan, p... | code_fim | hard | {
"lang": "python",
"repo": "praxes/praxes",
"path": "/praxes/frontend/mainwindow.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: praxes/praxes path: /praxes/frontend/mainwindow.py
"""
"""
from __future__ import absolute_import
import logging
import sys
import os
from PyQt4 import QtCore, QtGui, uic
import praxes
from .ui import resources
from .phynx import FileModel, FileView, ExportRawCSV, ExportCorrectedCSV
from prax... | code_fim | hard | {
"lang": "python",
"repo": "praxes/praxes",
"path": "/praxes/frontend/mainwindow.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|>print(f'(hex) x is {x:02x}, y is {y:02x}, z is {z:02x}')
print(f'(bin) x is {x:08b}, y is {y:08b}, z is {z:08b}')<|fim_prefix|># repo: IADT-y3-CMT-SWD/python_examples path: /Week03/bitwise.py
#!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
<|fim_middle|>r = 228
g = 00
b = 80
z = x >> y
... | code_fim | easy | {
"lang": "python",
"repo": "IADT-y3-CMT-SWD/python_examples",
"path": "/Week03/bitwise.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: IADT-y3-CMT-SWD/python_examples path: /Week03/bitwise.py
#!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
<|fim_suffix|>print(f'(hex) x is {x:02x}, y is {y:02x}, z is {z:02x}')
print(f'(bin) x is {x:08b}, y is {y:08b}, z is {z:08b}')<|fim_middle|>r = 228
g = 00
b = 80
z = x >> y
... | code_fim | easy | {
"lang": "python",
"repo": "IADT-y3-CMT-SWD/python_examples",
"path": "/Week03/bitwise.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|>if __name__ == "__main__":
if len(sys.argv) < 2:
sys.stderr.write("Usage: define [word]")
sys.exit(1)
console = Console()
curl_setup(sys.argv[1], console)
try:
req.perform()
console.print_content()
except pycurl.error, error:
errno, errstr = error
sys.stderr.write("Error {0}: {1}".forma... | code_fim | hard | {
"lang": "python",
"repo": "Hydrotoast/ConsoleDefine",
"path": "/define",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Hydrotoast/ConsoleDefine path: /define
#!/usr/bin/env python
import sys
import pycurl
class Console(object):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Console, cls).__new__(cls,
*args, **kwargs)
return cls._instance
def __init... | code_fim | hard | {
"lang": "python",
"repo": "Hydrotoast/ConsoleDefine",
"path": "/define",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: aaltinisik/CybroAddons path: /amount_currency_purchase/models/purchase.py
# -*- coding: utf-8 -*-
import re
from odoo import api, models, fields, _
class PurchaseCurrency(models.Model):
_inherit = 'purchase.order'
<|fim_suffix|> def find_amount(self):
for this in self:
... | code_fim | medium | {
"lang": "python",
"repo": "aaltinisik/CybroAddons",
"path": "/amount_currency_purchase/models/purchase.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> company_currency_amount = fields.Float(string='Company Currency Total', compute='find_amount')
def find_amount(self):
for this in self:
price = self.env['res.currency']._compute(this.currency_id, this.company_id.currency_id, this.amount_total)
this.company_currency... | code_fim | easy | {
"lang": "python",
"repo": "aaltinisik/CybroAddons",
"path": "/amount_currency_purchase/models/purchase.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: qs/awesomeproject path: /suggestions.py
from collections import OrderedDict
class Suggestions:
def __init__(self, db):
self.db = db
self.healthy_replacements = {
'6410405082657': '6410405113153'
}
def get_ranked_suggestions(self, username, user_prefe... | code_fim | hard | {
"lang": "python",
"repo": "qs/awesomeproject",
"path": "/suggestions.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> def ranked_suggestions(self, suggerstions, user_preferences):
pref_lookup = {'coop': 'cheap', 'replace': 'sustainability', 'borrow': 'comfort'}
result_suggestions = OrderedDict()
for suggerstion in suggerstions:
for k, v in suggerstion.items():
if v ... | code_fim | hard | {
"lang": "python",
"repo": "qs/awesomeproject",
"path": "/suggestions.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: hjkelly/django-flexible-content path: /flexible_content/default_item_types/forms.py
from django import forms
from django.utils.translation import ugettext as _
from django.utils import simplejson
import requests
from flexible_content.forms import BaseItemForm
from .models import Video
class V... | code_fim | hard | {
"lang": "python",
"repo": "hjkelly/django-flexible-content",
"path": "/flexible_content/default_item_types/forms.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Validate using Vimeo's API:
elif service == 'vimeo':
data = requests.get('http://vimeo.com/api/v2/video/{}.json'.
format(video_id))
# Ensure we can parse the JSON data.
try:
json = simplejson.loads(data.t... | code_fim | hard | {
"lang": "python",
"repo": "hjkelly/django-flexible-content",
"path": "/flexible_content/default_item_types/forms.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> """Opens a txt file & loads each line into a set"""
with txt_file_reader(path) as txt_file:
return {value_type(line.strip()) for line in txt_file}
def load_dict_from_txt_file(path, key_type=str, value_type=str):
"""Opens a txt file and loads tab-separated columns into a dictionary"""... | code_fim | hard | {
"lang": "python",
"repo": "lspss93189/scrappybara",
"path": "/scrappybara/utils/files.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: lspss93189/scrappybara path: /scrappybara/utils/files.py
import bz2
import os
import pickle
import scrappybara.config as cfg
def path_exists(path):
"""Whether a file/directory exists"""
return os.path.exists(path)
def files_in_dir(path):
"""Returns a list of filenames found in a ... | code_fim | hard | {
"lang": "python",
"repo": "lspss93189/scrappybara",
"path": "/scrappybara/utils/files.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> month_savings = get_month_savings(month_salary, portion_saved)
for month in range(1, TOTAL_MONTHS+1):
if is_raised_month(month):
month_savings = raise_month_savings(month_savings, SEMI_ANNUAL_RAISE)
savings += savings * MONTH_RETURN # add months invest return
s... | code_fim | hard | {
"lang": "python",
"repo": "nyasho4ka/MIT_6.0001",
"path": "/problem_set_1/ps1c.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: nyasho4ka/MIT_6.0001 path: /problem_set_1/ps1c.py
MONTH_COUNT = 12
ANNUAL_RETURN = 0.04
MONTH_RETURN = ANNUAL_RETURN / MONTH_COUNT
SEMI_ANNUAL_RAISE = 0.07
PORTION_SAVED = 0.5
TOTAL_MONTHS = 36
TOTAL_COST = 1_000_000
PORTION_DOWN_PAYMENT = 0.25
PORTION_COST = TOTAL_COST * PORTION_DOWN_PAYMENT
... | code_fim | hard | {
"lang": "python",
"repo": "nyasho4ka/MIT_6.0001",
"path": "/problem_set_1/ps1c.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: rexdiamante28/philsteel path: /models/cicf/cicf.py
# -*- coding: utf-8 -*-
from odoo import models, fields, api
class CICF(models.Model):
_name = 'philsteel.cicf'
jobsite_image = fields.Binary()
cicf_no = fields.Char(string="CICF. No:")
concern_dept = fields.Char(string='Concerned Departme... | code_fim | hard | {
"lang": "python",
"repo": "rexdiamante28/philsteel",
"path": "/models/cicf/cicf.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|>
@api.multi
def action_approved(self):
for visit in self:
visit.statuss = 'solved'
return True
@api.onchange('name')
def get_proj_details(self):
for recorda in self:
recorda.client = recorda.name.customer_name
recorda.ic_no = recorda.name.ic_no
recorda.sc_no = recorda.name.sc_no
... | code_fim | hard | {
"lang": "python",
"repo": "rexdiamante28/philsteel",
"path": "/models/cicf/cicf.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: yshao06/CTBA path: /0908_Submitted_html_scrape.py
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 08 00:34:08 2017
@author: micsh
"""
# Import regular expression and BeautifulSoup package
import requests
from bs4 import BeautifulSoup as bsoup
<|fim_suffix|># Create an empty list to a... | code_fim | hard | {
"lang": "python",
"repo": "yshao06/CTBA",
"path": "/0908_Submitted_html_scrape.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|># Create an empty list to append all the results
result_list = []
# Go into each block of 'tr', which contains 'County', 'State' and 'Registration Rate'
# Create an empty list to compile data from each row
for row in target_rows:
record = []
# In each block, iterate through 'td' to extract value... | code_fim | hard | {
"lang": "python",
"repo": "yshao06/CTBA",
"path": "/0908_Submitted_html_scrape.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Paulinholeo/wtxi path: /wtxi.py
import os
import time
import threading
import datetime
import psutil
from check_bricap import *
from logger import logger
import cfg
__author__ = "Paulo/Giovanne"
__copyright__ = "Copyright 2019, Brascontrol"
__status__ = "Development"
#Cria thread
class MainC... | code_fim | hard | {
"lang": "python",
"repo": "Paulinholeo/wtxi",
"path": "/wtxi.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|>def verificaTempo():
arquivoAntigo = leArquivo()
time.sleep(cfg.TEMPO_MAX_TXI)
arquivoNovo = leArquivo()
if arquivoAntigo == arquivoNovo:
return False
else:
return True
def main():
verificaTxi= MainClass()
verificaBri = SecondClass()
verificaBri.start()
... | code_fim | hard | {
"lang": "python",
"repo": "Paulinholeo/wtxi",
"path": "/wtxi.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> # 获取登录错误提示文本/toast
def get_error_text(self, toast):
if self.element_is_exist(page.error_txt):
return self.find_element(page.error_txt).text
else:
return self.driver.find_element_by_xpath(f"//*[contains(@text,'{toast}')]").text
def screenshot(self):
... | code_fim | hard | {
"lang": "python",
"repo": "lzy221180312/app-liantongyun",
"path": "/page/login_page.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: lzy221180312/app-liantongyun path: /page/login_page.py
import time
import page
from bases.base import Base
class LoginPage(Base):
def agree(self):
# 点击同意
self.click(page.agree_btn)
def login(self, username, pwd):
# 点击密码登录
self.click(page.pwd_login_link)... | code_fim | hard | {
"lang": "python",
"repo": "lzy221180312/app-liantongyun",
"path": "/page/login_page.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|>last = ans[-1]
ans = ans[:-1]
ind = alp1.index(last)
ind = (ind+K)%26
ans += alp1[ind]
print(ans)
else:
print(ans)<|fim_prefix|># repo: Aasthaengg/IBMdataset path: /Python_codes/p03994/s626270893.py
alp1 = list('abcdefghijklmnopqrstuvwxyz'[::-1])
num = [i for i in range(1,26)]
alp... | code_fim | hard | {
"lang": "python",
"repo": "Aasthaengg/IBMdataset",
"path": "/Python_codes/p03994/s626270893.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Aasthaengg/IBMdataset path: /Python_codes/p03994/s626270893.py
alp1 = list('abcdefghijklmnopqrstuvwxyz'[::-1])
num = [i for i in range(1,26)]
alp = {}
for a,n in zip(alp1,num):
alp[a] = n
s = inpu<|fim_suffix|>last = ans[-1]
ans = ans[:-1]
ind = alp1.index(last)
ind = (ind+K)%26
... | code_fim | hard | {
"lang": "python",
"repo": "Aasthaengg/IBMdataset",
"path": "/Python_codes/p03994/s626270893.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|>from django.core.wsgi import get_wsgi_application
#os.environ.setdefault("DJANGO_SETTINGS_MODULE", "onlinerequest.settings")
os.environ["DJANGO_SETTINGS_MODULE"] = "onlinerequest.settings"
application = get_wsgi_application()<|fim_prefix|># repo: rdadolfo/onlinerequest-dev path: /wsgi.py
"""
WSGI confi... | code_fim | hard | {
"lang": "python",
"repo": "rdadolfo/onlinerequest-dev",
"path": "/wsgi.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: rdadolfo/onlinerequest-dev path: /wsgi.py
"""
WSGI config for onlinerequest project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
<|fim_suffix|>import os
... | code_fim | medium | {
"lang": "python",
"repo": "rdadolfo/onlinerequest-dev",
"path": "/wsgi.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|>
@dataclass
class GenericDataClass:
@classmethod
def from_json(cls, input: Union[str, Dict]):
if isinstance(input, str):
input = json.loads(input)
input = _check_fields(input, cls)
return cls(**input)
@dataclass
class EventClass(GenericDataClass):
@classme... | code_fim | medium | {
"lang": "python",
"repo": "hypoport/python-aws-dataclasses",
"path": "/aws_dataclasses/base.py",
"mode": "spm",
"license": "Python-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> for i in range(len(obs)-1):
c2 += min(rate, obs[i])
writeLine("Case #{}: {} {}".format(t+1, c1, c2))<|fim_prefix|># repo: pkpio/codejam path: /2015/round-1A/a.py
from common import *
T = readInt()
for t in range(T):
_,obs = readInt(),readIntArr()
c1, c2, rate = 0,0,0
<|fim_midd... | code_fim | medium | {
"lang": "python",
"repo": "pkpio/codejam",
"path": "/2015/round-1A/a.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> writeLine("Case #{}: {} {}".format(t+1, c1, c2))<|fim_prefix|># repo: pkpio/codejam path: /2015/round-1A/a.py
from common import *
T = readInt()
for t in range(T):
_,obs = readInt(),readIntArr()
c1, c2, rate = 0,0,0
for i in range(len(obs)-1):
rate = max(rate, obs[i]-obs[i+1])
... | code_fim | medium | {
"lang": "python",
"repo": "pkpio/codejam",
"path": "/2015/round-1A/a.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: pkpio/codejam path: /2015/round-1A/a.py
from common import *
T = readInt()
for t in range(T):
_,obs = readInt(),readIntArr()
c1, c2, rate = 0,0,0
for i in range(len(obs)-1):
rate = max(rate, obs[i]-obs[i+1])
if obs[i]-obs[i+1] > 0:
c1 += obs[i]-obs[i+1]
<... | code_fim | medium | {
"lang": "python",
"repo": "pkpio/codejam",
"path": "/2015/round-1A/a.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|>@router.post("/booking", status_code=201, response_model=BookingModelOut)
async def create_user_booking(booking_model: BookingModelIn):
logger.info(f'Booking IN: {booking_model}')
return await create_booking(booking_model)<|fim_prefix|># repo: OrestOhorodnyk/two-phase-commit path: /app/api.py
imp... | code_fim | medium | {
"lang": "python",
"repo": "OrestOhorodnyk/two-phase-commit",
"path": "/app/api.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: OrestOhorodnyk/two-phase-commit path: /app/api.py
import logging
from fastapi import APIRouter
from app.db.models import (
AccountModelIn,
AccountModelOut,
BookingModelIn,
BookingModelOut,
)
from app.service import (
create_account,
create_booking,
)
router = APIRouter(... | code_fim | hard | {
"lang": "python",
"repo": "OrestOhorodnyk/two-phase-commit",
"path": "/app/api.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|>@router.post("/account", status_code=201, response_model=AccountModelOut)
async def create_user_account(account: AccountModelIn):
return await create_account(account)
@router.post("/booking", status_code=201, response_model=BookingModelOut)
async def create_user_booking(booking_model: BookingModelIn... | code_fim | medium | {
"lang": "python",
"repo": "OrestOhorodnyk/two-phase-commit",
"path": "/app/api.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> self.X_train, self.X_test, self.X_valid = self.features
self.y_train, self.y_test, self.y_valid = self.labels
self.class_weights = (1, sum(self.y_train == 0) / sum(self.y_train == 1))
def predict_test(self, test_df: pd.DataFrame):
lnr = test_df['LNR']
test_df... | code_fim | hard | {
"lang": "python",
"repo": "Jair-Ai/arvatoKaggle",
"path": "/process_and_ml/train.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> return grid_result
def train(self, model, params, tags, run_name: Optional[str], experiment_name: str, data: Optional[Dict[str, np.array]]=None):
model = model(**params)
experiment_id = create_experiment(experiment_name=experiment_name)
if not data:
x = s... | code_fim | hard | {
"lang": "python",
"repo": "Jair-Ai/arvatoKaggle",
"path": "/process_and_ml/train.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Jair-Ai/arvatoKaggle path: /process_and_ml/train.py
from collections import namedtuple
from typing import Optional, Union, Dict, List
import mlflow
import pandas as pd
import numpy as np
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import RepeatedStratifiedKFold, GridSe... | code_fim | hard | {
"lang": "python",
"repo": "Jair-Ai/arvatoKaggle",
"path": "/process_and_ml/train.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> print("Coefficients: ", model.coef_)
print("Intercept: ", model.intercept_)
print("Regression Equation: y = %.4fx+%.4f" %(model.coef_, model.intercept_))
print("Mean squared error: %.2f" % mean_squared_error(yTest, predictions))
print('Variance score: %.2f' % r2_score(yTest, prediction... | code_fim | hard | {
"lang": "python",
"repo": "sayedkamal2016/pharmacy-AWP-predictor",
"path": "/code.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: sayedkamal2016/pharmacy-AWP-predictor path: /code.py
import sys
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
import random
from openpyxl import Workbook, load_workbook
def outputToExcel(file... | code_fim | hard | {
"lang": "python",
"repo": "sayedkamal2016/pharmacy-AWP-predictor",
"path": "/code.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> totalSales = []
acq = []
awp = []
randomizedLines = lines[1:]
random.shuffle(randomizedLines)
# Fetch data that fall within certain criteria
for line in randomizedLines:
d,ndc,desc,qty,p,s,c,sales,acqCosts,profit,margin,dawcode,manu,acqUnit,price= parse(line)
... | code_fim | hard | {
"lang": "python",
"repo": "sayedkamal2016/pharmacy-AWP-predictor",
"path": "/code.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> response = self.client.get('/posts?order=-id&limit=2&offset=2')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.json()), 2)
self.assertSequenceEqual(list(map(itemgetter('title'), response.json())), ['Title 28', 'Title 27', ])
de... | code_fim | hard | {
"lang": "python",
"repo": "ttheapathy/hn-app",
"path": "/app/root/tests.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ttheapathy/hn-app path: /app/root/tests.py
from operator import itemgetter
from django.test import TestCase, Client
from django.conf import settings
from rest_framework import status
from .models import Post
from .views import PostSerializer
class PostTestCase(TestCase):
def setUp(self):... | code_fim | hard | {
"lang": "python",
"repo": "ttheapathy/hn-app",
"path": "/app/root/tests.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> response = self.client.get('/posts')
posts = Post.objects.all()[:settings.REST_FRAMEWORK.get('PAGE_SIZE')]
serializer = PostSerializer(posts, many=True)
self.assertEqual(response.data, serializer.data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
... | code_fim | hard | {
"lang": "python",
"repo": "ttheapathy/hn-app",
"path": "/app/root/tests.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: neoeno/advent_of_code_2018 path: /day-09/9-2.py
from collections import defaultdict
class CircularList():
def __init__(self, items):
self.items = items
self.dead = False
def get(self, place):
if self.dead: raise "Operating on dead list"
return self.items[... | code_fim | hard | {
"lang": "python",
"repo": "neoeno/advent_of_code_2018",
"path": "/day-09/9-2.py",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> def format_item(n):
if n == self.get(0): return f">{n: 3}"
return f" {n: 3}"
return " ".join(format_item(item) for item in self.circular_list.format())
def iterate(list, n):
if n % 23 == 0:
removed, list = list.remove(-7)
return n + removed, lis... | code_fim | hard | {
"lang": "python",
"repo": "neoeno/advent_of_code_2018",
"path": "/day-09/9-2.py",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.