uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8ee64ed931c3501873ea1a1a | train | function | @contextlib.contextmanager
def texpr_reductions_enabled():
old = torch._C._jit_set_texpr_reductions_enabled(True)
try:
yield
finally:
torch._C._jit_set_texpr_reductions_enabled(old)
| @contextlib.contextmanager
def texpr_reductions_enabled():
| old = torch._C._jit_set_texpr_reductions_enabled(True)
try:
yield
finally:
torch._C._jit_set_texpr_reductions_enabled(old)
| n for n in nodes if n.kind() not in profiling_opcodes]
def warmup_forward(f, *args, profiling_count=2):
for i in range(profiling_count):
results = f(*args)
return results
@contextlib.contextmanager
def texpr_reductions_enabled():
| 64 | 64 | 55 | 14 | 49 | vitaut/pytorch | test/test_jit_fuser_te.py | Python | texpr_reductions_enabled | texpr_reductions_enabled | 52 | 58 | 52 | 53 | e5582ebd3203bc764d33c67164d6171fcc6a8163 | bigcode/the-stack | train |
7f8652459c45c7ee0d386d9a | train | class | class Menu:
def __init__(self):
pass
def start(self):
self.handle_main_menu()
print("Goodbye")
def handle_main_menu(self):
option = self.show_main_menu()
while option != 0:
if option == 1:
self.handle_ispl_generator_menu()
eli... | class Menu:
| def __init__(self):
pass
def start(self):
self.handle_main_menu()
print("Goodbye")
def handle_main_menu(self):
option = self.show_main_menu()
while option != 0:
if option == 1:
self.handle_ispl_generator_menu()
elif option == ... | from stv.generators.ispl import CastlesIsplGeneratorObjective, CastlesIsplGeneratorSubjective
from stv.generators.ispl import BridgeModelIsplGenerator, AbsentMindedBridgeModelIsplGenerator
from stv.generators.ispl import SimpleVotingModelIsplGenerator, SimpleVotingModel2IsplGenerator
from stv.tools import FileTools
cla... | 81 | 256 | 1,795 | 3 | 77 | wp777/stv-compute | main.py | Python | Menu | Menu | 7 | 219 | 7 | 7 | cda6bc691106ae2e18b9067ff403b1fadedf98d9 | bigcode/the-stack | train |
42191cbe74c7d93d8a1e5dc3 | train | function | def extract_mre_diff(ud_files, mre_file, mre_diff):
known_keys = set()
for ud_f in ud_files:
with open(ud_f, 'rb') as f:
content = f.read().decode('utf-8')
sentences = parse(content)
keys = [sentence_key(s) for s in sentences]
known_keys.update(keys)
... | def extract_mre_diff(ud_files, mre_file, mre_diff):
| known_keys = set()
for ud_f in ud_files:
with open(ud_f, 'rb') as f:
content = f.read().decode('utf-8')
sentences = parse(content)
keys = [sentence_key(s) for s in sentences]
known_keys.update(keys)
with open(mre_file, 'rb') as f:
content = f.... |
from conllu import parse
def sentence_key(sentence):
skip_pos = {'PUNCT', 'SYM'}
tokens = [t['form'] for t in sentence if t['upostag'] not in skip_pos]
key = ' '.join(tokens).replace('_', ' ').strip().lower()
key = re.sub(r'\s+', ' ', key, flags=re.UNICODE)
return key
def extract_mre_diff(ud_fi... | 102 | 102 | 340 | 15 | 86 | shkarupa-alex/ruconlluconv | ruconlluconv/str.py | Python | extract_mre_diff | extract_mre_diff | 21 | 54 | 21 | 21 | 1d3c7a1f885d0eef49138a14e8d442912d41971a | bigcode/the-stack | train |
021be7b6cc913ed96c11e113 | train | function | def main():
parser = argparse.ArgumentParser(description='Extract STR additional sentences from MorphoRuEval2017 dataset')
parser.add_argument(
'ud_files',
type=str,
help='Directory with UD files')
parser.add_argument(
'mre_train',
type=argparse.FileType('rb'),
... | def main():
| parser = argparse.ArgumentParser(description='Extract STR additional sentences from MorphoRuEval2017 dataset')
parser.add_argument(
'ud_files',
type=str,
help='Directory with UD files')
parser.add_argument(
'mre_train',
type=argparse.FileType('rb'),
help='Morp... | for i, s in enumerate(sentences):
if not len(s):
continue
f.write('# sent_id = syntagrus_add_mre17_{}\n'.format(i + 1).encode('utf-8'))
f.write(s.serialize().encode('utf-8'))
def main():
| 64 | 65 | 219 | 3 | 61 | shkarupa-alex/ruconlluconv | ruconlluconv/str.py | Python | main | main | 57 | 83 | 57 | 57 | 159bfd68dd14dd2ff916c7f2f1f5932faa4ca124 | bigcode/the-stack | train |
b834d7c2cd4c0eeaaff2cde6 | train | function | def sentence_key(sentence):
skip_pos = {'PUNCT', 'SYM'}
tokens = [t['form'] for t in sentence if t['upostag'] not in skip_pos]
key = ' '.join(tokens).replace('_', ' ').strip().lower()
key = re.sub(r'\s+', ' ', key, flags=re.UNICODE)
return key
| def sentence_key(sentence):
| skip_pos = {'PUNCT', 'SYM'}
tokens = [t['form'] for t in sentence if t['upostag'] not in skip_pos]
key = ' '.join(tokens).replace('_', ' ').strip().lower()
key = re.sub(r'\s+', ' ', key, flags=re.UNICODE)
return key
| from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import re
from conllu import parse
def sentence_key(sentence):
| 43 | 64 | 80 | 5 | 37 | shkarupa-alex/ruconlluconv | ruconlluconv/str.py | Python | sentence_key | sentence_key | 11 | 18 | 11 | 11 | 1dbefa2ae046a1985e4dbc0e2247060fcc40a291 | bigcode/the-stack | train |
aa8f7b96e9b48dff2a061c88 | train | class | class TLM_PT_Utility(bpy.types.Panel):
bl_label = "Utilities"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "render"
bl_options = {'DEFAULT_CLOSED'}
bl_parent_id = "ARM_PT_BakePanel"
@classmethod
def poll(self, context):
scene = context.scene
retur... | class TLM_PT_Utility(bpy.types.Panel):
| bl_label = "Utilities"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "render"
bl_options = {'DEFAULT_CLOSED'}
bl_parent_id = "ARM_PT_BakePanel"
@classmethod
def poll(self, context):
scene = context.scene
return scene.arm_bakemode == "Lightmap"
... | if sceneProperties.tlm_encoding_mode_a == "RGBM":
row = layout.row(align=True)
row.prop(sceneProperties, "tlm_encoding_range")
row = layout.row(align=True)
row.prop(sceneProperties, "tlm_decoder_setup")
if sc... | 256 | 256 | 915 | 11 | 245 | onelsonic/armory | blender/arm/lightmapper/panels/scene.py | Python | TLM_PT_Utility | TLM_PT_Utility | 364 | 471 | 364 | 364 | b4fe29b5bfde08ec276f9226bf97aab7045d46a8 | bigcode/the-stack | train |
0a2b8ace92e07815b44e128a | train | class | class TLM_PT_Additional(bpy.types.Panel):
bl_label = "Additional"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "render"
bl_options = {'DEFAULT_CLOSED'}
bl_parent_id = "ARM_PT_BakePanel"
@classmethod
def poll(self, context):
scene = context.scene
r... | class TLM_PT_Additional(bpy.types.Panel):
| bl_label = "Additional"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "render"
bl_options = {'DEFAULT_CLOSED'}
bl_parent_id = "ARM_PT_BakePanel"
@classmethod
def poll(self, context):
scene = context.scene
return scene.arm_bakemode == "Lightmap"
... | row = layout.row(align=True)
row.label(text="Environment Probes")
row = layout.row()
row.operator("tlm.build_environmentprobe")
row = layout.row()
row.operator("tlm.clean_environmentprobe")
row = layout.row()
row.prop(sceneProperties, "tlm_environment_pr... | 256 | 256 | 997 | 11 | 245 | onelsonic/armory | blender/arm/lightmapper/panels/scene.py | Python | TLM_PT_Additional | TLM_PT_Additional | 473 | 584 | 473 | 473 | 779ebacff75ee790d4d1088806598f6a5b4da804 | bigcode/the-stack | train |
5cc54ce4215fc2faae154dd6 | train | class | class TLM_PT_Encoding(bpy.types.Panel):
bl_label = "Encoding"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "render"
bl_options = {'DEFAULT_CLOSED'}
bl_parent_id = "ARM_PT_BakePanel"
@classmethod
def poll(self, context):
scene = context.scene
retur... | class TLM_PT_Encoding(bpy.types.Panel):
| bl_label = "Encoding"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "render"
bl_options = {'DEFAULT_CLOSED'}
bl_parent_id = "ARM_PT_BakePanel"
@classmethod
def poll(self, context):
scene = context.scene
return scene.arm_bakemode == "Lightmap"
... | .row(align=True)
row.prop(scene.TLM_SceneProperties, "tlm_filtering_bilateral_color_deviation")
row = layout.row(align=True)
row.prop(scene.TLM_SceneProperties, "tlm_filtering_bilateral_coordinate_deviation")
row = layout.row(align=True)
... | 174 | 174 | 581 | 11 | 163 | onelsonic/armory | blender/arm/lightmapper/panels/scene.py | Python | TLM_PT_Encoding | TLM_PT_Encoding | 295 | 362 | 295 | 295 | 235775e894ece91723675db66c3d0e4ca03989b6 | bigcode/the-stack | train |
89094cc8fdbedc7608a8298d | train | class | class TLM_PT_Settings(bpy.types.Panel):
bl_label = "Settings"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "render"
bl_options = {'DEFAULT_CLOSED'}
bl_parent_id = "ARM_PT_BakePanel"
@classmethod
def poll(self, context):
scene = context.scene
retur... | class TLM_PT_Settings(bpy.types.Panel):
| bl_label = "Settings"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "render"
bl_options = {'DEFAULT_CLOSED'}
bl_parent_id = "ARM_PT_BakePanel"
@classmethod
def poll(self, context):
scene = context.scene
return scene.arm_bakemode == "Lightmap"
... | import bpy, importlib, math
from bpy.props import *
from bpy.types import Menu, Panel
from .. utility import icon
from .. properties.denoiser import oidn, optix
class TLM_PT_Settings(bpy.types.Panel):
| 50 | 256 | 1,467 | 10 | 39 | onelsonic/armory | blender/arm/lightmapper/panels/scene.py | Python | TLM_PT_Settings | TLM_PT_Settings | 7 | 165 | 7 | 7 | 4908347cacbaebe6e6d3440ec36b0b185c46260b | bigcode/the-stack | train |
56ea435b840ec425c87cc3aa | train | class | class TLM_PT_Filtering(bpy.types.Panel):
bl_label = "Filtering"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "render"
bl_options = {'DEFAULT_CLOSED'}
bl_parent_id = "ARM_PT_BakePanel"
@classmethod
def poll(self, context):
scene = context.scene
ret... | class TLM_PT_Filtering(bpy.types.Panel):
| bl_label = "Filtering"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "render"
bl_options = {'DEFAULT_CLOSED'}
bl_parent_id = "ARM_PT_BakePanel"
@classmethod
def poll(self, context):
scene = context.scene
return scene.arm_bakemode == "Lightmap"
... | row = layout.row(align=True)
row.prop(denoiseProperties, "tlm_oidn_maxmem")
row = layout.row(align=True)
row.prop(denoiseProperties, "tlm_oidn_affinity")
# row = layout.row(align=True)
# row.prop(denoiseProperties, "tlm_denoise_ao")
elif sceneProperti... | 209 | 209 | 698 | 11 | 198 | onelsonic/armory | blender/arm/lightmapper/panels/scene.py | Python | TLM_PT_Filtering | TLM_PT_Filtering | 225 | 292 | 225 | 225 | bc15d2638f0749d36cb5ee2646fe0facd3f1934e | bigcode/the-stack | train |
ccf203fa28442edc0955d66f | train | class | class TLM_PT_Denoise(bpy.types.Panel):
bl_label = "Denoise"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "render"
bl_options = {'DEFAULT_CLOSED'}
bl_parent_id = "ARM_PT_BakePanel"
@classmethod
def poll(self, context):
scene = context.scene
return ... | class TLM_PT_Denoise(bpy.types.Panel):
| bl_label = "Denoise"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "render"
bl_options = {'DEFAULT_CLOSED'}
bl_parent_id = "ARM_PT_BakePanel"
@classmethod
def poll(self, context):
scene = context.scene
return scene.arm_bakemode == "Lightmap"
d... | elif sceneProperties.tlm_lightmap_engine == "OctaneRender":
engineProperties = scene.TLM_Engine3Properties
#LUXCORE SETTINGS HERE
octane_available = True
row = layout.row(align=True)
row.operator("tlm.build_lightmaps")
row = layou... | 164 | 164 | 548 | 12 | 152 | onelsonic/armory | blender/arm/lightmapper/panels/scene.py | Python | TLM_PT_Denoise | TLM_PT_Denoise | 167 | 221 | 167 | 167 | 9093cbf833aca3beaded5855f10b7d8d397174ee | bigcode/the-stack | train |
4e3b59f82eba769be29884da | train | class | class MaxTweetsListener(StreamListener):
def __init__(self, max_tweets, *args, **kwargs):
# initialize the StreamListener
super().__init__(*args, **kwargs)
# set the instance attributes
self.max_tweets = max_tweets
self.counter = 0
def on_connect(self):
... | class MaxTweetsListener(StreamListener):
| def __init__(self, max_tweets, *args, **kwargs):
# initialize the StreamListener
super().__init__(*args, **kwargs)
# set the instance attributes
self.max_tweets = max_tweets
self.counter = 0
def on_connect(self):
print('connected. listening for incoming t... | script assumes you have a file called config.py
which stores the 4 required authentication tokens:
1. API_KEY
2. API_SECRET
3. ACCESS_TOKEN
4. ACCESS_TOKEN_SECRET
"""
auth = OAuthHandler(config.API_KEY, config.API_SECRET)
auth.set_access_token(config.ACCESS_TOKEN, confi... | 89 | 89 | 297 | 7 | 81 | dashnak90/Docker-data-pipeline | twitter_bot/tweet_collector/get_tweets_streaming2.py | Python | MaxTweetsListener | MaxTweetsListener | 30 | 74 | 30 | 31 | a1e445409c7d577f130d0c05a1b093e680db782d | bigcode/the-stack | train |
edb05b9a2e9301b87c57fe81 | train | function | def authenticate():
"""Function for handling Twitter Authentication. Please note
that this script assumes you have a file called config.py
which stores the 4 required authentication tokens:
1. API_KEY
2. API_SECRET
3. ACCESS_TOKEN
4. ACCESS_TOKEN_SECRET
"""
auth =... | def authenticate():
| """Function for handling Twitter Authentication. Please note
that this script assumes you have a file called config.py
which stores the 4 required authentication tokens:
1. API_KEY
2. API_SECRET
3. ACCESS_TOKEN
4. ACCESS_TOKEN_SECRET
"""
auth = OAuthHandler(config... | pymongo
import time
# create a connection - (create engine)
client = pymongo.MongoClient('mongodb') #name of the docker container
db = client.tweetsdb #the name of a database*(autom created)
collection = db.tweet_data #create a collection
def authenticate():
| 64 | 64 | 99 | 3 | 60 | dashnak90/Docker-data-pipeline | twitter_bot/tweet_collector/get_tweets_streaming2.py | Python | authenticate | authenticate | 14 | 28 | 14 | 14 | 8b4fb7f9d7cb2310c234bd4f5fbc4f5d1e87cb3b | bigcode/the-stack | train |
fd3547e31777769c96c2ec66 | train | function | @login_required(login_url='login')
def project(request, post):
post = Post.objects.get(title=post)
ratings = Rating.objects.filter(user=request.user, post=post).first()
rating_status = None
if ratings is None:
rating_status = False
else:
rating_status = True
if request.method == ... | @login_required(login_url='login')
def project(request, post):
| post = Post.objects.get(title=post)
ratings = Rating.objects.filter(user=request.user, post=post).first()
rating_status = None
if ratings is None:
rating_status = False
else:
rating_status = True
if request.method == 'POST':
form = RatingsForm(request.POST)
if for... | params)
@login_required(login_url='login')
def new_project(request):
# user = User.objects.get()
if request.method == 'POST':
proj_form = PostForm(request.POST)
if proj_form.is_valid():
proj_form.save()
return redirect('index')
else:
proj_form = PostForm()
... | 105 | 105 | 350 | 13 | 92 | Elrophi/Awards | awapp/views.py | Python | project | project | 113 | 156 | 113 | 114 | 61a7210b34d4f8c8a5920895475cfbfbe160b208 | bigcode/the-stack | train |
a2ffe98137fc63924dd459d7 | train | class | class ProfileViewSet(viewsets.ModelViewSet):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
| class ProfileViewSet(viewsets.ModelViewSet):
| queryset = Profile.objects.all()
serializer_class = ProfileSerializer
| 1)
random_post = posts[a_post]
print(random_post.photo)
except Post.DoesNotExist:
posts = None
return render(request, 'index.html', {'posts': posts, 'form': form, 'random_post': random_post})
class ProfileViewSet(viewsets.ModelViewSet):
| 64 | 64 | 24 | 10 | 54 | Elrophi/Awards | awapp/views.py | Python | ProfileViewSet | ProfileViewSet | 33 | 35 | 33 | 33 | 220a0dc578228473d27e6a577e32f2d0b0b97be2 | bigcode/the-stack | train |
4ef24ecae0b12b5de9bf2333 | train | class | class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
| class PostViewSet(viewsets.ModelViewSet):
| queryset = Post.objects.all()
serializer_class = PostSerializer
| random_post': random_post})
class ProfileViewSet(viewsets.ModelViewSet):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
class PostViewSet(viewsets.ModelViewSet):
| 64 | 64 | 24 | 10 | 53 | Elrophi/Awards | awapp/views.py | Python | PostViewSet | PostViewSet | 43 | 45 | 43 | 43 | 916af2140a2420c29d2bde559ad6d5205fc916e3 | bigcode/the-stack | train |
b3aeab151e44905d86472a6e | train | class | class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
| class UserViewSet(viewsets.ModelViewSet):
| queryset = User.objects.all()
serializer_class = UserSerializer
| posts = None
return render(request, 'index.html', {'posts': posts, 'form': form, 'random_post': random_post})
class ProfileViewSet(viewsets.ModelViewSet):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
class UserViewSet(viewsets.ModelViewSet):
| 64 | 64 | 24 | 10 | 53 | Elrophi/Awards | awapp/views.py | Python | UserViewSet | UserViewSet | 38 | 40 | 38 | 38 | 95db83b9e0020076a1950c99fa65f96081794af6 | bigcode/the-stack | train |
a69dd0b5b7c132b22fc1f7e3 | train | function | def user_profile(request, username):
user_prof = get_object_or_404(User, username=username)
if request.user == user_prof:
return redirect('profile', username=request.user.username)
params = {
'user_prof': user_prof,
}
return render(request, 'userprofile.html', params)
| def user_profile(request, username):
| user_prof = get_object_or_404(User, username=username)
if request.user == user_prof:
return redirect('profile', username=request.user.username)
params = {
'user_prof': user_prof,
}
return render(request, 'userprofile.html', params)
| login(request, user)
return redirect('index')
else:
form = SignupForm()
return render(request, 'registration/signup.html', {'form': form})
@login_required(login_url='login')
def profile(request, username):
return render(request, 'profile.html')
def user_profile(request, username):
| 64 | 64 | 66 | 7 | 57 | Elrophi/Awards | awapp/views.py | Python | user_profile | user_profile | 68 | 75 | 68 | 68 | 14f713a34080f09bebe15a032c99a1df05222258 | bigcode/the-stack | train |
377ad0e1e2587ad6e579dd91 | train | function | def search_project(request):
if request.method == 'GET':
title = request.GET.get("title")
results = Post.objects.filter(title__icontains=title).all()
print(results)
message = f'name'
params = {
'results': results,
'message': message
}
r... | def search_project(request):
| if request.method == 'GET':
title = request.GET.get("title")
results = Post.objects.filter(title__icontains=title).all()
print(results)
message = f'name'
params = {
'results': results,
'message': message
}
return render(request, 'result... | rate.save()
return HttpResponseRedirect(request.path_info)
else:
form = RatingsForm()
params = {
'post': post,
'rating_form': form,
'rating_status': rating_status
}
return render(request, 'project.html', params)
def search_project(request):
| 64 | 64 | 105 | 5 | 59 | Elrophi/Awards | awapp/views.py | Python | search_project | search_project | 159 | 172 | 159 | 159 | eae22645f454a960bfca56cafa56f223a46d2274 | bigcode/the-stack | train |
dd604a8b97ef490db6299c38 | train | function | @login_required(login_url='login')
def edit_profile(request, username):
user = User.objects.get(username=username)
if request.method == 'POST':
user_form = UpdateUserForm(request.POST, instance=request.user)
prof_form = UpdateUserProfileForm(request.POST, request.FILES, instance=request.user.pro... | @login_required(login_url='login')
def edit_profile(request, username):
| user = User.objects.get(username=username)
if request.method == 'POST':
user_form = UpdateUserForm(request.POST, instance=request.user)
prof_form = UpdateUserProfileForm(request.POST, request.FILES, instance=request.user.profile)
if user_form.is_valid() and prof_form.is_valid():
... | (User, username=username)
if request.user == user_prof:
return redirect('profile', username=request.user.username)
params = {
'user_prof': user_prof,
}
return render(request, 'userprofile.html', params)
@login_required(login_url='login')
def edit_profile(request, username):
| 64 | 64 | 157 | 14 | 50 | Elrophi/Awards | awapp/views.py | Python | edit_profile | edit_profile | 78 | 95 | 78 | 79 | 9a1a7b74cf7f949276829bc8097e6a788acb4705 | bigcode/the-stack | train |
1a5fd881a14cbaf560183e78 | train | function | @login_required(login_url='login')
def new_project(request):
# user = User.objects.get()
if request.method == 'POST':
proj_form = PostForm(request.POST)
if proj_form.is_valid():
proj_form.save()
return redirect('index')
else:
proj_form = PostForm()
params ... | @login_required(login_url='login')
def new_project(request):
# user = User.objects.get()
| if request.method == 'POST':
proj_form = PostForm(request.POST)
if proj_form.is_valid():
proj_form.save()
return redirect('index')
else:
proj_form = PostForm()
params = {
'proj_form': proj_form,
}
return render(request, 'index.html', params)
| _form = UpdateUserProfileForm(instance=request.user.profile)
params = {
'user_form': user_form,
'prof_form': prof_form
}
return render(request, 'edit.html', params)
@login_required(login_url='login')
def new_project(request):
# user = User.objects.get()
| 64 | 64 | 90 | 20 | 44 | Elrophi/Awards | awapp/views.py | Python | new_project | new_project | 97 | 110 | 97 | 99 | 8de68ca8d4c5716932d99a157e3358f755f610b2 | bigcode/the-stack | train |
3ffda9bc0294f178ccae434d | train | function | def index(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.user = request.user
post.save()
else:
form = PostForm()
try:
posts = Post.objects.all()
posts = ... | def index(request):
| if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.user = request.user
post.save()
else:
form = PostForm()
try:
posts = Post.objects.all()
posts = posts[::-1]
... | Form
from rest_framework import viewsets
from .models import Profile, Post, Rating
from .serializer import ProfileSerializer, UserSerializer, PostSerializer
from django.contrib.auth import login, authenticate
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
import random
def inde... | 64 | 64 | 137 | 4 | 59 | Elrophi/Awards | awapp/views.py | Python | index | index | 13 | 31 | 13 | 13 | 5ced12644bc2bf7e1d7002fa040542a346d5e4c5 | bigcode/the-stack | train |
82a66e7b99c3acdea9f8aace | train | function | @login_required(login_url='login')
def profile(request, username):
return render(request, 'profile.html')
| @login_required(login_url='login')
def profile(request, username):
| return render(request, 'profile.html')
| password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('index')
else:
form = SignupForm()
return render(request, 'registration/signup.html', {'form': form})
@login_required(login_url='login')
def profile(request,... | 64 | 64 | 22 | 13 | 51 | Elrophi/Awards | awapp/views.py | Python | profile | profile | 63 | 65 | 63 | 64 | 7ca256ada35047b72a7181cebc7d8f7a612bc309 | bigcode/the-stack | train |
312f31f808a185155378ea90 | train | function | def signup(request):
if request.method == 'POST':
form = SignupForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, pass... | def signup(request):
| if request.method == 'POST':
form = SignupForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
... | = Profile.objects.all()
serializer_class = ProfileSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
def signup(request):
| 64 | 64 | 100 | 4 | 59 | Elrophi/Awards | awapp/views.py | Python | signup | signup | 48 | 60 | 48 | 48 | c36eeecd538d6f5abb410f58258180e93279847c | bigcode/the-stack | train |
473fa80b57ce2cd584487cab | train | function | def url_parser(origin, target_list, deep=0, backend_cookies=""):
"""
通过分割url来给url分类,并试图去重
"""
origin_domain = urlparse(origin).netloc
pre_result_dict = {}
temp_result_list = []
result_list = []
for target in target_list:
parse_result = urlparse(target['url'])
if parse_... | def url_parser(origin, target_list, deep=0, backend_cookies=""):
| """
通过分割url来给url分类,并试图去重
"""
origin_domain = urlparse(origin).netloc
pre_result_dict = {}
temp_result_list = []
result_list = []
for target in target_list:
parse_result = urlparse(target['url'])
if parse_result.netloc == "":
target_domain = origin_domain
... | 15:46
@desc:
'''
import re
from urllib.parse import urlparse, parse_qs, urljoin
from web.spider.models import SubDomainList, UrlTable
from web.index.models import BanList
from utils.log import logger
from utils.base import get_now_scan_id
def checkbanlist(domain):
banlist = BanList.objects.filter(is_active=Tru... | 122 | 122 | 407 | 17 | 104 | laozhudetui/LSpider | core/urlparser.py | Python | url_parser | url_parser | 31 | 92 | 31 | 31 | 8b319982602bab0f2467c315554eee5ac28bd5bf | bigcode/the-stack | train |
2420eb8ebf296dd2990a6428 | train | function | def checkbanlist(domain):
banlist = BanList.objects.filter(is_active=True)
for banword in banlist:
if banword.ban_domain in domain:
return True
return False
| def checkbanlist(domain):
| banlist = BanList.objects.filter(is_active=True)
for banword in banlist:
if banword.ban_domain in domain:
return True
return False
|
@desc:
'''
import re
from urllib.parse import urlparse, parse_qs, urljoin
from web.spider.models import SubDomainList, UrlTable
from web.index.models import BanList
from utils.log import logger
from utils.base import get_now_scan_id
def checkbanlist(domain):
| 64 | 64 | 44 | 6 | 57 | laozhudetui/LSpider | core/urlparser.py | Python | checkbanlist | checkbanlist | 21 | 28 | 21 | 21 | 0e1ed3ec9e7cec57c50ecfd7e1f51aa96fd0c01c | bigcode/the-stack | train |
d8ea596624240b8106f79869 | train | function | def url_filter(target_list):
"""
url 去重
"""
result_list = []
# 存在黑名单路径的数量
black_path_count = 0
# 黑名单域名
BLACK_DOMAIN_NAME_LIST = ['docs', 'image', 'static', 'blogs']
for domain in target_list:
temp_list = {}
new_temp_list = {}
has_black_domain = False
... | def url_filter(target_list):
| """
url 去重
"""
result_list = []
# 存在黑名单路径的数量
black_path_count = 0
# 黑名单域名
BLACK_DOMAIN_NAME_LIST = ['docs', 'image', 'static', 'blogs']
for domain in target_list:
temp_list = {}
new_temp_list = {}
has_black_domain = False
url_dict_list = target_lis... | _dict[target_domain][parse_result] = 0
# 总结结果
temp_result_list = url_filter(pre_result_dict)
for temp_result in temp_result_list:
if temp_result.geturl():
if temp_result.netloc:
request_url = temp_result.geturl()
else:
request_url = urljoi... | 209 | 209 | 698 | 6 | 202 | laozhudetui/LSpider | core/urlparser.py | Python | url_filter | url_filter | 95 | 192 | 95 | 95 | 1788d887ff0c00399ac1b365f6e1576bbc3d966f | bigcode/the-stack | train |
6a7797a415032ff4d831303b | train | function | def check_same(flag, origin_target_list, new_target, black_path_count=0):
"""
检查相似性
需要和原本列表中的所有url都不相似
"""
BANWORD_LAST_LIST = ['.htm', '.png', '.jpg', '.mp']
BLACK_PATH_NAME = ['static', 'upload', 'docs', 'js', 'css', 'font', 'image']
check_flag = True
is_has_banword = False
for... | def check_same(flag, origin_target_list, new_target, black_path_count=0):
| """
检查相似性
需要和原本列表中的所有url都不相似
"""
BANWORD_LAST_LIST = ['.htm', '.png', '.jpg', '.mp']
BLACK_PATH_NAME = ['static', 'upload', 'docs', 'js', 'css', 'font', 'image']
check_flag = True
is_has_banword = False
for origin_target in origin_target_list:
i = 0
diff = 0
... | # 路径重复判定处理
path_parsers = target.path.split('/')
# 用一个特殊的思路来处理
# 使用A来代表纯数字,B来代表字符串
# 如果两个链接中只有A相同,那么则相似
# 如果只有B相同,则认为不相似
flag = ""
for path_par in path_parsers:
if re.search('^\d+$', path_par):
... | 249 | 249 | 832 | 18 | 230 | laozhudetui/LSpider | core/urlparser.py | Python | check_same | check_same | 195 | 303 | 195 | 195 | 528c68d0cd3685718a886e456ee1f45497c356b2 | bigcode/the-stack | train |
e4c2f686189a4ef7e3015097 | train | class | class EdgeModule(nn.Module):
"""
Edge branch.
"""
def __init__(self, in_fea=[256, 512, 1024], mid_fea=256, out_fea=2):
super(EdgeModule, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(in_fea[0], mid_fea, kernel_size=1, padding=0, dilation=1, bias=False),
... | class EdgeModule(nn.Module):
| """
Edge branch.
"""
def __init__(self, in_fea=[256, 512, 1024], mid_fea=256, out_fea=2):
super(EdgeModule, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(in_fea[0], mid_fea, kernel_size=1, padding=0, dilation=1, bias=False),
InPlaceABNSync(mid_fea)
... | def _make_stage(self, features, out_features, size):
prior = nn.AdaptiveAvgPool2d(output_size=(size, size))
conv = nn.Conv2d(features, out_features, kernel_size=1, bias=False)
bn = InPlaceABNSync(out_features)
return nn.Sequential(prior, conv, bn)
def forward(self, feats):
... | 163 | 163 | 545 | 6 | 156 | loaysh2010/Promising-Deep-Semantic-Nuclei-Segmentation-Models | networks/selfcorrection.py | Python | EdgeModule | EdgeModule | 123 | 165 | 123 | 123 | fa02e7ed8455c7a7ef3dbfaab7a8ea20c06f2adc | bigcode/the-stack | train |
e76c54a328352a255496cec6 | train | class | class DecoderModuleMax(nn.Module):
"""
Parsing Branch Decoder Module.
"""
def __init__(self, num_classes):
super(DecoderModuleMax, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(512+1, 256, kernel_size=1, padding=0, dilation=1, bias=False),
InPlaceABNSyn... | class DecoderModuleMax(nn.Module):
| """
Parsing Branch Decoder Module.
"""
def __init__(self, num_classes):
super(DecoderModuleMax, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(512+1, 256, kernel_size=1, padding=0, dilation=1, bias=False),
InPlaceABNSync(256)
)
self.conv2... | )
self.conv4 = nn.Conv2d(256, num_classes, kernel_size=1, padding=0, dilation=1, bias=True)
def forward(self, xt, xl):
_, _, h, w = xl.size()
xt = F.interpolate(self.conv1(xt), size=(h, w), mode='bilinear', align_corners=True)
xl = self.conv2(xl)
x = torch.cat([xt, xl], di... | 130 | 130 | 434 | 7 | 122 | loaysh2010/Promising-Deep-Semantic-Nuclei-Segmentation-Models | networks/selfcorrection.py | Python | DecoderModuleMax | DecoderModuleMax | 202 | 250 | 202 | 202 | 443d5b95fda2caf8594202fefc5b4054d5c2c92f | bigcode/the-stack | train |
c876ae00cb75aab4cda58646 | train | function | def SelfCorrectionMax(num_classes=2, pretrained='resnet101-imagenet.pth'):
model = ResNetMax(Bottleneck, [3, 4, 23, 3], num_classes)
settings = pretrained_settings['resnet101']['imagenet']
initialize_pretrained_model(model, settings, pretrained)
return model
| def SelfCorrectionMax(num_classes=2, pretrained='resnet101-imagenet.pth'):
| model = ResNetMax(Bottleneck, [3, 4, 23, 3], num_classes)
settings = pretrained_settings['resnet101']['imagenet']
initialize_pretrained_model(model, settings, pretrained)
return model
| , [3, 4, 23, 3], num_classes)
settings = pretrained_settings['resnet101']['imagenet']
initialize_pretrained_model(model, settings, pretrained)
return model
def SelfCorrectionMax(num_classes=2, pretrained='resnet101-imagenet.pth'):
| 64 | 64 | 73 | 20 | 43 | loaysh2010/Promising-Deep-Semantic-Nuclei-Segmentation-Models | networks/selfcorrection.py | Python | SelfCorrectionMax | SelfCorrectionMax | 642 | 646 | 642 | 642 | 301fb97a475989e0c6d6d5358aa08082db633db8 | bigcode/the-stack | train |
d0d59ae21a0cd86889c5ba38 | train | function | def SelfCorrectionAll(num_classes=2, pretrained='resnet101-imagenet.pth'):
model = ResNetAll(Bottleneck, [3, 4, 23, 3], num_classes)
settings = pretrained_settings['resnet101']['imagenet']
initialize_pretrained_model(model, settings, pretrained)
return model
| def SelfCorrectionAll(num_classes=2, pretrained='resnet101-imagenet.pth'):
| model = ResNetAll(Bottleneck, [3, 4, 23, 3], num_classes)
settings = pretrained_settings['resnet101']['imagenet']
initialize_pretrained_model(model, settings, pretrained)
return model
| , [3, 4, 23, 3], num_classes)
settings = pretrained_settings['resnet101']['imagenet']
initialize_pretrained_model(model, settings, pretrained)
return model
def SelfCorrectionAll(num_classes=2, pretrained='resnet101-imagenet.pth'):
| 64 | 64 | 73 | 20 | 43 | loaysh2010/Promising-Deep-Semantic-Nuclei-Segmentation-Models | networks/selfcorrection.py | Python | SelfCorrectionAll | SelfCorrectionAll | 648 | 652 | 648 | 648 | a8c6d6aca24e7e5efd683b0c894c8402c93c6922 | bigcode/the-stack | train |
13cbf71ce265b76ba5b80083 | train | class | class ResNetMax(nn.Module):
def __init__(self, block, layers, num_classes):
self.inplanes = 128
super(ResNetMax, self).__init__()
self.conv1 = conv3x3(3, 64, stride=2)
self.bn1 = nn.BatchNorm2d(64)
self.relu1 = nn.ReLU(inplace=False)
self.conv2 = conv3x3(64... | class ResNetMax(nn.Module):
| def __init__(self, block, layers, num_classes):
self.inplanes = 128
super(ResNetMax, self).__init__()
self.conv1 = conv3x3(3, 64, stride=2)
self.bn1 = nn.BatchNorm2d(64)
self.relu1 = nn.ReLU(inplace=False)
self.conv2 = conv3x3(64, 64)
self.bn2 = nn.... | (self.bn1(self.conv1(x)))
x = self.relu2(self.bn2(self.conv2(x)))
x = self.relu3(self.bn3(self.conv3(x)))
x1 = self.maxpool(x)
x2 = self.layer1(x1)
x3 = self.layer2(x2)
x4 = self.layer3(x3)
x5 = self.layer4(x4)
x = self.context_encoding(x5)
parsin... | 256 | 256 | 970 | 7 | 248 | loaysh2010/Promising-Deep-Semantic-Nuclei-Segmentation-Models | networks/selfcorrection.py | Python | ResNetMax | ResNetMax | 416 | 515 | 416 | 416 | ec69fd9546e2937c3fe246a2bad36d332ee6ca1e | bigcode/the-stack | train |
3bf530d2a9c8a3f9f1108ffb | train | class | class ResNetAll(nn.Module):
def __init__(self, block, layers, num_classes):
self.inplanes = 128
super(ResNetAll, self).__init__()
self.conv1 = conv3x3(3, 64, stride=2)
self.bn1 = nn.BatchNorm2d(64)
self.relu1 = nn.ReLU(inplace=False)
self.conv2 = conv3x3(64... | class ResNetAll(nn.Module):
| def __init__(self, block, layers, num_classes):
self.inplanes = 128
super(ResNetAll, self).__init__()
self.conv1 = conv3x3(3, 64, stride=2)
self.bn1 = nn.BatchNorm2d(64)
self.relu1 = nn.ReLU(inplace=False)
self.conv2 = conv3x3(64, 64)
self.bn2 = nn.... | x = self.relu3(self.bn3(self.conv3(x)))
x1 = self.maxpool(x)
x2 = self.layer1(x1)
x3 = self.layer2(x2)
x4 = self.layer3(x3)
x5 = self.layer4(x4)
#print('x5=',x5.size())
#print('**************************')
x = self.con... | 256 | 256 | 970 | 7 | 248 | loaysh2010/Promising-Deep-Semantic-Nuclei-Segmentation-Models | networks/selfcorrection.py | Python | ResNetAll | ResNetAll | 517 | 616 | 517 | 517 | 3d0582dfb46a094031f36313481989423fb99156 | bigcode/the-stack | train |
5c7d409af1c52410908c99a8 | train | class | class DecoderModuleAll(nn.Module):
"""
Parsing Branch Decoder Module.
"""
def __init__(self, num_classes):
super(DecoderModuleAll, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(512+4, 256, kernel_size=1, padding=0, dilation=1, bias=False),
InPlaceABNSyn... | class DecoderModuleAll(nn.Module):
| """
Parsing Branch Decoder Module.
"""
def __init__(self, num_classes):
super(DecoderModuleAll, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(512+4, 256, kernel_size=1, padding=0, dilation=1, bias=False),
InPlaceABNSync(256)
)
self.conv2... | InPlaceABNSync(256)
)
self.conv4 = nn.Conv2d(256+1, num_classes, kernel_size=1, padding=0, dilation=1, bias=True)
def forward(self, xt, xl):
_, _, h, w = xl.size()
mxt_=torch.max(xt, 1,True)[0]
xt=torch.cat([xt,mxt_],1)
xt = F.inter... | 232 | 232 | 775 | 7 | 224 | loaysh2010/Promising-Deep-Semantic-Nuclei-Segmentation-Models | networks/selfcorrection.py | Python | DecoderModuleAll | DecoderModuleAll | 252 | 320 | 252 | 252 | 02f42654441c8a8e51d80e7e7a5478e9be34838a | bigcode/the-stack | train |
e0de3bdc565821aceb650412 | train | class | class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, multi_grid=1):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.con... | class Bottleneck(nn.Module):
| expansion = 4
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, multi_grid=1):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes... | NSync.
Reference: https://github.com/mapillary/inplace_abn
"""
def __init__(self, num_features):
super(InPlaceABNSync, self).__init__()
self.bn = nn.BatchNorm2d(num_features)
self.leaky_relu = nn.LeakyReLU(inplace=True)
def forward(self, x):
x = self.bn(x)
x = s... | 100 | 100 | 336 | 6 | 93 | loaysh2010/Promising-Deep-Semantic-Nuclei-Segmentation-Models | networks/selfcorrection.py | Python | Bottleneck | Bottleneck | 53 | 91 | 53 | 53 | 7d8d27256b80876a93cfc19a808e5ef2338878c7 | bigcode/the-stack | train |
4e7c58d4213b5c9fe97ba2d6 | train | function | def SelfCorrection(num_classes=2, pretrained='networks/resnet101-imagenet.pth'):
model = ResNet(Bottleneck, [3, 4, 23, 3], num_classes)
settings = pretrained_settings['resnet101']['imagenet']
initialize_pretrained_model(model, settings, pretrained)
return model
| def SelfCorrection(num_classes=2, pretrained='networks/resnet101-imagenet.pth'):
| model = ResNet(Bottleneck, [3, 4, 23, 3], num_classes)
settings = pretrained_settings['resnet101']['imagenet']
initialize_pretrained_model(model, settings, pretrained)
return model
| = i.split('.')
if not i_parts[0] == 'fc':
new_params['.'.join(i_parts[0:])] = saved_state_dict[i]
model.load_state_dict(new_params)
def SelfCorrection(num_classes=2, pretrained='networks/resnet101-imagenet.pth'):
| 64 | 64 | 73 | 21 | 43 | loaysh2010/Promising-Deep-Semantic-Nuclei-Segmentation-Models | networks/selfcorrection.py | Python | SelfCorrection | SelfCorrection | 636 | 640 | 636 | 636 | 550011b219b9785433535ae35b4334ccaa358ad7 | bigcode/the-stack | train |
051da48129f60a8109f28214 | train | class | class DecoderModule(nn.Module):
"""
Parsing Branch Decoder Module.
"""
def __init__(self, num_classes):
super(DecoderModule, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(512, 256, kernel_size=1, padding=0, dilation=1, bias=False),
InPlaceABNSync(256)
... | class DecoderModule(nn.Module):
| """
Parsing Branch Decoder Module.
"""
def __init__(self, num_classes):
super(DecoderModule, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(512, 256, kernel_size=1, padding=0, dilation=1, bias=False),
InPlaceABNSync(256)
)
self.conv2 = nn... | inear', align_corners=True)
edge3 = F.interpolate(edge3, size=(h, w), mode='bilinear', align_corners=True)
edge = torch.cat([edge1, edge2, edge3], dim=1)
edge_fea = torch.cat([edge1_fea, edge2_fea, edge3_fea], dim=1)
edge = self.conv5(edge)
return edge, edge_fea
class DecoderMo... | 100 | 100 | 336 | 6 | 93 | loaysh2010/Promising-Deep-Semantic-Nuclei-Segmentation-Models | networks/selfcorrection.py | Python | DecoderModule | DecoderModule | 168 | 200 | 168 | 168 | 5f23b62a8a7f01c136aa83786705991f11be4876 | bigcode/the-stack | train |
a2c806481f9628cfbae57125 | train | class | class InPlaceABNSync(nn.Module):
"""
Serve same as the InplaceABNSync.
Reference: https://github.com/mapillary/inplace_abn
"""
def __init__(self, num_features):
super(InPlaceABNSync, self).__init__()
self.bn = nn.BatchNorm2d(num_features)
self.leaky_relu = nn.LeakyReLU(inpla... | class InPlaceABNSync(nn.Module):
| """
Serve same as the InplaceABNSync.
Reference: https://github.com/mapillary/inplace_abn
"""
def __init__(self, num_features):
super(InPlaceABNSync, self).__init__()
self.bn = nn.BatchNorm2d(num_features)
self.leaky_relu = nn.LeakyReLU(inplace=True)
def forward(self, x... | },
}
def conv3x3(in_planes, out_planes, stride=1):
"3x3 convolution with padding"
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class InPlaceABNSync(nn.Module):
| 64 | 64 | 113 | 9 | 55 | loaysh2010/Promising-Deep-Semantic-Nuclei-Segmentation-Models | networks/selfcorrection.py | Python | InPlaceABNSync | InPlaceABNSync | 37 | 51 | 37 | 37 | b6d0607abe7a84fb7de079a4a84ea9eb383dd7b5 | bigcode/the-stack | train |
f6a31a7d6fe865648157410d | train | class | class ResNet(nn.Module):
def __init__(self, block, layers, num_classes):
self.inplanes = 128
super(ResNet, self).__init__()
self.conv1 = conv3x3(3, 64, stride=2)
self.bn1 = nn.BatchNorm2d(64)
self.relu1 = nn.ReLU(inplace=False)
self.conv2 = conv3x3(64, 64)
s... | class ResNet(nn.Module):
| def __init__(self, block, layers, num_classes):
self.inplanes = 128
super(ResNet, self).__init__()
self.conv1 = conv3x3(3, 64, stride=2)
self.bn1 = nn.BatchNorm2d(64)
self.relu1 = nn.ReLU(inplace=False)
self.conv2 = conv3x3(64, 64)
self.bn2 = nn.BatchNorm2d(... | 1,keepdim=True)
#aggAll_=torch.cat([mx_,md_,mn_,std_],1)
#agg_=self.conv1x1(aggAll_);
agg_ = torch.cat([mx_,md_,mn_,std_],1)
xl = torch.cat([xl,agg_],1)
xl = self.conv2(xl)
x = torch.cat([xt, xl], dim=1)
x = self.conv3(x)
... | 256 | 256 | 940 | 6 | 249 | loaysh2010/Promising-Deep-Semantic-Nuclei-Segmentation-Models | networks/selfcorrection.py | Python | ResNet | ResNet | 323 | 414 | 323 | 323 | 3208fc919c28392221d683a29202ca90cb7abab8 | bigcode/the-stack | train |
fcebddeb493644a311b4092f | train | function | def conv3x3(in_planes, out_planes, stride=1):
"3x3 convolution with padding"
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
| def conv3x3(in_planes, out_planes, stride=1):
| "3x3 convolution with padding"
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
| ': [0.406, 0.456, 0.485],
'std': [0.225, 0.224, 0.229],
'num_classes': 1000
}
},
}
def conv3x3(in_planes, out_planes, stride=1):
| 64 | 64 | 53 | 15 | 49 | loaysh2010/Promising-Deep-Semantic-Nuclei-Segmentation-Models | networks/selfcorrection.py | Python | conv3x3 | conv3x3 | 32 | 35 | 32 | 32 | e529bbaa6f292c90b8bd4c84b523b353d9eb0fc8 | bigcode/the-stack | train |
e06984a947aa722edeba0339 | train | function | def initialize_pretrained_model(model, settings, pretrained='./models/resnet101-imagenet.pth'):
model.input_space = settings['input_space']
model.input_size = settings['input_size']
model.input_range = settings['input_range']
model.mean = settings['mean']
model.std = settings['std']
if pretrain... | def initialize_pretrained_model(model, settings, pretrained='./models/resnet101-imagenet.pth'):
| model.input_space = settings['input_space']
model.input_size = settings['input_size']
model.input_range = settings['input_range']
model.mean = settings['mean']
model.std = settings['std']
if pretrained is not None:
saved_state_dict = torch.load(pretrained)
new_params = model.sta... | _result=F.interpolate(input=fusion_result, size=(h, w), mode='bilinear', align_corners=True)
#print('after fusion_result=',fusion_result.size())
return fusion_result
def initialize_pretrained_model(model, settings, pretrained='./models/resnet101-imagenet.pth'):
| 64 | 64 | 148 | 21 | 42 | loaysh2010/Promising-Deep-Semantic-Nuclei-Segmentation-Models | networks/selfcorrection.py | Python | initialize_pretrained_model | initialize_pretrained_model | 619 | 633 | 619 | 619 | 49fbf196b84a7b9bec8381290f66015e291a5bbc | bigcode/the-stack | train |
c33216bc3f1a93b2f5291bf7 | train | class | class PSPModule(nn.Module):
"""
Reference:
Zhao, Hengshuang, et al. *"Pyramid scene parsing network."*
"""
def __init__(self, features=2048, out_features=512, sizes=(1, 2, 3, 6)):
super(PSPModule, self).__init__()
self.stages = []
self.stages = nn.ModuleList([self._make... | class PSPModule(nn.Module):
| """
Reference:
Zhao, Hengshuang, et al. *"Pyramid scene parsing network."*
"""
def __init__(self, features=2048, out_features=512, sizes=(1, 2, 3, 6)):
super(PSPModule, self).__init__()
self.stages = []
self.stages = nn.ModuleList([self._make_stage(features, out_feature... | self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
residual = self.downsample(x)
out = out + residual
out = se... | 94 | 94 | 316 | 6 | 87 | loaysh2010/Promising-Deep-Semantic-Nuclei-Segmentation-Models | networks/selfcorrection.py | Python | PSPModule | PSPModule | 93 | 121 | 93 | 93 | 9bae6ab8a07836b3adb5c8a4b9335bff69bc52f5 | bigcode/the-stack | train |
1c46e215ed0684613f6ee2f0 | train | class | class TestMolecularManipulationInvolvedInThermoEstimation(unittest.TestCase):
"""
Contains unit tests for methods of molecular manipulations for thermo estimation
"""
def test_convert_ring_to_sub_molecule(self):
# list out testing moleculess
smiles1 = 'C1CCCCC1'
smiles2 = 'C1CC... | class TestMolecularManipulationInvolvedInThermoEstimation(unittest.TestCase):
| """
Contains unit tests for methods of molecular manipulations for thermo estimation
"""
def test_convert_ring_to_sub_molecule(self):
# list out testing moleculess
smiles1 = 'C1CCCCC1'
smiles2 = 'C1CCC2CCCCC2C1'
smiles3 = 'C1CC2CCCC3CCCC(C1)C23'
mol1 = Molecule(... | 1C2" doesn't have controversial shared
atomtypes in correction estimation, which is regarded as a simple case.
"""
smiles = 'C1=CCC2=C1C2'
mol = Molecule().from_smiles(smiles)
# extract polyring from the molecule
polyring = mol.get_disparate_cycles()[1][0]
ther... | 256 | 256 | 4,762 | 17 | 239 | mbprend/RMG-Py | rmgpy/data/thermoTest.py | Python | TestMolecularManipulationInvolvedInThermoEstimation | TestMolecularManipulationInvolvedInThermoEstimation | 1,145 | 1,593 | 1,145 | 1,145 | 703a492b0a4c5fd34f3473c824cbce5e90c3af19 | bigcode/the-stack | train |
50a39240703e2bb18b42baf2 | train | class | class TestThermoDatabase(unittest.TestCase):
"""
Contains unit tests of the ThermoDatabase class.
"""
@classmethod
def setUpClass(self):
"""A function that is run ONCE before all unit tests in this class."""
global database
self.database = database.thermo
self.datab... | class TestThermoDatabase(unittest.TestCase):
| """
Contains unit tests of the ThermoDatabase class.
"""
@classmethod
def setUpClass(self):
"""A function that is run ONCE before all unit tests in this class."""
global database
self.database = database.thermo
self.databaseWithoutLibraries = ThermoDatabase()
... | _into_single_rings
from rmgpy.exceptions import DatabaseError
from rmgpy.ml.estimator import MLEstimator
from rmgpy.molecule.molecule import Molecule
from rmgpy.quantity import Quantity
from rmgpy.species import Species
################################################################################
def setUpModule(... | 256 | 256 | 6,642 | 9 | 247 | mbprend/RMG-Py | rmgpy/data/thermoTest.py | Python | TestThermoDatabase | TestThermoDatabase | 77 | 595 | 77 | 77 | 11ad64635b1e908599bbfacbb88a87d6a0ea139f | bigcode/the-stack | train |
bcbece30f6dbf1c47e7e617b | train | function | def is_tcd_available():
"""Check if TCD is available."""
import platform
import subprocess
host = get_testing_tcd_authentication_info()[0]
if host is not None:
arg = '-n' if platform.system() == 'Windows' else '-c'
result = subprocess.call(['ping', arg, '1', host]) == 0
else:
... | def is_tcd_available():
| """Check if TCD is available."""
import platform
import subprocess
host = get_testing_tcd_authentication_info()[0]
if host is not None:
arg = '-n' if platform.system() == 'Windows' else '-c'
result = subprocess.call(['ping', arg, '1', host]) == 0
else:
result = False
... | os.environ['TCD_USER']
password = os.environ['TCD_PW']
except KeyError:
print('Thermo Central Database Authentication Environment Variables Not Completely Set!')
return None, 0, None, None
return host, port, username, password
def is_tcd_available():
| 64 | 64 | 92 | 6 | 57 | mbprend/RMG-Py | rmgpy/data/thermoTest.py | Python | is_tcd_available | is_tcd_available | 1,609 | 1,621 | 1,609 | 1,609 | 28c58c81fb89675fcbedc3e2eae976a56c0f715a | bigcode/the-stack | train |
ac5f2129a5e297b9dd86ffca | train | function | def tearDownModule():
"""A function that is run ONCE after all unit tests in this module."""
from rmgpy.data import rmg
rmg.database = None
| def tearDownModule():
| """A function that is run ONCE after all unit tests in this module."""
from rmgpy.data import rmg
rmg.database = None
| .species import Species
################################################################################
def setUpModule():
"""A function that is run ONCE before all unit tests in this module."""
global database
database = RMGDatabase()
database.load_thermo(os.path.join(settings['database.directory']... | 63 | 64 | 39 | 5 | 58 | mbprend/RMG-Py | rmgpy/data/thermoTest.py | Python | tearDownModule | tearDownModule | 60 | 63 | 60 | 60 | 1a1139250f7ab5996dbb17c4a3c1b3e1445ce8e9 | bigcode/the-stack | train |
b9a22bd825c69cd0a1b92f65 | train | class | class TestThermoAccuracyAromatics(TestThermoAccuracy):
"""
Contains tests for accuracy of thermo estimates and symmetry calculations for aromatics only.
A copy of the above class, but with different test compounds.
"""
def setUp(self):
self.Tlist = [300, 400, 500, 600, 800, 1000, 1500]... | class TestThermoAccuracyAromatics(TestThermoAccuracy):
| """
Contains tests for accuracy of thermo estimates and symmetry calculations for aromatics only.
A copy of the above class, but with different test compounds.
"""
def setUp(self):
self.Tlist = [300, 400, 500, 600, 800, 1000, 1500]
self.testCases = [
# SMILES ... | in zip(self.Tlist, cp_list):
self.assertAlmostEqual(Cp, thermo_data.get_heat_capacity(T) / 4.184, places=1,
msg="Cp{3} error for {0}. Expected {1} but calculated {2}.".format(
smiles, Cp, thermo_data.get_heat_capacity(T) ... | 244 | 244 | 814 | 13 | 231 | mbprend/RMG-Py | rmgpy/data/thermoTest.py | Python | TestThermoAccuracyAromatics | TestThermoAccuracyAromatics | 684 | 747 | 684 | 684 | a4b26e844eeff3d98d0be74fe91483c44b23df5d | bigcode/the-stack | train |
95cb2977fb682946942ac99c | train | class | class TestThermoDatabaseLoading(unittest.TestCase):
def test_failing_loads_thermo_libraries(self):
database = ThermoDatabase()
libraries = ['primaryThermoLibrary', 'GRI-Mech3.0', 'I am a library not existing in official RMG']
path = os.path.join(settings['database.directory'], 'thermo')
... | class TestThermoDatabaseLoading(unittest.TestCase):
| def test_failing_loads_thermo_libraries(self):
database = ThermoDatabase()
libraries = ['primaryThermoLibrary', 'GRI-Mech3.0', 'I am a library not existing in official RMG']
path = os.path.join(settings['database.directory'], 'thermo')
with self.assertRaises(Exception):
... | thermo(os.path.join(settings['database.directory'], 'thermo'))
def tearDownModule():
"""A function that is run ONCE after all unit tests in this module."""
from rmgpy.data import rmg
rmg.database = None
class TestThermoDatabaseLoading(unittest.TestCase):
| 64 | 64 | 98 | 10 | 53 | mbprend/RMG-Py | rmgpy/data/thermoTest.py | Python | TestThermoDatabaseLoading | TestThermoDatabaseLoading | 66 | 74 | 66 | 67 | 01bfd4c75ad955879b1952470fefdecab73850cb | bigcode/the-stack | train |
bc8c8f24ba6a0f1085edaf0f | train | class | class TestCyclicThermo(unittest.TestCase):
"""
Contains unit tests of the ThermoDatabase class.
"""
@classmethod
def setUpClass(cls):
"""A function that is run ONCE before all unit tests in this class."""
global database
cls.database = database.thermo
def test_compute_g... | class TestCyclicThermo(unittest.TestCase):
| """
Contains unit tests of the ThermoDatabase class.
"""
@classmethod
def setUpClass(cls):
"""A function that is run ONCE before all unit tests in this class."""
global database
cls.database = database.thermo
def test_compute_group_additivity_thermo_for_two_ring_molecul... | o_OH_CHO', thermo.comment)
self.assertNotIn('p_OH_MeO', thermo.comment)
self.assertIn('o_Oj_CHO', thermo.comment)
self.assertIn('m_Oj_CHO', thermo.comment)
self.assertIn('p_Oj_OCH3', thermo.comment)
self.assertIn('o_CHO_CHO', thermo.comment)
self.assertIn('o_CHO_MeO', the... | 256 | 256 | 4,531 | 10 | 246 | mbprend/RMG-Py | rmgpy/data/thermoTest.py | Python | TestCyclicThermo | TestCyclicThermo | 750 | 1,142 | 750 | 750 | 6132a3eb6904e342bdc0555da9b6fecad1e131e7 | bigcode/the-stack | train |
b46c8a1812fab6083b6344c2 | train | class | class TestThermoAccuracy(unittest.TestCase):
"""
Contains tests for accuracy of thermo estimates and symmetry calculations.
"""
@classmethod
def setUpClass(cls):
"""A function that is run ONCE before all unit tests in this class."""
global database
cls.database = database.th... | class TestThermoAccuracy(unittest.TestCase):
| """
Contains tests for accuracy of thermo estimates and symmetry calculations.
"""
@classmethod
def setUpClass(cls):
"""A function that is run ONCE before all unit tests in this class."""
global database
cls.database = database.thermo
def setUp(self):
"""
... | = False # set the more stable molecule to nonreactive for this check
thermo_gav2 = self.database.get_thermo_data_from_groups(spec) # thermo of the speciesless stable molecule
self.assertTrue(thermo_gav2.get_enthalpy(298) > thermo_gav1.get_enthalpy(298),
msg="Did not select the... | 256 | 256 | 1,765 | 9 | 247 | mbprend/RMG-Py | rmgpy/data/thermoTest.py | Python | TestThermoAccuracy | TestThermoAccuracy | 598 | 681 | 598 | 598 | b9cf3c7e3e5cf823f8624aba55b8dbf36c82f36b | bigcode/the-stack | train |
6c47abb47db334a04e1c61d5 | train | function | def setUpModule():
"""A function that is run ONCE before all unit tests in this module."""
global database
database = RMGDatabase()
database.load_thermo(os.path.join(settings['database.directory'], 'thermo'))
| def setUpModule():
| """A function that is run ONCE before all unit tests in this module."""
global database
database = RMGDatabase()
database.load_thermo(os.path.join(settings['database.directory'], 'thermo'))
| clic_into_single_rings
from rmgpy.exceptions import DatabaseError
from rmgpy.ml.estimator import MLEstimator
from rmgpy.molecule.molecule import Molecule
from rmgpy.quantity import Quantity
from rmgpy.species import Species
################################################################################
def setUpModu... | 64 | 64 | 51 | 5 | 58 | mbprend/RMG-Py | rmgpy/data/thermoTest.py | Python | setUpModule | setUpModule | 53 | 57 | 53 | 53 | 874cf4e0e78dad77f48d3830cf9553bcdacee66c | bigcode/the-stack | train |
e2615fd216ac9bb398bffd21 | train | class | @unittest.skip('Skipping TCD unit tests because database is offline.')
class TestThermoCentralDatabaseInterface(unittest.TestCase):
"""
Contains unit tests for methods of ThermoCentralDatabaseInterface
"""
@classmethod
def setUpClass(self):
"""A function that is run ONCE before all unit tes... | @unittest.skip('Skipping TCD unit tests because database is offline.')
class TestThermoCentralDatabaseInterface(unittest.TestCase):
| """
Contains unit tests for methods of ThermoCentralDatabaseInterface
"""
@classmethod
def setUpClass(self):
"""A function that is run ONCE before all unit tests in this class."""
global database
self.database = database.thermo
def connect_to_test_central_database(self)... | )
self.assertEqual(saturated_ring_submol.multiplicity,
expected_saturated_ring_submol.multiplicity)
self.assertTrue(saturated_ring_submol.is_isomorphic(expected_saturated_ring_submol))
def get_testing_tcd_authentication_info():
try:
host = os.environ['TCD_HOST']
... | 256 | 256 | 2,059 | 26 | 229 | mbprend/RMG-Py | rmgpy/data/thermoTest.py | Python | TestThermoCentralDatabaseInterface | TestThermoCentralDatabaseInterface | 1,624 | 1,852 | 1,624 | 1,625 | 968f53a7d9ac2c38f04d45fe31fea631a5706a0f | bigcode/the-stack | train |
77aa407fe3a0909901767083 | train | function | def get_testing_tcd_authentication_info():
try:
host = os.environ['TCD_HOST']
port = int(os.environ['TCD_PORT'])
username = os.environ['TCD_USER']
password = os.environ['TCD_PW']
except KeyError:
print('Thermo Central Database Authentication Environment Variables Not Comp... | def get_testing_tcd_authentication_info():
| try:
host = os.environ['TCD_HOST']
port = int(os.environ['TCD_PORT'])
username = os.environ['TCD_USER']
password = os.environ['TCD_PW']
except KeyError:
print('Thermo Central Database Authentication Environment Variables Not Completely Set!')
return None, 0, None,... | ivity_values()
self.assertFalse(already_saturated)
self.assertEqual(saturated_ring_submol.multiplicity,
expected_saturated_ring_submol.multiplicity)
self.assertTrue(saturated_ring_submol.is_isomorphic(expected_saturated_ring_submol))
def get_testing_tcd_authentication_i... | 64 | 64 | 94 | 9 | 55 | mbprend/RMG-Py | rmgpy/data/thermoTest.py | Python | get_testing_tcd_authentication_info | get_testing_tcd_authentication_info | 1,596 | 1,606 | 1,596 | 1,596 | c48c085be0d9569d0262b1fe3f9f83c1039a044c | bigcode/the-stack | train |
095cc00b85547f3680841492 | train | class | class Command(BaseCommand):
help = 'create test datas'
def handle(self, *args, **options):
user = \
get_user_model().objects.get_or_create(email='test@test.com', username='测试用户',
password='test!q@w#eTYU')[0]
pcategory = Category.ob... | class Command(BaseCommand):
| help = 'create test datas'
def handle(self, *args, **options):
user = \
get_user_model().objects.get_or_create(email='test@test.com', username='测试用户',
password='test!q@w#eTYU')[0]
pcategory = Category.objects.get_or_create(name='我是... | PyCharm
@file: create_testdata.py
@time: 2017/3/11 上午1:58
"""
from django.core.management.base import BaseCommand
from blog.models import Article, Tag, Category
from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist
import datetime
class Command(BaseCommand):
| 73 | 73 | 244 | 5 | 67 | felixyin/qdqtrj_website | blog/management/commands/create_testdata.py | Python | Command | Command | 23 | 54 | 23 | 23 | 1f6da08879c31ef2b5fc0a20b925353886135d7e | bigcode/the-stack | train |
29bbde3cae55893c694b3843 | train | function | def stop(signum=None, frame=None):
"""
Graceful exit.
"""
GRACEFUL_STOP.set()
| def stop(signum=None, frame=None):
| """
Graceful exit.
"""
GRACEFUL_STOP.set()
| () for t in thread_list]
logging.info('waiting for interrupts')
# Interruptible joins require a timeout.
while thread_list:
thread_list = [t.join(timeout=3.14) for t in thread_list if t and t.isAlive()]
def stop(signum=None, frame=None):
| 63 | 64 | 25 | 9 | 54 | TeAmP0is0N/rucio | lib/rucio/daemons/atropos/atropos.py | Python | stop | stop | 231 | 235 | 231 | 231 | cb6f0897cb2f8834857030a9e65b2dbc1a266b9d | bigcode/the-stack | train |
5a71c3060ce5aa9a7fd78760 | train | function | def atropos(thread, bulk, date_check, dry_run=True, grace_period=86400,
once=True, unlock=False, spread_period=0, purge_replicas=False):
"""
Creates an Atropos Worker that gets a list of rules which have an eol_at expired and delete them.
:param thread: Thread number at startup.
:param bulk... | def atropos(thread, bulk, date_check, dry_run=True, grace_period=86400,
once=True, unlock=False, spread_period=0, purge_replicas=False):
| """
Creates an Atropos Worker that gets a list of rules which have an eol_at expired and delete them.
:param thread: Thread number at startup.
:param bulk: The number of requests to process.
:param grace_period: The grace_period for the rules.
:param once: Run only once.
"""
sleep_time... | IBLE
import datetime
import logging
import os
import random
import socket
import threading
import time
from sys import exc_info, stdout
from traceback import format_exception
from rucio.db.sqla.constants import LifetimeExceptionsState
from rucio.common.config import config_get
from rucio.common.exception import Inva... | 256 | 256 | 1,722 | 38 | 218 | TeAmP0is0N/rucio | lib/rucio/daemons/atropos/atropos.py | Python | atropos | atropos | 58 | 198 | 58 | 59 | 0a01a6b2e55bf6f1e65edaf11f74c1ecfb381c1c | bigcode/the-stack | train |
783c6c3c59c654a234eb65af | train | function | def run(threads=1, bulk=100, date_check=None, dry_run=True, grace_period=86400,
once=True, unlock=False, spread_period=0, purge_replicas=False):
"""
Starts up the atropos threads.
"""
if not date_check:
date_check = datetime.datetime.now()
else:
date_check = datetime.datetime... | def run(threads=1, bulk=100, date_check=None, dry_run=True, grace_period=86400,
once=True, unlock=False, spread_period=0, purge_replicas=False):
| """
Starts up the atropos threads.
"""
if not date_check:
date_check = datetime.datetime.now()
else:
date_check = datetime.datetime.strptime(date_check, '%Y-%m-%d')
if once:
logging.info('Will run only one iteration')
logging.info('starting atropos threads')
threa... | _str + 'Graceful stop requested')
heartbeat.die(executable, hostname, pid, hb_thread)
logging.info(prepend_str + 'Graceful stop done')
def run(threads=1, bulk=100, date_check=None, dry_run=True, grace_period=86400,
once=True, unlock=False, spread_period=0, purge_replicas=False):
| 78 | 78 | 262 | 43 | 35 | TeAmP0is0N/rucio | lib/rucio/daemons/atropos/atropos.py | Python | run | run | 201 | 228 | 201 | 202 | 531eb4e590de861ddb46639f5b433b65173d65e2 | bigcode/the-stack | train |
1b317ce9c075801680bca8f8 | train | class | class TestRunner(TestRunnerBase):
"""
A test runner for astropy tests
"""
def packages_path(self, packages, base_path, error=None, warning=None):
"""
Generates the path for multiple packages.
Parameters
----------
packages : str
Comma separated strin... | class TestRunner(TestRunnerBase):
| """
A test runner for astropy tests
"""
def packages_path(self, packages, base_path, error=None, warning=None):
"""
Generates the path for multiple packages.
Parameters
----------
packages : str
Comma separated string of packages.
base_path :... | in the given path, and returns a
``test()`` function which takes the same arguments as
``TestRunner.run_tests``.
The returned ``test()`` function will be defined in the module this
was called from. This is used to implement the ``astropy.test()``
function (or the equivalent fo... | 256 | 256 | 2,383 | 7 | 248 | emirkmo/astropy | astropy/tests/runner.py | Python | TestRunner | TestRunner | 278 | 604 | 278 | 278 | a2a828034cbec1b0fca0eba5f4e034a8f3948f6c | bigcode/the-stack | train |
41e87bd1c7a07daca739d24f | train | class | class keyword:
"""
A decorator to mark a method as keyword argument for the ``TestRunner``.
Parameters
----------
default_value : `object`
The default value for the keyword argument. (Default: `None`)
priority : `int`
keyword argument methods are executed in order of descending... | class keyword:
| """
A decorator to mark a method as keyword argument for the ``TestRunner``.
Parameters
----------
default_value : `object`
The default value for the keyword argument. (Default: `None`)
priority : `int`
keyword argument methods are executed in order of descending priority.
... | from functools import wraps
from astropy.config.paths import set_temp_config, set_temp_cache
from astropy.utils import find_current_module
from astropy.utils.exceptions import AstropyWarning, AstropyDeprecationWarning
__all__ = ['TestRunner', 'TestRunnerBase', 'keyword']
class keyword:
| 64 | 64 | 189 | 3 | 61 | emirkmo/astropy | astropy/tests/runner.py | Python | keyword | keyword | 22 | 49 | 22 | 22 | e7328195e2bfca98cca844be22f96300b11f4b96 | bigcode/the-stack | train |
7126122ab1db8c67564e4477 | train | class | class TestRunnerBase:
"""
The base class for the TestRunner.
A test runner can be constructed by creating a subclass of this class and
defining 'keyword' methods. These are methods that have the
:class:`~astropy.tests.runner.keyword` decorator, these methods are used to
construct allowed keywor... | class TestRunnerBase:
| """
The base class for the TestRunner.
A test runner can be constructed by creating a subclass of this class and
defining 'keyword' methods. These are methods that have the
:class:`~astropy.tests.runner.keyword` decorator, these methods are used to
construct allowed keyword arguments to the
... |
from functools import wraps
from astropy.config.paths import set_temp_config, set_temp_cache
from astropy.utils import find_current_module
from astropy.utils.exceptions import AstropyWarning, AstropyDeprecationWarning
__all__ = ['TestRunner', 'TestRunnerBase', 'keyword']
class keyword:
"""
A decorator to m... | 256 | 256 | 1,987 | 5 | 250 | emirkmo/astropy | astropy/tests/runner.py | Python | TestRunnerBase | TestRunnerBase | 52 | 275 | 52 | 52 | 852f5d63b6e2d339da62f3263202b0ddf2042bc6 | bigcode/the-stack | train |
2f1b36e393e0844cab0c0ab7 | train | class | class preprocess:
def extract_file_paths(self):
file_path = fp
self.file_name = file_path.run("data")
def filechecker(self):
check = path.exists(self.file_name)
return check
| class preprocess:
| def extract_file_paths(self):
file_path = fp
self.file_name = file_path.run("data")
def filechecker(self):
check = path.exists(self.file_name)
return check
| self.df = dataframe
def cloumn_to_delete(self):
self.to_remove = "system"
def delete_idx(self):
self.df = self.df.drop(self.to_remove, axis=1)
def converter(self):
self.df.to_csv(self.data_loc, index = None)
class preprocess:
| 64 | 64 | 47 | 3 | 61 | pranayjoshi/Medico | src/Data_process/json_to_csv.py | Python | preprocess | preprocess | 27 | 34 | 27 | 27 | bba180b087f2b275de0ede25e4fd08fc61cfa55c | bigcode/the-stack | train |
f646797782d5246cde64ee11 | train | class | class postprocess:
def __init__(self):
pass
def runall_pre(self):
self.pre_process = preprocess()
self.pre_process.extract_file_paths()
self.file_checker = self.pre_process.filechecker()
return self.file_checker
def runall_processing(self):
proces... | class postprocess:
| def __init__(self):
pass
def runall_pre(self):
self.pre_process = preprocess()
self.pre_process.extract_file_paths()
self.file_checker = self.pre_process.filechecker()
return self.file_checker
def runall_processing(self):
process = processing()
... | self.df.to_csv(self.data_loc, index = None)
class preprocess:
def extract_file_paths(self):
file_path = fp
self.file_name = file_path.run("data")
def filechecker(self):
check = path.exists(self.file_name)
return check
class postprocess:
| 64 | 64 | 93 | 4 | 59 | pranayjoshi/Medico | src/Data_process/json_to_csv.py | Python | postprocess | postprocess | 36 | 52 | 36 | 36 | f00e6103cc9d00f5e5bb628e360a175a47c0725e | bigcode/the-stack | train |
d62a63b080701de17f7cb852 | train | function | def runall():
post_process = postprocess()
post_process.runall_processing()
| def runall():
| post_process = postprocess()
post_process.runall_processing()
| _paths()
self.file_checker = self.pre_process.filechecker()
return self.file_checker
def runall_processing(self):
process = processing()
process.extract_file_paths()
process.create_dataframe()
process.cloumn_to_delete()
process.delete_idx()
... | 63 | 64 | 18 | 4 | 59 | pranayjoshi/Medico | src/Data_process/json_to_csv.py | Python | runall | runall | 54 | 56 | 54 | 54 | 4cfe81e5b65d29c58d8446e786362ca39b7f4834 | bigcode/the-stack | train |
966be9a811096b451d4c14e7 | train | class | class processing:
def __init__(self):
pass
def extract_file_paths(self):
file_path = fp
self.snomed_json_loc = fp.run("snomed_json")
self.data_loc = fp.run("initial_data")
def create_dataframe(self):
dataframe = pd.read_json(self.snomed_json_loc)
... | class processing:
| def __init__(self):
pass
def extract_file_paths(self):
file_path = fp
self.snomed_json_loc = fp.run("snomed_json")
self.data_loc = fp.run("initial_data")
def create_dataframe(self):
dataframe = pd.read_json(self.snomed_json_loc)
self.df = dataframe... | import pandas as pd
from os import path
import file_path as fp
class processing:
| 19 | 64 | 134 | 3 | 15 | pranayjoshi/Medico | src/Data_process/json_to_csv.py | Python | processing | processing | 5 | 25 | 5 | 5 | 5470df182c0feb8e189fb811106481ff5dfc9f44 | bigcode/the-stack | train |
0e9fd6ed65e81e76e5245205 | train | class | class FSUAdd(torch.nn.Module):
"""
This module is for unary addition for arbitrary scale, including scaled/non-scaled, unipolar/bipolar.
"""
def __init__(
self,
hwcfg={
"mode" : "bipolar",
"scale" : None,
"dima" : 0,
"depth" : 10,
... | class FSUAdd(torch.nn.Module):
| """
This module is for unary addition for arbitrary scale, including scaled/non-scaled, unipolar/bipolar.
"""
def __init__(
self,
hwcfg={
"mode" : "bipolar",
"scale" : None,
"dima" : 0,
"depth" : 10,
"entry" : None
}, ... | import torch
class FSUAdd(torch.nn.Module):
| 11 | 256 | 870 | 8 | 2 | diwu1990/UnaryComputingSim | kernel/add.py | Python | FSUAdd | FSUAdd | 3 | 99 | 3 | 3 | 73d7bedf1eca9238b9eee2d6956e66f210376fd0 | bigcode/the-stack | train |
92a55842464853a1f0dcc544 | train | class | class SecurityCenterClient(security_center_client.SecurityCenterClient):
__doc__ = security_center_client.SecurityCenterClient.__doc__
enums = enums
| class SecurityCenterClient(security_center_client.SecurityCenterClient):
| __doc__ = security_center_client.SecurityCenterClient.__doc__
enums = enums
| for Python 2.7."
"More details about Python 2 support for Google Cloud Client Libraries"
"can be found at https://cloud.google.com/python/docs/python2-sunset/"
)
warnings.warn(message, DeprecationWarning)
class SecurityCenterClient(security_center_client.SecurityCenterClient):
| 64 | 64 | 31 | 12 | 52 | tdh911/python-securitycenter | google/cloud/securitycenter_v1p1beta1/__init__.py | Python | SecurityCenterClient | SecurityCenterClient | 36 | 38 | 36 | 36 | f562940b99bfe1680860a6bf0638f1fc3c2fbc54 | bigcode/the-stack | train |
b9091741fe467e1f9cfd55d9 | train | class | class Word2vec(WordEmbeddings):
# https://arxiv.org/pdf/1301.3781.pdf
def __init__(self, top_k=100, skip_check=False):
super().__init__(top_k, skip_check)
try:
from gensim.models import KeyedVectors
except ModuleNotFoundError:
raise ModuleNotFoundError('Missed ge... | class Word2vec(WordEmbeddings):
# https://arxiv.org/pdf/1301.3781.pdf
| def __init__(self, top_k=100, skip_check=False):
super().__init__(top_k, skip_check)
try:
from gensim.models import KeyedVectors
except ModuleNotFoundError:
raise ModuleNotFoundError('Missed gensim library. Install transfomers by `pip install gensim`')
self.... | gensim.models import KeyedVectors
except ImportError:
# No installation required if not using this function
pass
from nlpaug.model.word_embs import WordEmbeddings
class Word2vec(WordEmbeddings):
# https://arxiv.org/pdf/1301.3781.pdf
| 64 | 64 | 149 | 25 | 38 | techthiyanes/nlpaug | nlpaug/model/word_embs/word2vec.py | Python | Word2vec | Word2vec | 10 | 25 | 10 | 11 | 6829a45f5533a51ae80d48ea2d837c39ddbfb19a | bigcode/the-stack | train |
78513fdaba88ee5476e70e97 | train | class | class BaseGenericInlineFormSet(BaseModelFormSet):
"""
A formset for generic inline objects to a parent.
"""
def __init__(self, data=None, files=None, instance=None, save_as_new=False,
prefix=None, queryset=None, **kwargs):
opts = self.model._meta
self.instance = instanc... | class BaseGenericInlineFormSet(BaseModelFormSet):
| """
A formset for generic inline objects to a parent.
"""
def __init__(self, data=None, files=None, instance=None, save_as_new=False,
prefix=None, queryset=None, **kwargs):
opts = self.model._meta
self.instance = instance
self.rel_name = (
opts.app_l... | from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.forms import ModelForm, modelformset_factory
from django.forms.models import BaseModelFormSet
class BaseGenericInlineFormSet(BaseModelFormSet):
| 50 | 109 | 366 | 11 | 38 | Lucas11200/LocaPy | Lib/site-packages/django/contrib/contenttypes/forms.py | Python | BaseGenericInlineFormSet | BaseGenericInlineFormSet | 7 | 49 | 7 | 7 | 87c3e044043d468423cedbc0ffb502a62e6e7903 | bigcode/the-stack | train |
e89762de6f02be5cdacda5a6 | train | function | def generic_inlineformset_factory(model, form=ModelForm,
formset=BaseGenericInlineFormSet,
ct_field="content_type", fk_field="object_id",
fields=None, exclude=None,
extra=3, can_order=... | def generic_inlineformset_factory(model, form=ModelForm,
formset=BaseGenericInlineFormSet,
ct_field="content_type", fk_field="object_id",
fields=None, exclude=None,
extra=3, can_order=... | """
Return a ``GenericInlineFormSet`` for the given kwargs.
You must provide ``ct_field`` and ``fk_field`` if they are different from
the defaults ``content_type`` and ``object_id`` respectively.
"""
opts = model._meta
# if there is no field called `ct_field` let the exception propagate
... | (form.instance, self.ct_fk_field.get_attname(), self.instance.pk)
return form.save(commit=commit)
def generic_inlineformset_factory(model, form=ModelForm,
formset=BaseGenericInlineFormSet,
ct_field="content_type", fk_field="object_id",
... | 109 | 109 | 365 | 86 | 23 | Lucas11200/LocaPy | Lib/site-packages/django/contrib/contenttypes/forms.py | Python | generic_inlineformset_factory | generic_inlineformset_factory | 52 | 82 | 52 | 59 | 404e05a8adca8650ca8ff4a64e2ddb239f02615e | bigcode/the-stack | train |
d698711fc690c659030cdd61 | train | function | def get_col_desc(ticker: str) -> parser.Descriptions:
"""Формирует список с описанием нужных столбцов."""
date_col = description.ColDesc(
num=6,
raw_name=("Rec. Date",),
name=col.DATE,
parser_func=cell_parser.date_us,
)
div_col = description.ColDesc(
num=1,
... | def get_col_desc(ticker: str) -> parser.Descriptions:
| """Формирует список с описанием нужных столбцов."""
date_col = description.ColDesc(
num=6,
raw_name=("Rec. Date",),
name=col.DATE,
parser_func=cell_parser.date_us,
)
div_col = description.ColDesc(
num=1,
raw_name=("Amount",),
name=ticker,
p... | import cell_parser, description, parser
from poptimizer.shared import adapters, col
# Параметры парсинга сайта
URL = "https://www.streetinsider.com/dividend_history.php?q="
TABLE_INDEX = 0
def get_col_desc(ticker: str) -> parser.Descriptions:
| 64 | 64 | 113 | 14 | 49 | Questtt/poptimizer | poptimizer/data/adapters/gateways/street_insider.py | Python | get_col_desc | get_col_desc | 15 | 29 | 15 | 15 | dda260ae858fee3f0f4e3fbd9ea27ed56e80bccd | bigcode/the-stack | train |
8be5bfc26f52c05e378c032a | train | class | class StreetInsider(gateways.DivGateway):
"""Обновление данных с https://www.streetinsider.com/."""
_logger = adapters.AsyncLogger()
async def __call__(self, ticker: str) -> Optional[pd.DataFrame]:
"""Получение дивидендов для заданного тикера."""
self._logger(ticker)
cols_desc = g... | class StreetInsider(gateways.DivGateway):
| """Обновление данных с https://www.streetinsider.com/."""
_logger = adapters.AsyncLogger()
async def __call__(self, ticker: str) -> Optional[pd.DataFrame]:
"""Получение дивидендов для заданного тикера."""
self._logger(ticker)
cols_desc = get_col_desc(ticker)
international_... | _func=cell_parser.date_us,
)
div_col = description.ColDesc(
num=1,
raw_name=("Amount",),
name=ticker,
parser_func=cell_parser.div_us,
)
return [date_col, div_col]
class StreetInsider(gateways.DivGateway):
| 64 | 64 | 162 | 10 | 54 | Questtt/poptimizer | poptimizer/data/adapters/gateways/street_insider.py | Python | StreetInsider | StreetInsider | 32 | 52 | 32 | 32 | 02988cc0e8d0358da7ba46ac8fd8f7fb4cf2dd5e | bigcode/the-stack | train |
eef7a23f64a32293ff95619b | train | function | def _factorize_array(values, check_nulls, na_sentinel=-1, size_hint=None):
"""Factorize an array-like to labels and uniques.
This doesn't do any coercion of types or unboxing before factorization.
Parameters
----------
values : ndarray
check_nulls : bool
Whether to check for nulls in t... | def _factorize_array(values, check_nulls, na_sentinel=-1, size_hint=None):
| """Factorize an array-like to labels and uniques.
This doesn't do any coercion of types or unboxing before factorization.
Parameters
----------
values : ndarray
check_nulls : bool
Whether to check for nulls in the hashtable's 'get_labels' method.
na_sentinel : int, default -1
s... | table.ismember_float64(x, y, checknull)
except (TypeError, ValueError):
values = values.astype(object)
comps = comps.astype(object)
return f(comps, values)
def _factorize_array(values, check_nulls, na_sentinel=-1, size_hint=None):
| 65 | 65 | 217 | 21 | 44 | mrocklin/pandas | pandas/core/algorithms.py | Python | _factorize_array | _factorize_array | 438 | 464 | 438 | 438 | 0cb0e54429a93240d311e96d892834742d7579b6 | bigcode/the-stack | train |
7205ecfd37402ac4a6647922 | train | function | def quantile(x, q, interpolation_method='fraction'):
"""
Compute sample quantile or quantiles of the input array. For example, q=0.5
computes the median.
The `interpolation_method` parameter supports three values, namely
`fraction` (default), `lower` and `higher`. Interpolation is done only,
if... | def quantile(x, q, interpolation_method='fraction'):
| """
Compute sample quantile or quantiles of the input array. For example, q=0.5
computes the median.
The `interpolation_method` parameter supports three values, namely
`fraction` (default), `lower` and `higher`. Interpolation is done only,
if the desired quantile lies between two data points `i... | b2[mask2] > arr[mask2]) & not_nan[mask2]).any())
if to_raise:
raise OverflowError("Overflow in int64 addition")
return arr + b
_rank1d_functions = {
'float64': algos.rank_1d_float64,
'int64': algos.rank_1d_int64,
'uint64': algos.rank_1d_uint64,
'object': algos.ra... | 178 | 178 | 595 | 12 | 166 | mrocklin/pandas | pandas/core/algorithms.py | Python | quantile | quantile | 870 | 947 | 870 | 870 | fd94a4042b70091e0b7b1de2524fe0cae6171599 | bigcode/the-stack | train |
a59355e72028535249a41535 | train | class | class SelectNSeries(SelectN):
"""
Implement n largest/smallest for Series
Parameters
----------
obj : Series
n : int
keep : {'first', 'last'}, default 'first'
Returns
-------
nordered : Series
"""
def compute(self, method):
n = self.n
dtype = self.obj.... | class SelectNSeries(SelectN):
| """
Implement n largest/smallest for Series
Parameters
----------
obj : Series
n : int
keep : {'first', 'last'}, default 'first'
Returns
-------
nordered : Series
"""
def compute(self, method):
n = self.n
dtype = self.obj.dtype
if not self.is_v... | must be either "first", "last"')
def nlargest(self):
return self.compute('nlargest')
def nsmallest(self):
return self.compute('nsmallest')
@staticmethod
def is_valid_dtype_n_method(dtype):
"""
Helper function to determine if dtype is valid for
nsmallest/nlarge... | 108 | 108 | 360 | 8 | 100 | mrocklin/pandas | pandas/core/algorithms.py | Python | SelectNSeries | SelectNSeries | 980 | 1,035 | 980 | 980 | af77d0f6ad9526bfd9bfa609df08c3f7776bcccd | bigcode/the-stack | train |
d323a3f4557cd8fca0635afe | train | function | def mode(values):
"""
Returns the mode(s) of an array.
Parameters
----------
values : array-like
Array over which to check for duplicate values.
Returns
-------
mode : Series
"""
from pandas import Series
values = _ensure_arraylike(values)
original = values
... | def mode(values):
| """
Returns the mode(s) of an array.
Parameters
----------
values : array-like
Array over which to check for duplicate values.
Returns
-------
mode : Series
"""
from pandas import Series
values = _ensure_arraylike(values)
original = values
# categorical is... | occurrence.
- False : Mark all duplicates as ``True``.
Returns
-------
duplicated : ndarray
"""
values, dtype, ndtype = _ensure_data(values)
f = getattr(htable, "duplicated_{dtype}".format(dtype=ndtype))
return f(values, keep=keep)
def mode(values):
| 71 | 71 | 239 | 4 | 67 | mrocklin/pandas | pandas/core/algorithms.py | Python | mode | mode | 685 | 725 | 685 | 685 | 89f75ea0eaed0faa5d204cf33d18880efe831248 | bigcode/the-stack | train |
01ca30a17dc74bbeb1d93a24 | train | class | class SelectNFrame(SelectN):
"""
Implement n largest/smallest for DataFrame
Parameters
----------
obj : DataFrame
n : int
keep : {'first', 'last'}, default 'first'
columns : list or str
Returns
-------
nordered : DataFrame
"""
def __init__(self, obj, n, keep, colum... | class SelectNFrame(SelectN):
| """
Implement n largest/smallest for DataFrame
Parameters
----------
obj : DataFrame
n : int
keep : {'first', 'last'}, default 'first'
columns : list or str
Returns
-------
nordered : DataFrame
"""
def __init__(self, obj, n, keep, columns):
super(SelectNFra... | self.keep == 'last' or method == 'nlargest')
ascending = method == 'nsmallest'
slc = np.s_[::-1] if reverse_it else np.s_[:]
return dropped[slc].sort_values(ascending=ascending).head(n)
# fast method
arr, _, _ = _ensure_data(dropped.values)
if method == 'nlar... | 207 | 207 | 690 | 8 | 199 | mrocklin/pandas | pandas/core/algorithms.py | Python | SelectNFrame | SelectNFrame | 1,038 | 1,126 | 1,038 | 1,038 | 368128466d1c3147a5f78add4c39321fdd827783 | bigcode/the-stack | train |
13aa7f3ff31acffa3e45d3a6 | train | function | def unique(values):
"""
Hash table-based unique. Uniques are returned in order
of appearance. This does NOT sort.
Significantly faster than numpy.unique. Includes NA values.
Parameters
----------
values : 1d array-like
Returns
-------
unique values.
- If the input is an ... | def unique(values):
| """
Hash table-based unique. Uniques are returned in order
of appearance. This does NOT sort.
Significantly faster than numpy.unique. Includes NA values.
Parameters
----------
values : 1d array-like
Returns
-------
unique values.
- If the input is an Index, the return is... | #
def match(to_match, values, na_sentinel=-1):
"""
Compute locations of to_match into values
Parameters
----------
to_match : array-like
values to find positions of
values : array-like
Unique set of values
na_sentinel : int, default -1
Value to mark "not found"
... | 238 | 238 | 794 | 4 | 233 | mrocklin/pandas | pandas/core/algorithms.py | Python | unique | unique | 279 | 374 | 279 | 279 | 2b418a39caa27e4ac48bfed0588e1edb7761d9ae | bigcode/the-stack | train |
394590c2afe4888002666f8d | train | function | def _take_nd_object(arr, indexer, out, axis, fill_value, mask_info):
if mask_info is not None:
mask, needs_masking = mask_info
else:
mask = indexer == -1
needs_masking = mask.any()
if arr.dtype != out.dtype:
arr = arr.astype(out.dtype)
if arr.shape[axis] > 0:
arr.... | def _take_nd_object(arr, indexer, out, axis, fill_value, mask_info):
| if mask_info is not None:
mask, needs_masking = mask_info
else:
mask = indexer == -1
needs_masking = mask.any()
if arr.dtype != out.dtype:
arr = arr.astype(out.dtype)
if arr.shape[axis] > 0:
arr.take(_ensure_platform_int(indexer), axis=axis, out=out)
if needs_... | for i in range(len(row_idx)):
u_ = row_idx[i]
for j in range(len(col_idx)):
v = col_idx[j]
out[i, j] = arr[u_, v]
def _take_nd_object(arr, indexer, out, axis, fill_value, mask_info):
| 64 | 64 | 145 | 20 | 44 | mrocklin/pandas | pandas/core/algorithms.py | Python | _take_nd_object | _take_nd_object | 1,178 | 1,191 | 1,178 | 1,178 | cf0c2957955d58e8a8136d0dbfb687a2658b07b9 | bigcode/the-stack | train |
a4be2e06a59900fe520f2921 | train | function | def _ensure_arraylike(values):
"""
ensure that we are arraylike if not already
"""
if not is_array_like(values):
inferred = lib.infer_dtype(values)
if inferred in ['mixed', 'string', 'unicode']:
if isinstance(values, tuple):
values = list(values)
v... | def _ensure_arraylike(values):
| """
ensure that we are arraylike if not already
"""
if not is_array_like(values):
inferred = lib.infer_dtype(values)
if inferred in ['mixed', 'string', 'unicode']:
if isinstance(values, tuple):
values = list(values)
values = construct_1d_object_arr... | elif is_bool_dtype(dtype):
values = values.astype(dtype)
# we only support object dtypes bool Index
if isinstance(original, Index):
values = values.astype(object)
elif dtype is not None:
values = values.astype(dtype)
return values
def _ensure_arraylike(values):
| 64 | 64 | 93 | 7 | 56 | mrocklin/pandas | pandas/core/algorithms.py | Python | _ensure_arraylike | _ensure_arraylike | 168 | 180 | 168 | 168 | 0e7283eddf95e57a8b4f91e1939ed7d493bffea6 | bigcode/the-stack | train |
f0edc4a7d6c92a42908ecedd | train | function | def _get_data_algo(values, func_map):
if is_categorical_dtype(values):
values = values._values_for_rank()
values, dtype, ndtype = _ensure_data(values)
if ndtype == 'object':
# its cheaper to use a String Hash Table than Object
if lib.infer_dtype(values) in ['string']:
... | def _get_data_algo(values, func_map):
| if is_categorical_dtype(values):
values = values._values_for_rank()
values, dtype, ndtype = _ensure_data(values)
if ndtype == 'object':
# its cheaper to use a String Hash Table than Object
if lib.infer_dtype(values) in ['string']:
ndtype = 'string'
f = func_map.get... | .infer_dtype(values) in ['string']:
ndtype = 'string'
else:
ndtype = 'object'
htable, table = _hashtables[ndtype]
return (htable, table, values, dtype, ndtype)
def _get_data_algo(values, func_map):
| 64 | 64 | 100 | 10 | 54 | mrocklin/pandas | pandas/core/algorithms.py | Python | _get_data_algo | _get_data_algo | 220 | 234 | 220 | 221 | 8478184f3b0f976c1351cf405c781eaf0b30f7dc | bigcode/the-stack | train |
6e17a167ca0a164793d78c11 | train | function | def _get_take_nd_function(ndim, arr_dtype, out_dtype, axis=0, mask_info=None):
if ndim <= 2:
tup = (arr_dtype.name, out_dtype.name)
if ndim == 1:
func = _take_1d_dict.get(tup, None)
elif ndim == 2:
if axis == 0:
func = _take_2d_axis0_dict.get(tup, None... | def _get_take_nd_function(ndim, arr_dtype, out_dtype, axis=0, mask_info=None):
| if ndim <= 2:
tup = (arr_dtype.name, out_dtype.name)
if ndim == 1:
func = _take_1d_dict.get(tup, None)
elif ndim == 2:
if axis == 0:
func = _take_2d_axis0_dict.get(tup, None)
else:
func = _take_2d_axis1_dict.get(tup, None)
... | algos.take_2d_multi_bool_object,
np.uint8, None),
('datetime64[ns]', 'datetime64[ns]'):
_view_wrapper(algos.take_2d_multi_int64_int64, np.int64, np.int64,
fill_wrap=np.int64)
}
def _get_take_nd_function(ndim, arr_dtype, out_dtype, axis=0, mask_info=None):
| 87 | 87 | 292 | 23 | 64 | mrocklin/pandas | pandas/core/algorithms.py | Python | _get_take_nd_function | _get_take_nd_function | 1,302 | 1,332 | 1,302 | 1,302 | e0cb014b69748c28e1df67a7c3fd04f61cc986ec | bigcode/the-stack | train |
583d3b30b5ac7030215e6768 | train | function | def checked_add_with_arr(arr, b, arr_mask=None, b_mask=None):
"""
Perform array addition that checks for underflow and overflow.
Performs the addition of an int64 array and an int64 integer (or array)
but checks that they do not result in overflow first. For elements that
are indicated to be NaN, w... | def checked_add_with_arr(arr, b, arr_mask=None, b_mask=None):
| """
Perform array addition that checks for underflow and overflow.
Performs the addition of an int64 array and an int64 integer (or array)
but checks that they do not result in overflow first. For elements that
are indicated to be NaN, whether or not there is overflow for that element
is automa... | top``: replace each NaN with either +/- inf so that they
there are ranked at the top
ascending : boolean, default True
Whether or not the elements should be ranked in ascending order.
pct : boolean, default False
Whether or not to the display the returned rankings in integer f... | 250 | 250 | 835 | 17 | 232 | mrocklin/pandas | pandas/core/algorithms.py | Python | checked_add_with_arr | checked_add_with_arr | 767 | 852 | 767 | 767 | ee4032b23ea247aa5b7e8c6137ba17f53af898fe | bigcode/the-stack | train |
0d6489a8fb39d17a97359177 | train | function | def _get_hashtable_algo(values):
"""
Parameters
----------
values : arraylike
Returns
-------
tuples(hashtable class,
vector class,
values,
dtype,
ndtype)
"""
values, dtype, ndtype = _ensure_data(values)
if ndtype == 'object':
... | def _get_hashtable_algo(values):
| """
Parameters
----------
values : arraylike
Returns
-------
tuples(hashtable class,
vector class,
values,
dtype,
ndtype)
"""
values, dtype, ndtype = _ensure_data(values)
if ndtype == 'object':
# its cheaper to use a String H... | table.UInt64Vector),
'int64': (htable.Int64HashTable, htable.Int64Vector),
'string': (htable.StringHashTable, htable.ObjectVector),
'object': (htable.PyObjectHashTable, htable.ObjectVector)
}
def _get_hashtable_algo(values):
| 64 | 64 | 139 | 8 | 56 | mrocklin/pandas | pandas/core/algorithms.py | Python | _get_hashtable_algo | _get_hashtable_algo | 192 | 217 | 192 | 192 | 6afab8ea53651f929b13a5b09dfa1d7d0ab5f1b2 | bigcode/the-stack | train |
41fd35e4ffab8cbad3c70eb4 | train | function | def isin(comps, values):
"""
Compute the isin boolean array
Parameters
----------
comps: array-like
values: array-like
Returns
-------
boolean array same length as comps
"""
if not is_list_like(comps):
raise TypeError("only list-like objects are allowed to be passe... | def isin(comps, values):
| """
Compute the isin boolean array
Parameters
----------
comps: array-like
values: array-like
Returns
-------
boolean array same length as comps
"""
if not is_list_like(comps):
raise TypeError("only list-like objects are allowed to be passed"
... | .unique()
original = values
htable, _, values, dtype, ndtype = _get_hashtable_algo(values)
table = htable(len(values))
uniques = table.unique(values)
uniques = _reconstruct_data(uniques, dtype, original)
if isinstance(original, ABCSeries) and is_datetime64tz_dtype(dtype):
# we are spe... | 141 | 141 | 473 | 7 | 133 | mrocklin/pandas | pandas/core/algorithms.py | Python | isin | isin | 380 | 435 | 380 | 380 | e9bd24962cbd2a9070f61709f6cf086ac529bf39 | bigcode/the-stack | train |
6cbf2f92687f0f4fb3ba93d9 | train | function | def take_2d_multi(arr, indexer, out=None, fill_value=np.nan, mask_info=None,
allow_fill=True):
"""
Specialized Cython take which sets NaN values in one pass
"""
if indexer is None or (indexer[0] is None and indexer[1] is None):
row_idx = np.arange(arr.shape[0], dtype=np.int64)
... | def take_2d_multi(arr, indexer, out=None, fill_value=np.nan, mask_info=None,
allow_fill=True):
| """
Specialized Cython take which sets NaN values in one pass
"""
if indexer is None or (indexer[0] is None and indexer[1] is None):
row_idx = np.arange(arr.shape[0], dtype=np.int64)
col_idx = np.arange(arr.shape[1], dtype=np.int64)
indexer = row_idx, col_idx
dtype, fill_... | len(indexer)
out_shape = tuple(out_shape)
if arr.flags.f_contiguous and axis == arr.ndim - 1:
# minor tweak that can make an order-of-magnitude difference
# for dataframes initialized directly from 2-d ndarrays
# (s.t. df.values is c-contiguous and df._data.blocks[0]... | 210 | 210 | 703 | 28 | 181 | mrocklin/pandas | pandas/core/algorithms.py | Python | take_2d_multi | take_2d_multi | 1,452 | 1,517 | 1,452 | 1,453 | cd059e8da9b796a9614078d562c34084de88ed82 | bigcode/the-stack | train |
20bdeee379adf99e25727019 | train | function | def take_nd(arr, indexer, axis=0, out=None, fill_value=np.nan, mask_info=None,
allow_fill=True):
"""
Specialized Cython take which sets NaN values in one pass
This dispatches to ``take`` defined on ExtensionArrays. It does not
currently dispatch to ``SparseArray.take`` for sparse ``arr``.
... | def take_nd(arr, indexer, axis=0, out=None, fill_value=np.nan, mask_info=None,
allow_fill=True):
| """
Specialized Cython take which sets NaN values in one pass
This dispatches to ``take`` defined on ExtensionArrays. It does not
currently dispatch to ``SparseArray.take`` for sparse ``arr``.
Parameters
----------
arr : array-like
Input array.
indexer : ndarray
1-D arr... | elif ndim == 2:
if axis == 0:
func = _take_2d_axis0_dict.get(tup, None)
else:
func = _take_2d_axis1_dict.get(tup, None)
if func is not None:
return func
tup = (out_dtype.name, out_dtype.name)
if ndim == 1:
func = _... | 256 | 256 | 1,056 | 29 | 226 | mrocklin/pandas | pandas/core/algorithms.py | Python | take_nd | take_nd | 1,335 | 1,446 | 1,335 | 1,336 | 2d932be3da25a47ea643c4641ad94aee7eced582 | bigcode/the-stack | train |
ba453f25740571a340fa95b9 | train | function | def diff(arr, n, axis=0):
"""
difference of n between self,
analogous to s-s.shift(n)
Parameters
----------
arr : ndarray
n : int
number of periods
axis : int
axis to shift on
Returns
-------
shifted
"""
n = int(n)
na = np.nan
dtype = arr.d... | def diff(arr, n, axis=0):
| """
difference of n between self,
analogous to s-s.shift(n)
Parameters
----------
arr : ndarray
n : int
number of periods
axis : int
axis to shift on
Returns
-------
shifted
"""
n = int(n)
na = np.nan
dtype = arr.dtype
is_timedelta = F... | if func is None:
def func(arr, indexer, out, fill_value=np.nan):
_take_2d_multi_object(arr, indexer, out, fill_value=fill_value,
mask_info=mask_info)
func(arr, indexer, out=out, fill_value=fill_value)
return out
# ---- #
# diff #
# ---- #
_diff_special... | 177 | 177 | 590 | 10 | 167 | mrocklin/pandas | pandas/core/algorithms.py | Python | diff | diff | 1,534 | 1,613 | 1,534 | 1,534 | b397027477a90111114455b43688ba2fe069857f | bigcode/the-stack | train |
af7e9878a21920f6e6f13b23 | train | function | def _view_wrapper(f, arr_dtype=None, out_dtype=None, fill_wrap=None):
def wrapper(arr, indexer, out, fill_value=np.nan):
if arr_dtype is not None:
arr = arr.view(arr_dtype)
if out_dtype is not None:
out = out.view(out_dtype)
if fill_wrap is not None:
fill_... | def _view_wrapper(f, arr_dtype=None, out_dtype=None, fill_wrap=None):
| def wrapper(arr, indexer, out, fill_value=np.nan):
if arr_dtype is not None:
arr = arr.view(arr_dtype)
if out_dtype is not None:
out = out.view(out_dtype)
if fill_wrap is not None:
fill_value = fill_wrap(fill_value)
f(arr, indexer, out, fill_value=... | len(indexer)
frame = frame.take(indexer)
# Restore the index on frame
frame.index = original_index.take(indexer)
return frame
# ------- ## ---- #
# take #
# ---- #
def _view_wrapper(f, arr_dtype=None, out_dtype=None, fill_wrap=None):
| 63 | 64 | 101 | 18 | 45 | mrocklin/pandas | pandas/core/algorithms.py | Python | _view_wrapper | _view_wrapper | 1,134 | 1,144 | 1,134 | 1,134 | 8e8cf3d8ab6a015fa3f2f6429267707ee4c89e62 | bigcode/the-stack | train |
7b7224720caf3f2c22e07eeb | train | function | def _convert_wrapper(f, conv_dtype):
def wrapper(arr, indexer, out, fill_value=np.nan):
arr = arr.astype(conv_dtype)
f(arr, indexer, out, fill_value=fill_value)
return wrapper
| def _convert_wrapper(f, conv_dtype):
| def wrapper(arr, indexer, out, fill_value=np.nan):
arr = arr.astype(conv_dtype)
f(arr, indexer, out, fill_value=fill_value)
return wrapper
| (arr_dtype)
if out_dtype is not None:
out = out.view(out_dtype)
if fill_wrap is not None:
fill_value = fill_wrap(fill_value)
f(arr, indexer, out, fill_value=fill_value)
return wrapper
def _convert_wrapper(f, conv_dtype):
| 64 | 64 | 51 | 9 | 54 | mrocklin/pandas | pandas/core/algorithms.py | Python | _convert_wrapper | _convert_wrapper | 1,147 | 1,152 | 1,147 | 1,147 | 109b06b3ad106ae163dcee5ed5ba0ea672f479cb | bigcode/the-stack | train |
356e525ddff6a501bead6abe | train | function | def rank(values, axis=0, method='average', na_option='keep',
ascending=True, pct=False):
"""
Rank the values along a given axis.
Parameters
----------
values : array-like
Array whose values will be ranked. The number of dimensions in this
array must not exceed 2.
axis :... | def rank(values, axis=0, method='average', na_option='keep',
ascending=True, pct=False):
| """
Rank the values along a given axis.
Parameters
----------
values : array-like
Array whose values will be ranked. The number of dimensions in this
array must not exceed 2.
axis : int, default 0
Axis over which to perform rankings.
method : {'average', 'min', 'max'... | uint64', 'object']:
ndtype = 'object'
values = _ensure_object(values)
f = getattr(htable, "mode_{dtype}".format(dtype=ndtype))
result = f(values)
try:
result = np.sort(result)
except TypeError as e:
warn("Unable to sort modes: {error}".format(error=e))
result = _rec... | 120 | 120 | 403 | 24 | 96 | mrocklin/pandas | pandas/core/algorithms.py | Python | rank | rank | 728 | 764 | 728 | 729 | 7a07a04fdb771965692fd10d108d13c6fa1432c6 | bigcode/the-stack | train |
5f560366919e4344f9aa8ff7 | train | function | def _ensure_data(values, dtype=None):
"""
routine to ensure that our data is of the correct
input dtype for lower-level routines
This will coerce:
- ints -> int64
- uint -> uint64
- bool -> uint64 (TODO this should be uint8)
- datetimelike -> i8
- datetime64tz -> i8 (in local tz)
... | def _ensure_data(values, dtype=None):
| """
routine to ensure that our data is of the correct
input dtype for lower-level routines
This will coerce:
- ints -> int64
- uint -> uint64
- bool -> uint64 (TODO this should be uint8)
- datetimelike -> i8
- datetime64tz -> i8 (in local tz)
- categorical -> codes
Paramete... | _unsigned_integer_dtype, is_signed_integer_dtype,
is_integer_dtype, is_complex_dtype,
is_object_dtype,
is_extension_array_dtype,
is_categorical_dtype, is_sparse,
is_period_dtype,
is_numeric_dtype, is_float_dtype,
is_bool_dtype, needs_i8_conversion,
is_datetimetz,
is_datetime64_any_dt... | 223 | 223 | 745 | 9 | 214 | mrocklin/pandas | pandas/core/algorithms.py | Python | _ensure_data | _ensure_data | 43 | 133 | 43 | 43 | e697235460983579086eadad653255553869a956 | bigcode/the-stack | train |
561fbd510f8f060feb5d3050 | train | function | @deprecate_kwarg(old_arg_name='order', new_arg_name=None)
def factorize(values, sort=False, order=None, na_sentinel=-1, size_hint=None):
"""
Encode input values as an enumerated type or categorical variable
Parameters
----------
values : Sequence
ndarrays must be 1-D. Sequences that aren't ... | @deprecate_kwarg(old_arg_name='order', new_arg_name=None)
def factorize(values, sort=False, order=None, na_sentinel=-1, size_hint=None):
| """
Encode input values as an enumerated type or categorical variable
Parameters
----------
values : Sequence
ndarrays must be 1-D. Sequences that aren't pandas objects are
coereced to ndarrays before factorization.
sort : boolean, default False
Sort by values
na_sen... | 'get_labels' method.
na_sentinel : int, default -1
size_hint : int, optional
Passsed through to the hashtable's 'get_labels' method
Returns
-------
labels, uniques : ndarray
"""
(hash_klass, vec_klass), values = _get_data_algo(values, _hashtables)
table = hash_klass(size_hint ... | 177 | 177 | 592 | 38 | 138 | mrocklin/pandas | pandas/core/algorithms.py | Python | factorize | factorize | 467 | 538 | 467 | 468 | fc9ff9fa13d732a26ca69bcebc8a10761f8d01fd | bigcode/the-stack | train |
0c223ba7aacdb3ee25af85ef | train | function | def value_counts(values, sort=True, ascending=False, normalize=False,
bins=None, dropna=True):
"""
Compute a histogram of the counts of non-null values.
Parameters
----------
values : ndarray (1-d)
sort : boolean, default True
Sort by values
ascending : boolean, def... | def value_counts(values, sort=True, ascending=False, normalize=False,
bins=None, dropna=True):
| """
Compute a histogram of the counts of non-null values.
Parameters
----------
values : ndarray (1-d)
sort : boolean, default True
Sort by values
ascending : boolean, default False
Sort in ascending order
normalize: boolean, default False
If True then compute a ... | = uniques.take(order)
except TypeError:
# Mixed types, where uniques.argsort fails.
uniques, labels = safe_sort(uniques, labels,
na_sentinel=na_sentinel,
assume_unique=True)
uniques = _reconstruct_data(... | 143 | 143 | 479 | 22 | 120 | mrocklin/pandas | pandas/core/algorithms.py | Python | value_counts | value_counts | 541 | 612 | 541 | 542 | 12cb93bd81aa0cc5fe834d4c48b413423fddf957 | bigcode/the-stack | train |
a202863a7bc35b74f50bfecc | train | function | def _reconstruct_data(values, dtype, original):
"""
reverse of _ensure_data
Parameters
----------
values : ndarray
dtype : pandas_dtype
original : ndarray-like
Returns
-------
Index for extension types, otherwise ndarray casted to dtype
"""
from pandas import Index
... | def _reconstruct_data(values, dtype, original):
| """
reverse of _ensure_data
Parameters
----------
values : ndarray
dtype : pandas_dtype
original : ndarray-like
Returns
-------
Index for extension types, otherwise ndarray casted to dtype
"""
from pandas import Index
if is_categorical_dtype(dtype):
pass
... | (not all do)
values = _ensure_int64(values)
return values, dtype, 'int64'
# we have failed, return object
values = np.asarray(values)
return _ensure_object(values), 'object', 'object'
def _reconstruct_data(values, dtype, original):
| 64 | 64 | 165 | 11 | 53 | mrocklin/pandas | pandas/core/algorithms.py | Python | _reconstruct_data | _reconstruct_data | 136 | 165 | 136 | 136 | f304d89968cfd6778ad75f206848b0fdcf944736 | bigcode/the-stack | train |
7afb29965d5497d7117bcd10 | train | function | def _take_2d_multi_object(arr, indexer, out, fill_value, mask_info):
# this is not ideal, performance-wise, but it's better than raising
# an exception (best to optimize in Cython to avoid getting here)
row_idx, col_idx = indexer
if mask_info is not None:
(row_mask, col_mask), (row_needs, col_ne... | def _take_2d_multi_object(arr, indexer, out, fill_value, mask_info):
# this is not ideal, performance-wise, but it's better than raising
# an exception (best to optimize in Cython to avoid getting here)
| row_idx, col_idx = indexer
if mask_info is not None:
(row_mask, col_mask), (row_needs, col_needs) = mask_info
else:
row_mask = row_idx == -1
col_mask = col_idx == -1
row_needs = row_mask.any()
col_needs = col_mask.any()
if fill_value is not None:
if row_ne... | out, fill_value=fill_value)
return wrapper
def _take_2d_multi_object(arr, indexer, out, fill_value, mask_info):
# this is not ideal, performance-wise, but it's better than raising
# an exception (best to optimize in Cython to avoid getting here)
| 65 | 65 | 218 | 53 | 11 | mrocklin/pandas | pandas/core/algorithms.py | Python | _take_2d_multi_object | _take_2d_multi_object | 1,155 | 1,175 | 1,155 | 1,157 | 8fe25004dd62516a7f97cb2140b3a1f4a421aeef | bigcode/the-stack | train |
78e78a8c91921ffe7d8c1b29 | train | function | def duplicated(values, keep='first'):
"""
Return boolean ndarray denoting duplicate values.
.. versionadded:: 0.19.0
Parameters
----------
values : ndarray-like
Array over which to check for duplicate values.
keep : {'first', 'last', False}, default 'first'
- ``first`` : Ma... | def duplicated(values, keep='first'):
| """
Return boolean ndarray denoting duplicate values.
.. versionadded:: 0.19.0
Parameters
----------
values : ndarray-like
Array over which to check for duplicate values.
keep : {'first', 'last', False}, default 'first'
- ``first`` : Mark duplicates as ``True`` except for t... | if not isna(keys).any():
keys = np.insert(keys, 0, np.NaN)
counts = np.insert(counts, 0, mask.sum())
keys = _reconstruct_data(keys, original.dtype, original)
return keys, counts
def duplicated(values, keep='first'):
| 64 | 64 | 171 | 8 | 55 | mrocklin/pandas | pandas/core/algorithms.py | Python | duplicated | duplicated | 658 | 682 | 658 | 658 | e81d090ec37ff9a724763f144f22625bb5077c95 | bigcode/the-stack | train |
11784fb8cc87431a6cd89c15 | train | class | class SelectN(object):
def __init__(self, obj, n, keep):
self.obj = obj
self.n = n
self.keep = keep
if self.keep not in ('first', 'last'):
raise ValueError('keep must be either "first", "last"')
def nlargest(self):
return self.compute('nlargest')
def n... | class SelectN(object):
| def __init__(self, obj, n, keep):
self.obj = obj
self.n = n
self.keep = keep
if self.keep not in ('first', 'last'):
raise ValueError('keep must be either "first", "last"')
def nlargest(self):
return self.compute('nlargest')
def nsmallest(self):
... | ")
return score
if is_scalar(q):
return _get_score(q)
else:
q = np.asarray(q, np.float64)
return algos.arrmap_float64(q, _get_score)
# --------------- #
# select n #
# --------------- #
class SelectN(object):
| 64 | 64 | 154 | 5 | 59 | mrocklin/pandas | pandas/core/algorithms.py | Python | SelectN | SelectN | 954 | 977 | 954 | 955 | dcd041fbb6e307f1742f57f97c8f51f32830ffc2 | bigcode/the-stack | train |
1b782873641d462a88387288 | train | function | def match(to_match, values, na_sentinel=-1):
"""
Compute locations of to_match into values
Parameters
----------
to_match : array-like
values to find positions of
values : array-like
Unique set of values
na_sentinel : int, default -1
Value to mark "not found"
Ex... | def match(to_match, values, na_sentinel=-1):
| """
Compute locations of to_match into values
Parameters
----------
to_match : array-like
values to find positions of
values : array-like
Unique set of values
na_sentinel : int, default -1
Value to mark "not found"
Examples
--------
Returns
-------
... | than Object
if lib.infer_dtype(values) in ['string']:
ndtype = 'string'
f = func_map.get(ndtype, func_map['object'])
return f, values
# --------------- #
# top-level algos #
# --------------- #
def match(to_match, values, na_sentinel=-1):
| 69 | 69 | 233 | 13 | 56 | mrocklin/pandas | pandas/core/algorithms.py | Python | match | match | 241 | 276 | 241 | 241 | 5266efed91d5213aebfcfb7f3f8a8f87d8e5f907 | bigcode/the-stack | train |
b36a287c6db274600e336fba | train | function | def _value_counts_arraylike(values, dropna):
"""
Parameters
----------
values : arraylike
dropna : boolean
Returns
-------
(uniques, counts)
"""
values = _ensure_arraylike(values)
original = values
values, dtype, ndtype = _ensure_data(values)
if needs_i8_conversion... | def _value_counts_arraylike(values, dropna):
| """
Parameters
----------
values : arraylike
dropna : boolean
Returns
-------
(uniques, counts)
"""
values = _ensure_arraylike(values)
original = values
values, dtype, ndtype = _ensure_data(values)
if needs_i8_conversion(dtype):
# i8
keys, counts =... | na)
if not isinstance(keys, Index):
keys = Index(keys)
result = Series(counts, index=keys, name=name)
if sort:
result = result.sort_values(ascending=ascending)
if normalize:
result = result / float(counts.sum())
return result
def _value_counts_arra... | 74 | 74 | 249 | 11 | 62 | mrocklin/pandas | pandas/core/algorithms.py | Python | _value_counts_arraylike | _value_counts_arraylike | 615 | 655 | 615 | 615 | 5ce1a9517f9c5d0d84c3c36179ff8d02dab3eceb | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.