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
19a5ac002ae36222c28b452c
train
function
def convert_namespace_to_omegaconf(args: Namespace) -> DictConfig: """Convert a flat argparse.Namespace to a structured DictConfig.""" # Here we are using field values provided in args to override counterparts inside config object overrides, deletes = override_module_args(args) # configs will be in fa...
def convert_namespace_to_omegaconf(args: Namespace) -> DictConfig:
"""Convert a flat argparse.Namespace to a structured DictConfig.""" # Here we are using field values provided in args to override counterparts inside config object overrides, deletes = override_module_args(args) # configs will be in fairseq/config after installation config_path = os.path.join(".."...
m_name = ARCH_MODEL_NAME_REGISTRY[args.arch] overrides.append("model={}".format(m_name)) overrides.append("model._name={}".format(args.arch)) # override model params with those exist in args overrides.extend(_override_at...
177
177
590
17
159
houshengyuan/Parsing_enhanced_NMT
fairseq/dataclass/utils.py
Python
convert_namespace_to_omegaconf
convert_namespace_to_omegaconf
353
416
353
353
c065f2e6348383bd6e07dfc98dda2424c5ac779c
bigcode/the-stack
train
d6a5b8040a1b41630eaef68f
train
function
def _set_legacy_defaults(args, cls): """Helper to set default arguments based on *add_args*.""" if not hasattr(cls, "add_args"): return import argparse parser = argparse.ArgumentParser( argument_default=argparse.SUPPRESS, allow_abbrev=False ) cls.add_args(parser) # copied f...
def _set_legacy_defaults(args, cls):
"""Helper to set default arguments based on *add_args*.""" if not hasattr(cls, "add_args"): return import argparse parser = argparse.ArgumentParser( argument_default=argparse.SUPPRESS, allow_abbrev=False ) cls.add_args(parser) # copied from argparse.py: defaults = argpa...
added elsewhere continue else: del kwargs["default"] if delete_default and "default" in kwargs: del kwargs["default"] try: parser.add_argument(*field_args, **kwargs) except ArgumentError: pass de...
64
64
165
10
53
houshengyuan/Parsing_enhanced_NMT
fairseq/dataclass/utils.py
Python
_set_legacy_defaults
_set_legacy_defaults
175
195
175
175
ab1ad140a03dca0ed65281e26f0f4598beecbbb6
bigcode/the-stack
train
ad6aaad8ba75e1346687d8b4
train
function
def render(session, path): # print(session.current_url) # render_path(session) if download_type==0 or download_type==2: # session.render(path+'.png') session.save_screenshot(path+'.png') if download_type==0 or download_type==1: f = open(path+'.html', 'wb') # f.write(sessi...
def render(session, path): # print(session.current_url) # render_path(session)
if download_type==0 or download_type==2: # session.render(path+'.png') session.save_screenshot(path+'.png') if download_type==0 or download_type==1: f = open(path+'.html', 'wb') # f.write(session.body().encode('utf-8')) f.write(session.page_source.encode('utf-8')) ...
-navbar-list > li:nth-child(n)')) >= 1) WebDriverWait(session, 30).until( lambda session: len(session.find_elements_by_css_selector(SIDEBAR_LOAD_URL)) >=1) def render(session, path): # print(session.current_url) # render_path(session)
64
64
100
19
45
Chillee/coursera-dl-all
dl_all.py
Python
render
render
37
47
37
39
d7883c85448dd0771d841a10e78f2458ae3f566c
bigcode/the-stack
train
6d3342cf9d98209f0b45395b
train
function
def wait_for_load(session): # session.wait_for(lambda session: len(session.css('#course-page-sidebar > div > ul.course-navbar-list > li:nth-child(n)')) >= 1) WebDriverWait(session, 30).until( lambda session: len(session.find_elements_by_css_selector(SIDEBAR_LOAD_URL)) >=1)
def wait_for_load(session): # session.wait_for(lambda session: len(session.css('#course-page-sidebar > div > ul.course-navbar-list > li:nth-child(n)')) >= 1)
WebDriverWait(session, 30).until( lambda session: len(session.find_elements_by_css_selector(SIDEBAR_LOAD_URL)) >=1)
def clean_filename(path): return "".join([c for c in path if re.match(r'\w', c)]) def wait_for_load(session): # session.wait_for(lambda session: len(session.css('#course-page-sidebar > div > ul.course-navbar-list > li:nth-child(n)')) >= 1)
63
64
71
39
24
Chillee/coursera-dl-all
dl_all.py
Python
wait_for_load
wait_for_load
32
35
32
33
d1db85c07edd0bb3b3110c3488661e93ba0c626f
bigcode/the-stack
train
042e020423f4a75a9d084f11
train
function
def get_quiz_info(session, url, category_name): session.get(url) wait_for_load(session) render(session, os.getcwd()+'/'+category_name) links = session.find_elements_by_css_selector('#spark > div.course-item-list > ul:nth-child(n) > li > div:nth-child(n) > div > a') for idx in range(len(links)): ...
def get_quiz_info(session, url, category_name):
session.get(url) wait_for_load(session) render(session, os.getcwd()+'/'+category_name) links = session.find_elements_by_css_selector('#spark > div.course-item-list > ul:nth-child(n) > li > div:nth-child(n) > div > a') for idx in range(len(links)): links[idx] = links[idx].get_attribute('href'...
sera.org'+links[idx][0], links[idx][1]) # print(links) links = [i for i in links if i[0].find('/quiz')!=-1] links = list(set(links)) return links def get_quiz_info(session, url, category_name):
64
64
183
12
51
Chillee/coursera-dl-all
dl_all.py
Python
get_quiz_info
get_quiz_info
172
185
172
172
6ee4129ef14dbee7576c3d253a6cff5686c36866
bigcode/the-stack
train
de8e6fc0f27a17a633f366b0
train
class
class Quiz(object): url = '' name = '' number = 0 def __init__(self, url, number, name): self.url = url self.number = number self.name = name
class Quiz(object):
url = '' name = '' number = 0 def __init__(self, url, number, name): self.url = url self.number = number self.name = name
4') for idx in range(len(names)): names[idx] = names[idx].text.replace(' ', '_') names[idx] = names[idx][:names[idx].rfind('Help Center')-len('Help Center')] # print(names) return zip(links, names) class Quiz(object):
64
64
49
4
60
Chillee/coursera-dl-all
dl_all.py
Python
Quiz
Quiz
187
194
187
187
c765f89f80779d65345470e5293c56149e3ff1d3
bigcode/the-stack
train
3d294236bd0d6661583f057f
train
function
def download_all_quizzes(session, quiz_info, category_name): # print(quiz_info) for idx, i in enumerate(quiz_info): quiz_obj = Quiz(i[0], idx, clean_filename(i[1])) download_quiz(session, quiz_obj, clean_filename(category_name))
def download_all_quizzes(session, quiz_info, category_name): # print(quiz_info)
for idx, i in enumerate(quiz_info): quiz_obj = Quiz(i[0], idx, clean_filename(i[1])) download_quiz(session, quiz_obj, clean_filename(category_name))
print(quiz.url+' not accessible.') wait_for_load(session) download_all_zips_on_page(session, path) render(session, os.getcwd()+'/'+path+str(quiz.number)+'_'+quiz.name) def download_all_quizzes(session, quiz_info, category_name): # print(quiz_info)
64
64
62
20
44
Chillee/coursera-dl-all
dl_all.py
Python
download_all_quizzes
download_all_quizzes
216
220
216
217
10268344ed349d29e1dd796eb30446b02638a04c
bigcode/the-stack
train
5730a2dff9141db3c0fa5205
train
function
def clean_filename(path): return "".join([c for c in path if re.match(r'\w', c)])
def clean_filename(path):
return "".join([c for c in path if re.match(r'\w', c)])
set() download_type = 0 SIDEBAR_LOAD_URL ='#course-page-sidebar > div > ul.course-navbar-list > li:nth-child(n)' class_url='' class_slug='' home_dir='' def mkdir_safe(path): if not os.path.exists(path): os.makedirs(path) def clean_filename(path):
64
64
24
5
59
Chillee/coursera-dl-all
dl_all.py
Python
clean_filename
clean_filename
28
29
28
28
830e75311e2460fb913dd248382d95450e2f2cac
bigcode/the-stack
train
e85aa9462b6d47dadcd609ca
train
function
def login(session, URL, email, password): #ugly ugly code in here session.get(URL) # print(session.find_elements_by_css_selector('#user-modal-email'))) WebDriverWait(session, 30).until( lambda session: len(session.find_elements_by_css_selector('#user-modal-email'))>2) x = session.find_eleme...
def login(session, URL, email, password): #ugly ugly code in here
session.get(URL) # print(session.find_elements_by_css_selector('#user-modal-email'))) WebDriverWait(session, 30).until( lambda session: len(session.find_elements_by_css_selector('#user-modal-email'))>2) x = session.find_elements_by_css_selector('#user-modal-email')[1] x.send_keys(email) ...
', 'wb') # f.write(session.body().encode('utf-8')) f.write(session.page_source.encode('utf-8')) f.close() # def render_path(session): # s = 'class.coursera.org/'+class_slug # path = session.current_url # path = path[path.find(s)+len(s)+1:] # # print('path: '+path) # if path=...
200
200
669
19
181
Chillee/coursera-dl-all
dl_all.py
Python
login
login
66
116
66
66
f94afe4ae01e54b52bf7ce39466774e280edd0b8
bigcode/the-stack
train
64802886fafc83c8346724a2
train
function
def download_sidebar_pages(session): links = session.find_elements_by_css_selector('#course-page-sidebar > div > ul.course-navbar-list > li:nth-child(n) > a') # print(links) for idx in range(len(links)): links[idx] = (links[idx].get_attribute('href'), clean_filename(links[idx].text)) if link...
def download_sidebar_pages(session):
links = session.find_elements_by_css_selector('#course-page-sidebar > div > ul.course-navbar-list > li:nth-child(n) > a') # print(links) for idx in range(len(links)): links[idx] = (links[idx].get_attribute('href'), clean_filename(links[idx].text)) if links[idx][0][0]=='/': links[...
[idx] = name[idx].split('\n')[0] print(name) return zip(links, name) def download_all_assignments(session, assign_info): for i in assign_info: session.get(i[0]) wait_for_load(session) download_all_zips_on_page(session, 'assignments/'+i[1]) def download_sidebar_pages(session):
77
77
259
6
71
Chillee/coursera-dl-all
dl_all.py
Python
download_sidebar_pages
download_sidebar_pages
246
265
246
246
eb8ed5dd6332a57e49552aacacd5fa9bc993d824
bigcode/the-stack
train
0d55923de8fada761b81dde5
train
function
def download_all_assignments(session, assign_info): for i in assign_info: session.get(i[0]) wait_for_load(session) download_all_zips_on_page(session, 'assignments/'+i[1])
def download_all_assignments(session, assign_info):
for i in assign_info: session.get(i[0]) wait_for_load(session) download_all_zips_on_page(session, 'assignments/'+i[1])
print(name[idx]) # name[idx] = name[idx][:name[idx].rfind('Help Center')-len('Help Center')] name[idx] = name[idx].split('\n')[0] print(name) return zip(links, name) def download_all_assignments(session, assign_info):
64
64
47
10
54
Chillee/coursera-dl-all
dl_all.py
Python
download_all_assignments
download_all_assignments
240
244
240
240
dcdff4ee9db812364e78f616db00d88e40b5be02
bigcode/the-stack
train
ef9890b5edbe47b89213d066
train
function
def download_quiz(session, quiz, category_name): session.get(quiz.url) wait_for_load(session) path = category_name+'/'+str(quiz.number)+'_'+clean_filename(quiz.name)+'/' mkdir_safe(path) if session.current_url.find('attempt')==-1: if len(session.find_elements_by_css_selector('#spark > form ...
def download_quiz(session, quiz, category_name):
session.get(quiz.url) wait_for_load(session) path = category_name+'/'+str(quiz.number)+'_'+clean_filename(quiz.name)+'/' mkdir_safe(path) if session.current_url.find('attempt')==-1: if len(session.find_elements_by_css_selector('#spark > form > p > input')) == 0: print("Error: Co...
links, names) class Quiz(object): url = '' name = '' number = 0 def __init__(self, url, number, name): self.url = url self.number = number self.name = name def download_quiz(session, quiz, category_name):
64
64
166
11
52
Chillee/coursera-dl-all
dl_all.py
Python
download_quiz
download_quiz
198
214
198
198
a15ac95472447e5ed82f81173a5611897441cb7b
bigcode/the-stack
train
4dec5945fc3133344b1a7a1d
train
function
def get_assign_info(session): session.get(class_url+'assignment') wait_for_load(session) render(session, os.getcwd()+'/assignment_home') links= session.find_elements_by_css_selector('#spark > div.course-item-list > ul:nth-child(n) > li > div:nth-child(2) > a') for idx in range(len(links)): l...
def get_assign_info(session):
session.get(class_url+'assignment') wait_for_load(session) render(session, os.getcwd()+'/assignment_home') links= session.find_elements_by_css_selector('#spark > div.course-item-list > ul:nth-child(n) > li > div:nth-child(2) > a') for idx in range(len(links)): links[idx] = links[idx].get_att...
izzes(session, quiz_info, category_name): # print(quiz_info) for idx, i in enumerate(quiz_info): quiz_obj = Quiz(i[0], idx, clean_filename(i[1])) download_quiz(session, quiz_obj, clean_filename(category_name)) def get_assign_info(session):
64
64
190
6
58
Chillee/coursera-dl-all
dl_all.py
Python
get_assign_info
get_assign_info
222
238
222
222
2e816ee3d6fcb72d607541c1e87e59fe85ba4d3d
bigcode/the-stack
train
4a21dc97d375eb996db153dc
train
function
def mkdir_safe(path): if not os.path.exists(path): os.makedirs(path)
def mkdir_safe(path):
if not os.path.exists(path): os.makedirs(path)
requests import argparse import csv import re import shutil downloaded_links = set() download_type = 0 SIDEBAR_LOAD_URL ='#course-page-sidebar > div > ul.course-navbar-list > li:nth-child(n)' class_url='' class_slug='' home_dir='' def mkdir_safe(path):
63
64
18
5
58
Chillee/coursera-dl-all
dl_all.py
Python
mkdir_safe
mkdir_safe
24
26
24
24
3c4e96977961bb7df1bbe50914c9ad75351b2eaf
bigcode/the-stack
train
d9cf573606a830518ddba057
train
function
def get_class_url_info(x): cur = x[0].rstrip() cur = cur.rstrip('/') class_slug = cur[cur.rfind('/')+1:] class_url = "https://class.coursera.org/"+class_slug+'/' return (class_url, class_slug)
def get_class_url_info(x):
cur = x[0].rstrip() cur = cur.rstrip('/') class_slug = cur[cur.rfind('/')+1:] class_url = "https://class.coursera.org/"+class_slug+'/' return (class_url, class_slug)
_page(session, path) print(path, os.listdir(os.getcwd()+'/'+path)) if len(os.listdir(os.getcwd()+'/'+path))==0: os.rmdir(os.getcwd()+'/'+path) path='' render(session, os.getcwd()+'/'+path+i[1]) def get_class_url_info(x):
64
64
60
7
57
Chillee/coursera-dl-all
dl_all.py
Python
get_class_url_info
get_class_url_info
267
273
267
267
eb2c584135d0fe64cd703c08c6ad7cb0ab291cca
bigcode/the-stack
train
e2539f51dd5e6cb7ce1b446d
train
function
def download_all_zips_on_page(session, path='assignments'): links = session.find_elements_by_css_selector('a') if not os.path.exists(path): os.makedirs(path) if args.download_type!=1: txt_file = open(path+'/links.txt', 'w') links = [url.get_attribute('href') for url in links] for u...
def download_all_zips_on_page(session, path='assignments'):
links = session.find_elements_by_css_selector('a') if not os.path.exists(path): os.makedirs(path) if args.download_type!=1: txt_file = open(path+'/links.txt', 'w') links = [url.get_attribute('href') for url in links] for url in links: if url==None: continue ...
_css_selector('#agreehonorcode'))>=1: session.find_elements_by_css_selector('#agreehonorcode')[0].click() wait_for_load(session) elif session.page_source.find('Remove from watchlist')!=-1: print("Error: Impossible to access course"+URL) return -1 render(session, os.getcwd()+'/co...
96
96
323
14
81
Chillee/coursera-dl-all
dl_all.py
Python
download_all_zips_on_page
download_all_zips_on_page
118
157
118
118
23261e595539f980e808993aa14ee39aeebf1c46
bigcode/the-stack
train
bd96024005e634e6910b90ce
train
function
def get_quiz_types(session): links = session.find_elements_by_css_selector('#course-page-sidebar > div > ul.course-navbar-list > li:nth-child(n) > a') for idx in range(len(links)): links[idx] = (links[idx].get_attribute('href'), links[idx].text) if links[idx][0][0]=='/': links[idx] =...
def get_quiz_types(session):
links = session.find_elements_by_css_selector('#course-page-sidebar > div > ul.course-navbar-list > li:nth-child(n) > a') for idx in range(len(links)): links[idx] = (links[idx].get_attribute('href'), links[idx].text) if links[idx][0][0]=='/': links[idx] = ('https://class.coursera.org...
download "+url) # continue print(url) r = requests.get(url) with open(path+url[url.rfind('/'):], 'wb') as f: f.write(r.content) render(session, os.getcwd()+'/'+path+'/zip_page') def get_quiz_types(session):
64
64
138
7
57
Chillee/coursera-dl-all
dl_all.py
Python
get_quiz_types
get_quiz_types
159
169
159
159
84aaea9ecf570cc72cf031505df28b402159334b
bigcode/the-stack
train
85175491cf19da4e4595d733
train
function
def test_existed_film_local_searching(app): search_target = u"Криминальное чтиво" app.ensure_logout() app.login(User.Admin()) assert app.is_logged_in() app.search_for_film(search_target) films_after_search = app.get_films_on_page() app.list_of_film_treatment(list_of_films=films_after_se...
def test_existed_film_local_searching(app):
search_target = u"Криминальное чтиво" app.ensure_logout() app.login(User.Admin()) assert app.is_logged_in() app.search_for_film(search_target) films_after_search = app.get_films_on_page() app.list_of_film_treatment(list_of_films=films_after_search, search_target=search_target) app.l...
# -*- coding: utf-8 -*- from model.user import User import unittest def test_existed_film_local_searching(app):
28
64
99
11
16
semenkravchenko/selenium-py-training-kravchenko
php4dvd/test_film_searching.py
Python
test_existed_film_local_searching
test_existed_film_local_searching
6
21
6
7
5b229a82689cf235c32c0a8554cbe3e6ac43a9dd
bigcode/the-stack
train
fdeb643f70d239c9a6407f6e
train
function
def test_not_existed_film_local_searching(app): search_target = u"Красная шапочка" app.ensure_logout() app.login(User.Admin()) assert app.is_logged_in() app.search_for_film(search_target, is_film_exists=False) films_after_search = app.get_films_on_page() app.list_of_film_treatment(list_...
def test_not_existed_film_local_searching(app):
search_target = u"Красная шапочка" app.ensure_logout() app.login(User.Admin()) assert app.is_logged_in() app.search_for_film(search_target, is_film_exists=False) films_after_search = app.get_films_on_page() app.list_of_film_treatment(list_of_films=films_after_search, search_target=search...
_film(search_target) films_after_search = app.get_films_on_page() app.list_of_film_treatment(list_of_films=films_after_search, search_target=search_target) app.logout() assert app.is_not_logged_in() def test_not_existed_film_local_searching(app):
64
64
110
12
52
semenkravchenko/selenium-py-training-kravchenko
php4dvd/test_film_searching.py
Python
test_not_existed_film_local_searching
test_not_existed_film_local_searching
23
38
23
24
a814f4d9c69f8c53fb3c617676b37b2ae93af742
bigcode/the-stack
train
6c640c3957faea0f83f4169d
train
class
class GreasePencilLayerMasksPanel: def draw_header(self, context): ob = context.active_object gpd = ob.data gpl = gpd.layers.active self.layout.prop(gpl, "use_mask_layer", text="") def draw(self, context): ob = context.active_object gpd = ob.data gpl = g...
class GreasePencilLayerMasksPanel:
def draw_header(self, context): ob = context.active_object gpd = ob.data gpl = gpd.layers.active self.layout.prop(gpl, "use_mask_layer", text="") def draw(self, context): ob = context.active_object gpd = ob.data gpl = gpd.layers.active layout = ...
_active and gpl.info not in gpl_active.mask_layers: done = True layout.operator("gpencil.layer_mask_add", text=gpl.info).name = gpl.info if done is False: layout.label(text="No layers to add") class GreasePencilLayerMasksPanel:
64
64
206
9
55
mmtt1998819/blender
release/scripts/startup/bl_ui/properties_grease_pencil_common.py
Python
GreasePencilLayerMasksPanel
GreasePencilLayerMasksPanel
794
819
794
794
ad41007b1fa3b6acda5afae78ba4bdaef5b1f5f3
bigcode/the-stack
train
6f0f9c76691c3dfca91e2bcb
train
class
class GPENCIL_UL_annotation_layer(UIList): def draw_item(self, _context, layout, _data, item, icon, _active_data, _active_propname, _index): # assert(isinstance(item, bpy.types.GPencilLayer) gpl = item if self.layout_type in {'DEFAULT', 'COMPACT'}: if gpl.lock: l...
class GPENCIL_UL_annotation_layer(UIList):
def draw_item(self, _context, layout, _data, item, icon, _active_data, _active_propname, _index): # assert(isinstance(item, bpy.types.GPencilLayer) gpl = item if self.layout_type in {'DEFAULT', 'COMPACT'}: if gpl.lock: layout.active = False split = l...
() layout.operator("gpencil.frame_clean_duplicate", text="Delete Duplicated Frames") layout.operator("gpencil.recalc_geometry", text="Recalculate Geometry") if ob.mode != 'PAINT_GPENCIL': layout.operator("gpencil.reproject") class GPENCIL_UL_annotation_layer(UIList):
64
64
176
9
55
mmtt1998819/blender
release/scripts/startup/bl_ui/properties_grease_pencil_common.py
Python
GPENCIL_UL_annotation_layer
GPENCIL_UL_annotation_layer
393
410
393
393
97fafb7579c703bb49d78d62820e095ebbd1e5a7
bigcode/the-stack
train
cc187b30c54431fd999d0155
train
class
class GreasePencilMaterialsPanel: # Mix-in, use for properties editor and top-bar. def draw(self, context): layout = self.layout show_full_ui = (self.bl_space_type == 'PROPERTIES') is_view3d = (self.bl_space_type == 'VIEW_3D') tool_settings = context.scene.tool_settings ...
class GreasePencilMaterialsPanel: # Mix-in, use for properties editor and top-bar.
def draw(self, context): layout = self.layout show_full_ui = (self.bl_space_type == 'PROPERTIES') is_view3d = (self.bl_space_type == 'VIEW_3D') tool_settings = context.scene.tool_settings gpencil_paint = tool_settings.gpencil_paint brush = gpencil_paint.brush ...
self.layout.prop(gpl, "use_annotation_onion_skinning", text="") def draw(self, context): layout = self.layout layout.use_property_decorate = False gpl = context.active_annotation_layer col = layout.column() split = col.split(factor=0.5) split.active = gpl.u...
215
215
719
21
194
mmtt1998819/blender
release/scripts/startup/bl_ui/properties_grease_pencil_common.py
Python
GreasePencilMaterialsPanel
GreasePencilMaterialsPanel
545
625
545
546
766f034c27d4cd9e122ef9175676787508f077d3
bigcode/the-stack
train
6224207a373119a23ecebfc7
train
class
class GPENCIL_MT_layer_active(Menu): bl_label = "Change Active Layer" def draw(self, context): layout = self.layout layout.operator_context = 'INVOKE_REGION_WIN' gpd = context.gpencil_data if gpd: gpl_active = context.active_gpencil_layer tot_layers = le...
class GPENCIL_MT_layer_active(Menu):
bl_label = "Change Active Layer" def draw(self, context): layout = self.layout layout.operator_context = 'INVOKE_REGION_WIN' gpd = context.gpencil_data if gpd: gpl_active = context.active_gpencil_layer tot_layers = len(gpd.layers) i = tot_lay...
layout.operator("gpencil.move_to_layer", text=gpl.info, icon=icon).layer = i i -= 1 layout.separator() layout.operator("gpencil.move_to_layer", text="New Layer", icon='ADD').layer = -1 class GPENCIL_MT_layer_active(Menu):
64
64
181
8
55
mmtt1998819/blender
release/scripts/startup/bl_ui/properties_grease_pencil_common.py
Python
GPENCIL_MT_layer_active
GPENCIL_MT_layer_active
299
322
299
299
4dc90f28dedaaca46146646772ac65eed7cce5fb
bigcode/the-stack
train
60008389a621800ed1e5db65
train
class
class GPENCIL_MT_cleanup(Menu): bl_label = "Clean Up" def draw(self, context): ob = context.active_object layout = self.layout layout.operator("gpencil.frame_clean_fill", text="Boundary Strokes").mode = 'ACTIVE' layout.operator("gpencil.frame_clean_fill", text="Boundary Strok...
class GPENCIL_MT_cleanup(Menu):
bl_label = "Clean Up" def draw(self, context): ob = context.active_object layout = self.layout layout.operator("gpencil.frame_clean_fill", text="Boundary Strokes").mode = 'ACTIVE' layout.operator("gpencil.frame_clean_fill", text="Boundary Strokes all Frames").mode = 'ALL' ...
layout.operator_context = 'INVOKE_REGION_WIN' layout.operator("gpencil.delete", text="Delete Active Keyframe (Active Layer)").type = 'FRAME' layout.operator("gpencil.active_frames_delete_all", text="Delete Active Keyframes (All Layers)") class GPENCIL_MT_cleanup(Menu):
63
64
186
7
56
mmtt1998819/blender
release/scripts/startup/bl_ui/properties_grease_pencil_common.py
Python
GPENCIL_MT_cleanup
GPENCIL_MT_cleanup
366
390
366
366
c00b1d3ebaf2b193b73915e10dc50b33d5c6719f
bigcode/the-stack
train
bf1c95c07acbb163da5f2091
train
class
class GreasePencilLayerAdjustmentsPanel: def draw(self, context): layout = self.layout layout.use_property_split = True scene = context.scene ob = context.object gpd = ob.data gpl = gpd.layers.active layout.active = not gpl.lock # Layer options ...
class GreasePencilLayerAdjustmentsPanel:
def draw(self, context): layout = self.layout layout.use_property_split = True scene = context.scene ob = context.object gpd = ob.data gpl = gpd.layers.active layout.active = not gpl.lock # Layer options # Offsets - Color Tint layout....
_gpencil_view_fill") col.prop(rd, "simplify_gpencil_modifier") col.prop(rd, "simplify_gpencil_shader_fx") col.prop(rd, "simplify_gpencil_tint") col.prop(rd, "simplify_gpencil_antialiasing") class GreasePencilLayerAdjustmentsPanel:
68
68
229
10
58
mmtt1998819/blender
release/scripts/startup/bl_ui/properties_grease_pencil_common.py
Python
GreasePencilLayerAdjustmentsPanel
GreasePencilLayerAdjustmentsPanel
730
760
730
731
56cde937dd0d2824995f6f55e6ed955f8d0c4511
bigcode/the-stack
train
836777b2ecd9a7865bb442bf
train
class
class AnnotationDataPanel: bl_label = "Annotations" bl_region_type = 'UI' bl_options = {'DEFAULT_CLOSED'} def draw_header(self, context): if context.space_data.type not in {'VIEW_3D', 'TOPBAR'}: self.layout.prop(context.space_data, "show_annotation", text="") def draw(self, con...
class AnnotationDataPanel:
bl_label = "Annotations" bl_region_type = 'UI' bl_options = {'DEFAULT_CLOSED'} def draw_header(self, context): if context.space_data.type not in {'VIEW_3D', 'TOPBAR'}: self.layout.prop(context.space_data, "show_annotation", text="") def draw(self, context): layout = sel...
", text="Recalculate Geometry") if ob.mode != 'PAINT_GPENCIL': layout.operator("gpencil.reproject") class GPENCIL_UL_annotation_layer(UIList): def draw_item(self, _context, layout, _data, item, icon, _active_data, _active_propname, _index): # assert(isinstance(item, bpy.types.GPencilLa...
208
208
695
5
203
mmtt1998819/blender
release/scripts/startup/bl_ui/properties_grease_pencil_common.py
Python
AnnotationDataPanel
AnnotationDataPanel
413
496
413
413
a1cadbb2c53bb91e0a461c2455386f9f04c09267
bigcode/the-stack
train
b02d90f485f4ef2e4ae93749
train
class
class GreasePencilLayerDisplayPanel: def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False ob = context.object gpd = ob.data gpl = gpd.layers.active use_colors = context.preferences.edit.use_anim...
class GreasePencilLayerDisplayPanel:
def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False ob = context.object gpd = ob.data gpl = gpd.layers.active use_colors = context.preferences.edit.use_anim_channel_group_colors col = l...
", text="Type") parent = gpl.parent if parent and gpl.parent_type == 'BONE' and parent.type == 'ARMATURE': col.prop_search(gpl, "parent_bone", parent.data, "bones", text="Bone") class GreasePencilLayerDisplayPanel:
64
64
159
9
55
mmtt1998819/blender
release/scripts/startup/bl_ui/properties_grease_pencil_common.py
Python
GreasePencilLayerDisplayPanel
GreasePencilLayerDisplayPanel
843
864
843
844
c17f3b11da29a654b13c871236358f561d785ee0
bigcode/the-stack
train
622f7c6a0e88da808bbdc9f4
train
class
class GPENCIL_UL_layer(UIList): def draw_item(self, _context, layout, _data, item, icon, _active_data, _active_propname, _index): # assert(isinstance(item, bpy.types.GPencilLayer) gpl = item if self.layout_type in {'DEFAULT', 'COMPACT'}: if gpl.lock: layout.activ...
class GPENCIL_UL_layer(UIList):
def draw_item(self, _context, layout, _data, item, icon, _active_data, _active_propname, _index): # assert(isinstance(item, bpy.types.GPencilLayer) gpl = item if self.layout_type in {'DEFAULT', 'COMPACT'}: if gpl.lock: layout.active = False row = lay...
.template_palette(gpencil_paint, "palette", color=True) if tool in {'DRAW', 'FILL'} and is_vertex is False: row = layout.row(align=True) row.prop(gp_settings, "vertex_mode", text="Mode") row = layout.row(align=True) row.prop(gp_settings, "vert...
92
92
307
8
84
mmtt1998819/blender
release/scripts/startup/bl_ui/properties_grease_pencil_common.py
Python
GPENCIL_UL_layer
GPENCIL_UL_layer
666
703
666
666
de03f95222652b6dd3ad685f39c0ad5521da46d4
bigcode/the-stack
train
8a99e4e61ea6db18ed6596cf
train
class
class GreasePencilDisplayPanel: bl_label = "Brush Tip" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): ob = context.active_object brush = context.tool_settings.gpencil_paint.brush if ob and ob.type == 'GPENCIL' and brush: if context.mode == 'PAIN...
class GreasePencilDisplayPanel:
bl_label = "Brush Tip" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): ob = context.active_object brush = context.tool_settings.gpencil_paint.brush if ob and ob.type == 'GPENCIL' and brush: if context.mode == 'PAINT_GPENCIL': retu...
ANDOMIZE'}) def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False tool_settings = context.scene.tool_settings settings = tool_settings.gpencil_sculpt_paint brush = settings.brush gp_settings = bru...
208
208
694
8
199
mmtt1998819/blender
release/scripts/startup/bl_ui/properties_grease_pencil_common.py
Python
GreasePencilDisplayPanel
GreasePencilDisplayPanel
97
178
97
97
97eb8db9a5027e5209a39517272b848b2a168694
bigcode/the-stack
train
000a768a418726b8348de6fe
train
class
class GreasePencilLayerRelationsPanel: def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False ob = context.object gpd = ob.data gpl = gpd.layers.active col = layout.column() col.active = n...
class GreasePencilLayerRelationsPanel:
def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False ob = context.object gpd = ob.data gpl = gpd.layers.active col = layout.column() col.active = not gpl.lock col.prop(gpl, "paren...
", rows=rows, sort_lock=True) col2 = row.column(align=True) col2.menu("GPENCIL_MT_layer_mask_menu", icon='ADD', text="") col2.operator("gpencil.layer_mask_remove", icon='REMOVE', text="") class GreasePencilLayerRelationsPanel:
63
64
150
9
55
mmtt1998819/blender
release/scripts/startup/bl_ui/properties_grease_pencil_common.py
Python
GreasePencilLayerRelationsPanel
GreasePencilLayerRelationsPanel
822
840
822
823
d049fe88d13b58b29cf63164d28ec773ce25e32e
bigcode/the-stack
train
d89eb4cdf779d80872f0eb13
train
class
class GPENCIL_MT_snap_pie(Menu): bl_label = "Snap" def draw(self, _context): layout = self.layout pie = layout.menu_pie() pie.operator("view3d.snap_cursor_to_grid", text="Cursor to Grid", icon='CURSOR') pie.operator("gpencil.snap_to_grid", text="Selection to Grid", icon='RESTRI...
class GPENCIL_MT_snap_pie(Menu):
bl_label = "Snap" def draw(self, _context): layout = self.layout pie = layout.menu_pie() pie.operator("view3d.snap_cursor_to_grid", text="Cursor to Grid", icon='CURSOR') pie.operator("gpencil.snap_to_grid", text="Selection to Grid", icon='RESTRICT_SELECT_OFF') pie.opera...
() layout.operator("gpencil.snap_cursor_to_selected", text="Cursor to Selected") layout.operator("view3d.snap_cursor_to_center", text="Cursor to World Origin") layout.operator("view3d.snap_cursor_to_grid", text="Cursor to Grid") class GPENCIL_MT_snap_pie(Menu):
64
64
209
9
55
mmtt1998819/blender
release/scripts/startup/bl_ui/properties_grease_pencil_common.py
Python
GPENCIL_MT_snap_pie
GPENCIL_MT_snap_pie
250
272
250
250
af2f090950c6d24572abc7fbc077833bde05638f
bigcode/the-stack
train
ad281dccf5e79f9a0f8878f1
train
class
class GPENCIL_UL_masks(UIList): def draw_item(self, _context, layout, _data, item, icon, _active_data, _active_propname, _index): mask = item if self.layout_type in {'DEFAULT', 'COMPACT'}: row = layout.row(align=True) row.prop(mask, "name", text="", emboss=False, icon_value=i...
class GPENCIL_UL_masks(UIList):
def draw_item(self, _context, layout, _data, item, icon, _active_data, _active_propname, _index): mask = item if self.layout_type in {'DEFAULT', 'COMPACT'}: row = layout.row(align=True) row.prop(mask, "name", text="", emboss=False, icon_value=icon) row.prop(mask, ...
, "pass_index") col = layout.row(align=True) col.prop_search(gpl, "viewlayer_render", scene, "view_layers", text="View Layer") col = layout.row(align=True) col.prop(gpl, "lock_material") class GPENCIL_UL_masks(UIList):
64
64
145
8
56
mmtt1998819/blender
release/scripts/startup/bl_ui/properties_grease_pencil_common.py
Python
GPENCIL_UL_masks
GPENCIL_UL_masks
763
773
763
763
ed415240bddd4902d1bef2829c87aa363ef636db
bigcode/the-stack
train
dae9891491bb8dfd9cb2bff9
train
class
class GreasePencilSimplifyPanel: def draw_header(self, context): rd = context.scene.render self.layout.prop(rd, "simplify_gpencil", text="") def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False rd =...
class GreasePencilSimplifyPanel:
def draw_header(self, context): rd = context.scene.render self.layout.prop(rd, "simplify_gpencil", text="") def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False rd = context.scene.render lay...
"hide", text="", emboss=False) row.prop(gpl, "lock", text="", emboss=False) elif self.layout_type == 'GRID': layout.alignment = 'CENTER' layout.label( text="", icon_value=icon, ) class GreasePencilSimplifyPanel:
64
64
173
9
55
mmtt1998819/blender
release/scripts/startup/bl_ui/properties_grease_pencil_common.py
Python
GreasePencilSimplifyPanel
GreasePencilSimplifyPanel
706
727
706
707
62bedde45d007a09b9fecde3d8652d6ac5e98f03
bigcode/the-stack
train
9d2324d0cbcf2fd9fca3c377
train
class
class GreasePencilBrushFalloff: bl_label = "Falloff" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): ts = context.tool_settings settings = None if context.mode == 'PAINT_GPENCIL': settings = ts.gpencil_paint if context.mode == 'SCULPT_GPE...
class GreasePencilBrushFalloff:
bl_label = "Falloff" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): ts = context.tool_settings settings = None if context.mode == 'PAINT_GPENCIL': settings = ts.gpencil_paint if context.mode == 'SCULPT_GPENCIL': settings = ts...
"cursor_color_add", text="Cursor Color") if brush.gpencil_sculpt_tool in {'THICKNESS', 'STRENGTH', 'PINCH', 'TWIST'}: col.prop(brush, "cursor_color_subtract", text="Inverse Color") elif ob.mode == 'WEIGHT_GPENCIL': col = layout.column(align=True) col.active ...
151
151
506
9
142
mmtt1998819/blender
release/scripts/startup/bl_ui/properties_grease_pencil_common.py
Python
GreasePencilBrushFalloff
GreasePencilBrushFalloff
181
230
181
181
02e4cb45195901d9b5362a412d9a3b580289b52b
bigcode/the-stack
train
62704d059c00cc86b02f984e
train
class
class GPENCIL_MT_material_active(Menu): bl_label = "Change Active Material" @classmethod def poll(cls, context): ob = context.active_object tool_settings = context.scene.tool_settings mode = tool_settings.gpencil_paint.color_mode if mode != 'MATERIAL': return Fal...
class GPENCIL_MT_material_active(Menu):
bl_label = "Change Active Material" @classmethod def poll(cls, context): ob = context.active_object tool_settings = context.scene.tool_settings mode = tool_settings.gpencil_paint.color_mode if mode != 'MATERIAL': return False if ob is None or len(ob.mate...
icon = 'NONE' layout.operator("gpencil.layer_active", text=gpl.info, icon=icon).layer = i i -= 1 layout.separator() layout.operator("gpencil.layer_add", text="New Layer", icon='ADD') class GPENCIL_MT_material_active(Menu):
64
64
184
8
56
mmtt1998819/blender
release/scripts/startup/bl_ui/properties_grease_pencil_common.py
Python
GPENCIL_MT_material_active
GPENCIL_MT_material_active
325
351
325
325
c30141e2707b0441e4fda2eb536334b40c655c72
bigcode/the-stack
train
0a67b07156ab330a8101bb37
train
class
class GreasePencilSculptOptionsPanel: bl_label = "Sculpt Strokes" @classmethod def poll(cls, context): tool_settings = context.scene.tool_settings settings = tool_settings.gpencil_sculpt_paint brush = settings.brush tool = brush.gpencil_sculpt_tool return bool(tool ...
class GreasePencilSculptOptionsPanel:
bl_label = "Sculpt Strokes" @classmethod def poll(cls, context): tool_settings = context.scene.tool_settings settings = tool_settings.gpencil_sculpt_paint brush = settings.brush tool = brush.gpencil_sculpt_tool return bool(tool in {'SMOOTH', 'RANDOMIZE'}) def d...
mode = 'DRAW_POLY' col.separator() col.label(text="Stroke Placement:") row = col.row(align=True) row.prop_enum(tool_settings, "annotation_stroke_placement_view2d", 'VIEW') row.prop_enum(tool_settings, "annotation_stroke_placement_view2d", 'CURSOR', text="Cursor") class GreasePe...
83
83
277
10
73
mmtt1998819/blender
release/scripts/startup/bl_ui/properties_grease_pencil_common.py
Python
GreasePencilSculptOptionsPanel
GreasePencilSculptOptionsPanel
62
93
62
62
17487336086fe8d472072c863d65d44576d27d0f
bigcode/the-stack
train
a4a0f1c5e9267d9a58ff17f8
train
class
class GreasePencilFlipTintColors(Operator): bl_label = "Flip Colors" bl_idname = "gpencil.tint_flip" bl_description = "Switch Tint colors" def execute(self, context): try: ts = context.tool_settings settings = None if context.mode == 'PAINT_GPENCIL': ...
class GreasePencilFlipTintColors(Operator):
bl_label = "Flip Colors" bl_idname = "gpencil.tint_flip" bl_description = "Switch Tint colors" def execute(self, context): try: ts = context.tool_settings settings = None if context.mode == 'PAINT_GPENCIL': settings = ts.gpencil_paint ...
= col.row(align=True) row.prop(gpl, "channel_color") if not use_colors: col.label(text="Channel Colors are disabled in Animation preferences") row = layout.row(align=True) row.prop(gpl, "use_solo_mode", text="Show Only on Keyframed") class GreasePencilFlipTintColors(Operato...
77
77
257
11
66
mmtt1998819/blender
release/scripts/startup/bl_ui/properties_grease_pencil_common.py
Python
GreasePencilFlipTintColors
GreasePencilFlipTintColors
867
902
867
867
6b3e89c104d9ff44a6438bff3f5cb473a870d45e
bigcode/the-stack
train
7cc497024ccc823beb1e920f
train
class
class GPENCIL_MT_layer_mask_menu(Menu): bl_label = "Layer Specials" def draw(self, context): layout = self.layout ob = context.object gpd = ob.data gpl_active = gpd.layers.active done = False for gpl in gpd.layers: if gpl != gpl_active and gpl.info no...
class GPENCIL_MT_layer_mask_menu(Menu):
bl_label = "Layer Specials" def draw(self, context): layout = self.layout ob = context.object gpd = ob.data gpl_active = gpd.layers.active done = False for gpl in gpd.layers: if gpl != gpl_active and gpl.info not in gpl_active.mask_layers: ...
invert", text="", emboss=False) row.prop(mask, "hide", text="", emboss=False) elif self.layout_type == 'GRID': layout.alignment = 'CENTER' layout.prop(mask, "name", text="", emboss=False, icon_value=icon) class GPENCIL_MT_layer_mask_menu(Menu):
64
64
129
9
55
mmtt1998819/blender
release/scripts/startup/bl_ui/properties_grease_pencil_common.py
Python
GPENCIL_MT_layer_mask_menu
GPENCIL_MT_layer_mask_menu
776
791
776
776
77856c9e4cbf755ecfa44d88f1265a7a9a3ad97e
bigcode/the-stack
train
25a6eb518fb4c9761374d805
train
class
class GPENCIL_MT_move_to_layer(Menu): bl_label = "Move to Layer" def draw(self, context): layout = self.layout gpd = context.gpencil_data if gpd: gpl_active = context.active_gpencil_layer tot_layers = len(gpd.layers) i = tot_layers - 1 whi...
class GPENCIL_MT_move_to_layer(Menu):
bl_label = "Move to Layer" def draw(self, context): layout = self.layout gpd = context.gpencil_data if gpd: gpl_active = context.active_gpencil_layer tot_layers = len(gpd.layers) i = tot_layers - 1 while i >= 0: gpl = gpd.l...
="Selection to Cursor (Keep Offset)", icon='RESTRICT_SELECT_OFF' ).use_offset = True pie.separator() pie.operator("view3d.snap_cursor_to_center", text="Cursor to World Origin", icon='CURSOR') pie.separator() class GPENCIL_MT_move_to_layer(Menu):
64
64
177
9
55
mmtt1998819/blender
release/scripts/startup/bl_ui/properties_grease_pencil_common.py
Python
GPENCIL_MT_move_to_layer
GPENCIL_MT_move_to_layer
275
296
275
275
b47f3fee898fa7582ee9cdd0b1ea1d7dea4671e5
bigcode/the-stack
train
1d6bd859da67e245a59710c1
train
class
class GreasePencilVertexcolorPanel: def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False ts = context.scene.tool_settings is_vertex = context.mode == 'VERTEX_GPENCIL' gpencil_paint = ts.gpencil_vertex_pa...
class GreasePencilVertexcolorPanel:
def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False ts = context.scene.tool_settings is_vertex = context.mode == 'VERTEX_GPENCIL' gpencil_paint = ts.gpencil_vertex_paint if is_vertex else ts.gpencil_pain...
material else: ma = gp_settings.material if ma is not None and ma.grease_pencil is not None: gpcolor = ma.grease_pencil if gpcolor.stroke_style == 'SOLID': row = layout.row() row.prop(gpcolor, "color...
99
99
330
9
90
mmtt1998819/blender
release/scripts/startup/bl_ui/properties_grease_pencil_common.py
Python
GreasePencilVertexcolorPanel
GreasePencilVertexcolorPanel
628
663
628
629
fc4ba5107b67545e79f45ef722760619e7f8cbfb
bigcode/the-stack
train
8b27f2207f6fb3b4815febd7
train
class
class AnnotationOnionSkin: bl_label = "Onion Skin" bl_region_type = 'UI' bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): # Show this panel as long as someone that might own this exists # AND the owner isn't an object (e.g. GP Object) if context.annotatio...
class AnnotationOnionSkin:
bl_label = "Onion Skin" bl_region_type = 'UI' bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): # Show this panel as long as someone that might own this exists # AND the owner isn't an object (e.g. GP Object) if context.annotation_data_owner is None: ...
.active_frame: lock_status = iface_("Locked") if gpl.lock_frame else iface_("Unlocked") lock_label = iface_("Frame: %d (%s)") % (gpl.active_frame.frame_number, lock_status) else: lock_label = iface_("Lock Frame") row.prop(gpl, "lock_frame", text=lo...
102
102
340
6
96
mmtt1998819/blender
release/scripts/startup/bl_ui/properties_grease_pencil_common.py
Python
AnnotationOnionSkin
AnnotationOnionSkin
499
542
499
499
62d5b06798e890a6244e74f69418882bdfa76318
bigcode/the-stack
train
b90e19123c08fc39a3575c94
train
class
class AnnotationDrawingToolsPanel: # subclass must set # bl_space_type = 'IMAGE_EDITOR' bl_label = "Annotation" bl_category = "Annotation" bl_region_type = 'TOOLS' def draw(self, context): layout = self.layout tool_settings = context.tool_settings is_clip_editor = cont...
class AnnotationDrawingToolsPanel: # subclass must set # bl_space_type = 'IMAGE_EDITOR'
bl_label = "Annotation" bl_category = "Annotation" bl_region_type = 'TOOLS' def draw(self, context): layout = self.layout tool_settings = context.tool_settings is_clip_editor = context.space_data.type == 'CLIP_EDITOR' col = layout.column(align=True) col.label...
1, USA. # # ##### END GPL LICENSE BLOCK ##### # <pep8 compliant> import bpy from bpy.types import Menu, UIList, Operator from bpy.app.translations import pgettext_iface as iface_ # XXX: To be replaced with active tools # Currently only used by the clip editor class AnnotationDrawingToolsPanel: # subclass must s...
87
87
293
22
64
mmtt1998819/blender
release/scripts/startup/bl_ui/properties_grease_pencil_common.py
Python
AnnotationDrawingToolsPanel
AnnotationDrawingToolsPanel
28
59
28
30
5bc1b660aae0ae3fb609a8ffdf8fad1d301ed538
bigcode/the-stack
train
3bbb258d84534ed287ce2a7e
train
class
class GPENCIL_MT_gpencil_draw_delete(Menu): bl_label = "Delete" def draw(self, _context): layout = self.layout layout.operator_context = 'INVOKE_REGION_WIN' layout.operator("gpencil.delete", text="Delete Active Keyframe (Active Layer)").type = 'FRAME' layout.operator("gpencil....
class GPENCIL_MT_gpencil_draw_delete(Menu):
bl_label = "Delete" def draw(self, _context): layout = self.layout layout.operator_context = 'INVOKE_REGION_WIN' layout.operator("gpencil.delete", text="Delete Active Keyframe (Active Layer)").type = 'FRAME' layout.operator("gpencil.active_frames_delete_all", text="Delete Acti...
_material for slot in ob.material_slots: mat = slot.material if mat: icon = mat.id_data.preview.icon_id layout.operator("gpencil.material_set", text=mat.name, icon_value=icon).slot = mat.name class GPENCIL_MT_gpencil_draw_delete(Menu):
64
64
87
10
53
mmtt1998819/blender
release/scripts/startup/bl_ui/properties_grease_pencil_common.py
Python
GPENCIL_MT_gpencil_draw_delete
GPENCIL_MT_gpencil_draw_delete
354
363
354
354
294b4273339d476c0b1bb74df1570192524dae36
bigcode/the-stack
train
3422b016a872978ee1075692
train
class
class GPENCIL_MT_snap(Menu): bl_label = "Snap" def draw(self, _context): layout = self.layout layout.operator("gpencil.snap_to_grid", text="Selection to Grid") layout.operator("gpencil.snap_to_cursor", text="Selection to Cursor").use_offset = False layout.operator("gpencil.snap...
class GPENCIL_MT_snap(Menu):
bl_label = "Snap" def draw(self, _context): layout = self.layout layout.operator("gpencil.snap_to_grid", text="Selection to Grid") layout.operator("gpencil.snap_to_cursor", text="Selection to Cursor").use_offset = False layout.operator("gpencil.snap_to_cursor", text="Selection ...
="").shape = 'SHARP' row.operator("brush.curve_preset", icon='LINCURVE', text="").shape = 'LINE' row.operator("brush.curve_preset", icon='NOCURVE', text="").shape = 'MAX' class GPENCIL_MT_snap(Menu):
64
64
147
7
57
mmtt1998819/blender
release/scripts/startup/bl_ui/properties_grease_pencil_common.py
Python
GPENCIL_MT_snap
GPENCIL_MT_snap
233
247
233
233
1662e60aae5f947f13192c8d6fb9278058af0189
bigcode/the-stack
train
bf5fe54fa16a2a1733269005
train
class
class SkyControllerExample: def __init__(self): self.skyctrl = olympe.SkyController("192.168.53.1") def skyctrl_connect(self): self.skyctrl.connect() def update_drones(self): discover_results = self.skyctrl(discover_drones()).wait(_timeout=20) if not discover_results.succes...
class SkyControllerExample:
def __init__(self): self.skyctrl = olympe.SkyController("192.168.53.1") def skyctrl_connect(self): self.skyctrl.connect() def update_drones(self): discover_results = self.skyctrl(discover_drones()).wait(_timeout=20) if not discover_results.success(): print("Upda...
# -*- coding: UTF-8 -*- from collections import OrderedDict import os import olympe from olympe.messages.drone_manager import ( discover_drones, connection_state, connect, forget, ) olympe.log.update_config({"loggers": {"olympe": {"level": "INFO"}}}) DRONE_SSID = os.environ.get("DRONE_SSID", "Anafi_P...
128
205
685
5
123
ndessart/olympe
src/olympe/doc/examples/skyctrl_drone_pairing.py
Python
SkyControllerExample
SkyControllerExample
20
104
20
20
90cacb6273ab50fa491984436af4edd212cd8e5d
bigcode/the-stack
train
344bf5ec521062181bd5e59e
train
function
def main(): example = SkyControllerExample() print("@ Connection to SkyController") example.skyctrl_connect() example.update_drones() print("@ Connection to a drone") if example.connect_drone(DRONE_SERIAL, DRONE_SECURITY_KEY): example.update_drones() print("@ Forgetting a drone")...
def main():
example = SkyControllerExample() print("@ Connection to SkyController") example.skyctrl_connect() example.update_drones() print("@ Connection to a drone") if example.connect_drone(DRONE_SERIAL, DRONE_SECURITY_KEY): example.update_drones() print("@ Forgetting a drone") exa...
Forgetting {} ...".format(drone_serial)) self.skyctrl( forget(serial=drone_serial) ).wait(_timeout=10) else: print("{} is an unknown drone".format(drone_serial)) def disconnect_skyctrl(self): self.skyctrl.disconnect() def main():
64
64
101
3
61
ndessart/olympe
src/olympe/doc/examples/skyctrl_drone_pairing.py
Python
main
main
107
119
107
107
c68dcede787c9afe264bd5888f9ff265ab0e9d36
bigcode/the-stack
train
8e81cdd384769e7a1eda2836
train
function
def rbg_to_int(rbg, alpha): """ Convert rbg color to ints for openeye Parameters ---------- rbg : list rbg alpha : int Returns ------- list of ints """ rbg[-1] = int(rbg[-1]*alpha) colors = [int(round(i*255)) for i in rbg[:-1]] colors.append(int(rbg[-1])) ...
def rbg_to_int(rbg, alpha):
""" Convert rbg color to ints for openeye Parameters ---------- rbg : list rbg alpha : int Returns ------- list of ints """ rbg[-1] = int(rbg[-1]*alpha) colors = [int(round(i*255)) for i in rbg[:-1]] colors.append(int(rbg[-1])) return colors
oedepict.OERenderMolecule(cell, disp) # oedepict.OEDrawCurvedBorder(cell, oedepict.OELightGreyPen, 10.0) return (oedepict.OEWriteReport(fname, report)) def rbg_to_int(rbg, alpha):
64
64
101
10
54
choderalab/fragmenter_examples
combinatorial_fragmentation/benchmark_fragmentation_schemes/torsion_scan_wbos.py
Python
rbg_to_int
rbg_to_int
100
117
100
100
4a42e93aa73af0759795bf013a6c45a0585796ca
bigcode/the-stack
train
7b169861077234243f748b58
train
function
def get_bond(mol, bond_tuple): a1 = mol.GetAtom(oechem.OEHasMapIdx(bond_tuple[0])) a2 = mol.GetAtom(oechem.OEHasMapIdx(bond_tuple[1])) if not a1 or not a2: print('no atoms') return False bond = mol.GetBond(a1, a2) if not bond: print('no bond') return False return ...
def get_bond(mol, bond_tuple):
a1 = mol.GetAtom(oechem.OEHasMapIdx(bond_tuple[0])) a2 = mol.GetAtom(oechem.OEHasMapIdx(bond_tuple[1])) if not a1 or not a2: print('no atoms') return False bond = mol.GetBond(a1, a2) if not bond: print('no bond') return False return bond
json from openeye import oechem, oequacpac, oedepict, oegraphsim import matplotlib.pyplot as plt import glob import seaborn as sbn import cmiles import itertools import numpy as np import openeye def get_bond(mol, bond_tuple):
64
64
103
10
53
choderalab/fragmenter_examples
combinatorial_fragmentation/benchmark_fragmentation_schemes/torsion_scan_wbos.py
Python
get_bond
get_bond
12
22
12
12
f3bb3960b6167b55d1f3b77fef24f7c1ed4ff3ad
bigcode/the-stack
train
e3ed7c9701bf9e460fb5b450
train
function
def visualize_mols(smiles, fname, rows, cols, bond_idx, wbos, colors, align_to=0): """ Visualize molecules with highlighted bond and labeled with WBO Parameters ---------- smiles : list of SMILES to visualize. bond atoms should have map indices fname : str filename rows : int...
def visualize_mols(smiles, fname, rows, cols, bond_idx, wbos, colors, align_to=0):
""" Visualize molecules with highlighted bond and labeled with WBO Parameters ---------- smiles : list of SMILES to visualize. bond atoms should have map indices fname : str filename rows : int cols : int bond_idx : tuple of atom maps of bond to highlight. wbos : ...
import fragmenter import json from openeye import oechem, oequacpac, oedepict, oegraphsim import matplotlib.pyplot as plt import glob import seaborn as sbn import cmiles import itertools import numpy as np import openeye def get_bond(mol, bond_tuple): a1 = mol.GetAtom(oechem.OEHasMapIdx(bond_tuple[0])) a2 = mo...
188
231
770
26
161
choderalab/fragmenter_examples
combinatorial_fragmentation/benchmark_fragmentation_schemes/torsion_scan_wbos.py
Python
visualize_mols
visualize_mols
24
98
24
24
82a5f1fa3b9f044c0b278467dfe519ecfc086a08
bigcode/the-stack
train
1becdc8bc0f618a815d24f64
train
function
def mail_message(subject,template,to,**kwargs): sender_email = 'ashrafzani585@gmail.com' email = Message(subject, sender=sender_email, recipients=[to]) email.body= render_template(template + ".txt",**kwargs) email.html = render_template(template + ".html",**kwargs) mail.send(email)
def mail_message(subject,template,to,**kwargs):
sender_email = 'ashrafzani585@gmail.com' email = Message(subject, sender=sender_email, recipients=[to]) email.body= render_template(template + ".txt",**kwargs) email.html = render_template(template + ".html",**kwargs) mail.send(email)
from flask_mail import Message from flask import render_template from . import mail def mail_message(subject,template,to,**kwargs):
28
64
72
11
16
Maalim18/Blog
app/email.py
Python
mail_message
mail_message
5
11
5
5
fbdd6f072409640a237f354c81be45ec3627c836
bigcode/the-stack
train
aaac7a0631e941cfb25b1173
train
class
class AdaBoost: """ Adaptive Boosting(自适应提升算法) """ def __init__(self, n_estimators: int, lr=0.01, eps=1e-5): """ :param n_estimators: 弱分类器个数 :param eps: 误差阈值 """ self.n_estimators, self.lr, self.eps = n_estimators, lr, eps self.estimators = [] sel...
class AdaBoost:
""" Adaptive Boosting(自适应提升算法) """ def __init__(self, n_estimators: int, lr=0.01, eps=1e-5): """ :param n_estimators: 弱分类器个数 :param eps: 误差阈值 """ self.n_estimators, self.lr, self.eps = n_estimators, lr, eps self.estimators = [] self.alpha = np.emp...
# -*- coding: utf-8 -*- # @Date : 2020/5/27 # @Author: Luokun # @Email : olooook@outlook.com import numpy as np class AdaBoost:
50
256
876
4
45
likeand/ml
models/adaboost.py
Python
AdaBoost
AdaBoost
9
74
9
9
262ec88e70bc370d649b8dbccca66bd4db6cb04e
bigcode/the-stack
train
b14fa6fb055a8908ed70eef3
train
class
class CollaborativeVAE(): def __init__(self, cvae_datagen, cvae_loss, learning_rate, pretrained_vae): self.data_gen = cvae_datagen self.params = self.data_gen.params self.vae = pretrained_vae.get_cvae_model(...
class CollaborativeVAE():
def __init__(self, cvae_datagen, cvae_loss, learning_rate, pretrained_vae): self.data_gen = cvae_datagen self.params = self.data_gen.params self.vae = pretrained_vae.get_cvae_model(self.params.lambda_V, self....
''' Copyright (c) 2020. IIP Lab, Wuhan University Author: Yaochen Zhu ''' import os import sys sys.path.append("libs") import numpy as np import scipy as sp import scipy.io as sio from tensorflow.keras import optimizers from layers import mse class CollaborativeVAE():
70
256
1,276
5
64
yaochenzhu/CVAE
libs/cvae.py
Python
CollaborativeVAE
CollaborativeVAE
17
135
17
17
b2dbd6a8506561fecc9ca2b57a8641df3b29d907
bigcode/the-stack
train
48e6ca0cfe52fbccd4e03961
train
class
class BaseInfo(object): # no doc def equal(self, *args, **kwargs): # real signature unknown pass def get_attribute(self, *args, **kwargs): # real signature unknown pass def get_container(self, *args, **kwargs): # real signature unknown pass def get_name(self, *args, **kwar...
class BaseInfo(object): # no doc
def equal(self, *args, **kwargs): # real signature unknown pass def get_attribute(self, *args, **kwargs): # real signature unknown pass def get_container(self, *args, **kwargs): # real signature unknown pass def get_name(self, *args, **kwargs): # real signature unknown ...
# encoding: utf-8 # module gi._gi # from /usr/lib/python3/dist-packages/gi/_gi.cpython-35m-x86_64-linux-gnu.so # by generator 1.145 # no doc # imports import _gobject as _gobject # <module '_gobject'> import _glib as _glib # <module '_glib'> import gi as __gi import gobject as __gobject from .object import object cl...
113
132
442
10
102
pyy1988/pyy_test1
pyy1/.pycharm_helpers/python_stubs/-1550516950/gi/_gi/BaseInfo.py
Python
BaseInfo
BaseInfo
16
78
16
17
ddb6ec202c9fcbc74e925e7a25b34d1bc4a873e1
bigcode/the-stack
train
0666ca24092401751fd2163a
train
function
def lru_cache(maxsize=100, typed=False): """Least-recently-used cache decorator. If *maxsize* is set to None, the LRU features are disabled and the cache can grow without bound. If *typed* is True, arguments of different types will be cached separately. For example, f(3.0) and f(3) will be treated...
def lru_cache(maxsize=100, typed=False):
"""Least-recently-used cache decorator. If *maxsize* is set to None, the LRU features are disabled and the cache can grow without bound. If *typed* is True, arguments of different types will be cached separately. For example, f(3.0) and f(3) will be treated as distinct calls with distinct resu...
es", "maxsize", "currsize"]) class _HashedSeq(list): __slots__ = 'hashvalue' def __init__(self, tup, hash=hash): self[:] = tup self.hashvalue = hash(tup) def __hash__(self): return self.hashvalue def _make_key(args, kwds, typed, kwd_mar...
256
256
1,196
12
244
bpachev/tapis-cli
tapis_cli/hashcache/lru_py27.py
Python
lru_cache
lru_cache
48
179
48
48
f01150226cd6ed34d1dbdd9f9518e3fc362fe104
bigcode/the-stack
train
820d835ec305bf8704512843
train
class
class _HashedSeq(list): __slots__ = 'hashvalue' def __init__(self, tup, hash=hash): self[:] = tup self.hashvalue = hash(tup) def __hash__(self): return self.hashvalue
class _HashedSeq(list):
__slots__ = 'hashvalue' def __init__(self, tup, hash=hash): self[:] = tup self.hashvalue = hash(tup) def __hash__(self): return self.hashvalue
y30-backport-of-python-33s-lru-cache/ from collections import namedtuple from functools import update_wrapper from threading import RLock _CacheInfo = namedtuple("CacheInfo", ["hits", "misses", "maxsize", "currsize"]) class _HashedSeq(list):
63
64
57
7
56
bpachev/tapis-cli
tapis_cli/hashcache/lru_py27.py
Python
_HashedSeq
_HashedSeq
12
20
12
12
98aa1ecb680ce881fce8564772c9ab0e0b03ce71
bigcode/the-stack
train
881b1c10dfbc6392adb81a3a
train
function
def _make_key(args, kwds, typed, kwd_mark=(object(), ), fasttypes={int, str, frozenset, type(None)}, sorted=sorted, tuple=tuple, type=type, len=len): 'Make a cache key from optionally typed positional and...
def _make_key(args, kwds, typed, kwd_mark=(object(), ), fasttypes={int, str, frozenset, type(None)}, sorted=sorted, tuple=tuple, type=type, len=len):
'Make a cache key from optionally typed positional and keyword arguments' key = args if kwds: sorted_items = sorted(kwds.items()) key += kwd_mark for item in sorted_items: key += item if typed: key += tuple(type(v) for v in args) if kwds: k...
__(self): return self.hashvalue def _make_key(args, kwds, typed, kwd_mark=(object(), ), fasttypes={int, str, frozenset, type(None)}, sorted=sorted, tuple=tuple, type=type, len=len):
64
64
176
55
8
bpachev/tapis-cli
tapis_cli/hashcache/lru_py27.py
Python
_make_key
_make_key
23
45
23
31
4e7b30af3d35f3034829c82ce68090447f337c5e
bigcode/the-stack
train
c80dd86f6e2eafbc2dfdcbe3
train
class
@mock.patch.object(MockScene, "download") class TestSceneCollectionDownload(unittest.TestCase): def setUp(self): properties = [ { "id": "foo:bar" + str(i), "bands": {"nir": {"dtype": "UInt16"}, "yellow": {"dtype": "UInt16"}}, "product": "foo", ...
@mock.patch.object(MockScene, "download") class TestSceneCollectionDownload(unittest.TestCase):
def setUp(self): properties = [ { "id": "foo:bar" + str(i), "bands": {"nir": {"dtype": "UInt16"}, "yellow": {"dtype": "UInt16"}}, "product": "foo", } for i in range(3) ] self.scenes = SceneCollection([MockSc...
3), ] ) scales, data_type = sc.scaling_parameters("red alpha", "display") assert scales == [(0, 4000, 0, 255), None] assert data_type == "Byte" def test_scaling_parameters_raw_range(self): sc = SceneCollection( [ MockScene({}, self.MOC...
221
221
737
19
202
carderne/descarteslabs-python
descarteslabs/scenes/tests/test_scenecollection.py
Python
TestSceneCollectionDownload
TestSceneCollectionDownload
450
537
450
451
a57e2a0acdbaebd6bcde16ea7049752f0459d252
bigcode/the-stack
train
ba4e764f8f0a8e19fcd4c525
train
class
class TestSceneCollection(unittest.TestCase): MOCK_RGBA_PROPERTIES = { "product": "mock_product", "id": "mock_id", "bands": { "red": { "type": "spectral", "dtype": "UInt16", "data_range": [0, 10000], "default_range"...
class TestSceneCollection(unittest.TestCase):
MOCK_RGBA_PROPERTIES = { "product": "mock_product", "id": "mock_id", "bands": { "red": { "type": "spectral", "dtype": "UInt16", "data_range": [0, 10000], "default_range": [0, 4000], "physical_range": ...
import pytest import unittest import mock import os.path import shapely.geometry import numpy as np from descarteslabs.client.addons import ThirdParty from descarteslabs.scenes import Scene, SceneCollection, geocontext from .test_scene import MockScene from .mock_data import _metadata_get, _metadata_get_bands, _raste...
87
256
4,348
8
78
carderne/descarteslabs-python
descarteslabs/scenes/tests/test_scenecollection.py
Python
TestSceneCollection
TestSceneCollection
15
447
15
16
ce89ba24d949fd9f9512f99ce5cba44b7f7beadc
bigcode/the-stack
train
93559c6a77e52aa25800c6f0
train
class
class DashboardTest(TestCase): def setUp(self): self.member = Members.objects.create( group_id=1, name="ali", family="alavi" ) self.transaction = Transaction.objects.create( Fund='200000', loan_p='3000000', payer_name='ali', members=self.member...
class DashboardTest(TestCase):
def setUp(self): self.member = Members.objects.create( group_id=1, name="ali", family="alavi" ) self.transaction = Transaction.objects.create( Fund='200000', loan_p='3000000', payer_name='ali', members=self.member ) self.setting...
import time from django.test import TestCase from django.urls import reverse from .forms import AccountCreateForm from .functions import get_unique_transaction_month, get_sum_cash_desk_month, get_object_members, \ get_list_members_month, get_choice_member_loan from .models import Members, Transaction, Setting, Peri...
88
256
1,663
6
81
majid1400/loan_fund
dashboard/tests.py
Python
DashboardTest
DashboardTest
11
173
11
11
c821d82db7ddd4f1f8b41e02bd30980fb62f0ea7
bigcode/the-stack
train
9aff41d114e4d5450a20d6f2
train
class
class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Car', fields=[ ('id', models.AutoField(auto_created=True, primary_ke...
class Migration(migrations.Migration):
initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Car', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='I...
# Generated by Django 2.0.7 on 2018-08-06 11:20 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
51
137
459
7
43
helmetwearer/uber-clone
uber/migrations/0001_initial.py
Python
Migration
Migration
8
64
8
9
5331e6c06b66e47c5b2ef3bda1445342b29de552
bigcode/the-stack
train
508c54a6800460206e2a68d0
train
class
class DatasetReader(object): """read dataset file""" def __init__(self, corpus_path, path_index_path, terminal_index_path): self.path_vocab = VocabReader(path_index_path).read() logger.info('path vocab size: {0}'.format(self.path_vocab.duplicate_len())) self.terminal_vocab = VocabReade...
class DatasetReader(object):
"""read dataset file""" def __init__(self, corpus_path, path_index_path, terminal_index_path): self.path_vocab = VocabReader(path_index_path).read() logger.info('path vocab size: {0}'.format(self.path_vocab.duplicate_len())) self.terminal_vocab = VocabReader(terminal_index_path).read()...
ANT_SYMBOL_CHARS.sub("", method_name) @staticmethod def get_method_subtokens(method_name): ans = [ x.lower() for x in Vocab.METHOD_SUBTOKEN_SEPARATOR.split(method_name) if x is not None and x != '' ] return ans """ from dataset_reader.py """ class ...
199
199
666
5
193
Ji-Xin/bovina
datasets/apache_paired_paths.py
Python
DatasetReader
DatasetReader
141
214
141
141
5f3db6ebcb21281919b85bf3fe17f12624408577
bigcode/the-stack
train
98e9faa6f836e873dedc2b78
train
class
class Vocab(object): """vocabulary (terminal symbols or path names or label(method names))""" REDUNDANT_SYMBOL_CHARS = re.compile(r"[_0-9]+") METHOD_SUBTOKEN_SEPARATOR = re.compile( r"([a-z]+)([A-Z][a-z]+)|([A-Z][a-z]+)") def __init__(self): self.stoi = {} self.itos = {} ...
class Vocab(object):
"""vocabulary (terminal symbols or path names or label(method names))""" REDUNDANT_SYMBOL_CHARS = re.compile(r"[_0-9]+") METHOD_SUBTOKEN_SEPARATOR = re.compile( r"([a-z]+)([A-Z][a-z]+)|([A-Z][a-z]+)") def __init__(self): self.stoi = {} self.itos = {} self.itosubtokens =...
], 'ends_curr': self.ends_curr[index], 'label': self.labels[index] } if self.transform: item = self.transform(item) return item class CodeData(object): """data corresponding to one method""" def __init__(self): self.id = None self.la...
110
111
370
5
105
Ji-Xin/bovina
datasets/apache_paired_paths.py
Python
Vocab
Vocab
64
115
64
64
8d81da7bc82bb1b9fa652e9b506e794d061ae894
bigcode/the-stack
train
5a0fc6568e3a072e844cb25a
train
class
class CodeData(object): """data corresponding to one method""" def __init__(self): self.id = None self.label = None self.normalized_label = None self.path_contexts_prev = [] self.path_contexts_curr = [] self.source = None self.aliases = {}
class CodeData(object):
"""data corresponding to one method""" def __init__(self): self.id = None self.label = None self.normalized_label = None self.path_contexts_prev = [] self.path_contexts_curr = [] self.source = None self.aliases = {}
_prev[index], 'starts_curr': self.starts_curr[index], 'paths_curr': self.paths_curr[index], 'ends_curr': self.ends_curr[index], 'label': self.labels[index] } if self.transform: item = self.transform(item) return item class CodeData(obje...
64
64
68
5
58
Ji-Xin/bovina
datasets/apache_paired_paths.py
Python
CodeData
CodeData
51
61
51
51
ebac0ec6d74c47ed837f89fb2657ab882285aaf7
bigcode/the-stack
train
43ad37556f51dc50b26ac924
train
class
class VocabReader(object): """read vocabulary file""" def __init__(self, filename): self.filename = filename def read(self): vocab = Vocab() with open(self.filename, mode="r", encoding="utf-8") as f: lines = f.readlines() for line in lines: d...
class VocabReader(object):
"""read vocabulary file""" def __init__(self, filename): self.filename = filename def read(self): vocab = Vocab() with open(self.filename, mode="r", encoding="utf-8") as f: lines = f.readlines() for line in lines: data = line.strip(' \r\n\t')...
@staticmethod def get_method_subtokens(method_name): ans = [ x.lower() for x in Vocab.METHOD_SUBTOKEN_SEPARATOR.split(method_name) if x is not None and x != '' ] return ans """ from dataset_reader.py """ class VocabReader(object):
63
64
126
6
57
Ji-Xin/bovina
datasets/apache_paired_paths.py
Python
VocabReader
VocabReader
120
138
120
120
37e5eb07c3226734bd06cc600dcb729d8c448d5d
bigcode/the-stack
train
e3efa8b2628fb2a439d714d2
train
class
class DatasetBuilder(object): """transform dataset for training and test""" def __init__(self, reader, option, split_ratio=0.2): self.reader = reader self.option = option # random.shuffle(reader.items) train_items = reader.items["train"] dev_items = reader.items["dev"] ...
class DatasetBuilder(object):
"""transform dataset for training and test""" def __init__(self, reader, option, split_ratio=0.2): self.reader = reader self.option = option # random.shuffle(reader.items) train_items = reader.items["train"] dev_items = reader.items["dev"] test_items = reader.it...
.append( normalized_lower_label, subtokens=subtokens) elif line.startswith('class:'): code_data.source = line[6:] elif line.startswith('prev_paths:'): parse_mode = 10 elif line.startsw...
255
256
1,241
5
250
Ji-Xin/bovina
datasets/apache_paired_paths.py
Python
DatasetBuilder
DatasetBuilder
219
347
219
219
70ae1e4c256db381d1aecfac78aafdea9d4533ad
bigcode/the-stack
train
9a49912cd5ce25ab30fbb832
train
class
class CodeDataset(Dataset): """dataset for training/test""" def __init__(self, ids, starts_prev, starts_curr, paths_prev, paths_curr, ends_prev, ends_curr, labels, transform=None): self.ids = ids self.starts_prev = starts_prev self.starts_curr = starts_curr ...
class CodeDataset(Dataset):
"""dataset for training/test""" def __init__(self, ids, starts_prev, starts_curr, paths_prev, paths_curr, ends_prev, ends_curr, labels, transform=None): self.ids = ids self.starts_prev = starts_prev self.starts_curr = starts_curr self.paths_prev = paths_p...
# Adapted from Isao Sonobe's code: https://github.com/sonoisa/code2vec import re import random import logging import torch from torch.utils.data import Dataset logger = logging.getLogger() """ from dataset.py """ class CodeDataset(Dataset):
58
70
234
6
52
Ji-Xin/bovina
datasets/apache_paired_paths.py
Python
CodeDataset
CodeDataset
16
48
16
16
182bd3125e44ee23dd20f6051367cacfdeeb81e3
bigcode/the-stack
train
fade24c3cdc4565a2ed78346
train
function
def boundary_sampling(path): try: if os.path.exists(path +'/boundary_{}_samples.npz'.format(args.sigma)): return off_path = path + '/isosurf_scaled.off' out_file = path +'/boundary_{}_samples.npz'.format(args.sigma) mesh = trimesh.load(off_path) points = mesh.s...
def boundary_sampling(path):
try: if os.path.exists(path +'/boundary_{}_samples.npz'.format(args.sigma)): return off_path = path + '/isosurf_scaled.off' out_file = path +'/boundary_{}_samples.npz'.format(args.sigma) mesh = trimesh.load(off_path) points = mesh.sample(sample_num) bo...
import trimesh import numpy as np import implicit_waterproofing as iw import glob import multiprocessing as mp from multiprocessing import Pool import argparse import os import traceback ROOT = 'shapenet/data' def boundary_sampling(path):
52
64
209
5
47
vedanthpadigelwar/if-net
data_processing/boundary_sampling.py
Python
boundary_sampling
boundary_sampling
14
37
14
14
c95ca35c23205936be5b4e7922a3afd5aa0d738b
bigcode/the-stack
train
7c0260675ac60927f73a9d50
train
function
def call(service: schema_pb2_grpc.ImmuServiceStub, rs: RootService, tx: int): request = schema_pb2.TxRequest( tx=tx ) try: msg = service.TxById(request) except Exception as e: if hasattr(e, 'details') and e.details() == 'tx not found': return None raise e ...
def call(service: schema_pb2_grpc.ImmuServiceStub, rs: RootService, tx: int):
request = schema_pb2.TxRequest( tx=tx ) try: msg = service.TxById(request) except Exception as e: if hasattr(e, 'details') and e.details() == 'tx not found': return None raise e ret = [] for t in msg.entries: ret.append(t.key[1:]) return re...
from immudb.grpc import schema_pb2 from immudb.grpc import schema_pb2_grpc from immudb.rootService import RootService from immudb import datatypes def call(service: schema_pb2_grpc.ImmuServiceStub, rs: RootService, tx: int):
64
64
106
23
40
cn-demo/immudb-py
immudb/handler/txbyid.py
Python
call
call
21
34
21
21
6f51241e95ebadecda14ce55c0950f5e56c635ff
bigcode/the-stack
train
f76087854a8dae4361f40abb
train
function
@click.command('show_invocation') @click.argument("workflow_id", type=str) @click.argument("invocation_id", type=str) @pass_context @custom_exception @dict_output def cli(ctx, workflow_id, invocation_id): """Get a workflow invocation object representing the scheduling of a workflow. This object may be sparse at fir...
@click.command('show_invocation') @click.argument("workflow_id", type=str) @click.argument("invocation_id", type=str) @pass_context @custom_exception @dict_output def cli(ctx, workflow_id, invocation_id):
"""Get a workflow invocation object representing the scheduling of a workflow. This object may be sparse at first (missing inputs and invocation steps) and will become more populated as the workflow is actually scheduled. Output: The workflow invocation. For example:: {u'history_id': u'...
import click from parsec.cli import pass_context, json_loads from parsec.decorators import custom_exception, dict_output @click.command('show_invocation') @click.argument("workflow_id", type=str) @click.argument("invocation_id", type=str) @pass_context @custom_exception @dict_output def cli(ctx, workflow_id, invocation...
74
183
612
48
25
innovate-invent/parsec
parsec/commands/workflows/show_invocation.py
Python
cli
cli
6
51
6
12
2c50d2ccd66849ba95636f4c518b1848a8306d43
bigcode/the-stack
train
a61a0b50b48b398a648516be
train
class
class BaseStat(ABC): """Abstract class for collecting stats.""" def __init__(self, api_key: str) -> None: """Initializes the API for the stats abstraction""" self.api_key = api_key @abstractmethod def send_event(self, event_type: str, pr: PR) -> None: """Abstract method for tra...
class BaseStat(ABC):
"""Abstract class for collecting stats.""" def __init__(self, api_key: str) -> None: """Initializes the API for the stats abstraction""" self.api_key = api_key @abstractmethod def send_event(self, event_type: str, pr: PR) -> None: """Abstract method for tracking events.""" ...
, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Library for defining common stat collecting features""" from abc import ABC, abstractmethod from pr import PR class BaseStat(AB...
64
64
122
6
57
errbotio/err-mergequeue
stats.py
Python
BaseStat
BaseStat
20
35
20
20
2b0a94b51b5e11e2e761dd8d8b5b9037e0a5015a
bigcode/the-stack
train
95d84464609033978b2a431a
train
class
class NoStats(BaseStat): """Generic class to be used if no stat class is passed""" def __init__(self): super().__init__('') def send_event(self, event_type: str, pr: PR) -> None: """NoStats does nothing with events.""" pass def send_metric(self, metric_name: str, metric_value:...
class NoStats(BaseStat):
"""Generic class to be used if no stat class is passed""" def __init__(self): super().__init__('') def send_event(self, event_type: str, pr: PR) -> None: """NoStats does nothing with events.""" pass def send_metric(self, metric_name: str, metric_value: float, pr: PR) -> None: ...
pr: PR) -> None: """Abstract method for tracking events.""" pass @abstractmethod def send_metric(self, metric_name: str, metric_value: float, pr: PR) -> None: """Abstract method for tracking individual metrics.""" pass class NoStats(BaseStat):
64
64
98
6
57
errbotio/err-mergequeue
stats.py
Python
NoStats
NoStats
38
50
38
38
3cfabbb4b4e6b93f49f922133688e49e14ec6e60
bigcode/the-stack
train
1ee6469cefd0a20cb1fedd9b
train
function
def test_groupby_crash_on_nunique(axis): # Fix following 30253 df = DataFrame({("A", "B"): [1, 2], ("A", "C"): [1, 3], ("D", "B"): [0, 0]}) axis_number = df._get_axis_number(axis) if not axis_number: df = df.T result = df.groupby(axis=axis_number, level=0).nunique() expected = DataFra...
def test_groupby_crash_on_nunique(axis): # Fix following 30253
df = DataFrame({("A", "B"): [1, 2], ("A", "C"): [1, 3], ("D", "B"): [0, 0]}) axis_number = df._get_axis_number(axis) if not axis_number: df = df.T result = df.groupby(axis=axis_number, level=0).nunique() expected = DataFrame({"A": [1, 2], "D": [1, 1]}) if not axis_number: expe...
args.extend([1, "D"]) result = getattr(grp_by, groupby_func)(*args) assert result.shape == (1, 2) tm.assert_index_equal(result.columns, idx) def test_groupby_crash_on_nunique(axis): # Fix following 30253
64
64
147
19
45
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_groupby_crash_on_nunique
test_groupby_crash_on_nunique
2,018
2,032
2,018
2,019
a2da7ccb803093dbb27b900cd7061d864d271aef
bigcode/the-stack
train
f5a7f889e7f01cdb31b91685
train
function
def test_groupby_multiindex_series_keys_len_equal_group_axis(): # GH 25704 index_array = [["x", "x"], ["a", "b"], ["k", "k"]] index_names = ["first", "second", "third"] ri = MultiIndex.from_arrays(index_array, names=index_names) s = Series(data=[1, 2], index=ri) result = s.groupby(["first", "thi...
def test_groupby_multiindex_series_keys_len_equal_group_axis(): # GH 25704
index_array = [["x", "x"], ["a", "b"], ["k", "k"]] index_names = ["first", "second", "third"] ri = MultiIndex.from_arrays(index_array, names=index_names) s = Series(data=[1, 2], index=ri) result = s.groupby(["first", "third"]).sum() index_array = [["x"], ["k"]] index_names = ["first", "thir...
df = DataFrame(values, columns=["apple", "b"]) msg = "Grouper and axis must be same length" with pytest.raises(ValueError, match=msg): df.groupby([[]]) def test_groupby_multiindex_series_keys_len_equal_group_axis(): # GH 25704
64
64
153
20
44
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_groupby_multiindex_series_keys_len_equal_group_axis
test_groupby_multiindex_series_keys_len_equal_group_axis
1,843
1,856
1,843
1,844
894e8335626036eca5f79e784a1a26deeca467d9
bigcode/the-stack
train
151cbb05a0fec4c5de03cad6
train
function
def test_indices_concatenation_order(): # GH 2808 def f1(x): y = x[(x.b % 2) == 1] ** 2 if y.empty: multiindex = MultiIndex(levels=[[]] * 2, codes=[[]] * 2, names=["b", "c"]) res = DataFrame(columns=["a"], index=multiindex) return res else: ...
def test_indices_concatenation_order(): # GH 2808
def f1(x): y = x[(x.b % 2) == 1] ** 2 if y.empty: multiindex = MultiIndex(levels=[[]] * 2, codes=[[]] * 2, names=["b", "c"]) res = DataFrame(columns=["a"], index=multiindex) return res else: y = y.set_index(["b", "c"]) return y ...
agged = grouped.agg(len) expected = Series([4, 2], index=["bar", "foo"]) tm.assert_series_equal(agged, expected, check_dtype=False) # assert issubclass(agged.dtype.type, np.integer) # explicitly return a float from my function def f(x): return float(len(x)) agged = grouped.agg(f)...
151
151
505
16
135
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_indices_concatenation_order
test_indices_concatenation_order
311
364
311
314
09c1c9f49c47e38d824c6edd7ef3116eb65ea642
bigcode/the-stack
train
a318c83bc95dc9bda2fb415c
train
function
def test_groupby_with_hier_columns(): tuples = list( zip( *[ ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"], ["one", "two", "one", "two", "one", "two", "one", "two"], ] ) ) index = MultiIndex.from_tuples(tuples) columns = ...
def test_groupby_with_hier_columns():
tuples = list( zip( *[ ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"], ["one", "two", "one", "two", "one", "two", "one", "two"], ] ) ) index = MultiIndex.from_tuples(tuples) columns = MultiIndex.from_tuples( [("A",...
, 1.0, 4.0, 5.0, 5.0, 7.0], index=Index(["a", "b", "d", "f", "g", "h"]) ) grouped = s1.groupby(s2) agged = grouped.mean() exp = s1.groupby(s2.reindex(s1.index).get).mean() tm.assert_series_equal(agged, exp) def test_groupby_with_hier_columns():
103
103
346
9
94
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_groupby_with_hier_columns
test_groupby_with_hier_columns
1,002
1,037
1,002
1,002
a3748e7cdd3332aa42380ccad74494d21e04426c
bigcode/the-stack
train
d90fbfb0150add78669b88d2
train
function
def test_tuple_correct_keyerror(): # https://github.com/pandas-dev/pandas/issues/18798 df = DataFrame(1, index=range(3), columns=MultiIndex.from_product([[1, 2], [3, 4]])) with pytest.raises(KeyError, match=r"^\(7, 8\)$"): df.groupby((7, 8)).mean()
def test_tuple_correct_keyerror(): # https://github.com/pandas-dev/pandas/issues/18798
df = DataFrame(1, index=range(3), columns=MultiIndex.from_product([[1, 2], [3, 4]])) with pytest.raises(KeyError, match=r"^\(7, 8\)$"): df.groupby((7, 8)).mean()
"b"))["c"].sum() expected = Series([4], name="c", index=Index([1], name=("a", "b"))) tm.assert_series_equal(result, expected) def test_tuple_correct_keyerror(): # https://github.com/pandas-dev/pandas/issues/18798
64
64
86
23
41
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_tuple_correct_keyerror
test_tuple_correct_keyerror
1,784
1,788
1,784
1,785
bbf3c05266785aece1e33c2d74b4efe276f7b991
bigcode/the-stack
train
a85f8f257a87345b6d837512
train
function
@pytest.mark.xfail(not IS64, reason="GH#38778: fail on 32-bit system") def test_groupby_numerical_stability_cumsum(): # GH#38934 data = [1e16, 1e16, 97, 98, -5e15, -5e15, -5e15, -5e15] df = DataFrame({"group": [1, 2] * 4, "a": data, "b": data}) result = df.groupby("group").cumsum() exp_data = ( ...
@pytest.mark.xfail(not IS64, reason="GH#38778: fail on 32-bit system") def test_groupby_numerical_stability_cumsum(): # GH#38934
data = [1e16, 1e16, 97, 98, -5e15, -5e15, -5e15, -5e15] df = DataFrame({"group": [1, 2] * 4, "a": data, "b": data}) result = df.groupby("group").cumsum() exp_data = ( [1e16] * 2 + [1e16 + 96, 1e16 + 98] + [5e15 + 97, 5e15 + 98] + [97.0, 98.0] ) expected = DataFrame({"a": exp_data, "b": e...
}, index=Index([1, 2], name="group")) tm.assert_frame_equal(result, expected) @pytest.mark.xfail(not IS64, reason="GH#38778: fail on 32-bit system") def test_groupby_numerical_stability_cumsum(): # GH#38934
64
64
210
41
23
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_groupby_numerical_stability_cumsum
test_groupby_numerical_stability_cumsum
2,170
2,180
2,170
2,172
b9ce53ae663928b47a9b099032ebc748db56ca42
bigcode/the-stack
train
e2e99ba01df85c2a920d84a8
train
function
def test_omit_nuisance_python_multiple(three_group): grouped = three_group.groupby(["A", "B"]) agged = grouped.agg(np.mean) exp = grouped.mean() tm.assert_frame_equal(agged, exp)
def test_omit_nuisance_python_multiple(three_group):
grouped = three_group.groupby(["A", "B"]) agged = grouped.agg(np.mean) exp = grouped.mean() tm.assert_frame_equal(agged, exp)
work with nuisance columns grouped = df.groupby("A") result = grouped.sem() expected = df.loc[:, ["A", "C", "D"]].groupby("A").sem() tm.assert_frame_equal(result, expected) def test_omit_nuisance_python_multiple(three_group):
64
64
52
13
51
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_omit_nuisance_python_multiple
test_omit_nuisance_python_multiple
856
861
856
856
fe3ce14559695c8c20a92a062fcc91b9550091bd
bigcode/the-stack
train
512a5a910c06c9a8016721f4
train
function
def test_subsetting_columns_axis_1(): # GH 37725 g = DataFrame({"A": [1], "B": [2], "C": [3]}).groupby([0, 0, 1], axis=1) match = "Cannot subset columns when using axis=1" with pytest.raises(ValueError, match=match): g[["A", "B"]].sum()
def test_subsetting_columns_axis_1(): # GH 37725
g = DataFrame({"A": [1], "B": [2], "C": [3]}).groupby([0, 0, 1], axis=1) match = "Cannot subset columns when using axis=1" with pytest.raises(ValueError, match=match): g[["A", "B"]].sum()
("a") expected = df.groupby("a", **{attr: value}) result = expected[["b"]] if klass is DataFrame else expected["b"] assert getattr(result, attr) == getattr(expected, attr) def test_subsetting_columns_axis_1(): # GH 37725
64
64
91
16
48
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_subsetting_columns_axis_1
test_subsetting_columns_axis_1
2,118
2,123
2,118
2,119
b39070eb2b58e4d29799d9678440147d8087c14f
bigcode/the-stack
train
9841356f21fb5352971c8d18
train
function
@pytest.mark.parametrize("grouper", ["A", ["A", "B"]]) def test_set_group_name(df, grouper): def f(group): assert group.name is not None return group def freduce(group): assert group.name is not None return group.sum() def foo(x): return freduce(x) grouped = df...
@pytest.mark.parametrize("grouper", ["A", ["A", "B"]]) def test_set_group_name(df, grouper):
def f(group): assert group.name is not None return group def freduce(group): assert group.name is not None return group.sum() def foo(x): return freduce(x) grouped = df.groupby(grouper) # make sure all these work grouped.apply(f) grouped.aggregate(...
["C"].apply(f) expected = df.groupby("A")["C"].apply(g) assert isinstance(result, Series) tm.assert_series_equal(result, expected) @pytest.mark.parametrize("grouper", ["A", ["A", "B"]]) def test_set_group_name(df, grouper):
64
64
160
28
36
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_set_group_name
test_set_group_name
1,455
1,479
1,455
1,456
a11f383611e54bb0dcc6b7725a50be0a68efd8cb
bigcode/the-stack
train
dca61cba36a1602c290e6f8c
train
function
def test_groupby_one_row(): # GH 11741 msg = r"^'Z'$" df1 = DataFrame(np.random.randn(1, 4), columns=list("ABCD")) with pytest.raises(KeyError, match=msg): df1.groupby("Z") df2 = DataFrame(np.random.randn(2, 4), columns=list("ABCD")) with pytest.raises(KeyError, match=msg): df2.g...
def test_groupby_one_row(): # GH 11741
msg = r"^'Z'$" df1 = DataFrame(np.random.randn(1, 4), columns=list("ABCD")) with pytest.raises(KeyError, match=msg): df1.groupby("Z") df2 = DataFrame(np.random.randn(2, 4), columns=list("ABCD")) with pytest.raises(KeyError, match=msg): df2.groupby("Z")
"values"], index=index) result = df.groupby([Grouper(level=0, freq=freq), "metric"]).mean() expected = df.set_index([df.index, "metric"]) tm.assert_frame_equal(result, expected) def test_groupby_one_row(): # GH 11741
64
64
102
14
50
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_groupby_one_row
test_groupby_one_row
1,247
1,255
1,247
1,248
afb5ea8f4071d810fa7a06db9b74a3f8da187ad9
bigcode/the-stack
train
ffed44239f436aa8883c2cfd
train
function
def test_group_name_available_in_inference_pass(): # gh-15062 df = DataFrame({"a": [0, 0, 1, 1, 2, 2], "b": np.arange(6)}) names = [] def f(group): names.append(group.name) return group.copy() df.groupby("a", sort=False, group_keys=False).apply(f) expected_names = [0, 1, 2] ...
def test_group_name_available_in_inference_pass(): # gh-15062
df = DataFrame({"a": [0, 0, 1, 1, 2, 2], "b": np.arange(6)}) names = [] def f(group): names.append(group.name) return group.copy() df.groupby("a", sort=False, group_keys=False).apply(f) expected_names = [0, 1, 2] assert names == expected_names
D": freduce}) grouped.transform(f) grouped["C"].apply(f) grouped["C"].aggregate(freduce) grouped["C"].aggregate([freduce, foo]) grouped["C"].transform(f) def test_group_name_available_in_inference_pass(): # gh-15062
64
64
108
17
47
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_group_name_available_in_inference_pass
test_group_name_available_in_inference_pass
1,482
1,495
1,482
1,483
9e9e50d53c2503589505974f029226965fa6ed9c
bigcode/the-stack
train
0f8300c7e87fdbadb3758c69
train
function
def test_as_index_series_return_frame(df): grouped = df.groupby("A", as_index=False) grouped2 = df.groupby(["A", "B"], as_index=False) result = grouped["C"].agg(np.sum) expected = grouped.agg(np.sum).loc[:, ["A", "C"]] assert isinstance(result, DataFrame) tm.assert_frame_equal(result, expected)...
def test_as_index_series_return_frame(df):
grouped = df.groupby("A", as_index=False) grouped2 = df.groupby(["A", "B"], as_index=False) result = grouped["C"].agg(np.sum) expected = grouped.agg(np.sum).loc[:, ["A", "C"]] assert isinstance(result, DataFrame) tm.assert_frame_equal(result, expected) result2 = grouped2["C"].agg(np.sum) ...
result = g.agg(reduction_func) tm.assert_frame_equal(result, expected) result = getattr(g["b"], reduction_func)() tm.assert_frame_equal(result, expected) result = g["b"].agg(reduction_func) tm.assert_frame_equal(result, expected) def test_as_index_series_return_frame(df):
69
69
231
9
60
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_as_index_series_return_frame
test_as_index_series_return_frame
716
738
716
716
b22b851a6c785c27c5ef7e63985f6c4a7196824f
bigcode/the-stack
train
eb031beddd795a2cbe4e5675
train
function
def test_groupby_list_level(): # GH 9790 expected = DataFrame(np.arange(0, 9).reshape(3, 3)) result = expected.groupby(level=[0]).mean() tm.assert_frame_equal(result, expected)
def test_groupby_list_level(): # GH 9790
expected = DataFrame(np.arange(0, 9).reshape(3, 3)) result = expected.groupby(level=[0]).mean() tm.assert_frame_equal(result, expected)
0).nunique() expected = DataFrame({"A": [1, 2], "D": [1, 1]}) if not axis_number: expected = expected.T tm.assert_frame_equal(result, expected) def test_groupby_list_level(): # GH 9790
64
64
54
14
50
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_groupby_list_level
test_groupby_list_level
2,035
2,039
2,035
2,036
5d25fb82dbbc79f5ae60656569f1dd0202eca22c
bigcode/the-stack
train
cbf27bdb4cfb2f119d79de80
train
function
def test_groupby_multiindex_not_lexsorted(): # GH 11640 # define the lexsorted version lexsorted_mi = MultiIndex.from_tuples( [("a", ""), ("b1", "c1"), ("b2", "c2")], names=["b", "c"] ) lexsorted_df = DataFrame([[1, 3, 4]], columns=lexsorted_mi) assert lexsorted_df.columns._is_lexsorted...
def test_groupby_multiindex_not_lexsorted(): # GH 11640 # define the lexsorted version
lexsorted_mi = MultiIndex.from_tuples( [("a", ""), ("b1", "c1"), ("b2", "c2")], names=["b", "c"] ) lexsorted_df = DataFrame([[1, 3, 4]], columns=lexsorted_mi) assert lexsorted_df.columns._is_lexsorted() # define the non-lexsorted version not_lexsorted_df = DataFrame( columns=["a...
5], } ) df = df.set_index(["group1", "group2"]) df_grouped = df.groupby(level=["group1", "group2"], sort=True) res = df_grouped.agg("sum") idx = MultiIndex.from_tuples( [("a", "c"), ("a", "d"), ("b", "c")], names=["group1", "group2"] ) exp = DataFrame([[2], [1], [5]], index...
149
149
499
26
123
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_groupby_multiindex_not_lexsorted
test_groupby_multiindex_not_lexsorted
1,577
1,624
1,577
1,580
9dd6a1c3ae2dd08cd9b2fbd19af0dacd0e7db95d
bigcode/the-stack
train
08ac007015b309fbb0e5d04a
train
function
def test_groupby_name_propagation(df): # GH 6124 def summarize(df, name=None): return Series({"count": 1, "mean": 2, "omissions": 3}, name=name) def summarize_random_name(df): # Provide a different name for each Series. In this case, groupby # should not attempt to propagate the Se...
def test_groupby_name_propagation(df): # GH 6124
def summarize(df, name=None): return Series({"count": 1, "mean": 2, "omissions": 3}, name=name) def summarize_random_name(df): # Provide a different name for each Series. In this case, groupby # should not attempt to propagate the Series name since they are # inconsistent. ...
.0, "D": np.arange(8), } ) expected = df.groupby(["A"]).B.count() result = df.B.groupby(df.A).count() tm.assert_series_equal(result, expected) def test_groupby_name_propagation(df): # GH 6124
64
64
192
17
47
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_groupby_name_propagation
test_groupby_name_propagation
1,107
1,123
1,107
1,108
d488be0f6b086494f56d54ea78a19b3d5d5ce7ad
bigcode/the-stack
train
308935521f1a092b4f43ae2e
train
function
def test_groupby_only_none_group(): # see GH21624 # this was crashing with "ValueError: Length of passed values is 1, index implies 0" df = DataFrame({"g": [None], "x": 1}) actual = df.groupby("g")["x"].transform("sum") expected = Series([np.nan], name="x") tm.assert_series_equal(actual, expect...
def test_groupby_only_none_group(): # see GH21624 # this was crashing with "ValueError: Length of passed values is 1, index implies 0"
df = DataFrame({"g": [None], "x": 1}) actual = df.groupby("g")["x"].transform("sum") expected = Series([np.nan], name="x") tm.assert_series_equal(actual, expected)
(expected).assign(time=lambda x: x.time.dt.tz_localize(tz)) tm.assert_frame_equal(result, expected) def test_groupby_only_none_group(): # see GH21624 # this was crashing with "ValueError: Length of passed values is 1, index implies 0"
64
64
91
38
26
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_groupby_only_none_group
test_groupby_only_none_group
1,961
1,968
1,961
1,963
acf5a831c5e4b984a3b7c401a8831b49e0403791
bigcode/the-stack
train
cf38665d3e8a1927ea77f962
train
function
def test_groupby_unit64_float_conversion(): #  GH: 30859 groupby converts unit64 to floats sometimes df = DataFrame({"first": [1], "second": [1], "value": [16148277970000000000]}) result = df.groupby(["first", "second"])["value"].max() expected = Series( [16148277970000000000], MultiInde...
def test_groupby_unit64_float_conversion(): #  GH: 30859 groupby converts unit64 to floats sometimes
df = DataFrame({"first": [1], "second": [1], "value": [16148277970000000000]}) result = df.groupby(["first", "second"])["value"].max() expected = Series( [16148277970000000000], MultiIndex.from_product([[1], [1]], names=["first", "second"]), name="value", ) tm.assert_series_e...
.float64) expected = DataFrame({"range": Series([], index=exp_index, dtype="int64")}) tm.assert_frame_equal(result, expected, by_blocks=True) def test_groupby_unit64_float_conversion(): #  GH: 30859 groupby converts unit64 to floats sometimes
64
64
122
27
37
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_groupby_unit64_float_conversion
test_groupby_unit64_float_conversion
1,207
1,216
1,207
1,208
c7b99a22a1b2a7f53e5b078b3044a67fa79cfd84
bigcode/the-stack
train
b9621460b566f272a1611362
train
function
@pytest.mark.parametrize("group_name", ["x", ["x"]]) def test_groupby_axis_1(group_name): # GH 27614 df = DataFrame( np.arange(12).reshape(3, 4), index=[0, 1, 0], columns=[10, 20, 10, 20] ) df.index.name = "y" df.columns.name = "x" results = df.groupby(group_name, axis=1).sum() expe...
@pytest.mark.parametrize("group_name", ["x", ["x"]]) def test_groupby_axis_1(group_name): # GH 27614
df = DataFrame( np.arange(12).reshape(3, 4), index=[0, 1, 0], columns=[10, 20, 10, 20] ) df.index.name = "y" df.columns.name = "x" results = df.groupby(group_name, axis=1).sum() expected = df.T.groupby(group_name).sum().T tm.assert_frame_equal(results, expected) # test on MI co...
assert result.groups == expected.groups result = df.groupby(["beta", Grouper(level="alpha")]) expected = df.groupby(["beta", "alpha"]) assert result.groups == expected.groups @pytest.mark.parametrize("group_name", ["x", ["x"]]) def test_groupby_axis_1(group_name): # GH 27614
72
72
242
31
40
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_groupby_axis_1
test_groupby_axis_1
1,873
1,892
1,873
1,875
70be293e56a5c92e2f812a091ab3252edf3c183c
bigcode/the-stack
train
1c46796c27f294779d7dd525
train
function
def test_groupby_as_index_agg(df): grouped = df.groupby("A", as_index=False) # single-key result = grouped.agg(np.mean) expected = grouped.mean() tm.assert_frame_equal(result, expected) result2 = grouped.agg({"C": np.mean, "D": np.sum}) expected2 = grouped.mean() expected2["D"] = grou...
def test_groupby_as_index_agg(df):
grouped = df.groupby("A", as_index=False) # single-key result = grouped.agg(np.mean) expected = grouped.mean() tm.assert_frame_equal(result, expected) result2 = grouped.agg({"C": np.mean, "D": np.sum}) expected2 = grouped.mean() expected2["D"] = grouped.sum()["D"] tm.assert_frame_...
.cumsum()) expected = Series( [2, 6, 6], name="B", index=MultiIndex.from_tuples([(0, 0), (0, 1), (1, 2)]) ) tm.assert_series_equal(result, expected) def test_groupby_as_index_select_column_sum_empty_df(): # GH 35246 df = DataFrame(columns=["A", "B", "C"]) left = df.groupby(by="A", as_i...
144
144
480
10
134
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_groupby_as_index_agg
test_groupby_as_index_agg
629
682
629
629
e597a1adcbff2dffd8251350a1289e702a117098
bigcode/the-stack
train
793813f88226166e43265715
train
function
def test_as_index_series_column_slice_raises(df): # GH15072 grouped = df.groupby("A", as_index=False) msg = r"Column\(s\) C already selected" with pytest.raises(IndexError, match=msg): grouped["C"].__getitem__("D")
def test_as_index_series_column_slice_raises(df): # GH15072
grouped = df.groupby("A", as_index=False) msg = r"Column\(s\) C already selected" with pytest.raises(IndexError, match=msg): grouped["C"].__getitem__("D")
grouped2["C"].sum() expected2 = grouped2.sum().loc[:, ["A", "B", "C"]] assert isinstance(result2, DataFrame) tm.assert_frame_equal(result2, expected2) def test_as_index_series_column_slice_raises(df): # GH15072
64
64
64
17
47
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_as_index_series_column_slice_raises
test_as_index_series_column_slice_raises
741
747
741
742
08ec83289c10874ac4b8bff7b646cbae900617a0
bigcode/the-stack
train
f9804efd2272b8a5a78cac2b
train
function
def test_groupby_level_mapper(mframe): deleveled = mframe.reset_index() mapper0 = {"foo": 0, "bar": 0, "baz": 1, "qux": 1} mapper1 = {"one": 0, "two": 0, "three": 1} result0 = mframe.groupby(mapper0, level=0).sum() result1 = mframe.groupby(mapper1, level=1).sum() mapped_level0 = np.array([map...
def test_groupby_level_mapper(mframe):
deleveled = mframe.reset_index() mapper0 = {"foo": 0, "bar": 0, "baz": 1, "qux": 1} mapper1 = {"one": 0, "two": 0, "three": 1} result0 = mframe.groupby(mapper0, level=0).sum() result1 = mframe.groupby(mapper1, level=1).sum() mapped_level0 = np.array([mapper0.get(x) for x in deleveled["first"]...
assert result.index.name == "first" result = mframe.groupby(level=1).count() assert result.index.name == "second" result = mframe["A"].groupby(level=0).count() assert result.index.name == "first" def test_groupby_level_mapper(mframe):
64
64
215
9
55
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_groupby_level_mapper
test_groupby_level_mapper
924
940
924
924
dad1417df875e4118c79488784e01034b54b5b5f
bigcode/the-stack
train
2d4bd626e13ea15a15d5ed4a
train
function
def test_groupby_complex(): # GH 12902 a = Series(data=np.arange(4) * (1 + 2j), index=[0, 0, 1, 1]) expected = Series((1 + 2j, 5 + 10j)) result = a.groupby(level=0).sum() tm.assert_series_equal(result, expected) result = a.sum(level=0) tm.assert_series_equal(result, expected)
def test_groupby_complex(): # GH 12902
a = Series(data=np.arange(4) * (1 + 2j), index=[0, 0, 1, 1]) expected = Series((1 + 2j, 5 + 10j)) result = a.groupby(level=0).sum() tm.assert_series_equal(result, expected) result = a.sum(level=0) tm.assert_series_equal(result, expected)
match=msg): s.groupby(level=[0, 1]) msg = "level > 0 or level < -1 only valid with MultiIndex" with pytest.raises(ValueError, match=msg): s.groupby(level=[1]) def test_groupby_complex(): # GH 12902
64
64
100
13
51
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_groupby_complex
test_groupby_complex
975
984
975
976
283c294877f286de5d714754d5c9060f8b05b9c5
bigcode/the-stack
train
d1d43182eb752825a2c7a6b9
train
function
def test_wrap_aggregated_output_multindex(mframe): df = mframe.T df["baz", "two"] = "peekaboo" keys = [np.array([0, 0, 1]), np.array([0, 0, 1])] agged = df.groupby(keys).agg(np.mean) assert isinstance(agged.columns, MultiIndex) def aggfun(ser): if ser.name == ("foo", "one"): ...
def test_wrap_aggregated_output_multindex(mframe):
df = mframe.T df["baz", "two"] = "peekaboo" keys = [np.array([0, 0, 1]), np.array([0, 0, 1])] agged = df.groupby(keys).agg(np.mean) assert isinstance(agged.columns, MultiIndex) def aggfun(ser): if ser.name == ("foo", "one"): raise TypeError else: return ...
df = DataFrame([0]) msg = r"unsupported operand type\(s\) for \+: 'int' and 'str'" with pytest.raises(TypeError, match=msg): df.groupby(lambda x: x + "foo") def test_wrap_aggregated_output_multindex(mframe):
64
64
144
12
52
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_wrap_aggregated_output_multindex
test_wrap_aggregated_output_multindex
895
910
895
895
669d8ad6aeb87ca5f21acb630ff6e3bde8c6bff0
bigcode/the-stack
train
714aced24cbe137fbb1a62d7
train
function
def test_groupby_list_infer_array_like(df): result = df.groupby(list(df["A"])).mean() expected = df.groupby(df["A"]).mean() tm.assert_frame_equal(result, expected, check_names=False) with pytest.raises(KeyError, match=r"^'foo'$"): df.groupby(list(df["A"][:-1])) # pathological case of ambig...
def test_groupby_list_infer_array_like(df):
result = df.groupby(list(df["A"])).mean() expected = df.groupby(df["A"]).mean() tm.assert_frame_equal(result, expected, check_names=False) with pytest.raises(KeyError, match=r"^'foo'$"): df.groupby(list(df["A"][:-1])) # pathological case of ambiguity df = DataFrame({"foo": [0, 1], "bar...
value"].max() expected = Series( [16148277970000000000], MultiIndex.from_product([[1], [1]], names=["first", "second"]), name="value", ) tm.assert_series_equal(result, expected) def test_groupby_list_infer_array_like(df):
64
64
148
11
53
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_groupby_list_infer_array_like
test_groupby_list_infer_array_like
1,219
1,231
1,219
1,219
a90add35015290d2c6e82e081572386427cd8f0d
bigcode/the-stack
train
cd8efb1b73c61120bc26d56a
train
function
def test_frame_groupby(tsframe): grouped = tsframe.groupby(lambda x: x.weekday()) # aggregate aggregated = grouped.aggregate(np.mean) assert len(aggregated) == 5 assert len(aggregated.columns) == 4 # by string tscopy = tsframe.copy() tscopy["weekday"] = [x.weekday() for x in tscopy.ind...
def test_frame_groupby(tsframe):
grouped = tsframe.groupby(lambda x: x.weekday()) # aggregate aggregated = grouped.aggregate(np.mean) assert len(aggregated) == 5 assert len(aggregated.columns) == 4 # by string tscopy = tsframe.copy() tscopy["weekday"] = [x.weekday() for x in tscopy.index] stragged = tscopy.groupby...
tm.assert_frame_equal(result, expected) # get attribute result = grouped.dtype expected = grouped.agg(lambda x: x.dtype) tm.assert_series_equal(result, expected) # make sure raises error msg = "'SeriesGroupBy' object has no attribute 'foo'" with pytest.raises(AttributeError, match=msg...
91
91
305
8
83
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_frame_groupby
test_frame_groupby
391
428
391
391
e6562ccc77002568fc8c0acf0809d9b3efd98583
bigcode/the-stack
train
6192cc971968b937671d6c6a
train
function
def test_seriesgroupby_name_attr(df): # GH 6265 result = df.groupby("A")["C"] assert result.count().name == "C" assert result.mean().name == "C" testFunc = lambda x: np.sum(x) * 2 assert result.agg(testFunc).name == "C"
def test_seriesgroupby_name_attr(df): # GH 6265
result = df.groupby("A")["C"] assert result.count().name == "C" assert result.mean().name == "C" testFunc = lambda x: np.sum(x) * 2 assert result.agg(testFunc).name == "C"
df.groupby([df["A"], df["B"]], as_index=False).mean() assert result.index.names == ("A", "B") assert "A" in result2 assert "B" in result2 def test_seriesgroupby_name_attr(df): # GH 6265
64
64
75
16
47
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_seriesgroupby_name_attr
test_seriesgroupby_name_attr
1,080
1,087
1,080
1,081
f093a3bf8774eb592080916615fd4c3fa8b9ed74
bigcode/the-stack
train
69071bbc89eb8ac2ea2a1ca1
train
function
@pytest.mark.parametrize( "max_seq_items, expected", [ (5, "{0: [0], 1: [1], 2: [2], 3: [3], 4: [4]}"), (4, "{0: [0], 1: [1], 2: [2], 3: [3], ...}"), (1, "{0: [0], ...}"), ], ) def test_groups_repr_truncates(max_seq_items, expected): # GH 1135 df = DataFrame(np.random.randn(5...
@pytest.mark.parametrize( "max_seq_items, expected", [ (5, "{0: [0], 1: [1], 2: [2], 3: [3], 4: [4]}"), (4, "{0: [0], 1: [1], 2: [2], 3: [3], ...}"), (1, "{0: [0], ...}"), ], ) def test_groups_repr_truncates(max_seq_items, expected): # GH 1135
df = DataFrame(np.random.randn(5, 1)) df["a"] = df.index with pd.option_context("display.max_seq_items", max_seq_items): result = df.groupby("a").groups.__repr__() assert result == expected result = df.groupby(np.array(df.a)).groups.__repr__() assert result == expected
@pytest.mark.parametrize( "max_seq_items, expected", [ (5, "{0: [0], 1: [1], 2: [2], 3: [3], 4: [4]}"), (4, "{0: [0], 1: [1], 2: [2], 3: [3], ...}"), (1, "{0: [0], ...}"), ], ) def test_groups_repr_truncates(max_seq_items, expected): # GH 1135
116
64
192
116
0
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_groups_repr_truncates
test_groups_repr_truncates
2,042
2,060
2,042
2,051
904307eef2b887c09d21c22ce1d03248527ecfb1
bigcode/the-stack
train
221ea3b5caed4b493f89f3ef
train
function
def test_attr_wrapper(ts): grouped = ts.groupby(lambda x: x.weekday()) result = grouped.std() expected = grouped.agg(lambda x: np.std(x, ddof=1)) tm.assert_series_equal(result, expected) # this is pretty cool result = grouped.describe() expected = {name: gp.describe() for name, gp in group...
def test_attr_wrapper(ts):
grouped = ts.groupby(lambda x: x.weekday()) result = grouped.std() expected = grouped.agg(lambda x: np.std(x, ddof=1)) tm.assert_series_equal(result, expected) # this is pretty cool result = grouped.describe() expected = {name: gp.describe() for name, gp in grouped} expected = DataFram...
").apply(f2) # should fail (incorrect shape) with pytest.raises(AssertionError, match=msg): df.groupby("a").apply(f3) with pytest.raises(AssertionError, match=msg): df2.groupby("a").apply(f3) def test_attr_wrapper(ts):
64
64
171
6
58
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_attr_wrapper
test_attr_wrapper
367
388
367
367
d09bb708d8fd0f79aa90e1bc28542437b86ea14e
bigcode/the-stack
train
f9e42c7825879be60dc99e1d
train
function
def test_groupby_sort_multi(): df = DataFrame( { "a": ["foo", "bar", "baz"], "b": [3, 2, 1], "c": [0, 1, 2], "d": np.random.randn(3), } ) tups = [tuple(row) for row in df[["a", "b", "c"]].values] tups = com.asarray_tuplesafe(tups) resu...
def test_groupby_sort_multi():
df = DataFrame( { "a": ["foo", "bar", "baz"], "b": [3, 2, 1], "c": [0, 1, 2], "d": np.random.randn(3), } ) tups = [tuple(row) for row in df[["a", "b", "c"]].values] tups = com.asarray_tuplesafe(tups) result = df.groupby(["a", "b", "c"]...
.assert_numpy_array_equal(tmp.values, res_values) def test_int32_overflow(): B = np.concatenate((np.arange(10000), np.arange(10000), np.arange(5000))) A = np.arange(25000) df = DataFrame({"A": A, "B": B, "C": A, "D": B, "E": np.random.randn(25000)}) left = df.groupby(["A", "B", "C", "D"]).sum() r...
140
140
467
7
133
Pawel-Kranzberg/pandas
pandas/tests/groupby/test_groupby.py
Python
test_groupby_sort_multi
test_groupby_sort_multi
1,350
1,388
1,350
1,350
87196f10937c82d2aeb238335f0e4345fea55ec0
bigcode/the-stack
train