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
d831dfda656416bd339cd059
train
class
class hrm_HumanResourceRepresent(S3Represent): """ Representation of human resource IDs """ def __init__(self, show_link=False): """ Constructor @param show_link: whether to add a URL to representations """ super(hrm_HumanResourceRepresent, self).__init__( ...
class hrm_HumanResourceRepresent(S3Represent):
""" Representation of human resource IDs """ def __init__(self, show_link=False): """ Constructor @param show_link: whether to add a URL to representations """ super(hrm_HumanResourceRepresent, self).__init__( lookup = "h...
output = {"items": items, "title": T("Assign %(staff)s") % {"staff": STAFF}, "list_filter_form": ff, "rheader": rheader, } elif representation == "aadata": # Ajax refresh ...
237
237
793
11
225
ramdesh/eden
modules/s3db/hrm.py
Python
hrm_HumanResourceRepresent
hrm_HumanResourceRepresent
6,095
6,207
6,095
6,095
b27a2ee018760bf2eee3fc566b14d3cde6c2756b
bigcode/the-stack
train
4ce0ce83f4a32f62aaeced7b
train
class
class HRProgrammeModel(S3Model): """ Programmes - record Volunteer Hours - categorise (Training) Events These are separate to the Project module's Programmes - @ToDo: setting to make them the same? """ names = ("hrm_programme", "hrm_programme_hou...
class HRProgrammeModel(S3Model):
""" Programmes - record Volunteer Hours - categorise (Training) Events These are separate to the Project module's Programmes - @ToDo: setting to make them the same? """ names = ("hrm_programme", "hrm_programme_hours", "hrm_programme_...
linary Action Type"), ), ), s3_comments(), *s3_meta_fields()) # --------------------------------------------------------------------- # Pass names back to global scope (s3.*) # ...
256
256
1,574
8
247
ramdesh/eden
modules/s3db/hrm.py
Python
HRProgrammeModel
HRProgrammeModel
4,849
5,093
4,849
4,849
1d2bfe0f8573ac6ee333cc2fc63eb702b0406e03
bigcode/the-stack
train
10566ffde960ad740c5b8f89
train
class
class hrm_AssignMethod(S3Method): """ Custom Method to allow human resources to be assigned to something e.g. Incident, Project, Site, Vehicle @ToDo: be able to filter by deployable status for the role """ # ------------------------------------------------------------------------- ...
class hrm_AssignMethod(S3Method):
""" Custom Method to allow human resources to be assigned to something e.g. Incident, Project, Site, Vehicle @ToDo: be able to filter by deployable status for the role """ # ------------------------------------------------------------------------- def __init__(self, ...
me_hours record = db(table.id == record_id).select(table.person_id, limitby=(0, 1), ).first() person_id = record.person_id # Recalculate the Active Status for this Volunteer active = vol_active(p...
256
256
2,846
10
245
ramdesh/eden
modules/s3db/hrm.py
Python
hrm_AssignMethod
hrm_AssignMethod
5,693
6,092
5,693
5,693
a7741757e5aab056f85254bcb95436a8f8dfc510
bigcode/the-stack
train
236c68483566dc4dc6928aad
train
class
class hrm_CV(S3Method): """ Curriculum Vitae, custom profile page with multiple DataTables: * Awards * Education * Experience * Training * Skills """ def __init__(self, form=None): """ Constructor @param fo...
class hrm_CV(S3Method):
""" Curriculum Vitae, custom profile page with multiple DataTables: * Awards * Education * Experience * Training * Skills """ def __init__(self, form=None): """ Constructor @param form: widget config to inj...
.institute.represent = lambda v: v or "" list_fields.extend((("Education Level", "person_id$education.level_id"), ("Degree Name", "person_id$education.award"), ("Major", "person_id$education.major"), ("Grade", "person_id$educati...
256
256
2,187
9
246
ramdesh/eden
modules/s3db/hrm.py
Python
hrm_CV
hrm_CV
9,275
9,578
9,275
9,275
275aa82cbaaa82d700c08cb1edd74c61471a1d8b
bigcode/the-stack
train
f4eeee85628650e52c2f5bfd
train
class
class HRTagModel(S3Model): """ Arbitrary Key:Value Tags for Human Resources """ names = ("hrm_human_resource_tag", ) def model(self): T = current.T # ===================================================================== # Human Resource Tags # tablena...
class HRTagModel(S3Model):
""" Arbitrary Key:Value Tags for Human Resources """ names = ("hrm_human_resource_tag", ) def model(self): T = current.T # ===================================================================== # Human Resource Tags # tablename = "hrm_human_resource_ta...
linary_type", label = T("Add Disciplinary Action Type"), ), ), s3_comments(), *s3_meta_fields()) # ---------------------------------------------...
64
64
200
8
55
ramdesh/eden
modules/s3db/hrm.py
Python
HRTagModel
HRTagModel
4,808
4,846
4,808
4,808
58bc585e2474bda6705806688c34e19889218f00
bigcode/the-stack
train
101e88139866ae564e608c98
train
function
def hrm_compose(): """ Send message to people/teams/participants @ToDo: Better rewritten as an S3Method """ s3db = current.s3db get_vars = current.request.get_vars pe_id = None if "human_resource.id" in get_vars: fieldname = "human_resource.id" record_id = get_...
def hrm_compose():
""" Send message to people/teams/participants @ToDo: Better rewritten as an S3Method """ s3db = current.s3db get_vars = current.request.get_vars pe_id = None if "human_resource.id" in get_vars: fieldname = "human_resource.id" record_id = get_vars.get(fieldname)...
# Set the Organisation in the Profile, if not already set profile["organisation_id"] = organisation_id if not user.site_id: # Set the Site in the Profile, if not already set profile["site_id"] = site_id else: # How many active HR re...
182
182
607
6
175
ramdesh/eden
modules/s3db/hrm.py
Python
hrm_compose
hrm_compose
6,733
6,810
6,733
6,733
8604f5137eb73b6d79aa9eacab9b15280a372b4d
bigcode/the-stack
train
2f056df38b749e1caf7bc1d9
train
function
def hrm_training_year(row): """ The Year of the training event """ if hasattr(row, "hrm_training"): row = row.hrm_training try: date = row.date except AttributeError: # not available date = None if date: return date.year else: return current.messag...
def hrm_training_year(row):
""" The Year of the training event """ if hasattr(row, "hrm_training"): row = row.hrm_training try: date = row.date except AttributeError: # not available date = None if date: return date.year else: return current.messages["NONE"]
try: date = row.date except AttributeError: # not available date = None if date: return "%s/%02d" % (date.year, date.month) else: return current.messages["NONE"] # ------------------------------------------------------------------------- def hrm_training_year(row...
64
64
77
7
57
ramdesh/eden
modules/s3db/hrm.py
Python
hrm_training_year
hrm_training_year
6,971
6,983
6,971
6,971
8319d5c44254c5d5f93ff036a7ecd58ffc63e711
bigcode/the-stack
train
d3feceddfa169443e0b4865c
train
function
def hrm_human_resource_filters(resource_type = None, module = None, hrm_type_opts = None): """ Get filter widgets for human resources @param resource_type: the HR type (staff/volunteer/both) if pre-determine...
def hrm_human_resource_filters(resource_type = None, module = None, hrm_type_opts = None):
""" Get filter widgets for human resources @param resource_type: the HR type (staff/volunteer/both) if pre-determined, otherwise None to render a filter widget @param module: the controller prefix of the request to render ...
"record": record_id}), _class="s3_modal", _title=current.T("Edit Training"), ) else: edit_btn = "" if permit("delete", table, record_id=record_id): delete_btn = A(ICON("delete"), _class="dl-item-delete", ...
256
256
1,481
25
230
ramdesh/eden
modules/s3db/hrm.py
Python
hrm_human_resource_filters
hrm_human_resource_filters
10,652
10,871
10,652
10,654
491e299b402c2efd6b3861d68f91d216e4eae46d
bigcode/the-stack
train
fd5c7fca90819fb6b357eb77
train
function
def hrm_training_onvalidation(form): """ If the Training is created from a Training Event (e.g. during Import), then auto-populate the fields from that """ form_vars = form.vars training_event_id = form_vars.get("training_event_id", None) if not training_event_id: # Nothing ...
def hrm_training_onvalidation(form):
""" If the Training is created from a Training Event (e.g. during Import), then auto-populate the fields from that """ form_vars = form.vars training_event_id = form_vars.get("training_event_id", None) if not training_event_id: # Nothing to do return db = curren...
organisation query &= (stable.organisation_id == otable.id) org = db(query).select(otable.realm_entity, limitby=(0, 1)).first() if org: return org.realm_entity return None # =================================================...
64
64
199
8
55
ramdesh/eden
modules/s3db/hrm.py
Python
hrm_training_onvalidation
hrm_training_onvalidation
3,949
3,977
3,949
3,949
263725474b1f04e204e9249fcd47fcef08daec3d
bigcode/the-stack
train
83c4825d28f5d98830c2b29a
train
function
def hrm_map_popup(r): """ Custom output to place inside a Map Popup - called from postp of human_resource controller """ T = current.T db = current.db s3db = current.s3db CONTACT_OPTS = current.msg.CONTACT_OPTS record = r.record if not record: return "" pers...
def hrm_map_popup(r):
""" Custom output to place inside a Map Popup - called from postp of human_resource controller """ T = current.T db = current.db s3db = current.s3db CONTACT_OPTS = current.msg.CONTACT_OPTS record = r.record if not record: return "" person_id = record.person_...
.db pe = db(query).select(table.pe_id, limitby=(0, 1)).first() if not pe: current.session.error = current.T("Record not found") redirect(URL(f="index")) pe_id = pe.pe_id if "hrm_id" in get_vars: # Get the individual's communicat...
256
256
1,177
7
248
ramdesh/eden
modules/s3db/hrm.py
Python
hrm_map_popup
hrm_map_popup
6,813
6,953
6,813
6,813
581794f92530d80af064684479e7282c8b6be411
bigcode/the-stack
train
48267dc81c64d877f71ca894
train
class
class HRInsuranceModel(S3Model): """ Data Model to track insurance information of staff members """ names = ("hrm_insurance", ) def model(self): T = current.T insurance_types = {"SOCIAL": T("Social Insurance"), "HEALTH": T("Health Insurance"), ...
class HRInsuranceModel(S3Model):
""" Data Model to track insurance information of staff members """ names = ("hrm_insurance", ) def model(self): T = current.T insurance_types = {"SOCIAL": T("Social Insurance"), "HEALTH": T("Health Insurance"), } ...
(self, row): """ Represent a row @param row: the Row """ try: name = row[self.tablename].name except AttributeError: return row.name try: organisation = row["org_organisation"] except AttributeError: ...
125
125
417
8
116
ramdesh/eden
modules/s3db/hrm.py
Python
HRInsuranceModel
HRInsuranceModel
1,728
1,794
1,728
1,728
dfd2086ed3b1ca39f819c02c685252db603de28d
bigcode/the-stack
train
43bf0e8cd3257eec20fd9486
train
function
def hrm_experience_controller(): """ Experience Controller, defined in the model for use from multiple controllers for unified menus - used for Adding/Editing on Profile page """ def prep(r): if r.method in ("create", "update"): # Coming from Profile page? ...
def hrm_experience_controller():
""" Experience Controller, defined in the model for use from multiple controllers for unified menus - used for Adding/Editing on Profile page """ def prep(r): if r.method in ("create", "update"): # Coming from Profile page? field = current.s3db.hrm_e...
s3.prep = prep return current.rest_controller("hrm", "credential", # @ToDo: Create these if-required #csv_stylesheet = ("hrm", "credential.xsl"), #csv_template = ("hrm", "credential"), ...
71
71
237
7
63
ramdesh/eden
modules/s3db/hrm.py
Python
hrm_experience_controller
hrm_experience_controller
7,849
7,876
7,849
7,849
251cdc7e5b4eaf8b28c28d63bc2a0fc2b68af408
bigcode/the-stack
train
ca01421952e3846bc4b7dc05
train
function
def hrm_xls_list_fields(r, staff=True, vol=True): """ Configure Human Resource list_fields for XLS Export - match the XLS Import - no l10n if column labels - simple represents """ s3db = current.s3db settings = current.deployment_settings table = r.table table....
def hrm_xls_list_fields(r, staff=True, vol=True):
""" Configure Human Resource list_fields for XLS Export - match the XLS Import - no l10n if column labels - simple represents """ s3db = current.s3db settings = current.deployment_settings table = r.table table.organisation_id.represent = s3db.org_OrganisationR...
r.interactive: # # @ToDo: Restore once the other part is working # if r.component_name == "participant" and \ # isinstance(output, dict): # showadd_btn = output.get("showadd_btn", None) # if showadd_btn: # # Add an Import button # ...
256
256
1,351
15
240
ramdesh/eden
modules/s3db/hrm.py
Python
hrm_xls_list_fields
hrm_xls_list_fields
9,160
9,272
9,160
9,160
f2692f37566fd49c38dde3c2ea575f008cc20b1a
bigcode/the-stack
train
cad745ddef00e5a87ca66dc3
train
class
class HREventProjectModel(S3Model): """ (Training) Events <> Projects Link Table """ names = ("hrm_event_project", ) def model(self): # ===================================================================== # (Training) Events <> Projects Link Table # ...
class HREventProjectModel(S3Model):
""" (Training) Events <> Projects Link Table """ names = ("hrm_event_project", ) def model(self): # ===================================================================== # (Training) Events <> Projects Link Table # tablename = "hrm_event_project" ...
), self.hrm_programme_id(empty = False, ondelete = "CASCADE", ), *s3_meta_fields()) # --------------------------------------------------------------------- ...
64
64
143
10
53
ramdesh/eden
modules/s3db/hrm.py
Python
HREventProjectModel
HREventProjectModel
4,227
4,253
4,227
4,227
c3ee332abba0ea80f2ed1a5fa0c0d653ebe07ba6
bigcode/the-stack
train
b2f905acf05bd74759f5b1f0
train
function
def hrm_human_resource_controller(extra_filter = None): """ Human Resources Controller, defined in the model for use from multiple controllers for unified menus - used for Summary & Profile views, Imports and S3AddPersonWidget """ T = current.T db = current.db s3db = curren...
def hrm_human_resource_controller(extra_filter = None):
""" Human Resources Controller, defined in the model for use from multiple controllers for unified menus - used for Summary & Profile views, Imports and S3AddPersonWidget """ T = current.T db = current.db s3db = current.s3db s3 = current.response.s3 settings = curre...
.permission.has_permission("update", c="hrm", f="compose"): s3.actions.append({ "url": URL(f="compose", vars = {"group_id": "[id]"}), "_class": "action-btn sen...
256
256
3,569
12
243
ramdesh/eden
modules/s3db/hrm.py
Python
hrm_human_resource_controller
hrm_human_resource_controller
8,074
8,555
8,074
8,074
5acd39b5f3eff5cbf69cf08d6c226e2c8cdc8236
bigcode/the-stack
train
63502115cf5d97fc8b8b905d
train
function
def hrm_credential_controller(): """ RESTful CRUD controller - could be used for Searching for people by Skill - used for Adding/Editing on Profile page """ s3 = current.response.s3 def prep(r): table = r.table if r.method in ("create", "create.popup", "update...
def hrm_credential_controller():
""" RESTful CRUD controller - could be used for Searching for people by Skill - used for Adding/Editing on Profile page """ s3 = current.response.s3 def prep(r): table = r.table if r.method in ("create", "create.popup", "update", "update.popup"): #...
return current.rest_controller("hrm", "competency", # @ToDo: Create these if-required #csv_stylesheet = ("hrm", "competency.xsl"), #csv_template = ("hrm", "competency"), ) # =...
65
65
218
7
57
ramdesh/eden
modules/s3db/hrm.py
Python
hrm_credential_controller
hrm_credential_controller
7,818
7,846
7,818
7,818
378d5fe868f2b74ecdbd102af825b834ad7d9678
bigcode/the-stack
train
43c3cbebe2c82b957fcf729b
train
function
def hrm_credential_list_layout(list_id, item_id, resource, rfields, record): """ Default dataList item renderer for Credentials on the HRM Profile @param list_id: the HTML ID of the list @param item_id: the HTML ID of the item @param resource: the S3Resource to render @param...
def hrm_credential_list_layout(list_id, item_id, resource, rfields, record):
""" Default dataList item renderer for Credentials on the HRM Profile @param list_id: the HTML ID of the list @param item_id: the HTML ID of the item @param resource: the S3Resource to render @param rfields: the S3ResourceFields to render @param record: the record as...
-item-delete", ) else: delete_btn = "" edit_bar = DIV(edit_btn, delete_btn, _class="edit-bar fright", ) # Render the item item = DIV(DIV(ICON("icon"), SPAN(" %s" % title, _...
180
180
603
20
159
ramdesh/eden
modules/s3db/hrm.py
Python
hrm_credential_list_layout
hrm_credential_list_layout
10,257
10,339
10,257
10,257
ad7893c2caac77363f8cc8bafd6d2e9e8fd9fa3e
bigcode/the-stack
train
2c8911d3f83b7a1312b5c605
train
function
def writeTable(failueSurface): etaX, thetaY, strain = failueSurface #print (etaX, thetaY) eta = etaX[0, :] theta = np.cos(np.pi / 2 * (1 - thetaY[:, 0])) print(eta.shape, strain.shape) with open ('mmc.tab','w+') as f: f.write('*DEFINE_TABLE\n') f.write('$#Lode Para...
def writeTable(failueSurface):
etaX, thetaY, strain = failueSurface #print (etaX, thetaY) eta = etaX[0, :] theta = np.cos(np.pi / 2 * (1 - thetaY[:, 0])) print(eta.shape, strain.shape) with open ('mmc.tab','w+') as f: f.write('*DEFINE_TABLE\n') f.write('$#Lode Parameter vs. load curves'+'\n') ...
for test in tests: xx, yy, zz = test[:, 0], test[:, 1], test[:, 2] ax.scatter(xx, yy, zz)#, cmap=cm.coolwarm,linewidth=0, antialiased=False) ax.xaxis.set_major_locator(LinearLocator(5)) ax.yaxis.set_major_locator(LinearLocator(5)) ax.set_xlabel('Triaxiality') ax.set_ylabel('Lode Param...
190
190
634
8
182
AaronGe88inTHU/pyMaterialTestsProcess
ExperimentProcess/GISSIMO/PY/DuctileFractureAcc.py
Python
writeTable
writeTable
333
386
333
333
aefe7570ecbbbc1c1387051c9df8fb29e1ed74f3
bigcode/the-stack
train
62c69c718fdf7241283b6780
train
function
def showFigure(faiureSurface, tests): print(tests.shape) XX, YY, zz = faiureSurface fig = plt.figure() #plt.xlabel('Triaxiality') #plt.ylabel('Lode Parameter') #plt.zlabel('Failure plastic strain') ax = fig.gca(projection='3d') #cs = ax.contourf(X, Y, z, locator=ticker.LogLocator(), cmap...
def showFigure(faiureSurface, tests):
print(tests.shape) XX, YY, zz = faiureSurface fig = plt.figure() #plt.xlabel('Triaxiality') #plt.ylabel('Lode Parameter') #plt.zlabel('Failure plastic strain') ax = fig.gca(projection='3d') #cs = ax.contourf(X, Y, z, locator=ticker.LogLocator(), cmap=cm.PuBu_r) #cbar = fig.colorbar(c...
different defination of lode parameter than mmc, transfer mmc model to lsdyna format ''' return etaX, thetaY, epsilon # In[31]: """ Input """ A = 426.2 n = 0.081 #print(np.array(tests)) resSimple= fitDamageAcc(tests) # In[32]: resSimple.x # In[35]: def showFigure(faiureSurface, tests):
96
96
323
10
86
AaronGe88inTHU/pyMaterialTestsProcess
ExperimentProcess/GISSIMO/PY/DuctileFractureAcc.py
Python
showFigure
showFigure
291
320
291
291
fb35adabee7e15cc26580a9fec407168e4f43087
bigcode/the-stack
train
3e3aa8211801148491a70f2f
train
function
def testResultsSimple(param, tests): """ tests result to damgaIndicator """ #indicators = np.zeros([tests.shape[0]]) """ for ii, test in enumerate(tests): eta = test[:, 0] theta = test[:, 1] epsilon = test[:, 2] damageIndicator = accumulatedDamage(simplifiedM...
def testResultsSimple(param, tests):
""" tests result to damgaIndicator """ #indicators = np.zeros([tests.shape[0]]) """ for ii, test in enumerate(tests): eta = test[:, 0] theta = test[:, 1] epsilon = test[:, 2] damageIndicator = accumulatedDamage(simplifiedMMC, eta, theta, epsilon, param) ...
#print(np.any(np.isnan(epsilonPlasticFailure))) except(RuntimeWarning): print('run time warning',A, n, c1, c2) epsilonPlasticFailure = np.zeros(comp.shape) return epsilonPlasticFailure # In[28]: def testResultsSimple(param, tests):
64
64
149
8
56
AaronGe88inTHU/pyMaterialTestsProcess
ExperimentProcess/GISSIMO/PY/DuctileFractureAcc.py
Python
testResultsSimple
testResultsSimple
219
238
219
219
bd5ee3e2f5a0e0b75e55a790be840ce03030b99c
bigcode/the-stack
train
d3a7bd3e413e175ef90b0663
train
function
def testResultsAcc(param, tests): """ tests result to damgaIndicator """ indicators = np.zeros([tests.shape[0]]) #print(tests.shape) for ii, test in enumerate(tests): eta = test[:, 0] theta = test[:, 1] epsilon = test[:, 2] damageIndicator = accumulatedDamage(simp...
def testResultsAcc(param, tests):
""" tests result to damgaIndicator """ indicators = np.zeros([tests.shape[0]]) #print(tests.shape) for ii, test in enumerate(tests): eta = test[:, 0] theta = test[:, 1] epsilon = test[:, 2] damageIndicator = accumulatedDamage(simplifiedMMC, eta, theta, epsilon, pa...
.trapz(1/ epsilonPlasticFailure, epsilon) #np.sum(epsilon / epsilonPlasticFailure) #integrate.tr (1 / epsilonPlaticFailure, epsilon) #print(epsilonPlasticFailure) return damageIndicator # In[24]: def testResultsAcc(param, tests):
64
64
110
8
56
AaronGe88inTHU/pyMaterialTestsProcess
ExperimentProcess/GISSIMO/PY/DuctileFractureAcc.py
Python
testResultsAcc
testResultsAcc
116
129
116
116
b2305e9c1a68e8b4a05a78c4f313fec109f3105b
bigcode/the-stack
train
65c8c2b8b54f571c0c1ce264
train
function
def readSimpleResult(file): xlsx = pd.ExcelFile(file) sheet = xlsx.sheet_names[0] df = pd.read_excel(xlsx, sheet) eta = eta = df.loc[:, 'TRI'].values.reshape(-1, 1) ''' lsdyna has different defination of lode parameter 27J3/2*sigma^3 than mmc, transfer lsdyna result to mmc model ''' ...
def readSimpleResult(file):
xlsx = pd.ExcelFile(file) sheet = xlsx.sheet_names[0] df = pd.read_excel(xlsx, sheet) eta = eta = df.loc[:, 'TRI'].values.reshape(-1, 1) ''' lsdyna has different defination of lode parameter 27J3/2*sigma^3 than mmc, transfer lsdyna result to mmc model ''' lodeAlt = df.loc[:, 'LODE']....
.026, 0.1, 500)) res = optimize.least_squares(errAcc, (0.1, 500), bounds=([0,0],[1000,10000]), args=(tests, targets)) return res # In[25]: def readSimpleResult(file):
64
64
173
6
58
AaronGe88inTHU/pyMaterialTestsProcess
ExperimentProcess/GISSIMO/PY/DuctileFractureAcc.py
Python
readSimpleResult
readSimpleResult
147
160
147
147
b62120f47a5a68fc57235f52c53a1f556ec3a7d4
bigcode/the-stack
train
f4c554bcc2e51a2be53bd8d4
train
function
def fitDamageAcc(tests): targets = np.ones([tests.shape[0]]) #result = testResults(tests,(996.68, 0.026, 0.1, 500)) res = optimize.least_squares(errAcc, (0.1, 500), bounds=([0,0],[1000,10000]), args=(tests, targets)) return res
def fitDamageAcc(tests):
targets = np.ones([tests.shape[0]]) #result = testResults(tests,(996.68, 0.026, 0.1, 500)) res = optimize.least_squares(errAcc, (0.1, 500), bounds=([0,0],[1000,10000]), args=(tests, targets)) return res
def errAcc(param, x, y): global A, n c1, c2 = param #print(Paramters.A, Paramters.n) return testResultsAcc((A,n, c1, c2), x) - y def fitDamageAcc(tests):
64
64
86
7
56
AaronGe88inTHU/pyMaterialTestsProcess
ExperimentProcess/GISSIMO/PY/DuctileFractureAcc.py
Python
fitDamageAcc
fitDamageAcc
137
141
137
137
0c8ec81a7b5428aecba6afc2469b93d36b6b0d06
bigcode/the-stack
train
0d3c83e3a35b40f5c821e7a7
train
function
def errSimple(param, x, y): global A, n c1, c2 = param #print(Paramters.A, Paramters.n) return testResultsSimple((A,n, c1, c2), x) - y
def errSimple(param, x, y):
global A, n c1, c2 = param #print(Paramters.A, Paramters.n) return testResultsSimple((A,n, c1, c2), x) - y
Indicator) indicators[ii] = damageIndicator """ eta = tests[:, 0] theta = tests[:, 1] #epsilon = tests[:, 2] eps_cal = simplifiedMMC(eta, theta, param) return eps_cal def errSimple(param, x, y):
64
64
56
9
54
AaronGe88inTHU/pyMaterialTestsProcess
ExperimentProcess/GISSIMO/PY/DuctileFractureAcc.py
Python
errSimple
errSimple
240
244
240
240
0c470a37bd5683c938a0d2fdff832f5c47a4d106
bigcode/the-stack
train
d419939588d2af5af309935b
train
function
def simplifiedMMC(eta, thetaBar, param): """ Ref. Application of extended Mohr Coulomb criterion to ductile fracture Eq. 25 output: epsilonPlasticFailure: failure strain """ A, n, c1, c2 = param try: unit = thetaBar * np.pi / 6 #print(param) comp1 = np.sqrt((1+np.powe...
def simplifiedMMC(eta, thetaBar, param):
""" Ref. Application of extended Mohr Coulomb criterion to ductile fracture Eq. 25 output: epsilonPlasticFailure: failure strain """ A, n, c1, c2 = param try: unit = thetaBar * np.pi / 6 #print(param) comp1 = np.sqrt((1+np.power(c1, 2)) / 3) * np.cos(unit) #print(...
.legend()# ax.xaxis.set_major_locator(LinearLocator(5)) ax.yaxis.set_major_locator(LinearLocator(5)) ax.set_xlabel('Triaxiality') ax.set_ylabel('Lode Parameter') ax.set_zlabel('Effective plastic strain') plt.show() """ # In[27]: def simplifiedMMC(eta, thetaBar, param):
74
75
252
11
63
AaronGe88inTHU/pyMaterialTestsProcess
ExperimentProcess/GISSIMO/PY/DuctileFractureAcc.py
Python
simplifiedMMC
simplifiedMMC
190
213
190
190
28c0c38415bad04425a6ca723b105a79426cdd7d
bigcode/the-stack
train
0d6bc7a11310c28f306ad528
train
function
def MMCSurface(*param): eta = np.arange(-0.99, .99, 0.1) theta = np.arange(-0.99, .99, 0.1) etaX, thetaY = np.meshgrid(eta, theta, sparse=False) #z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2) #h = plt.contourf(x,y,z) epsilon = simplifiedMMC(etaX, thetaY, param) ''' lsdyna has diff...
def MMCSurface(*param):
eta = np.arange(-0.99, .99, 0.1) theta = np.arange(-0.99, .99, 0.1) etaX, thetaY = np.meshgrid(eta, theta, sparse=False) #z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2) #h = plt.contourf(x,y,z) epsilon = simplifiedMMC(etaX, thetaY, param) ''' lsdyna has different defination of lode...
026, 0.1, 500)) res = optimize.least_squares(errSimple, (0.1, 500), bounds=([0,0],[1000,10000]), args=(tests, targets)) return res # In[29]: def MMCSurface(*param):
64
64
153
7
57
AaronGe88inTHU/pyMaterialTestsProcess
ExperimentProcess/GISSIMO/PY/DuctileFractureAcc.py
Python
MMCSurface
MMCSurface
256
268
256
256
312d8cd1442990c555188c13025dfe947a0777dc
bigcode/the-stack
train
ebc11377909dbe919bc69548
train
function
def accumulatedDamage(model, eta, thetaBar, epsilon, param): """ Accumulating Damage Model input: model: Damage mode eta: eta list thetaBar: theraBar list epsilon: epsilon List param: A, n, c1, c2 output: damage Indicator """ #'epsilonMMC = np.zero...
def accumulatedDamage(model, eta, thetaBar, epsilon, param):
""" Accumulating Damage Model input: model: Damage mode eta: eta list thetaBar: theraBar list epsilon: epsilon List param: A, n, c1, c2 output: damage Indicator """ #'epsilonMMC = np.zeros(eta.shape)' #'for ii, (eta, thetaBar) in enumerate(zip...
(5)) ax.yaxis.set_major_locator(LinearLocator(5)) ax.set_xlabel('Triaxiality') ax.set_ylabel('Lode Parameter') ax.set_zlabel('Effective plastic strain') plt.show() # In[23]: def accumulatedDamage(model, eta, thetaBar, epsilon, param):
64
64
191
14
50
AaronGe88inTHU/pyMaterialTestsProcess
ExperimentProcess/GISSIMO/PY/DuctileFractureAcc.py
Python
accumulatedDamage
accumulatedDamage
88
110
88
88
6a04ef97f458a1896eccf0f8d5bccf4a82f7a898
bigcode/the-stack
train
339a5316248f7075296ac699
train
function
def fitDamageSimple(tests): targets = tests[:, 2] #result = testResults(tests,(996.68, 0.026, 0.1, 500)) res = optimize.least_squares(errSimple, (0.1, 500), bounds=([0,0],[1000,10000]), args=(tests, targets)) return res
def fitDamageSimple(tests):
targets = tests[:, 2] #result = testResults(tests,(996.68, 0.026, 0.1, 500)) res = optimize.least_squares(errSimple, (0.1, 500), bounds=([0,0],[1000,10000]), args=(tests, targets)) return res
def errSimple(param, x, y): global A, n c1, c2 = param #print(Paramters.A, Paramters.n) return testResultsSimple((A,n, c1, c2), x) - y def fitDamageSimple(tests):
64
64
83
7
56
AaronGe88inTHU/pyMaterialTestsProcess
ExperimentProcess/GISSIMO/PY/DuctileFractureAcc.py
Python
fitDamageSimple
fitDamageSimple
246
250
246
246
93dd36c5b98fe2d61a92fe12152dc91b41163af3
bigcode/the-stack
train
c40ac034a46d766c87307b37
train
function
def read_tri_lodeAlt_eps_from_fem(fileName): """ read all sheets in xls file input: fileName output: listEta, listThetaBar, listEpsilon in sheets """ xlsx = pd.ExcelFile(fileName) etaThetaEpsilon = [] for sheet in xlsx.sheet_names: #print(sheet) df = pd.re...
def read_tri_lodeAlt_eps_from_fem(fileName):
""" read all sheets in xls file input: fileName output: listEta, listThetaBar, listEpsilon in sheets """ xlsx = pd.ExcelFile(fileName) etaThetaEpsilon = [] for sheet in xlsx.sheet_names: #print(sheet) df = pd.read_excel(xlsx, sheet) eta = df.loc[:,...
pd import logging import os from scipy import interpolate, optimize from scipy import integrate import warnings warnings.filterwarnings("error") import matplotlib.pyplot as plt from matplotlib import ticker, cm from mpl_toolkits.mplot3d import Axes3D from matplotlib.ticker import LinearLocator, FormatStrFormatter # ...
86
86
287
13
73
AaronGe88inTHU/pyMaterialTestsProcess
ExperimentProcess/GISSIMO/PY/DuctileFractureAcc.py
Python
read_tri_lodeAlt_eps_from_fem
read_tri_lodeAlt_eps_from_fem
23
54
23
23
ab0de207a4639d451b618ef6bb5f68d04b31eb05
bigcode/the-stack
train
59f8990d4fa54e1b3d293a8a
train
function
def errAcc(param, x, y): global A, n c1, c2 = param #print(Paramters.A, Paramters.n) return testResultsAcc((A,n, c1, c2), x) - y
def errAcc(param, x, y):
global A, n c1, c2 = param #print(Paramters.A, Paramters.n) return testResultsAcc((A,n, c1, c2), x) - y
] theta = test[:, 1] epsilon = test[:, 2] damageIndicator = accumulatedDamage(simplifiedMMC, eta, theta, epsilon, param) #print(damageIndicator) indicators[ii] = damageIndicator return indicators def errAcc(param, x, y):
64
64
56
9
54
AaronGe88inTHU/pyMaterialTestsProcess
ExperimentProcess/GISSIMO/PY/DuctileFractureAcc.py
Python
errAcc
errAcc
131
135
131
131
0752f56ca0a95789877ea696a3994fadd6691810
bigcode/the-stack
train
b700b584e6ac743ee42400ed
train
class
class _BoundTLSProperty: """ Simple proxy object to allow either calling it to get the TLS value, or get some other informations by calling methods. """ def __init__(self, tls_property, instance, owner): self.tls_property = tls_property self.instance = instance self.owner = o...
class _BoundTLSProperty:
""" Simple proxy object to allow either calling it to get the TLS value, or get some other informations by calling methods. """ def __init__(self, tls_property, instance, owner): self.tls_property = tls_property self.instance = instance self.owner = owner def __call__(se...
drawback is that it's not possible to do anything over than getting/setting/deleting. """ def getter(instance, owner=None): prop = self.__get__(instance, owner) return prop() return property(getter, self.__set__, self.__delete__) class _BoundTLSProperty:
64
64
156
6
58
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
_BoundTLSProperty
_BoundTLSProperty
858
882
858
858
33a57e123f841547895dab4195f90fffe5230638
bigcode/the-stack
train
b9be43a742feed49e7a641f3
train
function
@wrapt.decorator def memoized(wrapped, instance, args, kwargs): # pylint: disable=unused-argument """ A decorator for memoizing functions and methods. .. warning:: this may not detect changes to mutable types. As long as the memoized function was used with an object as an argument ...
@wrapt.decorator def memoized(wrapped, instance, args, kwargs): # pylint: disable=unused-argument
""" A decorator for memoizing functions and methods. .. warning:: this may not detect changes to mutable types. As long as the memoized function was used with an object as an argument before, the cached result will be returned, even if the structure of the...
(obj_pyobj), 32) obj_bytes = ctypes.string_at(ctypes.addressof(obj_pyobj), num_bytes) return '{}/{}'.format(obj_id, obj_bytes) @wrapt.decorator def memoized(wrapped, instance, args, kwargs): # pylint: disable=unused-argument
66
66
222
28
38
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
memoized
memoized
711
732
711
712
8970a8df473a0833a0c97038c835f156c6b2edac
bigcode/the-stack
train
cbbdbe357cbab2cdb1f89681
train
function
def convert_new_lines(text): """ Convert new lines to a common format. """ return text.replace('\r\n', '\n').replace('\r', '\n')
def convert_new_lines(text):
""" Convert new lines to a common format. """ return text.replace('\r\n', '\n').replace('\r', '\n')
, dict_type) return normalized elif isinstance(value, list): return [normalize(v, dict_type) for v in value] elif isinstance(value, tuple): return tuple([normalize(v, dict_type) for v in value]) else: return value def convert_new_lines(text):
64
64
36
6
57
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
convert_new_lines
convert_new_lines
451
453
451
451
2fca18626e73ae6daafc598ec38949d90237310a
bigcode/the-stack
train
e0b91a09f02040a5d9e9aebf
train
function
def get_cpu_mask(cores): """Return a string with the hex for the cpu mask for the specified core numbers.""" mask = 0 for i in cores: mask |= 1 << i return '0x{0:x}'.format(mask)
def get_cpu_mask(cores):
"""Return a string with the hex for the cpu mask for the specified core numbers.""" mask = 0 for i in cores: mask |= 1 << i return '0x{0:x}'.format(mask)
common_path.split(sep) other_split = file_list[0].split(sep) last = len(cp_split) - 1 if cp_split[last] != other_split[last]: cp_split = cp_split[:-1] return sep.join(cp_split) def get_cpu_mask(cores):
64
64
57
7
57
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
get_cpu_mask
get_cpu_mask
546
551
546
546
2f70e4c7bf81c8dc4e929744a8fe621ef0f05334
bigcode/the-stack
train
b92fbc739b49d3b341f08ccd
train
function
def check_subprocess_output(process, timeout=None, ignore=None, inputtext=None): output = None error = None # pylint: disable=too-many-branches if ignore is None: ignore = [] elif isinstance(ignore, int): ignore = [ignore] elif not isinstance(ignore, list) and ignore != 'all': ...
def check_subprocess_output(process, timeout=None, ignore=None, inputtext=None):
output = None error = None # pylint: disable=too-many-branches if ignore is None: ignore = [] elif isinstance(ignore, int): ignore = [ignore] elif not isinstance(ignore, list) and ignore != 'all': message = 'Invalid value for ignore parameter: "{}"; must be an int or a li...
stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') with check_output_lock: process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ...
82
82
276
17
64
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
check_subprocess_output
check_subprocess_output
172
202
172
172
7bfbf79d252985782ba8246af4daee020e7b57c2
bigcode/the-stack
train
eb45152d92f9d035a2019f74
train
function
@contextmanager def nullcontext(enter_result=None): """ Backport of Python 3.7 ``contextlib.nullcontext`` This context manager does nothing, so it can be used as a default placeholder for code that needs to select at runtime what context manager to use. :param enter_result: Object that will be...
@contextmanager def nullcontext(enter_result=None):
""" Backport of Python 3.7 ``contextlib.nullcontext`` This context manager does nothing, so it can be used as a default placeholder for code that needs to select at runtime what context manager to use. :param enter_result: Object that will be bound to the target of the with statement, ...
_list: list of kwargs dictionaries to be used to call ``f``. :type kwargs_list: list(dict) """ with ExitStack() as stack: for kwargs in kwargs_list: stack.enter_context(f(**kwargs)) yield @contextmanager def nullcontext(enter_result=None):
64
64
109
12
51
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
nullcontext
nullcontext
751
764
751
752
12547466b91ecfa31e1f611141f6f854fc78e694
bigcode/the-stack
train
a7594f232a61b92fc530ae84
train
class
class LoadSyntaxError(Exception): @property def message(self): if self.args: return self.args[0] return str(self) def __init__(self, message, filepath, lineno): super(LoadSyntaxError, self).__init__(message) self.filepath = filepath self.lineno = lineno ...
class LoadSyntaxError(Exception): @property
def message(self): if self.args: return self.args[0] return str(self) def __init__(self, message, filepath, lineno): super(LoadSyntaxError, self).__init__(message) self.filepath = filepath self.lineno = lineno def __str__(self): message = 'Syntax...
ash_colors(text): return _bash_color_regex.sub('', text) def get_random_string(length): """Returns a random ASCII string of the specified length).""" return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length)) class LoadSyntaxError(Exception): @property
64
64
111
10
54
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
LoadSyntaxError
LoadSyntaxError
587
602
587
589
e53362e7dff160ccbe44373479b339e035fadec4
bigcode/the-stack
train
57f6ab698ef801ec5c8e99b9
train
function
def escape_spaces(text): """ Escape spaces in the specified text .. note:: :func:`pipes.quote` should be favored where possible. """ return text.replace(' ', '\\ ')
def escape_spaces(text):
""" Escape spaces in the specified text .. note:: :func:`pipes.quote` should be favored where possible. """ return text.replace(' ', '\\ ')
Escape double quotes, and escaped double quotes, in the specified text. .. note:: :func:`pipes.quote` should be favored where possible. """ return re.sub(r'\\("|\')', r'\\\\\1', text).replace('\"', '\\\"') def escape_spaces(text):
64
64
41
5
59
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
escape_spaces
escape_spaces
493
499
493
493
242d2a5a5b01ab569bafef61b5085f4a08e008f5
bigcode/the-stack
train
e6f80c4881d98d0e87300b08
train
function
def commonprefix(file_list, sep=os.sep): """ Find the lowest common base folder of a passed list of files. """ common_path = os.path.commonprefix(file_list) cp_split = common_path.split(sep) other_split = file_list[0].split(sep) last = len(cp_split) - 1 if cp_split[last] != other_split[l...
def commonprefix(file_list, sep=os.sep):
""" Find the lowest common base folder of a passed list of files. """ common_path = os.path.commonprefix(file_list) cp_split = common_path.split(sep) other_split = file_list[0].split(sep) last = len(cp_split) - 1 if cp_split[last] != other_split[last]: cp_split = cp_split[:-1] ...
isinstance(obj, basestring) def as_relative(path): """Convert path to relative by stripping away the leading '/' on UNIX or the equivant on other platforms.""" path = os.path.splitdrive(path)[1] return path.lstrip(os.sep) def commonprefix(file_list, sep=os.sep):
64
64
100
10
54
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
commonprefix
commonprefix
533
543
533
533
7c186cf6269b8ca26c5a5aada587fd4ecb843629
bigcode/the-stack
train
8081d4779df6c5f73c01fcf3
train
function
def list_to_ranges(values): """Converts a list, e.g ``[0,2,3,4]``, into a sysfs-style ranges string, e.g. ``"0,2-4"``""" range_groups = [] for _, g in groupby(enumerate(values), lambda i_x: i_x[0] - i_x[1]): range_groups.append(list(map(itemgetter(1), g))) range_strings = [] for group in ran...
def list_to_ranges(values):
"""Converts a list, e.g ``[0,2,3,4]``, into a sysfs-style ranges string, e.g. ``"0,2-4"``""" range_groups = [] for _, g in groupby(enumerate(values), lambda i_x: i_x[0] - i_x[1]): range_groups.append(list(map(itemgetter(1), g))) range_strings = [] for group in range_groups: if len(gr...
""" values = [] for rg in ranges_string.split(','): if '-' in rg: first, last = list(map(int, rg.split('-'))) values.extend(range(first, last + 1)) else: values.append(int(rg)) return values def list_to_ranges(values):
64
64
150
6
57
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
list_to_ranges
list_to_ranges
647
658
647
647
e53d1e9c1e4c845a9a39beec56afd6339c674fdf
bigcode/the-stack
train
22fa5de6347b9bdd0855452f
train
function
def _merge_two_dicts(base, other, list_duplicates='all', match_types=False, # pylint: disable=R0912,R0914 dict_type=dict, should_normalize=True, should_merge_lists=True): """Merge dicts normalizing their keys.""" merged = dict_type() base_keys = list(base.keys()) other_keys = list(...
def _merge_two_dicts(base, other, list_duplicates='all', match_types=False, # pylint: disable=R0912,R0914 dict_type=dict, should_normalize=True, should_merge_lists=True):
"""Merge dicts normalizing their keys.""" merged = dict_type() base_keys = list(base.keys()) other_keys = list(other.keys()) norm = normalize if should_normalize else lambda x, y: x base_only = [] other_only = [] both = [] union = [] for k in base_keys: if k in other_key...
file can be created there. The file itself is *not* going to be created if it doesn't already exist. """ ensure_directory_exists(os.path.dirname(filepath)) return filepath def merge_dicts(*args, **kwargs): if not len(args) >= 2: raise ValueError('Must specify at least two dicts to me...
144
144
480
47
97
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
_merge_two_dicts
_merge_two_dicts
302
356
302
303
09a884788599993eea8c059583a656a5234ed2a7
bigcode/the-stack
train
2e5e881acd345655eef86822
train
function
def list_to_mask(values, base=0x0): """Converts the specified list of integer values into a bit mask for those values. Optinally, the list can be applied to an existing mask.""" for v in values: base |= (1 << v) return base
def list_to_mask(values, base=0x0):
"""Converts the specified list of integer values into a bit mask for those values. Optinally, the list can be applied to an existing mask.""" for v in values: base |= (1 << v) return base
for group in range_groups: if len(group) == 1: range_strings.append(str(group[0])) else: range_strings.append('{}-{}'.format(group[0], group[-1])) return ','.join(range_strings) def list_to_mask(values, base=0x0):
64
64
66
12
52
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
list_to_mask
list_to_mask
661
667
661
661
07eec9d5576283af1ace4b8e89e0012e8c5faa71
bigcode/the-stack
train
b2d181bbe8a99988d8bd1150
train
function
def get_subprocess(command, **kwargs): if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') with check_output_lock: process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=s...
def get_subprocess(command, **kwargs):
if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') with check_output_lock: process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ...
_output_logger = logging.getLogger('check_output') # Popen is not thread safe. If two threads attempt to call it at the same time, # one may lock up. See https://bugs.python.org/issue12739. check_output_lock = threading.RLock() def get_subprocess(command, **kwargs):
64
64
77
9
55
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
get_subprocess
get_subprocess
159
169
159
159
816e9d8000f2e320e3c8bfa9414d4e59807c8f17
bigcode/the-stack
train
a58006d6a26268066304f0af
train
function
def reset_memo_cache(): __memo_cache.clear()
def reset_memo_cache():
__memo_cache.clear()
in the mask.""" size = len(bin(mask)) - 2 # because of "0b" return [size - i - 1 for i in range(size) if mask & (1 << size - i - 1)] __memo_cache = {} def reset_memo_cache():
63
64
12
6
57
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
reset_memo_cache
reset_memo_cache
681
682
681
681
70ffdd8f974853684de99a12eed38c84aacd2762
bigcode/the-stack
train
3164d7e732860e58c3067d36
train
function
def sanitize_cmd_template(cmd): msg = ( '''Quoted placeholder should not be used, as it will result in quoting the text twice. {} should be used instead of '{}' or "{}" in the template: ''' ) for unwanted in ('"{}"', "'{}'"): if unwanted in cmd: warnings.warn(msg + cmd, stackleve...
def sanitize_cmd_template(cmd):
msg = ( '''Quoted placeholder should not be used, as it will result in quoting the text twice. {} should be used instead of '{}' or "{}" in the template: ''' ) for unwanted in ('"{}"', "'{}'"): if unwanted in cmd: warnings.warn(msg + cmd, stacklevel=2) cmd = cmd.repla...
return tuple([normalize(v, dict_type) for v in value]) else: return value def convert_new_lines(text): """ Convert new lines to a common format. """ return text.replace('\r\n', '\n').replace('\r', '\n') def sanitize_cmd_template(cmd):
64
64
90
6
58
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
sanitize_cmd_template
sanitize_cmd_template
455
464
455
455
834b128e4137e6ebc1e3980c10868267b54a11d9
bigcode/the-stack
train
bce5316fcedc4c98d9fe909e
train
function
def ensure_file_directory_exists(filepath): """ A filter for file paths to ensure the directory of the file exists and the file can be created there. The file itself is *not* going to be created if it doesn't already exist. """ ensure_directory_exists(os.path.dirname(filepath)) return f...
def ensure_file_directory_exists(filepath):
""" A filter for file paths to ensure the directory of the file exists and the file can be created there. The file itself is *not* going to be created if it doesn't already exist. """ ensure_directory_exists(os.path.dirname(filepath)) return filepath
quote(command), suffix1, suffix2) return (stdout, stderr, command) def ensure_directory_exists(dirpath): """A filter for directory paths to ensure they exist.""" if not os.path.isdir(dirpath): os.makedirs(dirpath) return dirpath def ensure_file_directory_exists(filepath):
64
64
69
7
56
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
ensure_file_directory_exists
ensure_file_directory_exists
283
292
283
283
e4ed3b8ef3522730c4d2653a10fb76b172826657
bigcode/the-stack
train
cbfd3dfba3b52d2b2e8f1213
train
class
class tls_property: """ Use it like `property` decorator, but the result will be memoized per thread. When the owning thread dies, the values for that thread will be destroyed. In order to get the values, it's necessary to call the object given by the property. This is necessary in order to be ...
class tls_property:
""" Use it like `property` decorator, but the result will be memoized per thread. When the owning thread dies, the values for that thread will be destroyed. In order to get the values, it's necessary to call the object given by the property. This is necessary in order to be able to add methods ...
arguments dict in the given list, in one go. :param f: Callable expected to return a context manager. :param kwargs_list: list of kwargs dictionaries to be used to call ``f``. :type kwargs_list: list(dict) """ with ExitStack() as stack: for kwargs in kwargs_list: stack.ent...
195
195
652
4
190
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
tls_property
tls_property
767
856
767
767
76d6c21fe2425aa4ee7f19ccc053039d5163822c
bigcode/the-stack
train
1cf94efba284937dd737fd23
train
function
def __get_memo_id(obj): """ An object's id() may be re-used after an object is freed, so it's not sufficiently unique to identify params for the memo cache (two different params may end up with the same id). this attempts to generate a more unique ID string. """ obj_id = id(obj) try: ...
def __get_memo_id(obj):
""" An object's id() may be re-used after an object is freed, so it's not sufficiently unique to identify params for the memo cache (two different params may end up with the same id). this attempts to generate a more unique ID string. """ obj_id = id(obj) try: return '{}/{}'.form...
integer bitmask into a list of indexes of bits that are set in the mask.""" size = len(bin(mask)) - 2 # because of "0b" return [size - i - 1 for i in range(size) if mask & (1 << size - i - 1)] __memo_cache = {} def reset_memo_cache(): __memo_cache.clear() def __get_memo_id(obj):
93
93
310
8
85
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
__get_memo_id
__get_memo_id
685
708
685
685
4b587e8e0a808c9d731109602f2781b9aa188550
bigcode/the-stack
train
e04a6375062937ffa0b28098
train
function
def redirect_streams(stdout, stderr, command): """ Update a command to redirect a given stream to /dev/null if it's ``subprocess.DEVNULL``. :return: A tuple (stdout, stderr, command) with stream set to ``subprocess.PIPE`` if the `stream` parameter was set to ``subprocess.DEVNULL``. """ ...
def redirect_streams(stdout, stderr, command):
""" Update a command to redirect a given stream to /dev/null if it's ``subprocess.DEVNULL``. :return: A tuple (stdout, stderr, command) with stream set to ``subprocess.PIPE`` if the `stream` parameter was set to ``subprocess.DEVNULL``. """ def redirect(stream, redirection): if s...
_mod.__path__): submod_path = '.'.join([path, name]) if ispkg: mods.extend(walk_modules(submod_path)) else: submod = __try_import(submod_path) mods.append(submod) return mods def redirect_streams(stdout, stderr, command):
67
67
226
10
56
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
redirect_streams
redirect_streams
249
274
249
249
7b738e442851768e86f303951ad56c18e62747a0
bigcode/the-stack
train
a2ab008a1c052ce749a98b73
train
function
def escape_single_quotes(text): """ Escape single quotes, and escaped single quotes, in the specified text. .. note:: :func:`pipes.quote` should be favored where possible. """ return re.sub(r'\\("|\')', r'\\\\\1', text).replace('\'', '\'\\\'\'')
def escape_single_quotes(text):
""" Escape single quotes, and escaped single quotes, in the specified text. .. note:: :func:`pipes.quote` should be favored where possible. """ return re.sub(r'\\("|\')', r'\\\\\1', text).replace('\'', '\'\\\'\'')
quotes, in the specified text. .. note:: :func:`pipes.quote` should be favored where possible. """ return re.sub(r'\\("|\')', r'\\\\\1', text).replace('\'', '\\\'').replace('\"', '\\\"') def escape_single_quotes(text):
64
64
69
6
58
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
escape_single_quotes
escape_single_quotes
475
481
475
475
b57183bfa9134622a779f3a9cc01da2144380581
bigcode/the-stack
train
44c075c01ba6480563c7a5b6
train
function
def which(name): """Platform-independent version of UNIX which utility.""" if os.name == 'nt': paths = os.getenv('PATH').split(os.pathsep) exts = os.getenv('PATHEXT').split(os.pathsep) for path in paths: testpath = os.path.join(path, name) if os.path.isfile(testpa...
def which(name):
"""Platform-independent version of UNIX which utility.""" if os.name == 'nt': paths = os.getenv('PATH').split(os.pathsep) exts = os.getenv('PATHEXT').split(os.pathsep) for path in paths: testpath = os.path.join(path, name) if os.path.isfile(testpath): ...
(cp_split) def get_cpu_mask(cores): """Return a string with the hex for the cpu mask for the specified core numbers.""" mask = 0 for i in cores: mask |= 1 << i return '0x{0:x}'.format(mask) def which(name):
64
64
167
4
60
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
which
which
554
572
554
554
e1482827d3d407b05d30cadadcef3b9ff810d196
bigcode/the-stack
train
02e629947055265e9e7683aa
train
function
def escape_quotes(text): """ Escape quotes, and escaped quotes, in the specified text. .. note:: :func:`pipes.quote` should be favored where possible. """ return re.sub(r'\\("|\')', r'\\\\\1', text).replace('\'', '\\\'').replace('\"', '\\\"')
def escape_quotes(text):
""" Escape quotes, and escaped quotes, in the specified text. .. note:: :func:`pipes.quote` should be favored where possible. """ return re.sub(r'\\("|\')', r'\\\\\1', text).replace('\'', '\\\'').replace('\"', '\\\"')
be used instead of '{}' or "{}" in the template: ''' ) for unwanted in ('"{}"', "'{}'"): if unwanted in cmd: warnings.warn(msg + cmd, stacklevel=2) cmd = cmd.replace(unwanted, '{}') return cmd def escape_quotes(text):
64
64
71
5
58
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
escape_quotes
escape_quotes
466
472
466
466
2eae4f35a1fae2c90de8ef44920063412fdaf1b1
bigcode/the-stack
train
87f950c1159cf08126e522eb
train
function
def strip_bash_colors(text): return _bash_color_regex.sub('', text)
def strip_bash_colors(text):
return _bash_color_regex.sub('', text)
: disable=E1103 except subprocess.CalledProcessError: return None # This matches most ANSI escape sequences, not just colors _bash_color_regex = re.compile(r'\x1b\[[0-9;]*[a-zA-Z]') def strip_bash_colors(text):
63
64
17
7
57
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
strip_bash_colors
strip_bash_colors
578
579
578
578
4d551e2a01d8d983434f3cdbfea0f54c3d3d9e8a
bigcode/the-stack
train
45458ef1c0cfca21b6c6db2d
train
function
def to_identifier(text): """Converts text to a valid Python identifier by replacing all whitespace and punctuation and adding a prefix if starting with a digit""" if text[:1].isdigit(): text = '_' + text return re.sub('_+', '_', str(text).translate(TRANS_TABLE))
def to_identifier(text):
"""Converts text to a valid Python identifier by replacing all whitespace and punctuation and adding a prefix if starting with a digit""" if text[:1].isdigit(): text = '_' + text return re.sub('_+', '_', str(text).translate(TRANS_TABLE))
-member if sys.version_info[0] == 3: TRANS_TABLE = str.maketrans(BAD_CHARS, '_' * len(BAD_CHARS)) else: TRANS_TABLE = string.maketrans(BAD_CHARS, '_' * len(BAD_CHARS)) def to_identifier(text):
64
64
64
5
59
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
to_identifier
to_identifier
614
619
614
614
00b1f6c0a68b990d3c3f9974412a2f89b0c6c663
bigcode/the-stack
train
974a13770d477315213fca74
train
function
def get_cpu_name(implementer, part, variant): part_data = CPU_PART_MAP.get(implementer, {}).get(part, {}) if None in part_data: # variant does not determine core Name for this vendor name = part_data[None] else: name = part_data.get(variant) return name
def get_cpu_name(implementer, part, variant):
part_data = CPU_PART_MAP.get(implementer, {}).get(part, {}) if None in part_data: # variant does not determine core Name for this vendor name = part_data[None] else: name = part_data.get(variant) return name
x1: 'MongooseM1'}, }, 0x56: { # Marvell 0x131: { 0x2: 'Feroceon 88F6281', } }, } def get_cpu_name(implementer, part, variant):
64
64
72
12
52
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
get_cpu_name
get_cpu_name
136
142
136
136
23a5db6eaba1eab634239f65664594c7f199dfa7
bigcode/the-stack
train
b35d6f4868fc39241b765b08
train
function
def getch(count=1): """Read ``count`` characters from standard input.""" if os.name == 'nt': import msvcrt # pylint: disable=F0401 return ''.join([msvcrt.getch() for _ in range(count)]) else: # assume Unix import tty # NOQA import termios # NOQA fd = sys.stdin.fil...
def getch(count=1):
"""Read ``count`` characters from standard input.""" if os.name == 'nt': import msvcrt # pylint: disable=F0401 return ''.join([msvcrt.getch() for _ in range(count)]) else: # assume Unix import tty # NOQA import termios # NOQA fd = sys.stdin.fileno() old_se...
r'\\\\\1', text).replace('\"', '\\\"') def escape_spaces(text): """ Escape spaces in the specified text .. note:: :func:`pipes.quote` should be favored where possible. """ return text.replace(' ', '\\ ') def getch(count=1):
63
64
147
7
56
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
getch
getch
502
517
502
502
260e308f5fb4d3af39c842ad1fb2491e7fe219d0
bigcode/the-stack
train
99f72a062f0f0c45c81536ee
train
function
def _merge_two_lists(base, other, duplicates='all', dict_type=dict): # pylint: disable=R0912 """ Merge lists, normalizing their entries. parameters: :base, other: the two lists to be merged. ``other`` will be merged on top of base. :duplicates: Indicates the strategy...
def _merge_two_lists(base, other, duplicates='all', dict_type=dict): # pylint: disable=R0912
""" Merge lists, normalizing their entries. parameters: :base, other: the two lists to be merged. ``other`` will be merged on top of base. :duplicates: Indicates the strategy of handling entries that appear in both lists. ``all`` will keep occurre...
merged[k] = norm(base_value.union(other_value), dict_type) else: merged[k] = norm(other_value, dict_type) else: # Should never get here raise AssertionError('Unexpected merge key: {}'.format(k)) return merged def merge_lists(*args, **kwargs): if not len(args)...
135
135
453
27
108
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
_merge_two_lists
_merge_two_lists
366
417
366
366
9977cff530628590007a76bb78517fc4b27854a9
bigcode/the-stack
train
018cf6b1ee5d9266c4e40c1f
train
function
@contextmanager def batch_contextmanager(f, kwargs_list): """ Return a context manager that will call the ``f`` callable with the keyword arguments dict in the given list, in one go. :param f: Callable expected to return a context manager. :param kwargs_list: list of kwargs dictionaries to be used...
@contextmanager def batch_contextmanager(f, kwargs_list):
""" Return a context manager that will call the ``f`` callable with the keyword arguments dict in the given list, in one go. :param f: Callable expected to return a context manager. :param kwargs_list: list of kwargs dictionaries to be used to call ``f``. :type kwargs_list: list(dict) """ ...
k, v in kwargs.items()) if id_string not in __memo_cache: __memo_cache[id_string] = wrapped(*args, **kwargs) return __memo_cache[id_string] return memoize_wrapper(*args, **kwargs) @contextmanager def batch_contextmanager(f, kwargs_list):
64
64
113
13
51
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
batch_contextmanager
batch_contextmanager
734
748
734
735
8a82eec348b2d6dfafb59e2d98f323a3dc866384
bigcode/the-stack
train
92abed861f3c132c2467239c
train
function
def mask_to_list(mask): """Converts the specfied integer bitmask into a list of indexes of bits that are set in the mask.""" size = len(bin(mask)) - 2 # because of "0b" return [size - i - 1 for i in range(size) if mask & (1 << size - i - 1)]
def mask_to_list(mask):
"""Converts the specfied integer bitmask into a list of indexes of bits that are set in the mask.""" size = len(bin(mask)) - 2 # because of "0b" return [size - i - 1 for i in range(size) if mask & (1 << size - i - 1)]
0x0): """Converts the specified list of integer values into a bit mask for those values. Optinally, the list can be applied to an existing mask.""" for v in values: base |= (1 << v) return base def mask_to_list(mask):
64
64
80
6
57
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
mask_to_list
mask_to_list
670
675
670
670
f14a38db2cdb38a91fe2c764e1836ad86d43e30d
bigcode/the-stack
train
45652aaaaa3771d2a111e901
train
function
def unique(alist): """ Returns a list containing only unique elements from the input list (but preserves order, unlike sets). """ result = [] for item in alist: if item not in result: result.append(item) return result
def unique(alist):
""" Returns a list containing only unique elements from the input list (but preserves order, unlike sets). """ result = [] for item in alist: if item not in result: result.append(item) return result
"""Converts text to a valid Python identifier by replacing all whitespace and punctuation and adding a prefix if starting with a digit""" if text[:1].isdigit(): text = '_' + text return re.sub('_+', '_', str(text).translate(TRANS_TABLE)) def unique(alist):
64
64
58
5
59
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
unique
unique
622
632
622
622
37d90727e0c93153816b99033df43c6e9abf9718
bigcode/the-stack
train
f8f0312fd4e4771034f643e4
train
function
def preexec_function(): # Change process group in case we have to kill the subprocess and all of # its children later. # TODO: this is Unix-specific; would be good to find an OS-agnostic way # to do this in case we wanna port WA to Windows. os.setpgrp()
def preexec_function(): # Change process group in case we have to kill the subprocess and all of # its children later. # TODO: this is Unix-specific; would be good to find an OS-agnostic way # to do this in case we wanna port WA to Windows.
os.setpgrp()
def preexec_function(): # Change process group in case we have to kill the subprocess and all of # its children later. # TODO: this is Unix-specific; would be good to find an OS-agnostic way # to do this in case we wanna port WA to Windows.
64
64
70
64
0
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
preexec_function
preexec_function
145
150
145
149
fe96c3a1864c1ce0826f50e5565def8dbafa73c6
bigcode/the-stack
train
25ee49d82fb6eb8e9a512abe
train
class
class InitCheckpoint(metaclass=InitCheckpointMeta): """ Inherit from this class to set the :class:`InitCheckpointMeta` metaclass. """ pass
class InitCheckpoint(metaclass=InitCheckpointMeta):
""" Inherit from this class to set the :class:`InitCheckpointMeta` metaclass. """ pass
property( fget=make_wrapper(attr.fget), fset=make_wrapper(attr.fset), fdel=make_wrapper(attr.fdel), doc=attr.__doc__, ) setattr(cls, name, prop) return cls class InitCheckpoint(metaclass=InitCheckpo...
64
64
37
11
52
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
InitCheckpoint
InitCheckpoint
969
973
969
969
63993d0d229f5c2b61e5eaf3364370406adc799e
bigcode/the-stack
train
1d6032d7a3dec5916a6737f9
train
function
def merge_dicts(*args, **kwargs): if not len(args) >= 2: raise ValueError('Must specify at least two dicts to merge.') func = partial(_merge_two_dicts, **kwargs) return reduce(func, args)
def merge_dicts(*args, **kwargs):
if not len(args) >= 2: raise ValueError('Must specify at least two dicts to merge.') func = partial(_merge_two_dicts, **kwargs) return reduce(func, args)
to ensure the directory of the file exists and the file can be created there. The file itself is *not* going to be created if it doesn't already exist. """ ensure_directory_exists(os.path.dirname(filepath)) return filepath def merge_dicts(*args, **kwargs):
64
64
55
10
53
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
merge_dicts
merge_dicts
295
299
295
295
62f5064b979039714bbed653c336513a148bc932
bigcode/the-stack
train
cc3c60013d1ca4e7988b9d4a
train
function
def _check_remove_item(the_list, item): """Helper function for merge_lists that implements checking wether an items should be removed from the list and doing so if needed. Returns ``True`` if the item has been removed and ``False`` otherwise.""" if not isinstance(item, basestring): return False ...
def _check_remove_item(the_list, item):
"""Helper function for merge_lists that implements checking wether an items should be removed from the list and doing so if needed. Returns ``True`` if the item has been removed and ``False`` otherwise.""" if not isinstance(item, basestring): return False if not item.startswith('~'): ...
_list, v): merged_list.append(v) return merged_list else: raise ValueError('Unexpected value for list duplicates argument: {}. '.format(duplicates) + 'Must be in {"all", "first", "last"}.') def _check_remove_item(the_list, item):
64
64
112
10
54
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
_check_remove_item
_check_remove_item
420
431
420
420
0e2385e98dd0533cf28c1f2ed25dd7a9eb4c3551
bigcode/the-stack
train
46bc6730b5f371e1e88804f6
train
function
def as_relative(path): """Convert path to relative by stripping away the leading '/' on UNIX or the equivant on other platforms.""" path = os.path.splitdrive(path)[1] return path.lstrip(os.sep)
def as_relative(path):
"""Convert path to relative by stripping away the leading '/' on UNIX or the equivant on other platforms.""" path = os.path.splitdrive(path)[1] return path.lstrip(os.sep)
RAIN, old_settings) return ch def isiterable(obj): """Returns ``True`` if the specified object is iterable and *is not a string type*, ``False`` otherwise.""" return hasattr(obj, '__iter__') and not isinstance(obj, basestring) def as_relative(path):
64
64
48
5
59
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
as_relative
as_relative
526
530
526
526
6c01741f560b152382407c3133e2ac4b3924f8f0
bigcode/the-stack
train
d559918294f2aaacdeb2afa5
train
function
def get_random_string(length): """Returns a random ASCII string of the specified length).""" return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))
def get_random_string(length):
"""Returns a random ASCII string of the specified length).""" return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))
return None # This matches most ANSI escape sequences, not just colors _bash_color_regex = re.compile(r'\x1b\[[0-9;]*[a-zA-Z]') def strip_bash_colors(text): return _bash_color_regex.sub('', text) def get_random_string(length):
64
64
40
6
58
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
get_random_string
get_random_string
582
584
582
582
1773a94fb5e07cca0a8e428438892d871086474c
bigcode/the-stack
train
65c3027f61348435f2fa8a98
train
function
def normalize(value, dict_type=dict): """Normalize values. Recursively normalizes dict keys to be lower case, no surrounding whitespace, underscore-delimited strings.""" if isinstance(value, dict): normalized = dict_type() for k, v in value.items(): key = k.strip().lower().replac...
def normalize(value, dict_type=dict):
"""Normalize values. Recursively normalizes dict keys to be lower case, no surrounding whitespace, underscore-delimited strings.""" if isinstance(value, dict): normalized = dict_type() for k, v in value.items(): key = k.strip().lower().replace(' ', '_') normalized[key...
if not isinstance(item, basestring): return False if not item.startswith('~'): return False actual_item = item[1:] if actual_item in the_list: del the_list[the_list.index(actual_item)] return True def normalize(value, dict_type=dict):
64
64
134
8
55
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
normalize
normalize
434
448
434
434
44213b29356c8655ffa0714888acc543b51ccb37
bigcode/the-stack
train
5a0ed49974b6f56d878ea46c
train
function
def groupby_value(dct): """ Process the input dict such that all keys sharing the same values are grouped in a tuple, used as key in the returned dict. """ key = itemgetter(1) items = sorted(dct.items(), key=key) return { tuple(map(itemgetter(0), _items)): v for v, _items in ...
def groupby_value(dct):
""" Process the input dict such that all keys sharing the same values are grouped in a tuple, used as key in the returned dict. """ key = itemgetter(1) items = sorted(dct.items(), key=key) return { tuple(map(itemgetter(0), _items)): v for v, _items in groupby(items, key=key) ...
doc=attr.__doc__, ) setattr(cls, name, prop) return cls class InitCheckpoint(metaclass=InitCheckpointMeta): """ Inherit from this class to set the :class:`InitCheckpointMeta` metaclass. """ pass def groupby_value(dct):
64
64
93
7
56
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
groupby_value
groupby_value
976
986
976
976
45bc00299e17a817e1f2fa75683ea7e3765cf809
bigcode/the-stack
train
abd7d05c6d9dbf96b73c2a8c
train
function
def isiterable(obj): """Returns ``True`` if the specified object is iterable and *is not a string type*, ``False`` otherwise.""" return hasattr(obj, '__iter__') and not isinstance(obj, basestring)
def isiterable(obj):
"""Returns ``True`` if the specified object is iterable and *is not a string type*, ``False`` otherwise.""" return hasattr(obj, '__iter__') and not isinstance(obj, basestring)
ileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(count) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch def isiterable(obj):
64
64
50
6
57
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
isiterable
isiterable
520
523
520
520
f977506baf0fd2644112691dea51b31645e54ec3
bigcode/the-stack
train
289d91d8f7787ccd94bc7b77
train
function
def ensure_directory_exists(dirpath): """A filter for directory paths to ensure they exist.""" if not os.path.isdir(dirpath): os.makedirs(dirpath) return dirpath
def ensure_directory_exists(dirpath):
"""A filter for directory paths to ensure they exist.""" if not os.path.isdir(dirpath): os.makedirs(dirpath) return dirpath
, suffix) stdout, suffix1 = redirect(stdout, '>') stderr, suffix2 = redirect(stderr, '2>') command = 'sh -c {} {} {}'.format(quote(command), suffix1, suffix2) return (stdout, stderr, command) def ensure_directory_exists(dirpath):
64
64
39
7
57
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
ensure_directory_exists
ensure_directory_exists
276
280
276
276
4f2a5eef447b45fac8bc196553d6e83f595ddb15
bigcode/the-stack
train
497eaf14e5c0c74f16c22860
train
function
def check_output(command, timeout=None, ignore=None, inputtext=None, **kwargs): """This is a version of subprocess.check_output that adds a timeout parameter to kill the subprocess if it does not return within the specified time.""" process = get_subprocess(command, **kwargs) return check_subprocess_out...
def check_output(command, timeout=None, ignore=None, inputtext=None, **kwargs):
"""This is a version of subprocess.check_output that adds a timeout parameter to kill the subprocess if it does not return within the specified time.""" process = get_subprocess(command, **kwargs) return check_subprocess_output(process, timeout=timeout, ignore=ignore, inputtext=inputtext)
retcode = process.poll() if retcode and ignore != 'all' and retcode not in ignore: raise subprocess.CalledProcessError(retcode, process.args, output, error) return output, error def check_output(command, timeout=None, ignore=None, inputtext=None, **kwargs):
64
64
81
18
45
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
check_output
check_output
205
209
205
205
12e66433e22ca9977f5e897c8f41dbcdd9173a52
bigcode/the-stack
train
707614cb7c40aaa030cbea7d
train
function
def escape_double_quotes(text): """ Escape double quotes, and escaped double quotes, in the specified text. .. note:: :func:`pipes.quote` should be favored where possible. """ return re.sub(r'\\("|\')', r'\\\\\1', text).replace('\"', '\\\"')
def escape_double_quotes(text):
""" Escape double quotes, and escaped double quotes, in the specified text. .. note:: :func:`pipes.quote` should be favored where possible. """ return re.sub(r'\\("|\')', r'\\\\\1', text).replace('\"', '\\\"')
, and escaped single quotes, in the specified text. .. note:: :func:`pipes.quote` should be favored where possible. """ return re.sub(r'\\("|\')', r'\\\\\1', text).replace('\'', '\'\\\'\'') def escape_double_quotes(text):
63
64
67
6
57
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
escape_double_quotes
escape_double_quotes
484
490
484
484
85dd5fb2e8c029b1f5f5cac0e512cba84f037ec0
bigcode/the-stack
train
65a625061017a9788c79b552
train
class
class InitCheckpointMeta(type): """ Metaclass providing an ``initialized`` and ``is_in_use`` boolean attributes on instances. ``initialized`` is set to ``True`` once the ``__init__`` constructor has returned. It will deal cleanly with nested calls to ``super().__init__``. ``is_in_use`` is set ...
class InitCheckpointMeta(type):
""" Metaclass providing an ``initialized`` and ``is_in_use`` boolean attributes on instances. ``initialized`` is set to ``True`` once the ``__init__`` constructor has returned. It will deal cleanly with nested calls to ``super().__init__``. ``is_in_use`` is set to ``True`` when an instance met...
owner) return prop() return property(getter, self.__set__, self.__delete__) class _BoundTLSProperty: """ Simple proxy object to allow either calling it to get the TLS value, or get some other informations by calling methods. """ def __init__(self, tls_property, instance, owner...
182
182
607
6
176
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
InitCheckpointMeta
InitCheckpointMeta
885
966
885
885
b71df50b5ab3c64a65589de7febc82fe0eb6ec6a
bigcode/the-stack
train
383aa35b5919c0583400ad7f
train
function
def ranges_to_list(ranges_string): """Converts a sysfs-style ranges string, e.g. ``"0,2-4"``, into a list ,e.g ``[0,2,3,4]``""" values = [] for rg in ranges_string.split(','): if '-' in rg: first, last = list(map(int, rg.split('-'))) values.extend(range(first, last + 1)) ...
def ranges_to_list(ranges_string):
"""Converts a sysfs-style ranges string, e.g. ``"0,2-4"``, into a list ,e.g ``[0,2,3,4]``""" values = [] for rg in ranges_string.split(','): if '-' in rg: first, last = list(map(int, rg.split('-'))) values.extend(range(first, last + 1)) else: values.append...
(alist): """ Returns a list containing only unique elements from the input list (but preserves order, unlike sets). """ result = [] for item in alist: if item not in result: result.append(item) return result def ranges_to_list(ranges_string):
64
64
106
8
55
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
ranges_to_list
ranges_to_list
635
644
635
635
62d1f4d11f160356cffcf40cd170f70ce1913a5b
bigcode/the-stack
train
41668be960ccaa8b6e14be8b
train
function
def merge_lists(*args, **kwargs): if not len(args) >= 2: raise ValueError('Must specify at least two lists to merge.') func = partial(_merge_two_lists, **kwargs) return reduce(func, args)
def merge_lists(*args, **kwargs):
if not len(args) >= 2: raise ValueError('Must specify at least two lists to merge.') func = partial(_merge_two_lists, **kwargs) return reduce(func, args)
[k] = norm(base_value.union(other_value), dict_type) else: merged[k] = norm(other_value, dict_type) else: # Should never get here raise AssertionError('Unexpected merge key: {}'.format(k)) return merged def merge_lists(*args, **kwargs):
64
64
52
9
54
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
merge_lists
merge_lists
359
363
359
359
f6ccd3305bbac29f404f2c28cb7c5f1334d81b67
bigcode/the-stack
train
26ff3b0586c68ff4e008f5e4
train
function
def walk_modules(path): """ Given package name, return a list of all modules (including submodules, etc) in that package. :raises HostError: if an exception is raised while trying to import one of the modules under ``path``. The exception will have addtional ...
def walk_modules(path):
""" Given package name, return a list of all modules (including submodules, etc) in that package. :raises HostError: if an exception is raised while trying to import one of the modules under ``path``. The exception will have addtional attributes set: ``modu...
check_output(command, timeout=None, ignore=None, inputtext=None, **kwargs): """This is a version of subprocess.check_output that adds a timeout parameter to kill the subprocess if it does not return within the specified time.""" process = get_subprocess(command, **kwargs) return check_subprocess_output...
85
85
286
5
80
douglas-raillard-arm/lisa
external/devlib/devlib/utils/misc.py
Python
walk_modules
walk_modules
212
247
212
212
3f9f150b1bcb4f063494b2d41e54d43eb44d708a
bigcode/the-stack
train
0aceeedeb5d8cd99e7d543d0
train
function
def test_ogr_libkml_check_write_kmz_use_doc_off(): return ogr_libkml_check_write('/vsimem/libkml_use_doc_off.kmz')
def test_ogr_libkml_check_write_kmz_use_doc_off():
return ogr_libkml_check_write('/vsimem/libkml_use_doc_off.kmz')
_DOC.KML", "NO") ret = ogr_libkml_write('/vsimem/libkml_use_doc_off.kmz') gdal.SetConfigOption("LIBKML_USE_DOC.KML", None) return ret def test_ogr_libkml_check_write_kmz_use_doc_off():
64
64
36
15
48
VirtualTim/gdal
autotest/ogr/ogr_libkml.py
Python
test_ogr_libkml_check_write_kmz_use_doc_off
test_ogr_libkml_check_write_kmz_use_doc_off
464
465
464
464
850d27d0cd6f69f90c818171cac1a380463d350a
bigcode/the-stack
train
7f14a64d3e4b8d6f57d24f6b
train
function
def test_ogr_libkml_write_update(): if not ogrtest.have_read_libkml: pytest.skip() for i in range(3): if i == 0: name = "/vsimem/ogr_libkml_write_update.kml" elif i == 1: name = "/vsimem/ogr_libkml_write_update.kmz" else: name = "/vsimem/ogr...
def test_ogr_libkml_write_update():
if not ogrtest.have_read_libkml: pytest.skip() for i in range(3): if i == 0: name = "/vsimem/ogr_libkml_write_update.kml" elif i == 1: name = "/vsimem/ogr_libkml_write_update.kmz" else: name = "/vsimem/ogr_libkml_write_update_dir" ds...
</IconStyle> </Style> <StyleMap id="style1"> <Pair> <key>normal</key> <styleUrl>#style1_normal</styleUrl> </Pair> <Pair> <key>highlight</key> <styleUrl>#style1_highlight</styleUrl> </Pair> </StyleMap>""" lines_got = lines[lines.index('<Style id="...
162
162
543
10
151
VirtualTim/gdal
autotest/ogr/ogr_libkml.py
Python
test_ogr_libkml_write_update
test_ogr_libkml_write_update
1,377
1,425
1,377
1,378
a9b06342a1803d91d76c1667f42a87bb2bb4078f
bigcode/the-stack
train
82e57a692a45752c2adb1c75
train
function
def test_ogr_libkml_xml_attributes(): if not ogrtest.have_read_libkml: pytest.skip() ds = ogr.Open('data/kml/description_with_xml.kml') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() if feat.GetField('description').find('Description<br></br><i attr="val">Interesting</i><br></br>') != 0...
def test_ogr_libkml_xml_attributes():
if not ogrtest.have_read_libkml: pytest.skip() ds = ogr.Open('data/kml/description_with_xml.kml') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() if feat.GetField('description').find('Description<br></br><i attr="val">Interesting</i><br></br>') != 0: print('got: %s ' % feat.GetFi...
for filename in files: gdal.Unlink('/vsimem/libkmldir/' + filename) gdal.Rmdir('/vsimem/libkmldir') return ret ############################################################################### # Test reading attributes with XML content in them # def test_ogr_libkml_xml_attributes():
63
64
120
10
53
VirtualTim/gdal
autotest/ogr/ogr_libkml.py
Python
test_ogr_libkml_xml_attributes
test_ogr_libkml_xml_attributes
488
502
488
489
6e7687902e51136a92edd6b2647bff97f1f58b8e
bigcode/the-stack
train
e274ef9271fc8db29050232e
train
function
def test_ogr_libkml_attributes_4(): if not ogrtest.have_read_libkml: pytest.skip() kml_ds = ogr.Open('data/kml/samples.kml') lyr = kml_ds.GetLayerByName('Google Campus') feat = lyr.GetNextFeature() i = 40 while feat is not None: name = 'Building %d' % i if feat.GetFie...
def test_ogr_libkml_attributes_4():
if not ogrtest.have_read_libkml: pytest.skip() kml_ds = ogr.Open('data/kml/samples.kml') lyr = kml_ds.GetLayerByName('Google Campus') feat = lyr.GetNextFeature() i = 40 while feat is not None: name = 'Building %d' % i if feat.GetField('Name') != name: print...
a simple straight-line path from point to point', \ 'Wrong description field value' feat = lyr.GetNextFeature() assert feat is not None, 'expected feature not found.' ############################################################################### # Test reading attributes for another layer (polygon)....
63
64
156
11
52
VirtualTim/gdal
autotest/ogr/ogr_libkml.py
Python
test_ogr_libkml_attributes_4
test_ogr_libkml_attributes_4
195
215
195
196
6ac4f9a574ce37cea3fbc88f6c604af793f0f37c
bigcode/the-stack
train
4f1325bcc47b9cc722f64113
train
function
def test_ogr_libkml_write_liststyle(): if not ogrtest.have_read_libkml: pytest.skip() options = ['LISTSTYLE_ICON_HREF=http://www.gdal.org/gdalicon.png'] ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_write_liststyle.kml", options=options) ds.CreateLayer('test', options...
def test_ogr_libkml_write_liststyle():
if not ogrtest.have_read_libkml: pytest.skip() options = ['LISTSTYLE_ICON_HREF=http://www.gdal.org/gdalicon.png'] ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_write_liststyle.kml", options=options) ds.CreateLayer('test', options=['LISTSTYLE_ICON_HREF=http://foo']) ...
') == -1 or \ data.find('<cookie>cookie</cookie>') == -1 or \ data.find('<message>message</message>') == -1 or \ data.find('<linkName>linkname</linkName>') == -1 or \ data.find('<linkDescription>linkdescription</linkDescription>') == -1 or \ ...
142
142
474
11
130
VirtualTim/gdal
autotest/ogr/ogr_libkml.py
Python
test_ogr_libkml_write_liststyle
test_ogr_libkml_write_liststyle
1,484
1,514
1,484
1,485
46a91c594caa569e75ce561ff48eeec7af440ab5
bigcode/the-stack
train
bded0cffab96dc3102fb86e1
train
function
def test_ogr_libkml_write_container_properties(): if not ogrtest.have_read_libkml: pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_write_container_properties.kml", options=['NAME=ds_name', 'DESCRIPTION=ds_des...
def test_ogr_libkml_write_container_properties():
if not ogrtest.have_read_libkml: pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_write_container_properties.kml", options=['NAME=ds_name', 'DESCRIPTION=ds_description', 'OPEN=1', 'VISIBILITY=1', 'SNIPPET=ds_sn...
assert (not (data.find('<Style id="test_liststyle">') == -1 or \ data.find('<href>http://foo</href>') == -1 or \ data.find('<Folder id="test">') == -1 or \ data.find('<styleUrl>#test_liststyle</styleUrl>') == -1 or \ data.find('<Folder id="test2">') == -1)) #############################...
113
113
378
11
101
VirtualTim/gdal
autotest/ogr/ogr_libkml.py
Python
test_ogr_libkml_write_container_properties
test_ogr_libkml_write_container_properties
1,728
1,752
1,728
1,729
f3890434bb2a3e2d8b5863a9f9b64cf9c313ed9b
bigcode/the-stack
train
cb2ebde99a4a713adccbfb72
train
function
def test_ogr_libkml_read_empty(): if not ogrtest.have_read_libkml: pytest.skip() ds = ogr.Open('data/kml/empty.kml') assert ds.GetLayerCount() == 0 ds = None
def test_ogr_libkml_read_empty():
if not ogrtest.have_read_libkml: pytest.skip() ds = ogr.Open('data/kml/empty.kml') assert ds.GetLayerCount() == 0 ds = None
ds = ogr.Open('data/kml/placemark.kml') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() assert feat is not None ds = None ############################################################################### # Test reading KML without any layer def test_ogr_libkml_read_empty():
64
64
55
10
53
VirtualTim/gdal
autotest/ogr/ogr_libkml.py
Python
test_ogr_libkml_read_empty
test_ogr_libkml_read_empty
560
568
560
561
9680dc2ef207ae631fbd41cef308b6fc17840499
bigcode/the-stack
train
3d345b78ffc0a3be8392aac6
train
function
def test_ogr_libkml_write_atom_link(): if not ogrtest.have_read_libkml: pytest.skip() filepath = '/vsimem/ogr_libkml_write_atom_link.kml' ds = ogr.GetDriverByName('LIBKML').CreateDataSource(filepath, options=['link=http://foo']) assert ds...
def test_ogr_libkml_write_atom_link():
if not ogrtest.have_read_libkml: pytest.skip() filepath = '/vsimem/ogr_libkml_write_atom_link.kml' ds = ogr.GetDriverByName('LIBKML').CreateDataSource(filepath, options=['link=http://foo']) assert ds is not None, ('Unable to create %s.' % ...
</atom:uri>') == -1 or \ data.find('<atom:email>foo@bar.com</atom:email>') == -1)), \ 'failure to find an atom string' ############################################################################### # Test writing <atom:link> def test_ogr_libkml_write_atom_link():
64
64
213
11
53
VirtualTim/gdal
autotest/ogr/ogr_libkml.py
Python
test_ogr_libkml_write_atom_link
test_ogr_libkml_write_atom_link
943
960
943
944
4ef4f577d5ed54aeb233cefb3c419d37f775532a
bigcode/the-stack
train
9b1f1f72cefcdc71b92b53ee
train
function
def test_ogr_libkml_read_tab_separated_coord_triplet(): if not ogrtest.have_read_libkml: pytest.skip() ds = ogr.Open('data/kml/tab_separated_coord_triplet.kml') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() wkt = 'LINESTRING Z (1 2 3,4 5 6)' assert not ogrtest.check_feature_geomet...
def test_ogr_libkml_read_tab_separated_coord_triplet():
if not ogrtest.have_read_libkml: pytest.skip() ds = ogr.Open('data/kml/tab_separated_coord_triplet.kml') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() wkt = 'LINESTRING Z (1 2 3,4 5 6)' assert not ogrtest.check_feature_geometry(feat, wkt)
lyr = ds.GetLayerByName('SubFolder1') assert lyr is not None assert lyr.GetFeatureCount() == 1 ############################################################################### # Test reading KML with coordinate tuples separated by tabulations (#7231) def test_ogr_libkml_read_tab_separated_coord_triplet():
64
64
101
15
49
VirtualTim/gdal
autotest/ogr/ogr_libkml.py
Python
test_ogr_libkml_read_tab_separated_coord_triplet
test_ogr_libkml_read_tab_separated_coord_triplet
1,826
1,837
1,826
1,827
cac93a814caf1bf97cb21c6d6c5aae92644e265e
bigcode/the-stack
train
dce443846a91555e6426e5e3
train
function
def test_ogr_libkml_camera(): if not ogrtest.have_read_libkml: pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_camera.kml") lyr = ds.CreateLayer('test') lyr.CreateField(ogr.FieldDefn("heading", ogr.OFTReal)) lyr.CreateField(ogr.FieldDefn("tilt", ogr.OF...
def test_ogr_libkml_camera():
if not ogrtest.have_read_libkml: pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_camera.kml") lyr = ds.CreateLayer('test') lyr.CreateField(ogr.FieldDefn("heading", ogr.OFTReal)) lyr.CreateField(ogr.FieldDefn("tilt", ogr.OFTReal)) lyr.CreateField(ogr...
Readable() pytest.fail() ds = None ############################################################################### # Test reading KML with <gx:MultiTrack> element def test_ogr_libkml_gxmultitrack(): if not ogrtest.have_read_libkml: pytest.skip() ds = ogr.Open('data/kml/gxmultitrack.kml'...
204
204
682
9
194
VirtualTim/gdal
autotest/ogr/ogr_libkml.py
Python
test_ogr_libkml_camera
test_ogr_libkml_camera
716
775
716
717
b699113e8a2a4ca32e58a2bb2d91fc647e8a4301
bigcode/the-stack
train
6b7a1cbb02275b0730b85ce5
train
function
def test_ogr_libkml_write_layer_lookat(): if not ogrtest.have_read_libkml: pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_write_layer_lookat.kml") options = ['LOOKAT_LONGITUDE=2', 'LOOKAT_LATITUDE=49', 'LOOKAT_RANGE=150'] ds.CreateLayer('test', options=op...
def test_ogr_libkml_write_layer_lookat():
if not ogrtest.have_read_libkml: pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_write_layer_lookat.kml") options = ['LOOKAT_LONGITUDE=2', 'LOOKAT_LATITUDE=49', 'LOOKAT_RANGE=150'] ds.CreateLayer('test', options=options) options = ['LOOKAT_LONGITUDE=3',...
feat.DumpReadable() pytest.fail() feat = lyr.GetNextFeature() if (feat.GetGeometryRef().ExportToWkt() != 'POINT (3 50 1)' or feat.GetField("heading") != -70.0 or feat.IsFieldSet("tilt") or feat.IsFieldSet("roll") or feat.GetField("altitudeMode") != 'relativeToGround...
133
133
446
13
119
VirtualTim/gdal
autotest/ogr/ogr_libkml.py
Python
test_ogr_libkml_write_layer_lookat
test_ogr_libkml_write_layer_lookat
781
811
781
782
ecd271cc079aac6c93a5ffb800c5e456d6e9e494
bigcode/the-stack
train
fb4d806eac187019e5b49c2b
train
function
def test_ogr_libkml_check_write_kml(): return ogr_libkml_check_write('/vsimem/libkml.kml')
def test_ogr_libkml_check_write_kml():
return ogr_libkml_check_write('/vsimem/libkml.kml')
0,2 3 0))', \ 'Unexpected geometry.' ds = None ############################################################################### def test_ogr_libkml_write_kml(): return ogr_libkml_write('/vsimem/libkml.kml') def test_ogr_libkml_check_write_kml():
64
64
30
12
52
VirtualTim/gdal
autotest/ogr/ogr_libkml.py
Python
test_ogr_libkml_check_write_kml
test_ogr_libkml_check_write_kml
445
446
445
445
72e23a5c1a42dd44c81987032f42989c146c6857
bigcode/the-stack
train
5ccc9a81a4ad87dc8c6c9a6f
train
function
def ogr_libkml_write(filename): ds = ogr.GetDriverByName('LIBKML').CreateDataSource(filename) if filename != '/vsimem/libkml_use_doc_off.kmz': srs = osr.SpatialReference() srs.SetWellKnownGeogCS('WGS72') lyr = ds.CreateLayer('test_wgs72', srs=srs) dst_feat = ogr.Feature(lyr.Ge...
def ogr_libkml_write(filename):
ds = ogr.GetDriverByName('LIBKML').CreateDataSource(filename) if filename != '/vsimem/libkml_use_doc_off.kmz': srs = osr.SpatialReference() srs.SetWellKnownGeogCS('WGS72') lyr = ds.CreateLayer('test_wgs72', srs=srs) dst_feat = ogr.Feature(lyr.GetLayerDefn()) dst_feat.Se...
37.421515697788713 19,-122.082850226966499 37.421762825764652 19,-122.082943578863507 37.421767769696352 19,-122.083217411188002 37.421792485526858 19,-122.0835970430103 37.421748007445601 19,-122.083945555677104 37.421693642376027 19,-122.084007789463698 37.421762838158529 19,-122.084113587521003 37.421748011043917 1...
256
256
954
8
247
VirtualTim/gdal
autotest/ogr/ogr_libkml.py
Python
ogr_libkml_write
ogr_libkml_write
324
383
324
325
c0a6dc36eb4cf574f270a52ac03f01c0dec5cb23
bigcode/the-stack
train
e9464eaa259b1fae244e9399
train
function
def test_ogr_libkml_check_write_dir(): if not ogrtest.have_read_libkml: pytest.skip() ret = ogr_libkml_check_write('/vsimem/libkmldir') files = gdal.ReadDir('/vsimem/libkmldir') for filename in files: gdal.Unlink('/vsimem/libkmldir/' + filename) gdal.Rmdir('/vsimem/libkmldir') r...
def test_ogr_libkml_check_write_dir():
if not ogrtest.have_read_libkml: pytest.skip() ret = ogr_libkml_check_write('/vsimem/libkmldir') files = gdal.ReadDir('/vsimem/libkmldir') for filename in files: gdal.Unlink('/vsimem/libkmldir/' + filename) gdal.Rmdir('/vsimem/libkmldir') return ret
_kmz_use_doc_off(): return ogr_libkml_check_write('/vsimem/libkml_use_doc_off.kmz') def test_ogr_libkml_write_dir(): return ogr_libkml_write('/vsimem/libkmldir') def test_ogr_libkml_check_write_dir():
64
64
101
11
53
VirtualTim/gdal
autotest/ogr/ogr_libkml.py
Python
test_ogr_libkml_check_write_dir
test_ogr_libkml_check_write_dir
472
481
472
472
3a612bfade595372ed96a4dd3dad405451a7ce79
bigcode/the-stack
train
b7a2f36125d943d325dc12c2
train
function
def test_ogr_libkml_write_kmz(): return ogr_libkml_write('/vsimem/libkml.kmz')
def test_ogr_libkml_write_kmz():
return ogr_libkml_write('/vsimem/libkml.kmz')
kml_write_kml(): return ogr_libkml_write('/vsimem/libkml.kml') def test_ogr_libkml_check_write_kml(): return ogr_libkml_check_write('/vsimem/libkml.kml') def test_ogr_libkml_write_kmz():
64
64
28
11
53
VirtualTim/gdal
autotest/ogr/ogr_libkml.py
Python
test_ogr_libkml_write_kmz
test_ogr_libkml_write_kmz
449
450
449
449
37b66832286eec37974dc84bdf78311448411543
bigcode/the-stack
train
ce11b2b7cebfbf246cb68bde
train
function
def test_ogr_libkml_polygon_read(): if not ogrtest.have_read_libkml: pytest.skip() kml_ds = ogr.Open('data/kml/samples.kml') lyr = kml_ds.GetLayerByName('Google Campus') lyr.ResetReading() feat = lyr.GetNextFeature() wkt = 'POLYGON ((-122.084893845961204 37.422571240447859 17,-122.08...
def test_ogr_libkml_polygon_read():
if not ogrtest.have_read_libkml: pytest.skip() kml_ds = ogr.Open('data/kml/samples.kml') lyr = kml_ds.GetLayerByName('Google Campus') lyr.ResetReading() feat = lyr.GetNextFeature() wkt = 'POLYGON ((-122.084893845961204 37.422571240447859 17,-122.084958097919795 37.422119226268563 17,-...
found.' wkt = 'LINESTRING (-112.265654928602004 36.094476726025462 2357,-112.266038452823807 36.093426088386707 2357,-112.266813901345301 36.092510587768807 2357,-112.267782683444494 36.091898273579957 2357,-112.268855751095202 36.091313794118697 2357,-112.269481071721899 36.090367720752099 2357,-112.269526855561...
255
256
1,847
10
245
VirtualTim/gdal
autotest/ogr/ogr_libkml.py
Python
test_ogr_libkml_polygon_read
test_ogr_libkml_polygon_read
288
318
288
289
6fb41bd485fbd0842339f59ae19044a001e6ac69
bigcode/the-stack
train
ef261980a64e8a218823a731
train
function
def test_ogr_libkml_read_emptylayers_without_folder(): if not ogrtest.have_read_libkml: pytest.skip() ds = ogr.Open('data/kml/emptylayers_without_folder.kml') assert ds.GetLayerCount() == 1 # --> One difference with the old KML driver assert ds.GetLayer(0).GetName() == 'Test', \ (...
def test_ogr_libkml_read_emptylayers_without_folder():
if not ogrtest.have_read_libkml: pytest.skip() ds = ogr.Open('data/kml/emptylayers_without_folder.kml') assert ds.GetLayerCount() == 1 # --> One difference with the old KML driver assert ds.GetLayer(0).GetName() == 'Test', \ ("Layer name must be '" + ds.GetLayer(0).GetName() + "'."...
Count() == 1 assert ds.GetLayer(1).GetFeatureCount() == 0 ds = None ############################################################################### # Test reading KML with empty layers ############################################################################### # Test reading KML with empty layers withou...
64
64
109
13
50
VirtualTim/gdal
autotest/ogr/ogr_libkml.py
Python
test_ogr_libkml_read_emptylayers_without_folder
test_ogr_libkml_read_emptylayers_without_folder
596
608
596
597
85f32ae0de517fcee03af837acadb5d17499ea98
bigcode/the-stack
train
b52127a932a2c368e7126f76
train
function
def test_ogr_libkml_gxmultitrack(): if not ogrtest.have_read_libkml: pytest.skip() ds = ogr.Open('data/kml/gxmultitrack.kml') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() if feat.GetField('begin') != '2013/05/28 12:00:00' or \ feat.GetField('end') != '2013/05/28 13:00:00' or \ ...
def test_ogr_libkml_gxmultitrack():
if not ogrtest.have_read_libkml: pytest.skip() ds = ogr.Open('data/kml/gxmultitrack.kml') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() if feat.GetField('begin') != '2013/05/28 12:00:00' or \ feat.GetField('end') != '2013/05/28 13:00:00' or \ feat.GetGeometryRef().ExportTo...
().ExportToWkt() != 'LINESTRING (2 49,3 50)': feat.DumpReadable() pytest.fail() ds = None ############################################################################### # Test reading KML with <gx:MultiTrack> element def test_ogr_libkml_gxmultitrack():
64
64
153
13
50
VirtualTim/gdal
autotest/ogr/ogr_libkml.py
Python
test_ogr_libkml_gxmultitrack
test_ogr_libkml_gxmultitrack
696
710
696
697
ca4fc4cb3b7804da4a97d38da5c370d8f472bb9b
bigcode/the-stack
train
c25e2c753191b5208be5dfe4
train
function
def test_ogr_libkml_read_geometries(): if not ogrtest.have_read_libkml: pytest.skip() ds = ogr.Open('data/kml/geometries.kml') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() while feat is not None: feat = lyr.GetNextFeature() ds = None
def test_ogr_libkml_read_geometries():
if not ogrtest.have_read_libkml: pytest.skip() ds = ogr.Open('data/kml/geometries.kml') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() while feat is not None: feat = lyr.GetNextFeature() ds = None
br></br>') != 0: print('got: %s ' % feat.GetField('description')) pytest.fail('Wrong description field value') ds = None ############################################################################### # Test reading all geometry types (#3558) # def test_ogr_libkml_read_geometries():
63
64
79
12
51
VirtualTim/gdal
autotest/ogr/ogr_libkml.py
Python
test_ogr_libkml_read_geometries
test_ogr_libkml_read_geometries
509
521
509
510
3210d195cca9bac9aa8841f6104334bb334f0925
bigcode/the-stack
train
8ae8f932725b3f80706df1ae
train
function
def test_ogr_libkml_write_screenoverlay(): if not ogrtest.have_read_libkml: pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_write_screenoverlay.kml") ds.CreateLayer('auto', options=['SO_HREF=http://foo']) ds.CreateLayer('manual', options=['SO_HREF=http://b...
def test_ogr_libkml_write_screenoverlay():
if not ogrtest.have_read_libkml: pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_write_screenoverlay.kml") ds.CreateLayer('auto', options=['SO_HREF=http://foo']) ds.CreateLayer('manual', options=['SO_HREF=http://bar', '...
>') == -1 or \ data.find('<east>180</east>') == -1 or \ data.find('<west>-180</west>') == -1 or \ data.find('<minLodPixels>128</minLodPixels>') == -1 or \ data.find('<maxLodPixels>10000000</maxLodPixels>') == -1 or \ data.find('<minFadeExtent>1</minFadeExtent>') == -1 or \ data...
143
143
479
11
131
VirtualTim/gdal
autotest/ogr/ogr_libkml.py
Python
test_ogr_libkml_write_screenoverlay
test_ogr_libkml_write_screenoverlay
1,029
1,065
1,029
1,030
73c4e33d803af314eee1b7b0f9fbff43a2068b49
bigcode/the-stack
train
914c1e753c49026259697ab7
train
function
def test_ogr_libkml_write_multigeometry(): if not ogrtest.have_read_libkml: pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_write_multigeometry.kml") lyr = ds.CreateLayer('test') feat = ogr.Feature(lyr.GetLayerDefn()) # Transformed into POINT per ATC 6...
def test_ogr_libkml_write_multigeometry():
if not ogrtest.have_read_libkml: pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_write_multigeometry.kml") lyr = ds.CreateLayer('test') feat = ogr.Feature(lyr.GetLayerDefn()) # Transformed into POINT per ATC 66 feat.SetGeometry(ogr.CreateGeometryFro...
heading>70</heading>') == -1 or \ data.find('<tilt>50</tilt>') == -1 or \ data.find('<roll>10</roll>') == -1 or \ data.find('<altitudeMode>relativeToGround</altitudeMode>') == -1)) ############################################################################### # Test writing MultiGeometry def test...
87
87
291
12
74
VirtualTim/gdal
autotest/ogr/ogr_libkml.py
Python
test_ogr_libkml_write_multigeometry
test_ogr_libkml_write_multigeometry
846
874
846
847
b645142f3863135ebcdf607f9a370ed20a967cb3
bigcode/the-stack
train
292d5cac38f4194f51590e68
train
function
def test_ogr_libkml_write_kmz_use_doc_off(): gdal.SetConfigOption("LIBKML_USE_DOC.KML", "NO") ret = ogr_libkml_write('/vsimem/libkml_use_doc_off.kmz') gdal.SetConfigOption("LIBKML_USE_DOC.KML", None) return ret
def test_ogr_libkml_write_kmz_use_doc_off():
gdal.SetConfigOption("LIBKML_USE_DOC.KML", "NO") ret = ogr_libkml_write('/vsimem/libkml_use_doc_off.kmz') gdal.SetConfigOption("LIBKML_USE_DOC.KML", None) return ret
_kmz(): return ogr_libkml_write('/vsimem/libkml.kmz') def test_ogr_libkml_check_write_kmz(): return ogr_libkml_check_write('/vsimem/libkml.kmz') def test_ogr_libkml_write_kmz_use_doc_off():
64
64
74
14
50
VirtualTim/gdal
autotest/ogr/ogr_libkml.py
Python
test_ogr_libkml_write_kmz_use_doc_off
test_ogr_libkml_write_kmz_use_doc_off
457
461
457
457
be2389a7a613275701a45e08480eb7ebe2193de6
bigcode/the-stack
train
a333fa53453c8ab6b0a451e7
train
function
def test_ogr_libkml_attributes_1(): if not ogrtest.have_read_libkml: pytest.skip() kml_ds = ogr.Open('data/kml/samples.kml') lyr = kml_ds.GetLayerByName('Placemarks') feat = lyr.GetNextFeature() assert feat.GetField('Name') == 'Simple placemark', 'Wrong name field value' if feat.Get...
def test_ogr_libkml_attributes_1():
if not ogrtest.have_read_libkml: pytest.skip() kml_ds = ogr.Open('data/kml/samples.kml') lyr = kml_ds.GetLayerByName('Placemarks') feat = lyr.GetNextFeature() assert feat.GetField('Name') == 'Simple placemark', 'Wrong name field value' if feat.GetField('description')[:23] != 'Attache...
/ogr_libkml_write_folder.kml") gdal.Unlink("/vsimem/ogr_libkml_write_container_properties.kml") # Re-register LIBKML driver if necessary if kml_drv is not None: print('Re-register KML driver') kml_drv.Register() ##############################################################################...
89
90
300
11
78
VirtualTim/gdal
autotest/ogr/ogr_libkml.py
Python
test_ogr_libkml_attributes_1
test_ogr_libkml_attributes_1
100
132
100
101
c0a2433ef54d834e1f439c7083d920d4df4fe367
bigcode/the-stack
train
230a14d2adad1288aa7a53ae
train
function
def test_ogr_libkml_write_photooverlay(): if not ogrtest.have_read_libkml: pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_write_photooverlay.kml") lyr = ds.CreateLayer('test') lyr.CreateField(ogr.FieldDefn('name', ogr.OFTString)) lyr.CreateField(ogr.F...
def test_ogr_libkml_write_photooverlay():
if not ogrtest.have_read_libkml: pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_write_photooverlay.kml") lyr = ds.CreateLayer('test') lyr.CreateField(ogr.FieldDefn('name', ogr.OFTString)) lyr.CreateField(ogr.FieldDefn("heading", ogr.OFTReal)) lyr.C...
\ data.find('<flyToView>1</flyToView>') == -1 or \ data.find('<href>http://developers.google.com/kml/documentation/Point.kml</href>') == -1 or \ data.find('<refreshMode>onInterval</refreshMode>') == -1 or \ data.find('<refreshInterval>60</refreshInterval>') == -1 or \ data.find('<htt...
256
256
1,198
11
244
VirtualTim/gdal
autotest/ogr/ogr_libkml.py
Python
test_ogr_libkml_write_photooverlay
test_ogr_libkml_write_photooverlay
1,586
1,664
1,586
1,587
8be20b44b88233eff6a28c9b742f1ee4170da4c4
bigcode/the-stack
train