text stringlengths 232 16.3k | domain stringclasses 1
value | difficulty stringclasses 3
values | meta dict |
|---|---|---|---|
<|fim_suffix|> op.create_table(
'daily_bar_data',
sa.Column('timestamp', sa.DateTime, primary_key=True),
sa.Column('symbol_id', sa.Integer, sa.ForeignKey('symbols.symbol_id'), primary_key=True),
sa.Column('open_price', sa.Float),
sa.Column('high_price', sa.Float),
sa.C... | code_fim | medium | {
"lang": "python",
"repo": "webclinic017/LJWEquities",
"path": "/alembic/versions/38051cbde0f9_added_dailybar_table.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: myoons/image-gpt-pytorch path: /utils/torch_utils.py
import os
import math
import torch
import logging
import platform
from torch.optim.lr_scheduler import LambdaLR
logger = logging.getLogger(__name__)
def set_optimizer(config, model):
# separate out all parameters to those that will and ... | code_fim | hard | {
"lang": "python",
"repo": "myoons/image-gpt-pytorch",
"path": "/utils/torch_utils.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def select_device(args, batch_size=None):
s = f'Image-GPT-PyTorch 🚀 '
cpu = args.device.lower() == 'cpu'
if cpu:
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
elif args.device:
os.environ['CUDA_VISIBLE_DEVICES'] = args.device # set environment variable
assert torch.c... | code_fim | hard | {
"lang": "python",
"repo": "myoons/image-gpt-pytorch",
"path": "/utils/torch_utils.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>_seed
import os
# Name should didn't be changed as it need to align with pypi
NAME = "pypi_seed"
# Change the version everytime when a upload to pypi to issue a new version
VERSION = "1.0.9"<|fim_prefix|># repo: py4ever/pypi_seed path: /pypi_seed/setting.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
... | code_fim | medium | {
"lang": "python",
"repo": "py4ever/pypi_seed",
"path": "/pypi_seed/setting.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: py4ever/pypi_seed path: /pypi_seed/setting.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/9/11 10:07 上午
# @Author : LeiXueWe<|fim_suffix|>_seed
import os
# Name should didn't be changed as it need to align with pypi
NAME = "pypi_seed"
# Change the version everytime when a upload... | code_fim | medium | {
"lang": "python",
"repo": "py4ever/pypi_seed",
"path": "/pypi_seed/setting.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Add word to list
if repeat == False:
passphrase += (word.strip('\n').capitalize() + str(randint(1,9)))
n += 1
print()
print(passphrase)
print()<|fim_prefix|># repo: nanohard/word_generator path: /pass.py
#!/usr/bin/env python3
from subprocess import Popen, PIPE
from random imp... | code_fim | medium | {
"lang": "python",
"repo": "nanohard/word_generator",
"path": "/pass.py",
"mode": "spm",
"license": "Unlicense",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Check word for apostrophe; discard if true.
for c in word:
if c == "'":
repeat = True
break
else:
repeat = False
# Add word to list
if repeat == False:
passphrase += (word.strip('\n').capitalize() + str(randint(1,9)))
n... | code_fim | hard | {
"lang": "python",
"repo": "nanohard/word_generator",
"path": "/pass.py",
"mode": "spm",
"license": "Unlicense",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: nanohard/word_generator path: /pass.py
#!/usr/bin/env python3
from subprocess import Popen, PIPE
from random import randint
print()
number_of_words = int(input('How many words? '))
passphrase = ''
n = 0
while n < number_of_words:
repeat = False
<|fim_suffix|> # Add word to list
if ... | code_fim | hard | {
"lang": "python",
"repo": "nanohard/word_generator",
"path": "/pass.py",
"mode": "psm",
"license": "Unlicense",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: briannemsick/barrage path: /barrage/dataset/loader.py
from typing import Optional
import numpy as np
from barrage import api
class KeySelector(api.RecordLoader):
"""Record loader for directly transforming keys from a record into a data record.
Args:
mode: RecordMode, load mod... | code_fim | hard | {
"lang": "python",
"repo": "briannemsick/barrage",
"path": "/barrage/dataset/loader.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def load(self, record: api.Record) -> api.DataRecord:
"""Load a record by selecting keys corresponding to inputs, outputs, and
maybe sample weights.
Args:
record: Record, record.
Returns:
DataRecord, data record.
"""
def _index... | code_fim | hard | {
"lang": "python",
"repo": "briannemsick/barrage",
"path": "/barrage/dataset/loader.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> X = {k: _index_dict_to_arr(record, v) for k, v in self.inputs.items()}
if self.mode == api.RecordMode.TRAIN or self.mode == api.RecordMode.VALIDATION:
y = {k: _index_dict_to_arr(record, v) for k, v in self.outputs.items()}
if self.sample_weights is not None:
... | code_fim | hard | {
"lang": "python",
"repo": "briannemsick/barrage",
"path": "/barrage/dataset/loader.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: dupeljan/nncf path: /nncf/torch/quantization/default_quantization.py
"""
Copyright (c) 2021 Intel Corporation
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 the License at
http://w... | code_fim | hard | {
"lang": "python",
"repo": "dupeljan/nncf",
"path": "/nncf/torch/quantization/default_quantization.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>DEFAULT_PT_QUANT_TRAIT_TO_OP_DICT = {
QuantizationTrait.INPUTS_QUANTIZABLE: [
operator_metatypes.Conv2dMetatype,
operator_metatypes.Conv3dMetatype,
operator_metatypes.ConvTranspose2dMetatype,
operator_metatypes.ConvTranspose3dMetatype,
operator_metatypes.Depthwi... | code_fim | hard | {
"lang": "python",
"repo": "dupeljan/nncf",
"path": "/nncf/torch/quantization/default_quantization.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> _path, idx, _url = self.provider.before_download_file(idx, url)
if _path is None:
return
if not is_file(_path) or file_size(_path) < 32:
self.download_file(_url, _path, idx)
_path, _in_arc_name = self.provider.after_file_save(_path, idx)
... | code_fim | hard | {
"lang": "python",
"repo": "manga-py/manga-py",
"path": "/manga_py/download_methods.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: manga-py/manga-py path: /manga_py/download_methods.py
import json
from concurrent.futures import ThreadPoolExecutor
from logging import info, warning, error
from sys import stderr
from PIL import Image
from .base_classes import Archive
from .base_classes.comic_info_builder import Page, ComicInf... | code_fim | hard | {
"lang": "python",
"repo": "manga-py/manga-py",
"path": "/manga_py/download_methods.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # if isinstance(self._storage['files'], list):
# info('Processing {} files'.format(len(self._storage['files'])))
#
# self.__images_cache = []
#
# # ///
#
# if not is_file(_path) or file_size(_path) < 32:
# self.http().download... | code_fim | hard | {
"lang": "python",
"repo": "manga-py/manga-py",
"path": "/manga_py/download_methods.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|># Band order is determined by collection order. Here, the collection is
# sorted in descending order of the date of observation (reverse of previous).
band_order = col.sort('DATE_ACQUIRED', False).toBands()
print('Customized band order:', band_order.getInfo())
# [END earthengine__apidocs__ee_imagecollecti... | code_fim | hard | {
"lang": "python",
"repo": "google/earthengine-community",
"path": "/samples/python/apidocs/ee_imagecollection_tobands.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: google/earthengine-community path: /samples/python/apidocs/ee_imagecollection_tobands.py
# Copyright 2023 The Google Earth Engine Community Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obta... | code_fim | hard | {
"lang": "python",
"repo": "google/earthengine-community",
"path": "/samples/python/apidocs/ee_imagecollection_tobands.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: matteobjornsson/blockchain path: /code/TransactionGenerator.py
from datetime import datetime
from time import sleep
from Transaction import Transaction
import boto3, random
message_queue_URLs = {
'0': 'https://sqs.us-east-1.amazonaws.com/000000000000/0.fifo',
'1': 'https://sqs.us-east-1.... | code_fim | medium | {
"lang": "python",
"repo": "matteobjornsson/blockchain",
"path": "/code/TransactionGenerator.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
if __name__ == '__main__':
txg = Tx_Generator()
while True:
tx = txg.make_tx()
msg_dict = {'contents': str(tx), 'type': 'Transaction'}
for node in txg.nodes:
not_this_node = txg.nodes[random.randrange(4)]
if node == not_this_node:
co... | code_fim | hard | {
"lang": "python",
"repo": "matteobjornsson/blockchain",
"path": "/code/TransactionGenerator.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> A duration expressing the difference between two date, time, or datetime instances to microsecond resolution.
class datetime.tzinfo
An abstract base class for time zone information objects. These are used by the datetime and time classes to provide a customizable notion of time adjustment (for e... | code_fim | medium | {
"lang": "python",
"repo": "dcburleigh/python-examples",
"path": "/scripts/dt.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: dcburleigh/python-examples path: /scripts/dt.py
#
# https://docs.python.org/3.6/tutorial/stdlib.html#dates-and-times
#
"""
https://docs.python.org/3.6/library/datetime.html#module-datetime
class datetime.date
An idealized naive date, assuming the current Gregorian calendar always was, and... | code_fim | medium | {
"lang": "python",
"repo": "dcburleigh/python-examples",
"path": "/scripts/dt.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def overlapArea(L, K, pos, angle):
return getOverlapArea(L, rotateImage(K, angle), pos)
def getArea(input):
return len(input.nonzero()[0])
if __name__ == '__main__':
L = cv2.imread('./58.png', cv2.IMREAD_GRAYSCALE)
K = cv2.imread('./59.png', cv2.IMREAD_GRAYSCALE)
print overlapArea(... | code_fim | hard | {
"lang": "python",
"repo": "bigfacebear/MaxOverlap",
"path": "/image_utils.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: bigfacebear/MaxOverlap path: /image_utils.py
import math
import cv2
import numpy as np
def rotateImage(input_img, angle):
"""
Rotate the input_img by angle degrees, Rotate center is image center.
:param input_img:np.array, the image to be rotated
:param angle:float, the countercl... | code_fim | hard | {
"lang": "python",
"repo": "bigfacebear/MaxOverlap",
"path": "/image_utils.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> Tasks performed on regular schedule, after first setup. For the job
queue, a list of GSE IDs is returned. The id list is filtered on
existing GSE soft files to prioritize unrepresented experiments for
download.
Arguments:
* eqfilt_path (str) : Filepath ... | code_fim | hard | {
"lang": "python",
"repo": "Shicheng-Guo/recountmethylation_server",
"path": "/src/server.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Shicheng-Guo/recountmethylation_server path: /src/server.py
#!/usr/bin/env python3
""" server.py
Authors: Sean Maden, Abhinav Nellore
Description:
Server script to manage an instance of the recount-methylation database.
Overview:
A recount-methylation instance consists of ... | code_fim | hard | {
"lang": "python",
"repo": "Shicheng-Guo/recountmethylation_server",
"path": "/src/server.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: MycroftAI/skill-alarm path: /test/unit/test_parse.py
# Copyright 2021 Mycroft AI Inc.
#
# 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 the License at
#
# http://www.apache.org/licen... | code_fim | medium | {
"lang": "python",
"repo": "MycroftAI/skill-alarm",
"path": "/test/unit/test_parse.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> midnight_datetime = datetime(2021, 3, 10, 0, 0, 0)
self.assertTrue(
utterance_has_midnight(
utterance="set an alarm for midnight",
init_time=midnight_datetime,
threshold=THRESHOLD,
)
)<|fim_prefix|># repo: Mycr... | code_fim | medium | {
"lang": "python",
"repo": "MycroftAI/skill-alarm",
"path": "/test/unit/test_parse.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> def test_basic_fuzzy_matching(self):
self.assertTrue(
fuzzy_match(word="foo", phrase="this is foo bar", threshold=THRESHOLD)
)
class TestUtteranceHasMidnight(unittest.TestCase):
def test_utterance_has_midnight(self):
midnight_datetime = datetime(2021, 3, 10, 0... | code_fim | medium | {
"lang": "python",
"repo": "MycroftAI/skill-alarm",
"path": "/test/unit/test_parse.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: lukaskoedijk/Green-Software path: /EnergyMeasurement/programs/fannkuchredux/fannkuchredux.python3-1.py
# The Computer Language Benchmarks Game
# http://shootout.alioth.debian.org/
#
# contributed by Miroslav Rubanets
# algorithm is based on Java 6 source code by Oleg Mazurov
# source is based on... | code_fim | hard | {
"lang": "python",
"repo": "lukaskoedijk/Green-Software",
"path": "/EnergyMeasurement/programs/fannkuchredux/fannkuchredux.python3-1.py",
"mode": "psm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>def main():
if len(sys.argv) < 2:
print(usage)
return 1
length = int(sys.argv[1])
if length < 3 or length > MAX_PROBLEM_SIZE:
print(usage)
return 2
n = min( cpu_count(), MAX_CPU_LIMIT )
processors = Pool(processes=n)
factorials = create_factorials... | code_fim | hard | {
"lang": "python",
"repo": "lukaskoedijk/Green-Software",
"path": "/EnergyMeasurement/programs/fannkuchredux/fannkuchredux.python3-1.py",
"mode": "spm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> x, y = shallow.load_data(args.data)
classifier = shallow.load_classifier(args.model)
normalizer = shallow.load_normalizer(args.model)
transformer = shallow.load_transformer(args.model)
evaluate(classifier, normalizer, transformer, x, y)<|fim_prefix|># repo: gazzola/infernal path: /scr... | code_fim | hard | {
"lang": "python",
"repo": "gazzola/infernal",
"path": "/scripts/evaluate.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> print('Accuracy: {:.2%}'.format(acc))
print('F1 macro: {:.3}'.format(f1))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('data', help='Preprocessed data (npz) to evaluate the'
'classifier on')
... | code_fim | hard | {
"lang": "python",
"repo": "gazzola/infernal",
"path": "/scripts/evaluate.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: gazzola/infernal path: /scripts/evaluate.py
# -*- coding: utf-8 -*-
"""
Evaluate a shallow classifier
"""
from __future__ import division, print_function, unicode_literals
import argparse
import numpy as np
from sklearn.metrics import f1_score
from infernal import shallow_utils as shallow
d... | code_fim | hard | {
"lang": "python",
"repo": "gazzola/infernal",
"path": "/scripts/evaluate.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Request is the response, too
request = event['Records'][0]['cf']['request']
# Check if the URI ends with '/', then append 'index.html' to it
if request['uri'].endswith('/'):
request['uri'] = request['uri'] + 'index.html'
# Return modified request
return request<|fim_pre... | code_fim | medium | {
"lang": "python",
"repo": "aws-samples/amazon-aurora-labs-for-mysql",
"path": "/website/lambda/indexdoc-function/src/function.py",
"mode": "spm",
"license": "MIT-0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: aws-samples/amazon-aurora-labs-for-mysql path: /website/lambda/indexdoc-function/src/function.py
"""
Amazon Aurora Labs for MySQL
AWS Lambda function to expand directory requests to an index.html file for CloudFront
<|fim_suffix|> # Request is the response, too
request = event['Records'][... | code_fim | hard | {
"lang": "python",
"repo": "aws-samples/amazon-aurora-labs-for-mysql",
"path": "/website/lambda/indexdoc-function/src/function.py",
"mode": "psm",
"license": "MIT-0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: eltrufas/terminado path: /app/views/curso.py
from flask import Blueprint, redirect, render_template
from flask import request, url_for, current_app, abort, flash, send_file
from flask_user import current_user, login_required, roles_accepted
from app.util import send_email
from app import db
from ... | code_fim | hard | {
"lang": "python",
"repo": "eltrufas/terminado",
"path": "/app/views/curso.py",
"mode": "psm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>@curso_blueprint.route('/curso/<int:course_id>/info_informe',methods=["POST","GET"])
def info_informe(course_id):
course = Course.query.get(course_id)
if not course:
return abort(404)
if course.responsable != current_user:
return abort(403)
form = InformeForm()
if fo... | code_fim | hard | {
"lang": "python",
"repo": "eltrufas/terminado",
"path": "/app/views/curso.py",
"mode": "spm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> self.loop_stack = deque([])
self.expr = None
def add_loop(self, var: Var, loop_type: Var, start: Number, stop: Number, step: Number, conds: list):
""" ADD_LOOP
========
"""
self.loop_stack.append(Loop(var, loop_type, start, stop, step, conds)... | code_fim | hard | {
"lang": "python",
"repo": "lucasvg/Satyrus3-FinalProject-EspTopsOTM",
"path": "/satyrus/sat/types/problem.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def set_expr(self, expr: Expr):
""" SET_EXPR
========
Sets the expr of this constraint in the C.N.F.
"""
self.expr = Expr.cnf(expr)
def get_expr(self, compiler):
""" GET_EXPR
========
"""
return self.... | code_fim | hard | {
"lang": "python",
"repo": "lucasvg/Satyrus3-FinalProject-EspTopsOTM",
"path": "/satyrus/sat/types/problem.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: lucasvg/Satyrus3-FinalProject-EspTopsOTM path: /satyrus/sat/types/problem.py
from collections import deque
## Local
from ...satlib import arange
from .expr import Expr
from .main import Var, Number
from .symbols import CONS_INT, CONS_OPT
from .symbols.tokens import T_FORALL, T_EXISTS, T... | code_fim | hard | {
"lang": "python",
"repo": "lucasvg/Satyrus3-FinalProject-EspTopsOTM",
"path": "/satyrus/sat/types/problem.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> update_result = client.cc.batch_update_inst(batch_update_kwargs)
if not update_result['result']:
message = handle_api_error(__group_name__,
'cc.batch_update_inst',
batch_update_kwargs,
... | code_fim | hard | {
"lang": "python",
"repo": "bk-sops/bk-sops",
"path": "/pipeline_plugins/components/collections/sites/open/cc.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: bk-sops/bk-sops path: /pipeline_plugins/components/collections/sites/open/cc.py
nents/atoms/sites/%s/cc/cc_batch_delete_set.js' % (settings.STATIC_URL, settings.RUN_VER)
class CCUpdateSetServiceStatusService(Service):
def execute(self, data, parent_data):
executor = parent_data.get... | code_fim | hard | {
"lang": "python",
"repo": "bk-sops/bk-sops",
"path": "/pipeline_plugins/components/collections/sites/open/cc.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: bk-sops/bk-sops path: /pipeline_plugins/components/collections/sites/open/cc.py
ot cc_host_prop_value:
data.set_outputs('ex_data', _(u"所属运营商校验失败,请重试并修改为正确的所属运营商"))
return False
elif cc_host_property == "bk_state_name":
bk_state_name = cc_format... | code_fim | hard | {
"lang": "python",
"repo": "bk-sops/bk-sops",
"path": "/pipeline_plugins/components/collections/sites/open/cc.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> def set_week_day(self, wday):
"""Set the week day name to spanish"""
wdays = ['Domingo', 'Lunes', 'Martes', 'Miercoles',
'Jueves', 'Viernes', 'Sabado']
for i in range(7):
if wday == i:
return wdays[i]
def set_day_state(self, day_or_night):
"""Check the daylight and return ... | code_fim | hard | {
"lang": "python",
"repo": "Andres2055/Kiwi-bot",
"path": "/kiwi/cogs/scpUtils.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Andres2055/Kiwi-bot path: /kiwi/cogs/scpUtils.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
from functools import lru_cache
from urllib import error, request
try:
from kiwi_db import COMMAND_NAME
except ImportError as IE:
print('Hubo un {0.__class__.__name__}'.format(I... | code_fim | hard | {
"lang": "python",
"repo": "Andres2055/Kiwi-bot",
"path": "/kiwi/cogs/scpUtils.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>class ComandoPersonalizado:
def __init__(self):
"""The class ComandoPersonalizado is a data handling of my own Database
based in the overwriting of .py files"""
pass
def _writer(self, code):
"""Overwrite the module kiwi_db to insert, remove or update commands"""
file = open('my_db\\... | code_fim | hard | {
"lang": "python",
"repo": "Andres2055/Kiwi-bot",
"path": "/kiwi/cogs/scpUtils.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: malihealikhani/deep_qa path: /deep_qa/layers/entailment_models/multiple_choice_tuple_entailment.py
from typing import Any, Dict
from keras import backend as K
from .word_alignment import WordAlignmentEntailment
from ...tensors.backend import switch
class MultipleChoiceTupleEntailment(WordAlig... | code_fim | hard | {
"lang": "python",
"repo": "malihealikhani/deep_qa",
"path": "/deep_qa/layers/entailment_models/multiple_choice_tuple_entailment.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> def call(self, x, mask=None):
# We assume the tuples are SVO and each slot is represented as vector.
# Moreover, we assume each answer option is encoded as a single vector.
# knowledge_embedding: (batch_size, num_tuples, tuple_size, embed_dim)
# question_embedding: (bat... | code_fim | hard | {
"lang": "python",
"repo": "malihealikhani/deep_qa",
"path": "/deep_qa/layers/entailment_models/multiple_choice_tuple_entailment.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> ## Step B2: Align answer with Subj
subj_knowledge_answer_alignment = self._align(subj_knowledge, answer_embedding, subj_knowledge_mask,
answer_mask, normalize_alignment=False)
tiled_vo_tuple_weights = K.dot(K.expand_dims(vo_tupl... | code_fim | hard | {
"lang": "python",
"repo": "malihealikhani/deep_qa",
"path": "/deep_qa/layers/entailment_models/multiple_choice_tuple_entailment.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: algofairness/info-access-clusters path: /helper_pipelines/graph_examples.py
import utils
import numpy as np
import networkx as nx
from copy import *
import matplotlib.pyplot as plt
import random
def depth_two_star(n):
# n is the number of nodes in the first layer out
G = nx.OrderedGraph... | code_fim | hard | {
"lang": "python",
"repo": "algofairness/info-access-clusters",
"path": "/helper_pipelines/graph_examples.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def main():
graph = depth_two_star(10)
graphs = independent_cascade(graph, [0], 0.4, 3)
# pos = nx.spring_layout(graph)
for graph in graphs:
color_map = color(graph)
print(graph)
# Figure out how to keep order of the nodes consistent in drawing
nx.draw_ka... | code_fim | hard | {
"lang": "python",
"repo": "algofairness/info-access-clusters",
"path": "/helper_pipelines/graph_examples.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
_MAIN = _descriptor.Descriptor(
name='Main',
full_name='Main',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='name', full_name='Main.name', index=0,
number=1, type=9, cpp_type=9, ... | code_fim | hard | {
"lang": "python",
"repo": "jviotti/binary-json-size-benchmark",
"path": "/benchmark/packagejson/protobuf/schema_pb2.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: jviotti/binary-json-size-benchmark path: /benchmark/packagejson/protobuf/schema_pb2.py
=15, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,... | code_fim | hard | {
"lang": "python",
"repo": "jviotti/binary-json-size-benchmark",
"path": "/benchmark/packagejson/protobuf/schema_pb2.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>
_ENGINES = _descriptor.Descriptor(
name='Engines',
full_name='Engines',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='node', full_name='Engines.node', index=0,
number=1, type=9, ... | code_fim | hard | {
"lang": "python",
"repo": "jviotti/binary-json-size-benchmark",
"path": "/benchmark/packagejson/protobuf/schema_pb2.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: zengchen1024/mindinsight path: /mindinsight/backend/lineagemgr/lineage_api.py
# Copyright 2019 Huawei Technologies Co., Ltd
#
# 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 the License... | code_fim | hard | {
"lang": "python",
"repo": "zengchen1024/mindinsight",
"path": "/mindinsight/backend/lineagemgr/lineage_api.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> lineages = lineage_info['object']
summary_base_dir = os.path.realpath(summary_base_dir)
length = len(summary_base_dir)
for lineage in lineages:
summary_dir = lineage['summary_dir']
summary_dir = os.path.realpath(summary_dir)
if summary_... | code_fim | hard | {
"lang": "python",
"repo": "zengchen1024/mindinsight",
"path": "/mindinsight/backend/lineagemgr/lineage_api.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: rubenvdvijver/KinBot path: /kinbot/molpro.py
###################################################
## ##
## This file is part of the KinBot code v2.0 ##
## ##
## The contents are covered by the terms of ... | code_fim | hard | {
"lang": "python",
"repo": "rubenvdvijver/KinBot",
"path": "/kinbot/molpro.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> with open(par.tpldir + 'molpro.tpl') as f:
file = f.read()
fname = str(species.chemid)
if wellorts: fname = species.name
geom = ''
nelectron = 0
for i,at in enumerate(atom):
x,y,z = species.geom[i]
geom += '{} {:.8f} {:.8f} {:.8f}\n'.format(at,x,y,... | code_fim | hard | {
"lang": "python",
"repo": "rubenvdvijver/KinBot",
"path": "/kinbot/molpro.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: wangyum/Anaconda path: /pkgs/mpmath-0.19-py27_0/lib/python2.7/site-packages/mpmath/tests/torture.py
"""
Torture tests for asymptotics and high precision evaluation of
special functions.
(Other torture tests may also be placed here.)
Running this file (gmpy and psyco recommended!) takes several ... | code_fim | hard | {
"lang": "python",
"repo": "wangyum/Anaconda",
"path": "/pkgs/mpmath-0.19-py27_0/lib/python2.7/site-packages/mpmath/tests/torture.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>cases = """\
test_bernoulli_huge()
test_asymp(lambda z: +pi, maxdps=10000)
test_asymp(lambda z: +e, maxdps=10000)
test_asymp(lambda z: +ln2, maxdps=10000)
test_asymp(lambda z: +ln10, maxdps=10000)
test_asymp(lambda z: +phi, maxdps=10000)
test_asymp(lambda z: +catalan, maxdps=5000)
test_asymp(lambda z: +eu... | code_fim | hard | {
"lang": "python",
"repo": "wangyum/Anaconda",
"path": "/pkgs/mpmath-0.19-py27_0/lib/python2.7/site-packages/mpmath/tests/torture.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>from mpmath import *
from mpmath.libmp.backend import exec_
def test_asymp(f, maxdps=150, verbose=False, huge_range=False):
dps = [5,15,25,50,90,150,500,1500,5000,10000]
dps = [p for p in dps if p <= maxdps]
def check(x,y,p,inpt):
if abs(x-y)/abs(y) < workprec(20)(power)(10, -p+1):
... | code_fim | hard | {
"lang": "python",
"repo": "wangyum/Anaconda",
"path": "/pkgs/mpmath-0.19-py27_0/lib/python2.7/site-packages/mpmath/tests/torture.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: uburuntu/throttler path: /throttler/execution_timer.py
import asyncio
import time
class ExecutionTimer:
"""
Context manager for time limiting of accessing to context block.
Simply sleep `period` secs before next accessing, not analog of Throttler.
Also it can align to start of m... | code_fim | medium | {
"lang": "python",
"repo": "uburuntu/throttler",
"path": "/throttler/execution_timer.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> self._start_time = 0.
self._next_time = 0.
def _start(self):
curr_time = time.time()
diff = self._next_time - curr_time
return diff
def _exit(self):
next_time = self._start_time + self._period
if self._align_sleep:
next_time -= ... | code_fim | medium | {
"lang": "python",
"repo": "uburuntu/throttler",
"path": "/throttler/execution_timer.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def __init__(self, *args, **kwargs):
requires_backends(self, ["sentencepiece"])
class FNetTokenizer(metaclass=DummyObject):
_backends = ["sentencepiece"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["sentencepiece"])
class GPTSw3Tokenizer(metaclass=DummyOb... | code_fim | hard | {
"lang": "python",
"repo": "huggingface/transformers",
"path": "/src/transformers/utils/dummy_sentencepiece_objects.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: huggingface/transformers path: /src/transformers/utils/dummy_sentencepiece_objects.py
# This file is autogenerated by the command `make fix-copies`, do not edit.
from ..utils import DummyObject, requires_backends
class AlbertTokenizer(metaclass=DummyObject):
_backends = ["sentencepiece"]
... | code_fim | hard | {
"lang": "python",
"repo": "huggingface/transformers",
"path": "/src/transformers/utils/dummy_sentencepiece_objects.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> _backends = ["sentencepiece"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["sentencepiece"])
class SpeechT5Tokenizer(metaclass=DummyObject):
_backends = ["sentencepiece"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["sentencepiece"])
... | code_fim | hard | {
"lang": "python",
"repo": "huggingface/transformers",
"path": "/src/transformers/utils/dummy_sentencepiece_objects.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> error("%s %s, %s" % (
type,
(fn.name if isinstance(fn, var) else fn),
args))
if not isinstance(fn, tuple):
if fn == GT:
if args[0] > args[1]:
return TRUE
return NIL
elif fn == PR:
prin... | code_fim | hard | {
"lang": "python",
"repo": "sri/my-blog-code",
"path": "/orange4.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: sri/my-blog-code path: /orange4.py
#! /usr/bin/env python2.5
#
# orange4.py -- an interpreter for a simple lisp-like language
# [under same license as Python]
# (inspired by Peter Norvig's JScheme)
#
# =================================================================
# + Notes +
# ==============... | code_fim | hard | {
"lang": "python",
"repo": "sri/my-blog-code",
"path": "/orange4.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>if __name__ == '__main__':
LOGGER = AppLogger(name='mylog', filepath=os.path.join(os.getcwd(), "test", "file", "my.log"))
LOGGER.debug("test_applogger")<|fim_prefix|># repo: bascker/py-note path: /test/test_applogger.py
# -*- coding: utf-8 -*-
import os
import sys
# 用于引入自定义模块: 若当前目录查不到,则 import 模... | code_fim | easy | {
"lang": "python",
"repo": "bascker/py-note",
"path": "/test/test_applogger.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: bascker/py-note path: /test/test_applogger.py
# -*- coding: utf-8 -*-
import os
import sys
# 用于引入自定义模块: 若当前目录查不到,则 import 模块从 sys.path 找
sys.path.append(os.getcwd())
<|fim_suffix|>if __name__ == '__main__':
LOGGER = AppLogger(name='mylog', filepath=os.path.join(os.getcwd(), "test", "file", "... | code_fim | easy | {
"lang": "python",
"repo": "bascker/py-note",
"path": "/test/test_applogger.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: pitluga/elephunk path: /tests/functional/http_test_case.py
from os.path import realpath, join
from urllib import urlencode
from tornado.httpclient import AsyncHTTPClient, HTTPRequest
from tornado.httputil import HTTPHeaders
from tornado.ioloop import IOLoop
from tornado.testing import AsyncHTTPTe... | code_fim | medium | {
"lang": "python",
"repo": "pitluga/elephunk",
"path": "/tests/functional/http_test_case.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def post(self, path, body, headers={}):
client = AsyncHTTPClient(IOLoop.instance())
request = HTTPRequest(self.get_url(path), method="POST", body=urlencode(body), headers=HTTPHeaders(headers), follow_redirects=False)
client.fetch(request, self.stop)
return self.wait()<|... | code_fim | hard | {
"lang": "python",
"repo": "pitluga/elephunk",
"path": "/tests/functional/http_test_case.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
# # Your MinStack object will be instantiated and called as such:
# x = 5
# obj = MinStack()
# obj.push(x)
# obj.push(3)
# print(obj.pop())
# param_3 = obj.top()
# param_4 = obj.getMin()
# print("top: ", param_3)
# print("min: ", param_4)
# minStack = MinStack()
# minStack.push(512)
# minStack.push(-1... | code_fim | hard | {
"lang": "python",
"repo": "pauldoust/Competitive-Programming",
"path": "/MinMaxStack/minMaxStack.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>
# minStack = MinStack()
# minStack.push(512)
# minStack.push(-1024)
# minStack.push(-1024)
# minStack.push(512)
# minStack.pop()
# print(minStack.getMin())
# minStack.pop()
# print(minStack.getMin())
# minStack.pop()
# print(minStack.getMin())
# elem = None
# print('elem: ', elem)
# print('elem: ', e... | code_fim | hard | {
"lang": "python",
"repo": "pauldoust/Competitive-Programming",
"path": "/MinMaxStack/minMaxStack.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: pauldoust/Competitive-Programming path: /MinMaxStack/minMaxStack.py
# https://leetcode.com/problems/min-stack/submissions/
# Runtime: 72 ms, faster than 73.80% of Python3 online submissions for Min Stack.
# Runtime: 68 ms, faster than 89.48% of Python3 online submissions for Min Stack.
class MinS... | code_fim | hard | {
"lang": "python",
"repo": "pauldoust/Competitive-Programming",
"path": "/MinMaxStack/minMaxStack.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> def valid_password(self, password):
""" valid password """
regex = "^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])[a-zA-Z0-9]{6,15}$"
return re.match(regex, password)
def valid_email(self, email):
""" valid email """
return re.match("^[^@]+@[^@]+\.[^@]+$", email)
... | code_fim | medium | {
"lang": "python",
"repo": "johnkabage/book-a-meal-API",
"path": "/APP/validators/validators.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: johnkabage/book-a-meal-API path: /APP/validators/validators.py
import re
class Validators:
def valid_fname(self, fname):
""" valid fname """
return re.match("^[a-zA-Z0-9]{4,20}$", fname)
def valid_lname(self, lname):
""" valid lname """
return re.match... | code_fim | medium | {
"lang": "python",
"repo": "johnkabage/book-a-meal-API",
"path": "/APP/validators/validators.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: T3p/potion path: /potion/common/misc_utils.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 12 23:12:09 2019
@author: Matteo Papini
"""
import random
import numpy as np
import torch
import os
from gym.spaces.box import Box
from gym.spaces.discrete import Discrete
separa... | code_fim | hard | {
"lang": "python",
"repo": "T3p/potion",
"path": "/potion/common/misc_utils.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> n = len(batch)
if horizon is not None:
time_factor = (1 - disc**horizon) / (1 - disc)
else:
time_factor = 1. / (1 - disc)
std, mean = torch.std_mean(torch.tensor(returns(batch, disc)),
unbiased=True)
ucb = mean.item() + std.item() * np.sq... | code_fim | hard | {
"lang": "python",
"repo": "T3p/potion",
"path": "/potion/common/misc_utils.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> Returns:
query_result (Dict[str, Dict[str, DataPoint]]]): Post processed query result
Raises:
HTTPException: If query was unsuccessful for reasons such as bad template, prom result contained no data or returned data in a non-vector form which cannot be post... | code_fim | hard | {
"lang": "python",
"repo": "mtoslalibu/iter8-analytics",
"path": "/iter8_analytics/api/analytics/metrics.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: mtoslalibu/iter8-analytics path: /iter8_analytics/api/analytics/metrics.py
BaseModel, Field
from fastapi import HTTPException
# iter8 dependencies
from iter8_analytics.api.analytics.types import *
import iter8_analytics.constants as constants
from iter8_analytics.config import env_config
logge... | code_fim | hard | {
"lang": "python",
"repo": "mtoslalibu/iter8-analytics",
"path": "/iter8_analytics/api/analytics/metrics.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: mtoslalibu/iter8-analytics path: /iter8_analytics/api/analytics/metrics.py
id_to_list_of_values
}
logger.debug("mert metricid")
logger.debug(metric_id_to_list_of_values)
for metric_id in metric_id_to_list_of_values:
try:
max_min_lists[metric_id][0], max_min_lis... | code_fim | hard | {
"lang": "python",
"repo": "mtoslalibu/iter8-analytics",
"path": "/iter8_analytics/api/analytics/metrics.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: zuxfoucault/twnews path: /twnews/__main__.py
"""
工具程式
"""
import sys
import locale
import os.path
from datetime import datetime
from twnews.common import get_logger, VERSION
from twnews.soup import NewsSoup
from twnews.search import NewsSearch
def soup(path):
"""
分解新聞
"""
print(... | code_fim | hard | {
"lang": "python",
"repo": "zuxfoucault/twnews",
"path": "/twnews/__main__.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> media = {
'appledaily': ' 蘋果',
'cna': '中央社',
'ettoday': ' 東森',
'ltn': ' 自由',
'setn': ' 三立',
'udn': ' 聯合'
}
for (channel, name) in media.items():
nsearch = NewsSearch(
channel,
beg_date=beg_date,
e... | code_fim | hard | {
"lang": "python",
"repo": "zuxfoucault/twnews",
"path": "/twnews/__main__.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: UKTV/django-preventconcurrentlogins path: /preventconcurrentlogins/models.py
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
<|fim_suffix|>class Visitor(models.Model):
user = models.OneToOneField(AUTH_USER_MODEL, null=False, related_n... | code_fim | medium | {
"lang": "python",
"repo": "UKTV/django-preventconcurrentlogins",
"path": "/preventconcurrentlogins/models.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> user = models.OneToOneField(AUTH_USER_MODEL, null=False, related_name='visitor')
session_key = models.CharField(null=False, max_length=40)<|fim_prefix|># repo: UKTV/django-preventconcurrentlogins path: /preventconcurrentlogins/models.py
from django.conf import settings
from django.contrib.auth.mo... | code_fim | medium | {
"lang": "python",
"repo": "UKTV/django-preventconcurrentlogins",
"path": "/preventconcurrentlogins/models.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> >>> split_if(['a', '2', 'c', 'z', '5'], str.isdigit)
[['2', '5'], ['a', 'c', 'z']]
"""
retval = []
for key, group in itertools.groupby(
sorted(seq, key=pred, reverse=True), key=pred):
retval.append(list(group))
return retval<|fim_prefix|># repo: jiangsy163/pythonPr... | code_fim | medium | {
"lang": "python",
"repo": "jiangsy163/pythonProject",
"path": "/venv/Lib/site-packages/commodity/sequences.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: jiangsy163/pythonProject path: /venv/Lib/site-packages/commodity/sequences.py
# -*- coding:utf-8; tab-width:4; mode:python -*-
import itertools
from functools import reduce
def uniq(alist):
'''
>>> list(uniq([1, 2, 2, 3, 2, 3, 5]))
[1, 2, 3, 5]
'''
s = set()
for i in a... | code_fim | hard | {
"lang": "python",
"repo": "jiangsy163/pythonProject",
"path": "/venv/Lib/site-packages/commodity/sequences.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: uktrade/lite-api path: /api/goods/migrations/0017_good_no_part_number_comments.py
# Generated by Django 3.2.14 on 2022-08-12 10:41
from django.db import migrations, models
<|fim_suffix|> dependencies = [
("goods", "0016_firearmgooddetails_not_deactivated_to_standard_comments"),
... | code_fim | medium | {
"lang": "python",
"repo": "uktrade/lite-api",
"path": "/api/goods/migrations/0017_good_no_part_number_comments.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> dependencies = [
("goods", "0016_firearmgooddetails_not_deactivated_to_standard_comments"),
]
operations = [
migrations.AddField(
model_name="good",
name="no_part_number_comments",
field=models.TextField(
blank=True, default=... | code_fim | medium | {
"lang": "python",
"repo": "uktrade/lite-api",
"path": "/api/goods/migrations/0017_good_no_part_number_comments.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: UB-info/estructura-datos path: /RafaelArqueroGimeno_S6/ABB_Rafael_Arquero_Gimeno.py
import copy
__author__ = "Rafael Arquero Gimeno"
class Node(object):
def __init__(self):
self.data = []
self.left = None
self.right = None
def clear(self):
"""Empty Node... | code_fim | hard | {
"lang": "python",
"repo": "UB-info/estructura-datos",
"path": "/RafaelArqueroGimeno_S6/ABB_Rafael_Arquero_Gimeno.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> """Returns the minimum value of the tree"""
return self.root.leftmost
@property
def max(self):
"""Returns the maximum value of the tree"""
return self.root.rightmost
@property
def depth(self):
return self.root.depth
def __copy__(self):
... | code_fim | hard | {
"lang": "python",
"repo": "UB-info/estructura-datos",
"path": "/RafaelArqueroGimeno_S6/ABB_Rafael_Arquero_Gimeno.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> if current < threshold:
if current.right:
self.deleteHigher(threshold, current.right, current)
elif current > threshold:
if current.left:
current.data = current.left.data
current.right = current.left.right
... | code_fim | hard | {
"lang": "python",
"repo": "UB-info/estructura-datos",
"path": "/RafaelArqueroGimeno_S6/ABB_Rafael_Arquero_Gimeno.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def test_mypy(action: Action = 'warn') -> None:
"""Test using mypy."""
if action not in ACTION:
raise ValueError(f"Invalid value for the 'action' parameter: {action!r}")
command = f"mypy {PACKAGE!r} --config-file {INI!r}"
out = subprocess.run(command, stdout=subprocess.PIPE, stde... | code_fim | medium | {
"lang": "python",
"repo": "nlesc-nano/swan",
"path": "/tests/test_mypy.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: nlesc-nano/swan path: /tests/test_mypy.py
"""Tests using mypy."""
import subprocess
import warnings
from typing_extensions import Literal
from .utils_test import PATH_SWAN, PATH_TEST
<|fim_suffix|> """Test using mypy."""
if action not in ACTION:
raise ValueError(f"Invalid value... | code_fim | hard | {
"lang": "python",
"repo": "nlesc-nano/swan",
"path": "/tests/test_mypy.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> if action == 'warn' and out.returncode != 0:
warnings.warn(stdout)
elif action == 'raise':
try:
assert out.returncode == 0, stdout
except AssertionError as ex:
msg = stdout.rsplit('\n', maxsplit=2)[1]
raise AssertionError(msg) from ex<|f... | code_fim | hard | {
"lang": "python",
"repo": "nlesc-nano/swan",
"path": "/tests/test_mypy.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>options = ["rock","paper","scissors"]
if user_choice in options: #in operator looks for a value or word in a list
pass #or use print("VALID") to show VALID when rock, paper, scissors is correctly inputted.
else:
print("INVALID SELECTION, PLEASE TRY AGAIN...")
exit()
# GENERATE COMPUT... | code_fim | medium | {
"lang": "python",
"repo": "pcotnoir/rock-paper-scissors-inclass",
"path": "/game.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: pcotnoir/rock-paper-scissors-inclass path: /game.py
# game.py
import random #always include imports of modules at the start of a Python script. Prevents error of computer selection.
print("Rock, Paper, Scissors, Shoot!")
<|fim_suffix|># GENERATE COMPUTER SELECTION
computer_choice = random.cho... | code_fim | hard | {
"lang": "python",
"repo": "pcotnoir/rock-paper-scissors-inclass",
"path": "/game.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>f.write("{:<10} {:10} {:10}\n".format("S/N", "Items", "Quantity"))
for item in list1:
f.write("{:<10} {:10} {:10}\n".format("S/N", "Items", "Quantity") + "\n")
f.close()<|fim_prefix|># repo: achrinza/np-csf02-answers path: /PRG1/Lectures/Week13/FileIODemo.py
import os
f = open("test.txt" "w")
<|f... | code_fim | medium | {
"lang": "python",
"repo": "achrinza/np-csf02-answers",
"path": "/PRG1/Lectures/Week13/FileIODemo.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.