text stringlengths 232 16.3k | domain stringclasses 1
value | difficulty stringclasses 3
values | meta dict |
|---|---|---|---|
<|fim_prefix|># repo: RedCiudadana/VotaithemeGuate path: /votainteligente_theme_red_ciudadana/forms.py
# coding=utf-8
from django import forms
class PersonalDataForm(forms.Form):
age = forms.IntegerField(label='Edad', required=False, initial=0)
lema = forms.CharField(label=u'Lema de campaña', required=False,... | code_fim | hard | {
"lang": "python",
"repo": "RedCiudadana/VotaithemeGuate",
"path": "/votainteligente_theme_red_ciudadana/forms.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> return itunes.tell('play playlist named "%s"' % playlist_name)<|fim_prefix|># repo: andrewp-as-is/itunes.py path: /itunes/playlists.py
__all__ = ['names', 'play']
import itunes
<|fim_middle|>
def names():
return itunes.tell('get name of playlists').split(", ")
def play(playlist_name):
| code_fim | medium | {
"lang": "python",
"repo": "andrewp-as-is/itunes.py",
"path": "/itunes/playlists.py",
"mode": "spm",
"license": "Unlicense",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def play(playlist_name):
return itunes.tell('play playlist named "%s"' % playlist_name)<|fim_prefix|># repo: andrewp-as-is/itunes.py path: /itunes/playlists.py
__all__ = ['names', 'play']
import itunes
<|fim_middle|>def names():
return itunes.tell('get name of playlists').split(", ")
| code_fim | medium | {
"lang": "python",
"repo": "andrewp-as-is/itunes.py",
"path": "/itunes/playlists.py",
"mode": "spm",
"license": "Unlicense",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: andrewp-as-is/itunes.py path: /itunes/playlists.py
__all__ = ['names', 'play']
import itunes
<|fim_suffix|> return itunes.tell('play playlist named "%s"' % playlist_name)<|fim_middle|>
def names():
return itunes.tell('get name of playlists').split(", ")
def play(playlist_name):
| code_fim | medium | {
"lang": "python",
"repo": "andrewp-as-is/itunes.py",
"path": "/itunes/playlists.py",
"mode": "psm",
"license": "Unlicense",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: revature-scalawags/Project2-Group4 path: /python-hashtag-scraper/scraper.py
import snscrape.modules.twitter as sntwitter
import sys
hashtag = sys.argv[1]
max_results = 10000
# get the tweets by hashtag and save them to a file
with open (hashtag + ".tsv", 'w', encoding='utf-8', newline='') as f:... | code_fim | medium | {
"lang": "python",
"repo": "revature-scalawags/Project2-Group4",
"path": "/python-hashtag-scraper/scraper.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>s\n")
for i,tweet in enumerate(sntwitter.TwitterHashtagScraper(hashtag).get_items()):
if i > max_results:
break
else:
text = tweet.content.replace('\n', ' ')
f.write(text + "\t" + tweet.user.username + "\t" + str(tweet.user.followersCount) + "\n")<|f... | code_fim | medium | {
"lang": "python",
"repo": "revature-scalawags/Project2-Group4",
"path": "/python-hashtag-scraper/scraper.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>
@borg.on(admin_cmd(pattern="ver(.*)"))
async def bot_ver(event):
"""For .ver command, get the bot version."""
if which("git") is not None:
invokever = "git describe --all --long"
ver = await asyncrunapp(
invokever,
stdout=asyncPIPE,
stderr=async... | code_fim | medium | {
"lang": "python",
"repo": "prono69/PepeBot",
"path": "/stdplugins/botversion.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: prono69/PepeBot path: /stdplugins/botversion.py
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
#
""" Userbot module for getting information about... | code_fim | hard | {
"lang": "python",
"repo": "prono69/PepeBot",
"path": "/stdplugins/botversion.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>
_import_structure = {
"configuration_bert": ["BERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BertConfig", "BertOnnxConfig"],
"tokenization_bert": ["BasicTokenizer", "BertTokenizer", "WordpieceTokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except O... | code_fim | hard | {
"lang": "python",
"repo": "huggingface/transformers",
"path": "/src/transformers/models/bert/__init__.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: huggingface/transformers path: /src/transformers/models/bert/__init__.py
# Copyright 2020 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of th... | code_fim | hard | {
"lang": "python",
"repo": "huggingface/transformers",
"path": "/src/transformers/models/bert/__init__.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_import_structure["modeling_tf_bert"] = [
"TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFBertEmbeddings",
"TFBertForMaskedLM",
"TFBertFor... | code_fim | hard | {
"lang": "python",
"repo": "huggingface/transformers",
"path": "/src/transformers/models/bert/__init__.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> return c.execute(query, (search_query, page_number, cache_expiration)).fetchone()
def put(self, search_query, page_number, search_results):
"""
put the results into the database
"""
timestamp = int(time.time())
with self.get_conn() as conn:
... | code_fim | hard | {
"lang": "python",
"repo": "kylelk/Rotten-Tomatoes",
"path": "/RottenTomatoes.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: kylelk/Rotten-Tomatoes path: /RottenTomatoes.py
# The MIT License (MIT)
#
# Copyright (c) 2014 kyle kersey
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Softw... | code_fim | hard | {
"lang": "python",
"repo": "kylelk/Rotten-Tomatoes",
"path": "/RottenTomatoes.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def put(self, search_query, page_number, search_results):
"""
put the results into the database
"""
timestamp = int(time.time())
with self.get_conn() as conn:
c = conn.cursor()
insert = """INSERT OR REPLACE INTO movies
... | code_fim | hard | {
"lang": "python",
"repo": "kylelk/Rotten-Tomatoes",
"path": "/RottenTomatoes.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: wbknez/breakdb path: /tests/io/export/voc/test_create_bounding_box.py
"""
Contains unit tests to ensure bounding boxes are converted correctly from
a DICOM annotation to a Pascal VOC compatible format.
"""
from xml.etree.ElementTree import Element, SubElement
import numpy as np
from breakdb.io.... | code_fim | hard | {
"lang": "python",
"repo": "wbknez/breakdb",
"path": "/tests/io/export/voc/test_create_bounding_box.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> """
Test suite for :function: 'create_bounding_box'.
"""
def test_create_bounding_box_computes_extrema_correctly(self):
coords = np.random.randint(0, 1200, 10)
x = coords[0::2]
y = coords[1::2]
bndbox = create_bounding_box(coords)
x_max = bndbox.f... | code_fim | medium | {
"lang": "python",
"repo": "wbknez/breakdb",
"path": "/tests/io/export/voc/test_create_bounding_box.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|># Parallel
from multiprocessing import Pool,cpu_count
from joblib import Parallel, delayed
import re
def loop_func(index,shares,views):
if(index<630):
return
num_steps = 6000
s_i = np.array(shares[index])
v_i = np.array(views[index])
train, test = generate_set(s_i,v... | code_fim | hard | {
"lang": "python",
"repo": "RuiZhang2016/GANforPointProcess",
"path": "/tensorflow-lstm-regression/attempt/Embedding_For_PointProcess.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Define the first hidden layer
with tf.variable_scope('Output') as scope_output:
# dim of scores: vocabulary_size*batch_size
try:
W_ouput= tf.get_variable('W_ouput', [v_nclass,hidden_size],
initializer=tf.random_normal_initializer(stddev=0.5))
excep... | code_fim | hard | {
"lang": "python",
"repo": "RuiZhang2016/GANforPointProcess",
"path": "/tensorflow-lstm-regression/attempt/Embedding_For_PointProcess.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: RuiZhang2016/GANforPointProcess path: /tensorflow-lstm-regression/attempt/Embedding_For_PointProcess.py
# coding = uft-8
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import json
from os import... | code_fim | hard | {
"lang": "python",
"repo": "RuiZhang2016/GANforPointProcess",
"path": "/tensorflow-lstm-regression/attempt/Embedding_For_PointProcess.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def is_variant_iupac(variant):
'''
A function to determine whether a variant is an IUPAC code, note that
we are treating N as a distinct value.
Arguments:
* variant: a string representing the variant
Return Value:
Function returns a boolean
'''
variant = str(v... | code_fim | hard | {
"lang": "python",
"repo": "connor-lab/ncov-tools",
"path": "/parser/ncov/parser/Alleles.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> Arguments:
* variant: a string representing the variant
Return Value:
Function returns a boolean
'''
variant = str(variant).upper()
iupac_codes = '[RYSWKMBDHVN]'
return re.search(iupac_codes, variant)
def is_variant_base(variant):
'''
A method to determin... | code_fim | hard | {
"lang": "python",
"repo": "connor-lab/ncov-tools",
"path": "/parser/ncov/parser/Alleles.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: connor-lab/ncov-tools path: /parser/ncov/parser/Alleles.py
'''
A class for handling allele date from the alleles.tsv files generated by the
ARTIC nCoV pipeline.
'''
import os
import sys
import csv
import re
class Alleles():
'''
The Alleles class for handling the alleles.tsv file.
''... | code_fim | hard | {
"lang": "python",
"repo": "connor-lab/ncov-tools",
"path": "/parser/ncov/parser/Alleles.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>ecific project.
url(r'^(?P<pk>[^/]+)/$',
views.ProjectAppListView.as_view(),
name='index'),
]<|fim_prefix|># repo: emiamar/djangomom path: /djangomom/app/urls.py
from django.conf.urls import url
import views
urlpatterns = [
# Creates new App Obj
url(r'^create/$',
<|fim_middl... | code_fim | hard | {
"lang": "python",
"repo": "emiamar/djangomom",
"path": "/djangomom/app/urls.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: emiamar/djangomom path: /djangomom/app/urls.py
from django.conf.urls import url
import views
urlpatterns = [
# Creates new App Obj
url(r'^create/$',
<|fim_suffix|>ecific project.
url(r'^(?P<pk>[^/]+)/$',
views.ProjectAppListView.as_view(),
name='index'),
]<|fim_middl... | code_fim | hard | {
"lang": "python",
"repo": "emiamar/djangomom",
"path": "/djangomom/app/urls.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> views.ResourcesListView.as_view(),
name='resources_list'),
# Project deatil or list of app for specific project.
url(r'^(?P<pk>[^/]+)/$',
views.ProjectAppListView.as_view(),
name='index'),
]<|fim_prefix|># repo: emiamar/djangomom path: /djangomom/app/urls.py
from django... | code_fim | medium | {
"lang": "python",
"repo": "emiamar/djangomom",
"path": "/djangomom/app/urls.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> path = _download_extract_validate(root, URL, MD5, os.path.join(root, _PATH), os.path.join(root, _EXTRACTED_FILES[split]),
_EXTRACTED_FILES_MD5[split], hash_type="md5")
logging.info('Creating {} data'.format(split))
return _RawTextIterableDataset("AmazonRev... | code_fim | medium | {
"lang": "python",
"repo": "carolineechen/text",
"path": "/torchtext/datasets/amazonreviewfull.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>@_add_docstring_header(num_lines=NUM_LINES, num_classes=5)
@_wrap_split_argument(('train', 'test'))
def AmazonReviewFull(root, split):
def _create_data_from_csv(data_path):
with io.open(data_path, encoding="utf8") as f:
reader = unicode_csv_reader(f)
for row in reader:
... | code_fim | hard | {
"lang": "python",
"repo": "carolineechen/text",
"path": "/torchtext/datasets/amazonreviewfull.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: carolineechen/text path: /torchtext/datasets/amazonreviewfull.py
from torchtext.utils import unicode_csv_reader
from torchtext.data.datasets_utils import _RawTextIterableDataset
from torchtext.data.datasets_utils import _wrap_split_argument
from torchtext.data.datasets_utils import _add_docstring... | code_fim | medium | {
"lang": "python",
"repo": "carolineechen/text",
"path": "/torchtext/datasets/amazonreviewfull.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def parse_file(self, rows):
insertion_list = []
print "Ingesting Surfaces..."
for keys in rows:
surface_name = self.column_unicode("description", **keys)
surface_type = self.column("type", **keys)
if not self.record_exists(Surfaces, descript... | code_fim | hard | {
"lang": "python",
"repo": "josemeza2183/marcotti",
"path": "/etl/ecsv/validation.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: josemeza2183/marcotti path: /etl/ecsv/validation.py
from models.common.overview import Countries, Timezones, Surfaces
from models.common.personnel import Positions
from models.common.enums import ConfederationType, PositionType, SurfaceType
from ..base import BaseCSV
class CountryIngest(BaseCSV... | code_fim | hard | {
"lang": "python",
"repo": "josemeza2183/marcotti",
"path": "/etl/ecsv/validation.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> for j in range(self.number_of_particles):
swarm_particle[j].update_velocity(global_best_particle_position)
swarm_particle[j].update_position()
if self.number_of_variables == 2:
x.append(swarm_particle[j].pa... | code_fim | hard | {
"lang": "python",
"repo": "champbodhibaum/programming-practice-2021",
"path": "/exercise_4/exercise_4.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: champbodhibaum/programming-practice-2021 path: /exercise_4/exercise_4.py
def exercise_4(inputs): # DO NOT CHANGE THIS LINE
"""
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import random
#optimization method
def evaluation_salomon... | code_fim | hard | {
"lang": "python",
"repo": "champbodhibaum/programming-practice-2021",
"path": "/exercise_4/exercise_4.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: marek2901/django-graphene path: /testgraphane/sampleapi/schema.py
import graphene
from graphene_django import DjangoObjectType
from promise import Promise
from promise.dataloader import DataLoader
from .models import SampleObject, ObjectsChild
class SampleTypeChild(DjangoObjectType):
clas... | code_fim | hard | {
"lang": "python",
"repo": "marek2901/django-graphene",
"path": "/testgraphane/sampleapi/schema.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def batch_load_fn(self, keys):
children_mapping = {}
for child in ObjectsChild.objects.filter(parent_id__in=keys):
if not children_mapping.get(child.parent_id):
children_mapping[child.parent_id] = []
children_mapping[child.parent_id].append(child... | code_fim | medium | {
"lang": "python",
"repo": "marek2901/django-graphene",
"path": "/testgraphane/sampleapi/schema.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ssabit/simulation-modeling path: /5.py
# -*- coding: utf-8 -*-
"""5.ipynb
Automatically generated by Colaboratory.
<|fim_suffix|>start=25
end=50
print("Prime numbers between",start,"and",end,"are:")
for n in range(start,end+1):
if n>1:
for i in range(2,n):
if(n%i)... | code_fim | medium | {
"lang": "python",
"repo": "ssabit/simulation-modeling",
"path": "/5.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>print("Prime numbers between",start,"and",end,"are:")
for n in range(start,end+1):
if n>1:
for i in range(2,n):
if(n%i)==0:
break
else:
print(n)<|fim_prefix|># repo: ssabit/simulation-modeling path: /5.py
# -*- coding: utf-8 -*-
"""5.ipynb... | code_fim | easy | {
"lang": "python",
"repo": "ssabit/simulation-modeling",
"path": "/5.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> return obj
def to_string(self) -> str:
"""Convert an ImaKeyrings into its string representation; this does not include the tenant keyring"""
return json.dumps(self.to_json())
@staticmethod
def from_string(stringrepr: str) -> Optional["ImaKeyrings"]:
"""Convert... | code_fim | hard | {
"lang": "python",
"repo": "mbestavros/keylime",
"path": "/keylime/ima/file_signatures.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> """Load the filedata as a DER public key"""
try:
return serialization.load_der_public_key(filedata, backend=backend), None
except Exception:
return None, None
def _get_pubkey_from_pem_public_key(filedata: bytes, backend: Any) -> Tuple[Any, None]:
"""Load the filedata as a... | code_fim | hard | {
"lang": "python",
"repo": "mbestavros/keylime",
"path": "/keylime/ima/file_signatures.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: mbestavros/keylime path: /keylime/ima/file_signatures.py
28 = 8
HASH_ALGO_RIPE_MD_256 = 9
HASH_ALGO_RIPE_MD_320 = 10
HASH_ALGO_WP_256 = 11
HASH_ALGO_WP_384 = 12
HASH_ALGO_WP_512 = 13
HASH_ALGO_TGR_128 = 14
HASH_ALGO_TGR_160 = 15
HASH_ALGO_TGR_192 = 16
HASH_ALGO... | code_fim | hard | {
"lang": "python",
"repo": "mbestavros/keylime",
"path": "/keylime/ima/file_signatures.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: longlostsoul/EvoYellow path: /extras/tests/test_dump_sections.py
# -*- coding: utf-8 -*-
try:
import unittest2 as unittest
except ImportError:
import unittest
# check for things we need in unittest
if not hasattr(unittest.TestCase, 'setUpClass'):
sys.stderr.write("The unittest2 modu... | code_fim | hard | {
"lang": "python",
"repo": "longlostsoul/EvoYellow",
"path": "/extras/tests/test_dump_sections.py",
"mode": "psm",
"license": "Unlicense",
"source": "the-stack-v2"
} |
<|fim_suffix|> separator = "\t\t" # dumb
self.assertIn(separator, dump_incbin_for_section(0, separator=separator))
def test_dump_incbin_for_section_default(self):
rom = "baserom.gbc"
self.assertIn(rom, dump_incbin_for_section(0))
rom = "baserom"
self.assertIn(rom, du... | code_fim | hard | {
"lang": "python",
"repo": "longlostsoul/EvoYellow",
"path": "/extras/tests/test_dump_sections.py",
"mode": "spm",
"license": "Unlicense",
"source": "the-stack-v2"
} |
<|fim_suffix|>plt.plot(np.arange(1,iterN),ll)
plt.show()
# 2c
if pi[0] > pi[1]:
label2 = 0
label6 = 1
else:
label2 = 1
label6 = 0
mean_2 = mean[:,label2].reshape((28,28)).transpose()
plt.imshow(mean_2)
plt.show()
mean_6 = mean[:,label6].reshape((28,28)).transpose()
plt.imshow(mean_6)
plt.show()
# ... | code_fim | hard | {
"lang": "python",
"repo": "xia0nan/Gatech-CS6740",
"path": "/REF2/hw_3_solution/hw_3_solution/hw3_2.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: xia0nan/Gatech-CS6740 path: /REF2/hw_3_solution/hw_3_solution/hw3_2.py
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import random as rd
import math
from sklearn.cluster import KMeans
data = np.genfromtxt('data.dat')
label = np.genfromtxt('label.dat')
x = data.T
N = 1990... | code_fim | hard | {
"lang": "python",
"repo": "xia0nan/Gatech-CS6740",
"path": "/REF2/hw_3_solution/hw_3_solution/hw3_2.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|># 2c
if pi[0] > pi[1]:
label2 = 0
label6 = 1
else:
label2 = 1
label6 = 0
mean_2 = mean[:,label2].reshape((28,28)).transpose()
plt.imshow(mean_2)
plt.show()
mean_6 = mean[:,label6].reshape((28,28)).transpose()
plt.imshow(mean_6)
plt.show()
# 2d here you can just use packages to get k-means... | code_fim | hard | {
"lang": "python",
"repo": "xia0nan/Gatech-CS6740",
"path": "/REF2/hw_3_solution/hw_3_solution/hw3_2.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: cjhenck/outline-bots path: /src/email/responder.py
# Copyright 2020 ASL19 Organization
#
# 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/lic... | code_fim | hard | {
"lang": "python",
"repo": "cjhenck/outline-bots",
"path": "/src/email/responder.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> elif recipient == CONFIG['DELETE_USER_EMAIL']:
try:
deleted = api.delete_user(user_id=source_email)
except Exception:
email(source_email, 'try_again.j2')
return False
if deleted:
email(source_email, 'unsubscribed.j2')
... | code_fim | hard | {
"lang": "python",
"repo": "cjhenck/outline-bots",
"path": "/src/email/responder.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> logger.debug('Source Email {} recipient {}'.format(
source_email, recipient))
if recipient == CONFIG['TEST_EMAIL']:
feedback.send_email(
CONFIG['REPLY_EMAIL'],
source_email,
TEMPLATES['EMAIL_SUBJECT'],
'a',
'a',
... | code_fim | hard | {
"lang": "python",
"repo": "cjhenck/outline-bots",
"path": "/src/email/responder.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>
class DweetSerializer(serializers.ModelSerializer):
latest_comments = serializers.SerializerMethodField()
reply_to = serializers.PrimaryKeyRelatedField(
queryset=Dweet.with_deleted.all()
)
class Meta:
model = Dweet
fields = ('pk', 'code', 'posted', 'author',
... | code_fim | medium | {
"lang": "python",
"repo": "whackashoe/dwitter",
"path": "/dwitter/serializers.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: whackashoe/dwitter path: /dwitter/serializers.py
from rest_framework import serializers
from dwitter.models import Dweet, Comment
from dwitter.templatetags.insert_magic_links import insert_magic_links
from django.contrib.auth.models import User
from django.template.defaultfilters import urlizetru... | code_fim | medium | {
"lang": "python",
"repo": "whackashoe/dwitter",
"path": "/dwitter/serializers.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: cgsunkel/data-hub-api path: /datahub/omis/invoice/utils.py
from datetime import timedelta
from datahub.omis.invoice.constants import (
PAYMENT_DUE_DAYS_BEFORE_DELIVERY,
PAYMENT_DUE_DAYS_FROM_NOW,
)
def calculate_payment_due_date(order):
<|fim_suffix|> with a = 21, b = 14 and y = 30
... | code_fim | hard | {
"lang": "python",
"repo": "cgsunkel/data-hub-api",
"path": "/datahub/omis/invoice/utils.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> The resulting date is not going to be in the past because the constants
are so that there's always a gap between the quote expiry date
and the payment due date.
Given the quote expiry date as
[delivery date - a days] OR [date quote created + y days]
and payment due date as
... | code_fim | hard | {
"lang": "python",
"repo": "cgsunkel/data-hub-api",
"path": "/datahub/omis/invoice/utils.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: github4n/hsstock path: /hsstock/model/mysql/ft_5M.py
from sqlalchemy import Column, Integer, String, BigInteger,Date,DateTime,Float
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class FT5MBase(object):
code = Column(String, primary_key=True)
time_ke... | code_fim | hard | {
"lang": "python",
"repo": "github4n/hsstock",
"path": "/hsstock/model/mysql/ft_5M.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def getClass5mByIndex(tindex):
return globals()['FT5M{}'.format(tindex)]
class FT5M18(Base,FT5MBase):
__tablename__ = 'ft_5M_18'
class FT5M19(Base,FT5MBase):
__tablename__ = 'ft_5M_19'
class FT5M20(Base,FT5MBase):
__tablename__ = 'ft_5M_20'
class FT5M21(Base,FT5MBase):
__tablename__ = 'ft_... | code_fim | hard | {
"lang": "python",
"repo": "github4n/hsstock",
"path": "/hsstock/model/mysql/ft_5M.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: didib/ansible-navigator path: /src/ansible_navigator/actions/collections.py
""" :doc """
import curses
import json
import os
import shlex
import sys
from copy import deepcopy
from json.decoder import JSONDecodeError
from typing import Any
from typing import Dict
from typing import List
from typ... | code_fim | hard | {
"lang": "python",
"repo": "didib/ansible-navigator",
"path": "/src/ansible_navigator/actions/collections.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> self._collection_cache.open()
selected_collection = self._collections[self.steps.current.index]
cname_col = f"__{selected_collection['known_as']}"
plugins = []
for plugin_chksum, details in selected_collection["plugin_chksums"].items():
try:
... | code_fim | hard | {
"lang": "python",
"repo": "didib/ansible-navigator",
"path": "/src/ansible_navigator/actions/collections.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> """build the content for one option"""
return Step(
name="plugin_content",
tipe="content",
value=self.steps.current.value,
index=self.steps.current.index,
)
def _run_runner(self) -> None:
"""spin up runner"""
if ... | code_fim | hard | {
"lang": "python",
"repo": "didib/ansible-navigator",
"path": "/src/ansible_navigator/actions/collections.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: polatory/polatory path: /python/examples/test.py
#!/usr/bin/env python3
import numpy as np
import polatory as po
horse = np.loadtxt("../../data/horse.asc", delimiter=",")
points, normals = horse[:, :3], horse[:, 3:]
sdf = po.SdfDataGenerator(points, normals, 1e-4, 1e-3)
sdf_points, sdf_values ... | code_fim | medium | {
"lang": "python",
"repo": "polatory/polatory",
"path": "/python/examples/test.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|># print("values:", inter.evaluate(points))
# print("centers:", inter.centers)
# print("weights:", inter.weights)
bbox = po.Bbox3d([-1.0, -1.0, -1.0], [1.0, 1.0, 1.0])
fn = po.RbfFieldFunction(inter)
iso = po.Isosurface(bbox, 5e-4)
surf = iso.generate_from_seed_points(points, fn)
surf.export_obj("horse.ob... | code_fim | medium | {
"lang": "python",
"repo": "polatory/polatory",
"path": "/python/examples/test.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>bbox = po.Bbox3d([-1.0, -1.0, -1.0], [1.0, 1.0, 1.0])
fn = po.RbfFieldFunction(inter)
iso = po.Isosurface(bbox, 5e-4)
surf = iso.generate_from_seed_points(points, fn)
surf.export_obj("horse.obj")<|fim_prefix|># repo: polatory/polatory path: /python/examples/test.py
#!/usr/bin/env python3
import numpy as... | code_fim | hard | {
"lang": "python",
"repo": "polatory/polatory",
"path": "/python/examples/test.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: sepmoon/django_blog_demo path: /apps/articleApp/views.py
# -*- coding: utf-8 -*-
from django.views.generic.base import View
from django.shortcuts import render
from django.http import HttpResponseNotFound
from CacheFun.blog_cache import get_articles, get_all_articles, get_art_id, get_tag_search
... | code_fim | hard | {
"lang": "python",
"repo": "sepmoon/django_blog_demo",
"path": "/apps/articleApp/views.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def get(self, request, art_id):
art_data = get_articles(art_id)
# 上一篇和下一篇按钮,到顶部或者到底部的判断.
left_top = False
right_top = False
# 判断文章id在结果中的位置排位
id_list = get_art_id()
try:
list_position = id_list.index(int(art_id))
except Valu... | code_fim | hard | {
"lang": "python",
"repo": "sepmoon/django_blog_demo",
"path": "/apps/articleApp/views.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|># 搜索结果视图
class SearchView(View):
def get(self, request):
search_q = request.GET.get('search_q')
search_response = HttpResponseNotFound(charset='gb2312')
if search_q:
result = ArticleModel.objects.filter(
Q(article_title__icontains=search_q) | Q(artic... | code_fim | hard | {
"lang": "python",
"repo": "sepmoon/django_blog_demo",
"path": "/apps/articleApp/views.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> actual = gen.drain()
assert actual == expected
@pytest.mark.parametrize('array,batch_size,expected', [
(
[[1, 1, 1, 1, 1],
[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[0, 0, 0, 0, 0]],
2,
[
[[1, 1, 1, 1, 1], [0, 0, 0, 0, 0]],
... | code_fim | hard | {
"lang": "python",
"repo": "devforfu/SwissKnife-Old",
"path": "/tests/utils/test_batch_generator.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: devforfu/SwissKnife-Old path: /tests/utils/test_batch_generator.py
import pytest
import numpy as np
from swissknife.utils import BatchGenerator
@pytest.mark.parametrize('array,batch_size,expected', [
([1, 2, 3, 4, 5, 6], 1, [[1], [2], [3], [4], [5], [6]]),
([1, 2, 3, 4, 5, 6], 2, [[1, ... | code_fim | hard | {
"lang": "python",
"repo": "devforfu/SwissKnife-Old",
"path": "/tests/utils/test_batch_generator.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>if __name__ == '__main__':
img_path = r''
epsilon = 2
img_out_path = r''
img = imread(img_path)
contours = get_contours(img)
# contours = get_approx_contours(contours, epsilon)
contours = get_convex_hull(contours)
img_contour = write_contours(contours, img.shape)
imsav... | code_fim | hard | {
"lang": "python",
"repo": "piyush-jaiswal/image-processing",
"path": "/utils/contours.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: piyush-jaiswal/image-processing path: /utils/contours.py
import numpy as np
from imageio import imread, imsave
import cv2
def get_contours(img):
contours, _ = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
return contours
def get_approx_contours(contours, epsilon=2):
... | code_fim | medium | {
"lang": "python",
"repo": "piyush-jaiswal/image-processing",
"path": "/utils/contours.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
if __name__ == '__main__':
img_path = r''
epsilon = 2
img_out_path = r''
img = imread(img_path)
contours = get_contours(img)
# contours = get_approx_contours(contours, epsilon)
contours = get_convex_hull(contours)
img_contour = write_contours(contours, img.shape)
imsa... | code_fim | hard | {
"lang": "python",
"repo": "piyush-jaiswal/image-processing",
"path": "/utils/contours.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
common_startup()
# ---------------------------------- !common startup site handling -----------------------------------<|fim_prefix|># repo: rBrenick/script-tree path: /_install_/scripts/userSetup.py
# ---------------------------------- common startup site handling -----------------------------------
i... | code_fim | hard | {
"lang": "python",
"repo": "rBrenick/script-tree",
"path": "/_install_/scripts/userSetup.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: rBrenick/script-tree path: /_install_/scripts/userSetup.py
# ---------------------------------- common startup site handling -----------------------------------
import inspect
import os
import site
import sys
def common_startup():
<|fim_suffix|># ---------------------------------- !common start... | code_fim | hard | {
"lang": "python",
"repo": "rBrenick/script-tree",
"path": "/_install_/scripts/userSetup.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>nums=[1,2,3,4,5,5,6,7,8]
print(findDup(nums))<|fim_prefix|># repo: darrencheng0817/AlgorithmLearning path: /Python/interview/practiceTwice/repeatNumber.py
'''
Created on 2015年12月1日
给你一个数组,range[1,n]inclusive,然后说如果有个n+1的数组的话这里面有没
有重复?为什么?
然后followup:怎么找到那个重复的数字?有可能有多个重复
继续followup;如果说不让你交换数字,即不能排序怎么办?可以用空... | code_fim | easy | {
"lang": "python",
"repo": "darrencheng0817/AlgorithmLearning",
"path": "/Python/interview/practiceTwice/repeatNumber.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: darrencheng0817/AlgorithmLearning path: /Python/interview/practiceTwice/repeatNumber.py
'''
Created on 2015年12月1日
给你一个数组,range[1,n]inclusive,然后说如果有个n+1的数组的话这里面有没
有重复?为什么?
然后followup:怎么找到那个重复的数字?有可能有多个重复
继续followup;如果说不让你交换数字,即不能排序怎么办?可以用空间.
继续followup:如果说没有空间怎么办?
@author: Darren
'''
<|fim_suffix... | code_fim | easy | {
"lang": "python",
"repo": "darrencheng0817/AlgorithmLearning",
"path": "/Python/interview/practiceTwice/repeatNumber.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: kbrodt/tor4 path: /tests/nn/logsoftmax_test.py
import numpy as np
import tor4
import tor4.nn as nn
def test_logsoftmax_backward():
a = tor4.tensor([0.0, 0, 0], requires_grad=True)
lsm = nn.functional.log_softmax(a, dim=-1)
lsm.backward(tor4.tensor([1, 1, 2.0]))
assert np.allcl... | code_fim | hard | {
"lang": "python",
"repo": "kbrodt/tor4",
"path": "/tests/nn/logsoftmax_test.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def test_logsoftmax_backward2():
a = tor4.tensor([[1, 2, -3], [10.0, 0, -1]], requires_grad=True)
lsm = nn.functional.log_softmax(a, dim=-1)
lsm.backward(tor4.tensor([[2, 4, -1], [1, 1, 2.0]]))
assert np.allclose(
lsm.tolist(),
[[-1.3182, -0.31818, -5.3182], [0, -10, -11]... | code_fim | hard | {
"lang": "python",
"repo": "kbrodt/tor4",
"path": "/tests/nn/logsoftmax_test.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> print("\nThin Inventory")
print("=" * len("Thin Inventory"))
for module_name, module in chassis.get_thin_inventory().items():
print(module_name)
for port_name in module.ports:
print(port_name)
if __name__ == "__main__":
stc = init_stc(api, logger, install_dir=... | code_fim | hard | {
"lang": "python",
"repo": "jongku87/PyTestCenter",
"path": "/testcenter/samples/stc_samples.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> stc.send_arp_ns()
print(stc.get_arp_cache())
stc.start_devices()
time.sleep(8)
stc.stop_devices()
def manage_traffic():
stc.start_traffic()
time.sleep(8)
stc.stop_traffic()
port_stats = StcStats("generatorportresults")
port_stats.read_stats()
# You can get a... | code_fim | hard | {
"lang": "python",
"repo": "jongku87/PyTestCenter",
"path": "/testcenter/samples/stc_samples.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: jongku87/PyTestCenter path: /testcenter/samples/stc_samples.py
"""
Stand alone samples for STC package functionality.
Setup:
Two STC ports connected back to back.
"""
import json
import logging
import sys
import time
from pathlib import Path
from trafficgenerator.tgn_utils import ApiType, is_fa... | code_fim | hard | {
"lang": "python",
"repo": "jongku87/PyTestCenter",
"path": "/testcenter/samples/stc_samples.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: thankjura/gentoo-gnome path: /scripts/curses_log.py
import curses
import signal
import sys
from collections import OrderedDict
class CursesLog:
def __init__(self):
self._rows = OrderedDict()
self._screen = curses.initscr()
curses.def_shell_mode()
curses.start_... | code_fim | hard | {
"lang": "python",
"repo": "thankjura/gentoo-gnome",
"path": "/scripts/curses_log.py",
"mode": "psm",
"license": "LicenseRef-scancode-warranty-disclaimer",
"source": "the-stack-v2"
} |
<|fim_suffix|> @staticmethod
def exit():
curses.echo()
curses.nocbreak()
curses.reset_shell_mode()
curses.endwin()
def signal_handler(signal, frame):
CursesLog.exit()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)<|fim_prefix|># repo: thankjura/gentoo-gnome p... | code_fim | hard | {
"lang": "python",
"repo": "thankjura/gentoo-gnome",
"path": "/scripts/curses_log.py",
"mode": "spm",
"license": "LicenseRef-scancode-warranty-disclaimer",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: pythonitalia/pycon path: /backend/newsletters/admin.py
from django.contrib import admin
from .models import Subscription
<|fim_suffix|> list_display = ("email", "date_subscribed")<|fim_middle|>@admin.register(Subscription)
class SubscriptionAdmin(admin.ModelAdmin):
| code_fim | medium | {
"lang": "python",
"repo": "pythonitalia/pycon",
"path": "/backend/newsletters/admin.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> list_display = ("email", "date_subscribed")<|fim_prefix|># repo: pythonitalia/pycon path: /backend/newsletters/admin.py
from django.contrib import admin
from .models import Subscription
<|fim_middle|>@admin.register(Subscription)
class SubscriptionAdmin(admin.ModelAdmin):
| code_fim | medium | {
"lang": "python",
"repo": "pythonitalia/pycon",
"path": "/backend/newsletters/admin.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> out = []
out.append(str(len(teams)))
for team in teams:
L = [len(team)] + team
s = ' '.join(map(str, L))
out.append(s)
return '\n'.join(out)<|fim_prefix|># repo: exoji2e/Hashcode-demo-uccps-2021 path: /solvers/solve_simple.py
import argparse
import random
from col... | code_fim | hard | {
"lang": "python",
"repo": "exoji2e/Hashcode-demo-uccps-2021",
"path": "/solvers/solve_simple.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: exoji2e/Hashcode-demo-uccps-2021 path: /solvers/solve_simple.py
import argparse
import random
from collections import *
from dataparser import parse
# inp is an input file as a single string
# return your output as a string
def solve(inp, args):
<|fim_suffix|> for _ in range(ns.T3):
p... | code_fim | hard | {
"lang": "python",
"repo": "exoji2e/Hashcode-demo-uccps-2021",
"path": "/solvers/solve_simple.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: unixpickle/sgdstore-py path: /sgdstore/cell.py
"""
RNNCell implementations.
"""
import math
import numpy as np
import tensorflow as tf
from tensorflow.contrib.rnn import RNNCell # pylint: disable=E0611
from .loss import batched_mse
# pylint: disable=R0902
class Cell(RNNCell):
"""
A re... | code_fim | hard | {
"lang": "python",
"repo": "unixpickle/sgdstore-py",
"path": "/sgdstore/cell.py",
"mode": "psm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> new_state = self._train_state(inputs, state)
outputs = self._run_query(inputs, new_state)
if self._flatten_output:
outputs = tf.reshape(outputs, (tf.shape(outputs)[0], self.output_size))
return outputs, new_state
def _train_state(self, inputs, state):
... | code_fim | hard | {
"lang": "python",
"repo": "unixpickle/sgdstore-py",
"path": "/sgdstore/cell.py",
"mode": "spm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> def _run_query(self, inputs, state):
"""
Get the result of applying the query.
"""
in_shape = (self._query_batch,) + self._layer.input_shape
queries = self._projection('Query', inputs, in_shape)
return self._layer.apply(queries, list(state))
def _pr... | code_fim | hard | {
"lang": "python",
"repo": "unixpickle/sgdstore-py",
"path": "/sgdstore/cell.py",
"mode": "spm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: python-visualization/folium path: /tests/test_features.py
""""
Folium Features Tests
---------------------
"""
import json
import os
import warnings
import pytest
from branca.element import Element
import folium
from folium import Choropleth, ClickForMarker, GeoJson, Map, Popup
@pytest.fixt... | code_fim | hard | {
"lang": "python",
"repo": "python-visualization/folium",
"path": "/tests/test_features.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> if not os.path.exists(file):
raise FileNotFoundError(f"The vegalite data {file} does not exist.")
with open(file) as f:
spec = json.load(f)
if version is None or "$schema" in spec:
return spec
# Sample versions that might show up
schema_version = {2: "v2.6.0"... | code_fim | hard | {
"lang": "python",
"repo": "python-visualization/folium",
"path": "/tests/test_features.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def main():
agents = [UniformRandom(), NashEq(), StackelbergEq()]
s_header = 'gamma '
s = ''
# s = 'gamma V0_ur V1_ur V2_ur V3_ur V0_n V1_n V2_n V3_n V0_s V1_s V2_s V3_s'
for gamma in range(0, 100, 5):
gamma = gamma/100.0
s += '\n{} '.format(gamma)
... | code_fim | hard | {
"lang": "python",
"repo": "Acveah/MarkovGameSolvers",
"path": "/src/general-sum/agents.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Acveah/MarkovGameSolvers path: /src/general-sum/agents.py
import numpy as np
import nashpy as nash
from strategy import Strategy
__author__ = "Sailik Sengupta"
class UniformRandom(Strategy):
def get_name(self):
return 'UR'
def get_value(self, s, A_D, A_A, R_D, R_A, T, Q_D, Q_A)... | code_fim | hard | {
"lang": "python",
"repo": "Acveah/MarkovGameSolvers",
"path": "/src/general-sum/agents.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Add constraints to make attaker have a pure strategy
con = self.lib.LinExpr()
for j in range(num_a):
con.add(q[j])
m.addConstr(con==1)
# Add constrains to make attacker select dominant pure strategy
for j in range(num_a):
val =... | code_fim | hard | {
"lang": "python",
"repo": "Acveah/MarkovGameSolvers",
"path": "/src/general-sum/agents.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> :param urls: [Array of String] URLs to download. e.g. [.../9709_s16_ms_21.pdf, .../9709_s16_ms_22.pdf]
:param to_dir: String, directory to download e.g. "./9709/"
:param threads: Number of files downloading at the same time
:param timeout: [int] Time in seconds for timeout. When timeout a ... | code_fim | hard | {
"lang": "python",
"repo": "Astatine-213-Tian/Past-Paper-Crawler",
"path": "/DownloadModule.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Astatine-213-Tian/Past-Paper-Crawler path: /DownloadModule.py
import threading
import ssl
import urllib.request as rq
import urllib.error
import time
import os
ssl._create_default_https_context = ssl._create_unverified_context
forge_agent_header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW... | code_fim | hard | {
"lang": "python",
"repo": "Astatine-213-Tian/Past-Paper-Crawler",
"path": "/DownloadModule.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def statistics(update_global=True):
"""
Current statistics of the download.
:param update_global: To update the global variable.
:return: <Dict> information of downloading task. See the Task Class for explainations.
"""
info = {
"Q": 0,
"D": 0,
"T": 0,
... | code_fim | hard | {
"lang": "python",
"repo": "Astatine-213-Tian/Past-Paper-Crawler",
"path": "/DownloadModule.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: lablup/backend.ai-client-py path: /src/ai/backend/client/auth.py
from datetime import datetime
import enum
import hashlib
import hmac
from typing import (
Mapping,
Tuple,
)
import attr
from yarl import URL
__all__ = (
'AuthToken',
'AuthTokenTypes',
'generate_signature',
)
... | code_fim | hard | {
"lang": "python",
"repo": "lablup/backend.ai-client-py",
"path": "/src/ai/backend/client/auth.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> sign_str = '{}\n{}\n{}\nhost:{}\ncontent-type:{}\nx-backendai-version:{}\n{}'.format( # noqa
method.upper(),
rel_url,
date.isoformat(),
hostname,
content_type.lower(),
version,
body_hash,
)
sign_bytes = sign_str.encode()
sign_key = ... | code_fim | hard | {
"lang": "python",
"repo": "lablup/backend.ai-client-py",
"path": "/src/ai/backend/client/auth.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> sign_key = hmac.new(secret_key.encode(),
date.strftime('%Y%m%d').encode(), hash_type).digest()
sign_key = hmac.new(sign_key, hostname.encode(), hash_type).digest()
signature = hmac.new(sign_key, sign_bytes, hash_type).hexdigest()
headers = {
'Authorization'... | code_fim | hard | {
"lang": "python",
"repo": "lablup/backend.ai-client-py",
"path": "/src/ai/backend/client/auth.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: sennerholm/k8s-bigip-ctlr path: /cmd/k8s-bigip-ctlr/test/bigipconfigdriver.py
#!/usr/bin/env python
import signal
import socket
import sys
def signal_handler(signal, frame):
sys.stderr.write("WARNING: Received signal"+ str(signal))
sys.exit(0)
<|fim_suffix|>s = socket.socket(socket.AF_... | code_fim | easy | {
"lang": "python",
"repo": "sennerholm/k8s-bigip-ctlr",
"path": "/cmd/k8s-bigip-ctlr/test/bigipconfigdriver.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> sys.stderr.write("WARNING: Received signal"+ str(signal))
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 0))
s.listen(5)
while 1:
try:
sys.stderr.write("DEBUG: Python Driver listening")
client, addres... | code_fim | easy | {
"lang": "python",
"repo": "sennerholm/k8s-bigip-ctlr",
"path": "/cmd/k8s-bigip-ctlr/test/bigipconfigdriver.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: webclinic017/LJWEquities path: /alembic/versions/38051cbde0f9_added_dailybar_table.py
"""added DailyBar table
Revision ID: 38051cbde0f9
Revises: 0b857bc76ed7
Create Date: 2021-08-30 15:01:06.312908
<|fim_suffix|># revision identifiers, used by Alembic.
revision = '38051cbde0f9'
down_revision = ... | code_fim | medium | {
"lang": "python",
"repo": "webclinic017/LJWEquities",
"path": "/alembic/versions/38051cbde0f9_added_dailybar_table.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def upgrade():
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... | code_fim | medium | {
"lang": "python",
"repo": "webclinic017/LJWEquities",
"path": "/alembic/versions/38051cbde0f9_added_dailybar_table.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.