repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
bsolomon1124/pyfinance | pyfinance/utils.py | _uniquewords | def _uniquewords(*args):
"""Dictionary of words to their indices. Helper function to `encode.`"""
words = {}
n = 0
for word in itertools.chain(*args):
if word not in words:
words[word] = n
n += 1
return words | python | def _uniquewords(*args):
"""Dictionary of words to their indices. Helper function to `encode.`"""
words = {}
n = 0
for word in itertools.chain(*args):
if word not in words:
words[word] = n
n += 1
return words | [
"def",
"_uniquewords",
"(",
"*",
"args",
")",
":",
"words",
"=",
"{",
"}",
"n",
"=",
"0",
"for",
"word",
"in",
"itertools",
".",
"chain",
"(",
"*",
"args",
")",
":",
"if",
"word",
"not",
"in",
"words",
":",
"words",
"[",
"word",
"]",
"=",
"n",
... | Dictionary of words to their indices. Helper function to `encode.` | [
"Dictionary",
"of",
"words",
"to",
"their",
"indices",
".",
"Helper",
"function",
"to",
"encode",
"."
] | c95925209a809b4e648e79cbeaf7711d8e5ff1a6 | https://github.com/bsolomon1124/pyfinance/blob/c95925209a809b4e648e79cbeaf7711d8e5ff1a6/pyfinance/utils.py#L418-L426 | train | 204,300 |
bsolomon1124/pyfinance | pyfinance/utils.py | encode | def encode(*args):
"""One-hot encode the given input strings."""
args = [arg.split() for arg in args]
unique = _uniquewords(*args)
feature_vectors = np.zeros((len(args), len(unique)))
for vec, s in zip(feature_vectors, args):
for word in s:
vec[unique[word]] = 1
return feature_vectors | python | def encode(*args):
"""One-hot encode the given input strings."""
args = [arg.split() for arg in args]
unique = _uniquewords(*args)
feature_vectors = np.zeros((len(args), len(unique)))
for vec, s in zip(feature_vectors, args):
for word in s:
vec[unique[word]] = 1
return feature_vectors | [
"def",
"encode",
"(",
"*",
"args",
")",
":",
"args",
"=",
"[",
"arg",
".",
"split",
"(",
")",
"for",
"arg",
"in",
"args",
"]",
"unique",
"=",
"_uniquewords",
"(",
"*",
"args",
")",
"feature_vectors",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",... | One-hot encode the given input strings. | [
"One",
"-",
"hot",
"encode",
"the",
"given",
"input",
"strings",
"."
] | c95925209a809b4e648e79cbeaf7711d8e5ff1a6 | https://github.com/bsolomon1124/pyfinance/blob/c95925209a809b4e648e79cbeaf7711d8e5ff1a6/pyfinance/utils.py#L429-L437 | train | 204,301 |
bsolomon1124/pyfinance | pyfinance/utils.py | unique_everseen | def unique_everseen(iterable, filterfalse_=itertools.filterfalse):
"""Unique elements, preserving order."""
# Itertools recipes:
# https://docs.python.org/3/library/itertools.html#itertools-recipes
seen = set()
seen_add = seen.add
for element in filterfalse_(seen.__contains__, iterable):
seen_add(element)
yield element | python | def unique_everseen(iterable, filterfalse_=itertools.filterfalse):
"""Unique elements, preserving order."""
# Itertools recipes:
# https://docs.python.org/3/library/itertools.html#itertools-recipes
seen = set()
seen_add = seen.add
for element in filterfalse_(seen.__contains__, iterable):
seen_add(element)
yield element | [
"def",
"unique_everseen",
"(",
"iterable",
",",
"filterfalse_",
"=",
"itertools",
".",
"filterfalse",
")",
":",
"# Itertools recipes:\r",
"# https://docs.python.org/3/library/itertools.html#itertools-recipes\r",
"seen",
"=",
"set",
"(",
")",
"seen_add",
"=",
"seen",
".",
... | Unique elements, preserving order. | [
"Unique",
"elements",
"preserving",
"order",
"."
] | c95925209a809b4e648e79cbeaf7711d8e5ff1a6 | https://github.com/bsolomon1124/pyfinance/blob/c95925209a809b4e648e79cbeaf7711d8e5ff1a6/pyfinance/utils.py#L768-L776 | train | 204,302 |
otto-torino/django-baton | baton/views.py | GetAppListJsonView.dispatch | def dispatch(self, *args, **kwargs):
""" Only staff members can access this view """
return super(GetAppListJsonView, self).dispatch(*args, **kwargs) | python | def dispatch(self, *args, **kwargs):
""" Only staff members can access this view """
return super(GetAppListJsonView, self).dispatch(*args, **kwargs) | [
"def",
"dispatch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"GetAppListJsonView",
",",
"self",
")",
".",
"dispatch",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Only staff members can access this view | [
"Only",
"staff",
"members",
"can",
"access",
"this",
"view"
] | e791b5db3a0814bb49d8dfbdfb989d45e03594b7 | https://github.com/otto-torino/django-baton/blob/e791b5db3a0814bb49d8dfbdfb989d45e03594b7/baton/views.py#L15-L17 | train | 204,303 |
otto-torino/django-baton | baton/views.py | GetAppListJsonView.get | def get(self, request):
""" Returns a json representing the menu voices
in a format eaten by the js menu.
Raised ImproperlyConfigured exceptions can be viewed
in the browser console
"""
self.app_list = site.get_app_list(request)
self.apps_dict = self.create_app_list_dict()
# no menu provided
items = get_config('MENU')
if not items:
voices = self.get_default_voices()
else:
voices = []
for item in items:
self.add_voice(voices, item)
return JsonResponse(voices, safe=False) | python | def get(self, request):
""" Returns a json representing the menu voices
in a format eaten by the js menu.
Raised ImproperlyConfigured exceptions can be viewed
in the browser console
"""
self.app_list = site.get_app_list(request)
self.apps_dict = self.create_app_list_dict()
# no menu provided
items = get_config('MENU')
if not items:
voices = self.get_default_voices()
else:
voices = []
for item in items:
self.add_voice(voices, item)
return JsonResponse(voices, safe=False) | [
"def",
"get",
"(",
"self",
",",
"request",
")",
":",
"self",
".",
"app_list",
"=",
"site",
".",
"get_app_list",
"(",
"request",
")",
"self",
".",
"apps_dict",
"=",
"self",
".",
"create_app_list_dict",
"(",
")",
"# no menu provided",
"items",
"=",
"get_conf... | Returns a json representing the menu voices
in a format eaten by the js menu.
Raised ImproperlyConfigured exceptions can be viewed
in the browser console | [
"Returns",
"a",
"json",
"representing",
"the",
"menu",
"voices",
"in",
"a",
"format",
"eaten",
"by",
"the",
"js",
"menu",
".",
"Raised",
"ImproperlyConfigured",
"exceptions",
"can",
"be",
"viewed",
"in",
"the",
"browser",
"console"
] | e791b5db3a0814bb49d8dfbdfb989d45e03594b7 | https://github.com/otto-torino/django-baton/blob/e791b5db3a0814bb49d8dfbdfb989d45e03594b7/baton/views.py#L19-L36 | train | 204,304 |
otto-torino/django-baton | baton/views.py | GetAppListJsonView.add_voice | def add_voice(self, voices, item):
""" Adds a voice to the list
"""
voice = None
if item.get('type') == 'title':
voice = self.get_title_voice(item)
elif item.get('type') == 'app':
voice = self.get_app_voice(item)
elif item.get('type') == 'model':
voice = self.get_app_model_voice(item)
elif item.get('type') == 'free':
voice = self.get_free_voice(item)
if voice:
voices.append(voice) | python | def add_voice(self, voices, item):
""" Adds a voice to the list
"""
voice = None
if item.get('type') == 'title':
voice = self.get_title_voice(item)
elif item.get('type') == 'app':
voice = self.get_app_voice(item)
elif item.get('type') == 'model':
voice = self.get_app_model_voice(item)
elif item.get('type') == 'free':
voice = self.get_free_voice(item)
if voice:
voices.append(voice) | [
"def",
"add_voice",
"(",
"self",
",",
"voices",
",",
"item",
")",
":",
"voice",
"=",
"None",
"if",
"item",
".",
"get",
"(",
"'type'",
")",
"==",
"'title'",
":",
"voice",
"=",
"self",
".",
"get_title_voice",
"(",
"item",
")",
"elif",
"item",
".",
"g... | Adds a voice to the list | [
"Adds",
"a",
"voice",
"to",
"the",
"list"
] | e791b5db3a0814bb49d8dfbdfb989d45e03594b7 | https://github.com/otto-torino/django-baton/blob/e791b5db3a0814bb49d8dfbdfb989d45e03594b7/baton/views.py#L38-L51 | train | 204,305 |
otto-torino/django-baton | baton/views.py | GetAppListJsonView.get_title_voice | def get_title_voice(self, item):
""" Title voice
Returns the js menu compatible voice dict if the user
can see it, None otherwise
"""
view = True
if item.get('perms', None):
view = self.check_user_permission(item.get('perms', []))
elif item.get('apps', None):
view = self.check_apps_permission(item.get('apps', []))
if view:
return {
'type': 'title',
'label': item.get('label', ''),
'icon': item.get('icon', None)
}
return None | python | def get_title_voice(self, item):
""" Title voice
Returns the js menu compatible voice dict if the user
can see it, None otherwise
"""
view = True
if item.get('perms', None):
view = self.check_user_permission(item.get('perms', []))
elif item.get('apps', None):
view = self.check_apps_permission(item.get('apps', []))
if view:
return {
'type': 'title',
'label': item.get('label', ''),
'icon': item.get('icon', None)
}
return None | [
"def",
"get_title_voice",
"(",
"self",
",",
"item",
")",
":",
"view",
"=",
"True",
"if",
"item",
".",
"get",
"(",
"'perms'",
",",
"None",
")",
":",
"view",
"=",
"self",
".",
"check_user_permission",
"(",
"item",
".",
"get",
"(",
"'perms'",
",",
"[",
... | Title voice
Returns the js menu compatible voice dict if the user
can see it, None otherwise | [
"Title",
"voice",
"Returns",
"the",
"js",
"menu",
"compatible",
"voice",
"dict",
"if",
"the",
"user",
"can",
"see",
"it",
"None",
"otherwise"
] | e791b5db3a0814bb49d8dfbdfb989d45e03594b7 | https://github.com/otto-torino/django-baton/blob/e791b5db3a0814bb49d8dfbdfb989d45e03594b7/baton/views.py#L53-L69 | train | 204,306 |
otto-torino/django-baton | baton/views.py | GetAppListJsonView.get_free_voice | def get_free_voice(self, item):
""" Free voice
Returns the js menu compatible voice dict if the user
can see it, None otherwise
"""
view = True
if item.get('perms', None):
view = self.check_user_permission(item.get('perms', []))
elif item.get('apps', None):
view = self.check_apps_permission(item.get('apps', []))
if view:
return {
'type': 'free',
'label': item.get('label', ''),
'icon': item.get('icon', None),
'url': item.get('url', None)
}
return None | python | def get_free_voice(self, item):
""" Free voice
Returns the js menu compatible voice dict if the user
can see it, None otherwise
"""
view = True
if item.get('perms', None):
view = self.check_user_permission(item.get('perms', []))
elif item.get('apps', None):
view = self.check_apps_permission(item.get('apps', []))
if view:
return {
'type': 'free',
'label': item.get('label', ''),
'icon': item.get('icon', None),
'url': item.get('url', None)
}
return None | [
"def",
"get_free_voice",
"(",
"self",
",",
"item",
")",
":",
"view",
"=",
"True",
"if",
"item",
".",
"get",
"(",
"'perms'",
",",
"None",
")",
":",
"view",
"=",
"self",
".",
"check_user_permission",
"(",
"item",
".",
"get",
"(",
"'perms'",
",",
"[",
... | Free voice
Returns the js menu compatible voice dict if the user
can see it, None otherwise | [
"Free",
"voice",
"Returns",
"the",
"js",
"menu",
"compatible",
"voice",
"dict",
"if",
"the",
"user",
"can",
"see",
"it",
"None",
"otherwise"
] | e791b5db3a0814bb49d8dfbdfb989d45e03594b7 | https://github.com/otto-torino/django-baton/blob/e791b5db3a0814bb49d8dfbdfb989d45e03594b7/baton/views.py#L71-L89 | train | 204,307 |
otto-torino/django-baton | baton/views.py | GetAppListJsonView.get_app_voice | def get_app_voice(self, item):
""" App voice
Returns the js menu compatible voice dict if the user
can see it, None otherwise
"""
if item.get('name', None) is None:
raise ImproperlyConfigured('App menu voices must have a name key')
if self.check_apps_permission([item.get('name', None)]):
children = []
if item.get('models', None) is None:
for name, model in self.apps_dict[item.get('name')]['models'].items(): # noqa
children.append({
'type': 'model',
'label': model.get('name', ''),
'url': model.get('admin_url', '')
})
else:
for model_item in item.get('models', []):
voice = self.get_model_voice(item.get('name'), model_item)
if voice:
children.append(voice)
return {
'type': 'app',
'label': item.get('label', ''),
'icon': item.get('icon', None),
'children': children
}
return None | python | def get_app_voice(self, item):
""" App voice
Returns the js menu compatible voice dict if the user
can see it, None otherwise
"""
if item.get('name', None) is None:
raise ImproperlyConfigured('App menu voices must have a name key')
if self.check_apps_permission([item.get('name', None)]):
children = []
if item.get('models', None) is None:
for name, model in self.apps_dict[item.get('name')]['models'].items(): # noqa
children.append({
'type': 'model',
'label': model.get('name', ''),
'url': model.get('admin_url', '')
})
else:
for model_item in item.get('models', []):
voice = self.get_model_voice(item.get('name'), model_item)
if voice:
children.append(voice)
return {
'type': 'app',
'label': item.get('label', ''),
'icon': item.get('icon', None),
'children': children
}
return None | [
"def",
"get_app_voice",
"(",
"self",
",",
"item",
")",
":",
"if",
"item",
".",
"get",
"(",
"'name'",
",",
"None",
")",
"is",
"None",
":",
"raise",
"ImproperlyConfigured",
"(",
"'App menu voices must have a name key'",
")",
"if",
"self",
".",
"check_apps_permis... | App voice
Returns the js menu compatible voice dict if the user
can see it, None otherwise | [
"App",
"voice",
"Returns",
"the",
"js",
"menu",
"compatible",
"voice",
"dict",
"if",
"the",
"user",
"can",
"see",
"it",
"None",
"otherwise"
] | e791b5db3a0814bb49d8dfbdfb989d45e03594b7 | https://github.com/otto-torino/django-baton/blob/e791b5db3a0814bb49d8dfbdfb989d45e03594b7/baton/views.py#L91-L119 | train | 204,308 |
otto-torino/django-baton | baton/views.py | GetAppListJsonView.get_app_model_voice | def get_app_model_voice(self, app_model_item):
""" App Model voice
Returns the js menu compatible voice dict if the user
can see it, None otherwise
"""
if app_model_item.get('name', None) is None:
raise ImproperlyConfigured('Model menu voices must have a name key') # noqa
if app_model_item.get('app', None) is None:
raise ImproperlyConfigured('Model menu voices must have an app key') # noqa
return self.get_model_voice(app_model_item.get('app'), app_model_item) | python | def get_app_model_voice(self, app_model_item):
""" App Model voice
Returns the js menu compatible voice dict if the user
can see it, None otherwise
"""
if app_model_item.get('name', None) is None:
raise ImproperlyConfigured('Model menu voices must have a name key') # noqa
if app_model_item.get('app', None) is None:
raise ImproperlyConfigured('Model menu voices must have an app key') # noqa
return self.get_model_voice(app_model_item.get('app'), app_model_item) | [
"def",
"get_app_model_voice",
"(",
"self",
",",
"app_model_item",
")",
":",
"if",
"app_model_item",
".",
"get",
"(",
"'name'",
",",
"None",
")",
"is",
"None",
":",
"raise",
"ImproperlyConfigured",
"(",
"'Model menu voices must have a name key'",
")",
"# noqa",
"if... | App Model voice
Returns the js menu compatible voice dict if the user
can see it, None otherwise | [
"App",
"Model",
"voice",
"Returns",
"the",
"js",
"menu",
"compatible",
"voice",
"dict",
"if",
"the",
"user",
"can",
"see",
"it",
"None",
"otherwise"
] | e791b5db3a0814bb49d8dfbdfb989d45e03594b7 | https://github.com/otto-torino/django-baton/blob/e791b5db3a0814bb49d8dfbdfb989d45e03594b7/baton/views.py#L121-L132 | train | 204,309 |
otto-torino/django-baton | baton/views.py | GetAppListJsonView.get_model_voice | def get_model_voice(self, app, model_item):
""" Model voice
Returns the js menu compatible voice dict if the user
can see it, None otherwise
"""
if model_item.get('name', None) is None:
raise ImproperlyConfigured('Model menu voices must have a name key') # noqa
if self.check_model_permission(app, model_item.get('name', None)):
return {
'type': 'model',
'label': model_item.get('label', ''),
'icon': model_item.get('icon', None),
'url': self.apps_dict[app]['models'][model_item.get('name')]['admin_url'], # noqa
}
return None | python | def get_model_voice(self, app, model_item):
""" Model voice
Returns the js menu compatible voice dict if the user
can see it, None otherwise
"""
if model_item.get('name', None) is None:
raise ImproperlyConfigured('Model menu voices must have a name key') # noqa
if self.check_model_permission(app, model_item.get('name', None)):
return {
'type': 'model',
'label': model_item.get('label', ''),
'icon': model_item.get('icon', None),
'url': self.apps_dict[app]['models'][model_item.get('name')]['admin_url'], # noqa
}
return None | [
"def",
"get_model_voice",
"(",
"self",
",",
"app",
",",
"model_item",
")",
":",
"if",
"model_item",
".",
"get",
"(",
"'name'",
",",
"None",
")",
"is",
"None",
":",
"raise",
"ImproperlyConfigured",
"(",
"'Model menu voices must have a name key'",
")",
"# noqa",
... | Model voice
Returns the js menu compatible voice dict if the user
can see it, None otherwise | [
"Model",
"voice",
"Returns",
"the",
"js",
"menu",
"compatible",
"voice",
"dict",
"if",
"the",
"user",
"can",
"see",
"it",
"None",
"otherwise"
] | e791b5db3a0814bb49d8dfbdfb989d45e03594b7 | https://github.com/otto-torino/django-baton/blob/e791b5db3a0814bb49d8dfbdfb989d45e03594b7/baton/views.py#L134-L150 | train | 204,310 |
otto-torino/django-baton | baton/views.py | GetAppListJsonView.create_app_list_dict | def create_app_list_dict(self):
""" Creates a more efficient to check dictionary from
the app_list list obtained from django admin
"""
d = {}
for app in self.app_list:
models = {}
for model in app.get('models', []):
models[model.get('object_name').lower()] = model
d[app.get('app_label').lower()] = {
'app_url': app.get('app_url', ''),
'app_label': app.get('app_label'),
'models': models
}
return d | python | def create_app_list_dict(self):
""" Creates a more efficient to check dictionary from
the app_list list obtained from django admin
"""
d = {}
for app in self.app_list:
models = {}
for model in app.get('models', []):
models[model.get('object_name').lower()] = model
d[app.get('app_label').lower()] = {
'app_url': app.get('app_url', ''),
'app_label': app.get('app_label'),
'models': models
}
return d | [
"def",
"create_app_list_dict",
"(",
"self",
")",
":",
"d",
"=",
"{",
"}",
"for",
"app",
"in",
"self",
".",
"app_list",
":",
"models",
"=",
"{",
"}",
"for",
"model",
"in",
"app",
".",
"get",
"(",
"'models'",
",",
"[",
"]",
")",
":",
"models",
"[",... | Creates a more efficient to check dictionary from
the app_list list obtained from django admin | [
"Creates",
"a",
"more",
"efficient",
"to",
"check",
"dictionary",
"from",
"the",
"app_list",
"list",
"obtained",
"from",
"django",
"admin"
] | e791b5db3a0814bb49d8dfbdfb989d45e03594b7 | https://github.com/otto-torino/django-baton/blob/e791b5db3a0814bb49d8dfbdfb989d45e03594b7/baton/views.py#L152-L166 | train | 204,311 |
otto-torino/django-baton | baton/views.py | GetAppListJsonView.check_apps_permission | def check_apps_permission(self, apps):
""" Checks if one of apps is listed in apps_dict
Since apps_dict is derived from the app_list
given by django admin, it lists only the apps
the user can view
"""
for app in apps:
if app in self.apps_dict:
return True
return False | python | def check_apps_permission(self, apps):
""" Checks if one of apps is listed in apps_dict
Since apps_dict is derived from the app_list
given by django admin, it lists only the apps
the user can view
"""
for app in apps:
if app in self.apps_dict:
return True
return False | [
"def",
"check_apps_permission",
"(",
"self",
",",
"apps",
")",
":",
"for",
"app",
"in",
"apps",
":",
"if",
"app",
"in",
"self",
".",
"apps_dict",
":",
"return",
"True",
"return",
"False"
] | Checks if one of apps is listed in apps_dict
Since apps_dict is derived from the app_list
given by django admin, it lists only the apps
the user can view | [
"Checks",
"if",
"one",
"of",
"apps",
"is",
"listed",
"in",
"apps_dict",
"Since",
"apps_dict",
"is",
"derived",
"from",
"the",
"app_list",
"given",
"by",
"django",
"admin",
"it",
"lists",
"only",
"the",
"apps",
"the",
"user",
"can",
"view"
] | e791b5db3a0814bb49d8dfbdfb989d45e03594b7 | https://github.com/otto-torino/django-baton/blob/e791b5db3a0814bb49d8dfbdfb989d45e03594b7/baton/views.py#L174-L184 | train | 204,312 |
otto-torino/django-baton | baton/views.py | GetAppListJsonView.check_model_permission | def check_model_permission(self, app, model):
""" Checks if model is listed in apps_dict
Since apps_dict is derived from the app_list
given by django admin, it lists only the apps
and models the user can view
"""
if self.apps_dict.get(app, False) and model in self.apps_dict[app]['models']:
return True
return False | python | def check_model_permission(self, app, model):
""" Checks if model is listed in apps_dict
Since apps_dict is derived from the app_list
given by django admin, it lists only the apps
and models the user can view
"""
if self.apps_dict.get(app, False) and model in self.apps_dict[app]['models']:
return True
return False | [
"def",
"check_model_permission",
"(",
"self",
",",
"app",
",",
"model",
")",
":",
"if",
"self",
".",
"apps_dict",
".",
"get",
"(",
"app",
",",
"False",
")",
"and",
"model",
"in",
"self",
".",
"apps_dict",
"[",
"app",
"]",
"[",
"'models'",
"]",
":",
... | Checks if model is listed in apps_dict
Since apps_dict is derived from the app_list
given by django admin, it lists only the apps
and models the user can view | [
"Checks",
"if",
"model",
"is",
"listed",
"in",
"apps_dict",
"Since",
"apps_dict",
"is",
"derived",
"from",
"the",
"app_list",
"given",
"by",
"django",
"admin",
"it",
"lists",
"only",
"the",
"apps",
"and",
"models",
"the",
"user",
"can",
"view"
] | e791b5db3a0814bb49d8dfbdfb989d45e03594b7 | https://github.com/otto-torino/django-baton/blob/e791b5db3a0814bb49d8dfbdfb989d45e03594b7/baton/views.py#L186-L195 | train | 204,313 |
otto-torino/django-baton | baton/views.py | GetAppListJsonView.get_default_voices | def get_default_voices(self):
""" When no custom menu is defined in settings
Retrieves a js menu ready dict from the django admin app list
"""
voices = []
for app in self.app_list:
children = []
for model in app.get('models', []):
child = {
'type': 'model',
'label': model.get('name', ''),
'url': model.get('admin_url', '')
}
children.append(child)
voice = {
'type': 'app',
'label': app.get('name', ''),
'url': app.get('app_url', ''),
'children': children
}
voices.append(voice)
return voices | python | def get_default_voices(self):
""" When no custom menu is defined in settings
Retrieves a js menu ready dict from the django admin app list
"""
voices = []
for app in self.app_list:
children = []
for model in app.get('models', []):
child = {
'type': 'model',
'label': model.get('name', ''),
'url': model.get('admin_url', '')
}
children.append(child)
voice = {
'type': 'app',
'label': app.get('name', ''),
'url': app.get('app_url', ''),
'children': children
}
voices.append(voice)
return voices | [
"def",
"get_default_voices",
"(",
"self",
")",
":",
"voices",
"=",
"[",
"]",
"for",
"app",
"in",
"self",
".",
"app_list",
":",
"children",
"=",
"[",
"]",
"for",
"model",
"in",
"app",
".",
"get",
"(",
"'models'",
",",
"[",
"]",
")",
":",
"child",
... | When no custom menu is defined in settings
Retrieves a js menu ready dict from the django admin app list | [
"When",
"no",
"custom",
"menu",
"is",
"defined",
"in",
"settings",
"Retrieves",
"a",
"js",
"menu",
"ready",
"dict",
"from",
"the",
"django",
"admin",
"app",
"list"
] | e791b5db3a0814bb49d8dfbdfb989d45e03594b7 | https://github.com/otto-torino/django-baton/blob/e791b5db3a0814bb49d8dfbdfb989d45e03594b7/baton/views.py#L197-L219 | train | 204,314 |
draperjames/qtpandas | qtpandas/views/DataTableView.py | DataTableWidget.uncheckButton | def uncheckButton(self):
"""Removes the checked stated of all buttons in this widget.
This method is also a slot.
"""
#for button in self.buttons[1:]:
for button in self.buttons:
# supress editButtons toggled event
button.blockSignals(True)
if button.isChecked():
button.setChecked(False)
button.blockSignals(False) | python | def uncheckButton(self):
"""Removes the checked stated of all buttons in this widget.
This method is also a slot.
"""
#for button in self.buttons[1:]:
for button in self.buttons:
# supress editButtons toggled event
button.blockSignals(True)
if button.isChecked():
button.setChecked(False)
button.blockSignals(False) | [
"def",
"uncheckButton",
"(",
"self",
")",
":",
"#for button in self.buttons[1:]:",
"for",
"button",
"in",
"self",
".",
"buttons",
":",
"# supress editButtons toggled event",
"button",
".",
"blockSignals",
"(",
"True",
")",
"if",
"button",
".",
"isChecked",
"(",
")... | Removes the checked stated of all buttons in this widget.
This method is also a slot. | [
"Removes",
"the",
"checked",
"stated",
"of",
"all",
"buttons",
"in",
"this",
"widget",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/DataTableView.py#L205-L217 | train | 204,315 |
draperjames/qtpandas | qtpandas/views/DataTableView.py | DataTableWidget.addColumn | def addColumn(self, columnName, dtype, defaultValue):
"""Adds a column with the given parameters to the underlying model
This method is also a slot.
If no model is set, nothing happens.
Args:
columnName (str): The name of the new column.
dtype (numpy.dtype): The datatype of the new column.
defaultValue (object): Fill the column with this value.
"""
model = self.tableView.model()
if model is not None:
model.addDataFrameColumn(columnName, dtype, defaultValue)
self.addColumnButton.setChecked(False) | python | def addColumn(self, columnName, dtype, defaultValue):
"""Adds a column with the given parameters to the underlying model
This method is also a slot.
If no model is set, nothing happens.
Args:
columnName (str): The name of the new column.
dtype (numpy.dtype): The datatype of the new column.
defaultValue (object): Fill the column with this value.
"""
model = self.tableView.model()
if model is not None:
model.addDataFrameColumn(columnName, dtype, defaultValue)
self.addColumnButton.setChecked(False) | [
"def",
"addColumn",
"(",
"self",
",",
"columnName",
",",
"dtype",
",",
"defaultValue",
")",
":",
"model",
"=",
"self",
".",
"tableView",
".",
"model",
"(",
")",
"if",
"model",
"is",
"not",
"None",
":",
"model",
".",
"addDataFrameColumn",
"(",
"columnName... | Adds a column with the given parameters to the underlying model
This method is also a slot.
If no model is set, nothing happens.
Args:
columnName (str): The name of the new column.
dtype (numpy.dtype): The datatype of the new column.
defaultValue (object): Fill the column with this value. | [
"Adds",
"a",
"column",
"with",
"the",
"given",
"parameters",
"to",
"the",
"underlying",
"model"
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/DataTableView.py#L220-L237 | train | 204,316 |
draperjames/qtpandas | qtpandas/views/DataTableView.py | DataTableWidget.showAddColumnDialog | def showAddColumnDialog(self, triggered):
"""Display the dialog to add a column to the model.
This method is also a slot.
Args:
triggered (bool): If the corresponding button was
activated, the dialog will be created and shown.
"""
if triggered:
dialog = AddAttributesDialog(self)
dialog.accepted.connect(self.addColumn)
dialog.rejected.connect(self.uncheckButton)
dialog.show() | python | def showAddColumnDialog(self, triggered):
"""Display the dialog to add a column to the model.
This method is also a slot.
Args:
triggered (bool): If the corresponding button was
activated, the dialog will be created and shown.
"""
if triggered:
dialog = AddAttributesDialog(self)
dialog.accepted.connect(self.addColumn)
dialog.rejected.connect(self.uncheckButton)
dialog.show() | [
"def",
"showAddColumnDialog",
"(",
"self",
",",
"triggered",
")",
":",
"if",
"triggered",
":",
"dialog",
"=",
"AddAttributesDialog",
"(",
"self",
")",
"dialog",
".",
"accepted",
".",
"connect",
"(",
"self",
".",
"addColumn",
")",
"dialog",
".",
"rejected",
... | Display the dialog to add a column to the model.
This method is also a slot.
Args:
triggered (bool): If the corresponding button was
activated, the dialog will be created and shown. | [
"Display",
"the",
"dialog",
"to",
"add",
"a",
"column",
"to",
"the",
"model",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/DataTableView.py#L240-L254 | train | 204,317 |
draperjames/qtpandas | qtpandas/views/DataTableView.py | DataTableWidget.addRow | def addRow(self, triggered):
"""Adds a row to the model.
This method is also a slot.
Args:
triggered (bool): If the corresponding button was
activated, the row will be appended to the end.
"""
if triggered:
model = self.tableView.model()
model.addDataFrameRows()
self.sender().setChecked(False) | python | def addRow(self, triggered):
"""Adds a row to the model.
This method is also a slot.
Args:
triggered (bool): If the corresponding button was
activated, the row will be appended to the end.
"""
if triggered:
model = self.tableView.model()
model.addDataFrameRows()
self.sender().setChecked(False) | [
"def",
"addRow",
"(",
"self",
",",
"triggered",
")",
":",
"if",
"triggered",
":",
"model",
"=",
"self",
".",
"tableView",
".",
"model",
"(",
")",
"model",
".",
"addDataFrameRows",
"(",
")",
"self",
".",
"sender",
"(",
")",
".",
"setChecked",
"(",
"Fa... | Adds a row to the model.
This method is also a slot.
Args:
triggered (bool): If the corresponding button was
activated, the row will be appended to the end. | [
"Adds",
"a",
"row",
"to",
"the",
"model",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/DataTableView.py#L257-L270 | train | 204,318 |
draperjames/qtpandas | qtpandas/views/DataTableView.py | DataTableWidget.removeRow | def removeRow(self, triggered):
"""Removes a row to the model.
This method is also a slot.
Args:
triggered (bool): If the corresponding button was
activated, the selected row will be removed
from the model.
"""
if triggered:
model = self.tableView.model()
selection = self.tableView.selectedIndexes()
rows = [index.row() for index in selection]
model.removeDataFrameRows(set(rows))
self.sender().setChecked(False) | python | def removeRow(self, triggered):
"""Removes a row to the model.
This method is also a slot.
Args:
triggered (bool): If the corresponding button was
activated, the selected row will be removed
from the model.
"""
if triggered:
model = self.tableView.model()
selection = self.tableView.selectedIndexes()
rows = [index.row() for index in selection]
model.removeDataFrameRows(set(rows))
self.sender().setChecked(False) | [
"def",
"removeRow",
"(",
"self",
",",
"triggered",
")",
":",
"if",
"triggered",
":",
"model",
"=",
"self",
".",
"tableView",
".",
"model",
"(",
")",
"selection",
"=",
"self",
".",
"tableView",
".",
"selectedIndexes",
"(",
")",
"rows",
"=",
"[",
"index"... | Removes a row to the model.
This method is also a slot.
Args:
triggered (bool): If the corresponding button was
activated, the selected row will be removed
from the model. | [
"Removes",
"a",
"row",
"to",
"the",
"model",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/DataTableView.py#L274-L291 | train | 204,319 |
draperjames/qtpandas | qtpandas/views/DataTableView.py | DataTableWidget.removeColumns | def removeColumns(self, columnNames):
"""Removes one or multiple columns from the model.
This method is also a slot.
Args:
columnNames (list): A list of columns, which shall
be removed from the model.
"""
model = self.tableView.model()
if model is not None:
model.removeDataFrameColumns(columnNames)
self.removeColumnButton.setChecked(False) | python | def removeColumns(self, columnNames):
"""Removes one or multiple columns from the model.
This method is also a slot.
Args:
columnNames (list): A list of columns, which shall
be removed from the model.
"""
model = self.tableView.model()
if model is not None:
model.removeDataFrameColumns(columnNames)
self.removeColumnButton.setChecked(False) | [
"def",
"removeColumns",
"(",
"self",
",",
"columnNames",
")",
":",
"model",
"=",
"self",
".",
"tableView",
".",
"model",
"(",
")",
"if",
"model",
"is",
"not",
"None",
":",
"model",
".",
"removeDataFrameColumns",
"(",
"columnNames",
")",
"self",
".",
"rem... | Removes one or multiple columns from the model.
This method is also a slot.
Args:
columnNames (list): A list of columns, which shall
be removed from the model. | [
"Removes",
"one",
"or",
"multiple",
"columns",
"from",
"the",
"model",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/DataTableView.py#L294-L309 | train | 204,320 |
draperjames/qtpandas | qtpandas/views/DataTableView.py | DataTableWidget.setViewModel | def setViewModel(self, model):
"""Sets the model for the enclosed TableView in this widget.
Args:
model (DataFrameModel): The model to be displayed by
the Table View.
"""
if isinstance(model, DataFrameModel):
self.enableEditing(False)
self.uncheckButton()
selectionModel = self.tableView.selectionModel()
self.tableView.setModel(model)
model.dtypeChanged.connect(self.updateDelegate)
model.dataChanged.connect(self.updateDelegates)
del selectionModel | python | def setViewModel(self, model):
"""Sets the model for the enclosed TableView in this widget.
Args:
model (DataFrameModel): The model to be displayed by
the Table View.
"""
if isinstance(model, DataFrameModel):
self.enableEditing(False)
self.uncheckButton()
selectionModel = self.tableView.selectionModel()
self.tableView.setModel(model)
model.dtypeChanged.connect(self.updateDelegate)
model.dataChanged.connect(self.updateDelegates)
del selectionModel | [
"def",
"setViewModel",
"(",
"self",
",",
"model",
")",
":",
"if",
"isinstance",
"(",
"model",
",",
"DataFrameModel",
")",
":",
"self",
".",
"enableEditing",
"(",
"False",
")",
"self",
".",
"uncheckButton",
"(",
")",
"selectionModel",
"=",
"self",
".",
"t... | Sets the model for the enclosed TableView in this widget.
Args:
model (DataFrameModel): The model to be displayed by
the Table View. | [
"Sets",
"the",
"model",
"for",
"the",
"enclosed",
"TableView",
"in",
"this",
"widget",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/DataTableView.py#L331-L347 | train | 204,321 |
draperjames/qtpandas | qtpandas/views/DataTableView.py | DataTableWidget.updateDelegates | def updateDelegates(self):
"""reset all delegates"""
for index, column in enumerate(self.tableView.model().dataFrame().columns):
dtype = self.tableView.model().dataFrame()[column].dtype
self.updateDelegate(index, dtype) | python | def updateDelegates(self):
"""reset all delegates"""
for index, column in enumerate(self.tableView.model().dataFrame().columns):
dtype = self.tableView.model().dataFrame()[column].dtype
self.updateDelegate(index, dtype) | [
"def",
"updateDelegates",
"(",
"self",
")",
":",
"for",
"index",
",",
"column",
"in",
"enumerate",
"(",
"self",
".",
"tableView",
".",
"model",
"(",
")",
".",
"dataFrame",
"(",
")",
".",
"columns",
")",
":",
"dtype",
"=",
"self",
".",
"tableView",
".... | reset all delegates | [
"reset",
"all",
"delegates"
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/DataTableView.py#L390-L394 | train | 204,322 |
draperjames/qtpandas | qtpandas/models/ProgressThread.py | createThread | def createThread(parent, worker, deleteWorkerLater=False):
"""Create a new thread for given worker.
Args:
parent (QObject): parent of thread and worker.
worker (ProgressWorker): worker to use in thread.
deleteWorkerLater (bool, optional): delete the worker if thread finishes.
Returns:
QThread
"""
thread = QtCore.QThread(parent)
thread.started.connect(worker.doWork)
worker.finished.connect(thread.quit)
if deleteWorkerLater:
thread.finished.connect(worker.deleteLater)
worker.moveToThread(thread)
worker.setParent(parent)
return thread | python | def createThread(parent, worker, deleteWorkerLater=False):
"""Create a new thread for given worker.
Args:
parent (QObject): parent of thread and worker.
worker (ProgressWorker): worker to use in thread.
deleteWorkerLater (bool, optional): delete the worker if thread finishes.
Returns:
QThread
"""
thread = QtCore.QThread(parent)
thread.started.connect(worker.doWork)
worker.finished.connect(thread.quit)
if deleteWorkerLater:
thread.finished.connect(worker.deleteLater)
worker.moveToThread(thread)
worker.setParent(parent)
return thread | [
"def",
"createThread",
"(",
"parent",
",",
"worker",
",",
"deleteWorkerLater",
"=",
"False",
")",
":",
"thread",
"=",
"QtCore",
".",
"QThread",
"(",
"parent",
")",
"thread",
".",
"started",
".",
"connect",
"(",
"worker",
".",
"doWork",
")",
"worker",
"."... | Create a new thread for given worker.
Args:
parent (QObject): parent of thread and worker.
worker (ProgressWorker): worker to use in thread.
deleteWorkerLater (bool, optional): delete the worker if thread finishes.
Returns:
QThread | [
"Create",
"a",
"new",
"thread",
"for",
"given",
"worker",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/models/ProgressThread.py#L41-L61 | train | 204,323 |
draperjames/qtpandas | qtpandas/models/SupportedDtypes.py | SupportedDtypesTranslator.description | def description(self, value):
"""Fetches the translated description for the given datatype.
The given value will be converted to a `numpy.dtype` object, matched
against the supported datatypes and the description will be translated
into the preferred language. (Usually a settings dialog should be
available to change the language).
If the conversion fails or no match can be found, `None` will be returned.
Args:
value (type|numpy.dtype): Any object or type.
Returns:
str: The translated description of the datatype
None: If no match could be found or an error occured during convertion.
"""
# lists, tuples, dicts refer to numpy.object types and
# return a 'text' description - working as intended or bug?
try:
value = np.dtype(value)
except TypeError as e:
return None
for (dtype, string) in self._all:
if dtype == value:
return string
# no match found return given value
return None | python | def description(self, value):
"""Fetches the translated description for the given datatype.
The given value will be converted to a `numpy.dtype` object, matched
against the supported datatypes and the description will be translated
into the preferred language. (Usually a settings dialog should be
available to change the language).
If the conversion fails or no match can be found, `None` will be returned.
Args:
value (type|numpy.dtype): Any object or type.
Returns:
str: The translated description of the datatype
None: If no match could be found or an error occured during convertion.
"""
# lists, tuples, dicts refer to numpy.object types and
# return a 'text' description - working as intended or bug?
try:
value = np.dtype(value)
except TypeError as e:
return None
for (dtype, string) in self._all:
if dtype == value:
return string
# no match found return given value
return None | [
"def",
"description",
"(",
"self",
",",
"value",
")",
":",
"# lists, tuples, dicts refer to numpy.object types and",
"# return a 'text' description - working as intended or bug?",
"try",
":",
"value",
"=",
"np",
".",
"dtype",
"(",
"value",
")",
"except",
"TypeError",
"as"... | Fetches the translated description for the given datatype.
The given value will be converted to a `numpy.dtype` object, matched
against the supported datatypes and the description will be translated
into the preferred language. (Usually a settings dialog should be
available to change the language).
If the conversion fails or no match can be found, `None` will be returned.
Args:
value (type|numpy.dtype): Any object or type.
Returns:
str: The translated description of the datatype
None: If no match could be found or an error occured during convertion. | [
"Fetches",
"the",
"translated",
"description",
"for",
"the",
"given",
"datatype",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/models/SupportedDtypes.py#L112-L141 | train | 204,324 |
draperjames/qtpandas | qtpandas/utils.py | convertTimestamps | def convertTimestamps(column):
"""Convert a dtype of a given column to a datetime.
This method tries to do this by brute force.
Args:
column (pandas.Series): A Series object with all rows.
Returns:
column: Converted to datetime if no errors occured, else the
original column will be returned.
"""
tempColumn = column
try:
# Try to convert the first row and a random row instead of the complete
# column, might be faster
# tempValue = np.datetime64(column[0])
tempValue = np.datetime64(column[randint(0, len(column.index) - 1)])
tempColumn = column.apply(to_datetime)
except Exception:
pass
return tempColumn | python | def convertTimestamps(column):
"""Convert a dtype of a given column to a datetime.
This method tries to do this by brute force.
Args:
column (pandas.Series): A Series object with all rows.
Returns:
column: Converted to datetime if no errors occured, else the
original column will be returned.
"""
tempColumn = column
try:
# Try to convert the first row and a random row instead of the complete
# column, might be faster
# tempValue = np.datetime64(column[0])
tempValue = np.datetime64(column[randint(0, len(column.index) - 1)])
tempColumn = column.apply(to_datetime)
except Exception:
pass
return tempColumn | [
"def",
"convertTimestamps",
"(",
"column",
")",
":",
"tempColumn",
"=",
"column",
"try",
":",
"# Try to convert the first row and a random row instead of the complete",
"# column, might be faster",
"# tempValue = np.datetime64(column[0])",
"tempValue",
"=",
"np",
".",
"datetime64... | Convert a dtype of a given column to a datetime.
This method tries to do this by brute force.
Args:
column (pandas.Series): A Series object with all rows.
Returns:
column: Converted to datetime if no errors occured, else the
original column will be returned. | [
"Convert",
"a",
"dtype",
"of",
"a",
"given",
"column",
"to",
"a",
"datetime",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/utils.py#L33-L56 | train | 204,325 |
draperjames/qtpandas | qtpandas/utils.py | superReadCSV | def superReadCSV(filepath, first_codec='UTF_8', usecols=None,
low_memory=False, dtype=None, parse_dates=True,
sep=',', chunksize=None, verbose=False, **kwargs):
"""
A wrap to pandas read_csv with mods to accept a dataframe or
filepath. returns dataframe untouched, reads filepath and returns
dataframe based on arguments.
"""
if isinstance(filepath, pd.DataFrame):
return filepath
assert isinstance(first_codec, str), "first_codec must be a string"
codecs = ['UTF_8', 'ISO-8859-1', 'ASCII', 'UTF_16', 'UTF_32']
try:
codecs.remove(first_codec)
except ValueError as not_in_list:
pass
codecs.insert(0, first_codec)
errors = []
for c in codecs:
try:
return pd.read_csv(filepath,
usecols=usecols,
low_memory=low_memory,
encoding=c,
dtype=dtype,
parse_dates=parse_dates,
sep=sep,
chunksize=chunksize,
**kwargs)
# Need to catch `UnicodeError` here, not just `UnicodeDecodeError`,
# because pandas 0.23.1 raises it when decoding with UTF_16 and the
# file is not in that format:
except (UnicodeError, UnboundLocalError) as e:
errors.append(e)
except Exception as e:
errors.append(e)
if 'tokenizing' in str(e):
pass
else:
raise
if verbose:
[print(e) for e in errors]
raise UnicodeDecodeError("Tried {} codecs and failed on all: \n CODECS: {} \n FILENAME: {}".format(
len(codecs), codecs, os.path.basename(filepath))) | python | def superReadCSV(filepath, first_codec='UTF_8', usecols=None,
low_memory=False, dtype=None, parse_dates=True,
sep=',', chunksize=None, verbose=False, **kwargs):
"""
A wrap to pandas read_csv with mods to accept a dataframe or
filepath. returns dataframe untouched, reads filepath and returns
dataframe based on arguments.
"""
if isinstance(filepath, pd.DataFrame):
return filepath
assert isinstance(first_codec, str), "first_codec must be a string"
codecs = ['UTF_8', 'ISO-8859-1', 'ASCII', 'UTF_16', 'UTF_32']
try:
codecs.remove(first_codec)
except ValueError as not_in_list:
pass
codecs.insert(0, first_codec)
errors = []
for c in codecs:
try:
return pd.read_csv(filepath,
usecols=usecols,
low_memory=low_memory,
encoding=c,
dtype=dtype,
parse_dates=parse_dates,
sep=sep,
chunksize=chunksize,
**kwargs)
# Need to catch `UnicodeError` here, not just `UnicodeDecodeError`,
# because pandas 0.23.1 raises it when decoding with UTF_16 and the
# file is not in that format:
except (UnicodeError, UnboundLocalError) as e:
errors.append(e)
except Exception as e:
errors.append(e)
if 'tokenizing' in str(e):
pass
else:
raise
if verbose:
[print(e) for e in errors]
raise UnicodeDecodeError("Tried {} codecs and failed on all: \n CODECS: {} \n FILENAME: {}".format(
len(codecs), codecs, os.path.basename(filepath))) | [
"def",
"superReadCSV",
"(",
"filepath",
",",
"first_codec",
"=",
"'UTF_8'",
",",
"usecols",
"=",
"None",
",",
"low_memory",
"=",
"False",
",",
"dtype",
"=",
"None",
",",
"parse_dates",
"=",
"True",
",",
"sep",
"=",
"','",
",",
"chunksize",
"=",
"None",
... | A wrap to pandas read_csv with mods to accept a dataframe or
filepath. returns dataframe untouched, reads filepath and returns
dataframe based on arguments. | [
"A",
"wrap",
"to",
"pandas",
"read_csv",
"with",
"mods",
"to",
"accept",
"a",
"dataframe",
"or",
"filepath",
".",
"returns",
"dataframe",
"untouched",
"reads",
"filepath",
"and",
"returns",
"dataframe",
"based",
"on",
"arguments",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/utils.py#L59-L108 | train | 204,326 |
draperjames/qtpandas | qtpandas/utils.py | dedupe_cols | def dedupe_cols(frame):
"""
Need to dedupe columns that have the same name.
"""
cols = list(frame.columns)
for i, item in enumerate(frame.columns):
if item in frame.columns[:i]:
cols[i] = "toDROP"
frame.columns = cols
return frame.drop("toDROP", 1, errors='ignore') | python | def dedupe_cols(frame):
"""
Need to dedupe columns that have the same name.
"""
cols = list(frame.columns)
for i, item in enumerate(frame.columns):
if item in frame.columns[:i]:
cols[i] = "toDROP"
frame.columns = cols
return frame.drop("toDROP", 1, errors='ignore') | [
"def",
"dedupe_cols",
"(",
"frame",
")",
":",
"cols",
"=",
"list",
"(",
"frame",
".",
"columns",
")",
"for",
"i",
",",
"item",
"in",
"enumerate",
"(",
"frame",
".",
"columns",
")",
":",
"if",
"item",
"in",
"frame",
".",
"columns",
"[",
":",
"i",
... | Need to dedupe columns that have the same name. | [
"Need",
"to",
"dedupe",
"columns",
"that",
"have",
"the",
"same",
"name",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/utils.py#L208-L218 | train | 204,327 |
draperjames/qtpandas | qtpandas/views/CustomDelegates.py | BigIntSpinboxDelegate.setEditorData | def setEditorData(self, spinBox, index):
"""Sets the data to be displayed and edited by the editor from the data model item specified by the model index.
Args:
spinBox (BigIntSpinbox): editor widget.
index (QModelIndex): model data index.
"""
if index.isValid():
value = index.model().data(index, QtCore.Qt.EditRole)
spinBox.setValue(value) | python | def setEditorData(self, spinBox, index):
"""Sets the data to be displayed and edited by the editor from the data model item specified by the model index.
Args:
spinBox (BigIntSpinbox): editor widget.
index (QModelIndex): model data index.
"""
if index.isValid():
value = index.model().data(index, QtCore.Qt.EditRole)
spinBox.setValue(value) | [
"def",
"setEditorData",
"(",
"self",
",",
"spinBox",
",",
"index",
")",
":",
"if",
"index",
".",
"isValid",
"(",
")",
":",
"value",
"=",
"index",
".",
"model",
"(",
")",
".",
"data",
"(",
"index",
",",
"QtCore",
".",
"Qt",
".",
"EditRole",
")",
"... | Sets the data to be displayed and edited by the editor from the data model item specified by the model index.
Args:
spinBox (BigIntSpinbox): editor widget.
index (QModelIndex): model data index. | [
"Sets",
"the",
"data",
"to",
"be",
"displayed",
"and",
"edited",
"by",
"the",
"editor",
"from",
"the",
"data",
"model",
"item",
"specified",
"by",
"the",
"model",
"index",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/CustomDelegates.py#L91-L100 | train | 204,328 |
draperjames/qtpandas | qtpandas/views/CustomDelegates.py | DtypeComboDelegate.createEditor | def createEditor(self, parent, option, index):
"""Creates an Editor Widget for the given index.
Enables the user to manipulate the displayed data in place. An editor
is created, which performs the change.
The widget used will be a `QComboBox` with all available datatypes in the
`pandas` project.
Args:
parent (QtCore.QWidget): Defines the parent for the created editor.
option (QtGui.QStyleOptionViewItem): contains all the information
that QStyle functions need to draw the items.
index (QtCore.QModelIndex): The item/index which shall be edited.
Returns:
QtGui.QWidget: he widget used to edit the item specified by index
for editing.
"""
combo = QtGui.QComboBox(parent)
combo.addItems(SupportedDtypes.names())
combo.currentIndexChanged.connect(self.currentIndexChanged)
return combo | python | def createEditor(self, parent, option, index):
"""Creates an Editor Widget for the given index.
Enables the user to manipulate the displayed data in place. An editor
is created, which performs the change.
The widget used will be a `QComboBox` with all available datatypes in the
`pandas` project.
Args:
parent (QtCore.QWidget): Defines the parent for the created editor.
option (QtGui.QStyleOptionViewItem): contains all the information
that QStyle functions need to draw the items.
index (QtCore.QModelIndex): The item/index which shall be edited.
Returns:
QtGui.QWidget: he widget used to edit the item specified by index
for editing.
"""
combo = QtGui.QComboBox(parent)
combo.addItems(SupportedDtypes.names())
combo.currentIndexChanged.connect(self.currentIndexChanged)
return combo | [
"def",
"createEditor",
"(",
"self",
",",
"parent",
",",
"option",
",",
"index",
")",
":",
"combo",
"=",
"QtGui",
".",
"QComboBox",
"(",
"parent",
")",
"combo",
".",
"addItems",
"(",
"SupportedDtypes",
".",
"names",
"(",
")",
")",
"combo",
".",
"current... | Creates an Editor Widget for the given index.
Enables the user to manipulate the displayed data in place. An editor
is created, which performs the change.
The widget used will be a `QComboBox` with all available datatypes in the
`pandas` project.
Args:
parent (QtCore.QWidget): Defines the parent for the created editor.
option (QtGui.QStyleOptionViewItem): contains all the information
that QStyle functions need to draw the items.
index (QtCore.QModelIndex): The item/index which shall be edited.
Returns:
QtGui.QWidget: he widget used to edit the item specified by index
for editing. | [
"Creates",
"an",
"Editor",
"Widget",
"for",
"the",
"given",
"index",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/CustomDelegates.py#L276-L298 | train | 204,329 |
draperjames/qtpandas | qtpandas/views/CustomDelegates.py | DtypeComboDelegate.setEditorData | def setEditorData(self, editor, index):
"""Sets the current data for the editor.
The data displayed has the same value as `index.data(Qt.EditRole)`
(the translated name of the datatype). Therefor a lookup for all items
of the combobox is made and the matching item is set as the currently
displayed item.
Signals emitted by the editor are blocked during exection of this method.
Args:
editor (QtGui.QComboBox): The current editor for the item. Should be
a `QtGui.QComboBox` as defined in `createEditor`.
index (QtCore.QModelIndex): The index of the current item.
"""
editor.blockSignals(True)
data = index.data()
dataIndex = editor.findData(data)
# dataIndex = editor.findData(data, role=Qt.EditRole)
editor.setCurrentIndex(dataIndex)
editor.blockSignals(False) | python | def setEditorData(self, editor, index):
"""Sets the current data for the editor.
The data displayed has the same value as `index.data(Qt.EditRole)`
(the translated name of the datatype). Therefor a lookup for all items
of the combobox is made and the matching item is set as the currently
displayed item.
Signals emitted by the editor are blocked during exection of this method.
Args:
editor (QtGui.QComboBox): The current editor for the item. Should be
a `QtGui.QComboBox` as defined in `createEditor`.
index (QtCore.QModelIndex): The index of the current item.
"""
editor.blockSignals(True)
data = index.data()
dataIndex = editor.findData(data)
# dataIndex = editor.findData(data, role=Qt.EditRole)
editor.setCurrentIndex(dataIndex)
editor.blockSignals(False) | [
"def",
"setEditorData",
"(",
"self",
",",
"editor",
",",
"index",
")",
":",
"editor",
".",
"blockSignals",
"(",
"True",
")",
"data",
"=",
"index",
".",
"data",
"(",
")",
"dataIndex",
"=",
"editor",
".",
"findData",
"(",
"data",
")",
"# dataIndex = editor... | Sets the current data for the editor.
The data displayed has the same value as `index.data(Qt.EditRole)`
(the translated name of the datatype). Therefor a lookup for all items
of the combobox is made and the matching item is set as the currently
displayed item.
Signals emitted by the editor are blocked during exection of this method.
Args:
editor (QtGui.QComboBox): The current editor for the item. Should be
a `QtGui.QComboBox` as defined in `createEditor`.
index (QtCore.QModelIndex): The index of the current item. | [
"Sets",
"the",
"current",
"data",
"for",
"the",
"editor",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/CustomDelegates.py#L300-L321 | train | 204,330 |
draperjames/qtpandas | qtpandas/views/CustomDelegates.py | DtypeComboDelegate.setModelData | def setModelData(self, editor, model, index):
"""Updates the model after changing data in the editor.
Args:
editor (QtGui.QComboBox): The current editor for the item. Should be
a `QtGui.QComboBox` as defined in `createEditor`.
model (ColumnDtypeModel): The model which holds the displayed data.
index (QtCore.QModelIndex): The index of the current item of the model.
"""
model.setData(index, editor.itemText(editor.currentIndex())) | python | def setModelData(self, editor, model, index):
"""Updates the model after changing data in the editor.
Args:
editor (QtGui.QComboBox): The current editor for the item. Should be
a `QtGui.QComboBox` as defined in `createEditor`.
model (ColumnDtypeModel): The model which holds the displayed data.
index (QtCore.QModelIndex): The index of the current item of the model.
"""
model.setData(index, editor.itemText(editor.currentIndex())) | [
"def",
"setModelData",
"(",
"self",
",",
"editor",
",",
"model",
",",
"index",
")",
":",
"model",
".",
"setData",
"(",
"index",
",",
"editor",
".",
"itemText",
"(",
"editor",
".",
"currentIndex",
"(",
")",
")",
")"
] | Updates the model after changing data in the editor.
Args:
editor (QtGui.QComboBox): The current editor for the item. Should be
a `QtGui.QComboBox` as defined in `createEditor`.
model (ColumnDtypeModel): The model which holds the displayed data.
index (QtCore.QModelIndex): The index of the current item of the model. | [
"Updates",
"the",
"model",
"after",
"changing",
"data",
"in",
"the",
"editor",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/CustomDelegates.py#L323-L333 | train | 204,331 |
draperjames/qtpandas | qtpandas/views/MultiFileDialogs.py | DataFrameExportDialog.accepted | def accepted(self):
"""Successfully close the widget and emit an export signal.
This method is also a `SLOT`.
The dialog will be closed, when the `Export Data` button is
pressed. If errors occur during the export, the status bar
will show the error message and the dialog will not be closed.
"""
#return super(DataFrameExportDialog, self).accepted
try:
self._saveModel()
except Exception as err:
self._statusBar.showMessage(str(err))
raise
else:
self._resetWidgets()
self.exported.emit(True)
self.accept() | python | def accepted(self):
"""Successfully close the widget and emit an export signal.
This method is also a `SLOT`.
The dialog will be closed, when the `Export Data` button is
pressed. If errors occur during the export, the status bar
will show the error message and the dialog will not be closed.
"""
#return super(DataFrameExportDialog, self).accepted
try:
self._saveModel()
except Exception as err:
self._statusBar.showMessage(str(err))
raise
else:
self._resetWidgets()
self.exported.emit(True)
self.accept() | [
"def",
"accepted",
"(",
"self",
")",
":",
"#return super(DataFrameExportDialog, self).accepted",
"try",
":",
"self",
".",
"_saveModel",
"(",
")",
"except",
"Exception",
"as",
"err",
":",
"self",
".",
"_statusBar",
".",
"showMessage",
"(",
"str",
"(",
"err",
")... | Successfully close the widget and emit an export signal.
This method is also a `SLOT`.
The dialog will be closed, when the `Export Data` button is
pressed. If errors occur during the export, the status bar
will show the error message and the dialog will not be closed. | [
"Successfully",
"close",
"the",
"widget",
"and",
"emit",
"an",
"export",
"signal",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/MultiFileDialogs.py#L40-L58 | train | 204,332 |
draperjames/qtpandas | qtpandas/views/MultiFileDialogs.py | DataFrameExportDialog.rejected | def rejected(self):
"""Close the widget and reset its inital state.
This method is also a `SLOT`.
The dialog will be closed and all changes reverted, when the
`cancel` button is pressed.
"""
self._resetWidgets()
self.exported.emit(False)
self.reject() | python | def rejected(self):
"""Close the widget and reset its inital state.
This method is also a `SLOT`.
The dialog will be closed and all changes reverted, when the
`cancel` button is pressed.
"""
self._resetWidgets()
self.exported.emit(False)
self.reject() | [
"def",
"rejected",
"(",
"self",
")",
":",
"self",
".",
"_resetWidgets",
"(",
")",
"self",
".",
"exported",
".",
"emit",
"(",
"False",
")",
"self",
".",
"reject",
"(",
")"
] | Close the widget and reset its inital state.
This method is also a `SLOT`.
The dialog will be closed and all changes reverted, when the
`cancel` button is pressed. | [
"Close",
"the",
"widget",
"and",
"reset",
"its",
"inital",
"state",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/MultiFileDialogs.py#L61-L71 | train | 204,333 |
draperjames/qtpandas | qtpandas/views/BigIntSpinbox.py | BigIntSpinbox.stepEnabled | def stepEnabled(self):
"""Virtual function that determines whether stepping up and down is legal at any given time.
Returns:
ored combination of StepUpEnabled | StepDownEnabled
"""
if self.value() > self.minimum() and self.value() < self.maximum():
return self.StepUpEnabled | self.StepDownEnabled
elif self.value() <= self.minimum():
return self.StepUpEnabled
elif self.value() >= self.maximum():
return self.StepDownEnabled | python | def stepEnabled(self):
"""Virtual function that determines whether stepping up and down is legal at any given time.
Returns:
ored combination of StepUpEnabled | StepDownEnabled
"""
if self.value() > self.minimum() and self.value() < self.maximum():
return self.StepUpEnabled | self.StepDownEnabled
elif self.value() <= self.minimum():
return self.StepUpEnabled
elif self.value() >= self.maximum():
return self.StepDownEnabled | [
"def",
"stepEnabled",
"(",
"self",
")",
":",
"if",
"self",
".",
"value",
"(",
")",
">",
"self",
".",
"minimum",
"(",
")",
"and",
"self",
".",
"value",
"(",
")",
"<",
"self",
".",
"maximum",
"(",
")",
":",
"return",
"self",
".",
"StepUpEnabled",
"... | Virtual function that determines whether stepping up and down is legal at any given time.
Returns:
ored combination of StepUpEnabled | StepDownEnabled | [
"Virtual",
"function",
"that",
"determines",
"whether",
"stepping",
"up",
"and",
"down",
"is",
"legal",
"at",
"any",
"given",
"time",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/BigIntSpinbox.py#L82-L93 | train | 204,334 |
draperjames/qtpandas | qtpandas/views/BigIntSpinbox.py | BigIntSpinbox.setSingleStep | def setSingleStep(self, singleStep):
"""setter to _singleStep. converts negativ values to positiv ones.
Args:
singleStep (int): new _singleStep value. converts negativ values to positiv ones.
Raises:
TypeError: If the given argument is not an integer.
Returns:
int or long: the absolute value of the given argument.
"""
if not isinstance(singleStep, int):
raise TypeError("Argument is not of type int")
# don't use negative values
self._singleStep = abs(singleStep)
return self._singleStep | python | def setSingleStep(self, singleStep):
"""setter to _singleStep. converts negativ values to positiv ones.
Args:
singleStep (int): new _singleStep value. converts negativ values to positiv ones.
Raises:
TypeError: If the given argument is not an integer.
Returns:
int or long: the absolute value of the given argument.
"""
if not isinstance(singleStep, int):
raise TypeError("Argument is not of type int")
# don't use negative values
self._singleStep = abs(singleStep)
return self._singleStep | [
"def",
"setSingleStep",
"(",
"self",
",",
"singleStep",
")",
":",
"if",
"not",
"isinstance",
"(",
"singleStep",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"Argument is not of type int\"",
")",
"# don't use negative values",
"self",
".",
"_singleStep",
"=",... | setter to _singleStep. converts negativ values to positiv ones.
Args:
singleStep (int): new _singleStep value. converts negativ values to positiv ones.
Raises:
TypeError: If the given argument is not an integer.
Returns:
int or long: the absolute value of the given argument. | [
"setter",
"to",
"_singleStep",
".",
"converts",
"negativ",
"values",
"to",
"positiv",
"ones",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/BigIntSpinbox.py#L99-L115 | train | 204,335 |
draperjames/qtpandas | qtpandas/views/BigIntSpinbox.py | BigIntSpinbox.setMinimum | def setMinimum(self, minimum):
"""setter to _minimum.
Args:
minimum (int or long): new _minimum value.
Raises:
TypeError: If the given argument is not an integer.
"""
if not isinstance(minimum, int):
raise TypeError("Argument is not of type int or long")
self._minimum = minimum | python | def setMinimum(self, minimum):
"""setter to _minimum.
Args:
minimum (int or long): new _minimum value.
Raises:
TypeError: If the given argument is not an integer.
"""
if not isinstance(minimum, int):
raise TypeError("Argument is not of type int or long")
self._minimum = minimum | [
"def",
"setMinimum",
"(",
"self",
",",
"minimum",
")",
":",
"if",
"not",
"isinstance",
"(",
"minimum",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"Argument is not of type int or long\"",
")",
"self",
".",
"_minimum",
"=",
"minimum"
] | setter to _minimum.
Args:
minimum (int or long): new _minimum value.
Raises:
TypeError: If the given argument is not an integer. | [
"setter",
"to",
"_minimum",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/BigIntSpinbox.py#L121-L132 | train | 204,336 |
draperjames/qtpandas | qtpandas/views/BigIntSpinbox.py | BigIntSpinbox.setMaximum | def setMaximum(self, maximum):
"""setter to _maximum.
Args:
maximum (int or long): new _maximum value
"""
if not isinstance(maximum, int):
raise TypeError("Argument is not of type int or long")
self._maximum = maximum | python | def setMaximum(self, maximum):
"""setter to _maximum.
Args:
maximum (int or long): new _maximum value
"""
if not isinstance(maximum, int):
raise TypeError("Argument is not of type int or long")
self._maximum = maximum | [
"def",
"setMaximum",
"(",
"self",
",",
"maximum",
")",
":",
"if",
"not",
"isinstance",
"(",
"maximum",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"Argument is not of type int or long\"",
")",
"self",
".",
"_maximum",
"=",
"maximum"
] | setter to _maximum.
Args:
maximum (int or long): new _maximum value | [
"setter",
"to",
"_maximum",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/BigIntSpinbox.py#L138-L146 | train | 204,337 |
draperjames/qtpandas | qtpandas/models/DataFrameModelManager.py | DataFrameModelManager.save_file | def save_file(self, filepath, save_as=None, keep_orig=False, **kwargs):
"""
Saves a DataFrameModel to a file.
:param filepath: (str)
The filepath of the DataFrameModel to save.
:param save_as: (str, default None)
The new filepath to save as.
:param keep_orig: (bool, default False)
True keeps the original filepath/DataFrameModel if save_as is specified.
:param kwargs:
pandas.DataFrame.to_excel(**kwargs) if .xlsx
pandas.DataFrame.to_csv(**kwargs) otherwise.
:return: None
"""
df = self._models[filepath].dataFrame()
kwargs['index'] = kwargs.get('index', False)
if save_as is not None:
to_path = save_as
else:
to_path = filepath
ext = os.path.splitext(to_path)[1].lower()
if ext == ".xlsx":
kwargs.pop('sep', None)
df.to_excel(to_path, **kwargs)
elif ext in ['.csv','.txt']:
df.to_csv(to_path, **kwargs)
else:
raise NotImplementedError("Cannot save file of type {}".format(ext))
if save_as is not None:
if keep_orig is False:
# Re-purpose the original model
# Todo - capture the DataFrameModelManager._updates too
model = self._models.pop(filepath)
model._filePath = to_path
else:
# Create a new model.
model = DataFrameModel()
model.setDataFrame(df, copyDataFrame=True, filePath=to_path)
self._models[to_path] = model | python | def save_file(self, filepath, save_as=None, keep_orig=False, **kwargs):
"""
Saves a DataFrameModel to a file.
:param filepath: (str)
The filepath of the DataFrameModel to save.
:param save_as: (str, default None)
The new filepath to save as.
:param keep_orig: (bool, default False)
True keeps the original filepath/DataFrameModel if save_as is specified.
:param kwargs:
pandas.DataFrame.to_excel(**kwargs) if .xlsx
pandas.DataFrame.to_csv(**kwargs) otherwise.
:return: None
"""
df = self._models[filepath].dataFrame()
kwargs['index'] = kwargs.get('index', False)
if save_as is not None:
to_path = save_as
else:
to_path = filepath
ext = os.path.splitext(to_path)[1].lower()
if ext == ".xlsx":
kwargs.pop('sep', None)
df.to_excel(to_path, **kwargs)
elif ext in ['.csv','.txt']:
df.to_csv(to_path, **kwargs)
else:
raise NotImplementedError("Cannot save file of type {}".format(ext))
if save_as is not None:
if keep_orig is False:
# Re-purpose the original model
# Todo - capture the DataFrameModelManager._updates too
model = self._models.pop(filepath)
model._filePath = to_path
else:
# Create a new model.
model = DataFrameModel()
model.setDataFrame(df, copyDataFrame=True, filePath=to_path)
self._models[to_path] = model | [
"def",
"save_file",
"(",
"self",
",",
"filepath",
",",
"save_as",
"=",
"None",
",",
"keep_orig",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"df",
"=",
"self",
".",
"_models",
"[",
"filepath",
"]",
".",
"dataFrame",
"(",
")",
"kwargs",
"[",
"'... | Saves a DataFrameModel to a file.
:param filepath: (str)
The filepath of the DataFrameModel to save.
:param save_as: (str, default None)
The new filepath to save as.
:param keep_orig: (bool, default False)
True keeps the original filepath/DataFrameModel if save_as is specified.
:param kwargs:
pandas.DataFrame.to_excel(**kwargs) if .xlsx
pandas.DataFrame.to_csv(**kwargs) otherwise.
:return: None | [
"Saves",
"a",
"DataFrameModel",
"to",
"a",
"file",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/models/DataFrameModelManager.py#L63-L109 | train | 204,338 |
draperjames/qtpandas | qtpandas/ui/fallback/easygui/boxes/utils.py | exception_format | def exception_format():
"""
Convert exception info into a string suitable for display.
"""
return "".join(traceback.format_exception(
sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]
)) | python | def exception_format():
"""
Convert exception info into a string suitable for display.
"""
return "".join(traceback.format_exception(
sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]
)) | [
"def",
"exception_format",
"(",
")",
":",
"return",
"\"\"",
".",
"join",
"(",
"traceback",
".",
"format_exception",
"(",
"sys",
".",
"exc_info",
"(",
")",
"[",
"0",
"]",
",",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
",",
"sys",
".",
"exc_in... | Convert exception info into a string suitable for display. | [
"Convert",
"exception",
"info",
"into",
"a",
"string",
"suitable",
"for",
"display",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/ui/fallback/easygui/boxes/utils.py#L74-L80 | train | 204,339 |
draperjames/qtpandas | qtpandas/ui/fallback/easygui/boxes/utils.py | load_tk_image | def load_tk_image(filename):
"""
Load in an image file and return as a tk Image.
:param filename: image filename to load
:return: tk Image object
"""
if filename is None:
return None
if not os.path.isfile(filename):
raise ValueError('Image file {} does not exist.'.format(filename))
tk_image = None
filename = os.path.normpath(filename)
_, ext = os.path.splitext(filename)
try:
pil_image = PILImage.open(filename)
tk_image = PILImageTk.PhotoImage(pil_image)
except:
try:
# Fallback if PIL isn't available
tk_image = tk.PhotoImage(file=filename)
except:
msg = "Cannot load {}. Check to make sure it is an image file.".format(filename)
try:
_ = PILImage
except:
msg += "\nPIL library isn't installed. If it isn't installed, only .gif files can be used."
raise ValueError(msg)
return tk_image | python | def load_tk_image(filename):
"""
Load in an image file and return as a tk Image.
:param filename: image filename to load
:return: tk Image object
"""
if filename is None:
return None
if not os.path.isfile(filename):
raise ValueError('Image file {} does not exist.'.format(filename))
tk_image = None
filename = os.path.normpath(filename)
_, ext = os.path.splitext(filename)
try:
pil_image = PILImage.open(filename)
tk_image = PILImageTk.PhotoImage(pil_image)
except:
try:
# Fallback if PIL isn't available
tk_image = tk.PhotoImage(file=filename)
except:
msg = "Cannot load {}. Check to make sure it is an image file.".format(filename)
try:
_ = PILImage
except:
msg += "\nPIL library isn't installed. If it isn't installed, only .gif files can be used."
raise ValueError(msg)
return tk_image | [
"def",
"load_tk_image",
"(",
"filename",
")",
":",
"if",
"filename",
"is",
"None",
":",
"return",
"None",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"raise",
"ValueError",
"(",
"'Image file {} does not exist.'",
".",
"format",
... | Load in an image file and return as a tk Image.
:param filename: image filename to load
:return: tk Image object | [
"Load",
"in",
"an",
"image",
"file",
"and",
"return",
"as",
"a",
"tk",
"Image",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/ui/fallback/easygui/boxes/utils.py#L153-L186 | train | 204,340 |
draperjames/qtpandas | qtpandas/models/ColumnDtypeModel.py | ColumnDtypeModel.setDataFrame | def setDataFrame(self, dataFrame):
"""setter function to _dataFrame. Holds all data.
Note:
It's not implemented with python properties to keep Qt conventions.
Raises:
TypeError: if dataFrame is not of type pandas.core.frame.DataFrame.
Args:
dataFrame (pandas.core.frame.DataFrame): assign dataFrame to _dataFrame. Holds all the data displayed.
"""
if not isinstance(dataFrame, pandas.core.frame.DataFrame):
raise TypeError('Argument is not of type pandas.core.frame.DataFrame')
self.layoutAboutToBeChanged.emit()
self._dataFrame = dataFrame
self.layoutChanged.emit() | python | def setDataFrame(self, dataFrame):
"""setter function to _dataFrame. Holds all data.
Note:
It's not implemented with python properties to keep Qt conventions.
Raises:
TypeError: if dataFrame is not of type pandas.core.frame.DataFrame.
Args:
dataFrame (pandas.core.frame.DataFrame): assign dataFrame to _dataFrame. Holds all the data displayed.
"""
if not isinstance(dataFrame, pandas.core.frame.DataFrame):
raise TypeError('Argument is not of type pandas.core.frame.DataFrame')
self.layoutAboutToBeChanged.emit()
self._dataFrame = dataFrame
self.layoutChanged.emit() | [
"def",
"setDataFrame",
"(",
"self",
",",
"dataFrame",
")",
":",
"if",
"not",
"isinstance",
"(",
"dataFrame",
",",
"pandas",
".",
"core",
".",
"frame",
".",
"DataFrame",
")",
":",
"raise",
"TypeError",
"(",
"'Argument is not of type pandas.core.frame.DataFrame'",
... | setter function to _dataFrame. Holds all data.
Note:
It's not implemented with python properties to keep Qt conventions.
Raises:
TypeError: if dataFrame is not of type pandas.core.frame.DataFrame.
Args:
dataFrame (pandas.core.frame.DataFrame): assign dataFrame to _dataFrame. Holds all the data displayed. | [
"setter",
"function",
"to",
"_dataFrame",
".",
"Holds",
"all",
"data",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/models/ColumnDtypeModel.py#L63-L81 | train | 204,341 |
draperjames/qtpandas | qtpandas/models/ColumnDtypeModel.py | ColumnDtypeModel.setEditable | def setEditable(self, editable):
"""setter to _editable. apply changes while changing dtype.
Raises:
TypeError: if editable is not of type bool.
Args:
editable (bool): apply changes while changing dtype.
"""
if not isinstance(editable, bool):
raise TypeError('Argument is not of type bool')
self._editable = editable | python | def setEditable(self, editable):
"""setter to _editable. apply changes while changing dtype.
Raises:
TypeError: if editable is not of type bool.
Args:
editable (bool): apply changes while changing dtype.
"""
if not isinstance(editable, bool):
raise TypeError('Argument is not of type bool')
self._editable = editable | [
"def",
"setEditable",
"(",
"self",
",",
"editable",
")",
":",
"if",
"not",
"isinstance",
"(",
"editable",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"'Argument is not of type bool'",
")",
"self",
".",
"_editable",
"=",
"editable"
] | setter to _editable. apply changes while changing dtype.
Raises:
TypeError: if editable is not of type bool.
Args:
editable (bool): apply changes while changing dtype. | [
"setter",
"to",
"_editable",
".",
"apply",
"changes",
"while",
"changing",
"dtype",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/models/ColumnDtypeModel.py#L87-L99 | train | 204,342 |
draperjames/qtpandas | qtpandas/models/ColumnDtypeModel.py | ColumnDtypeModel.data | def data(self, index, role=Qt.DisplayRole):
"""Retrieve the data stored in the model at the given `index`.
Args:
index (QtCore.QModelIndex): The model index, which points at a
data object.
role (Qt.ItemDataRole, optional): Defaults to `Qt.DisplayRole`. You
have to use different roles to retrieve different data for an
`index`. Accepted roles are `Qt.DisplayRole`, `Qt.EditRole` and
`DTYPE_ROLE`.
Returns:
None if an invalid index is given, the role is not accepted by the
model or the column is greater than `1`.
The column name will be returned if the given column number equals `0`
and the role is either `Qt.DisplayRole` or `Qt.EditRole`.
The datatype will be returned, if the column number equals `1`. The
`Qt.DisplayRole` or `Qt.EditRole` return a human readable, translated
string, whereas the `DTYPE_ROLE` returns the raw data type.
"""
# an index is invalid, if a row or column does not exist or extends
# the bounds of self.columnCount() or self.rowCount()
# therefor a check for col>1 is unnecessary.
if not index.isValid():
return None
col = index.column()
#row = self._dataFrame.columns[index.column()]
columnName = self._dataFrame.columns[index.row()]
columnDtype = self._dataFrame[columnName].dtype
if role == Qt.DisplayRole or role == Qt.EditRole:
if col == 0:
if columnName == index.row():
return index.row()
return columnName
elif col == 1:
return SupportedDtypes.description(columnDtype)
elif role == DTYPE_ROLE:
if col == 1:
return columnDtype
else:
return None | python | def data(self, index, role=Qt.DisplayRole):
"""Retrieve the data stored in the model at the given `index`.
Args:
index (QtCore.QModelIndex): The model index, which points at a
data object.
role (Qt.ItemDataRole, optional): Defaults to `Qt.DisplayRole`. You
have to use different roles to retrieve different data for an
`index`. Accepted roles are `Qt.DisplayRole`, `Qt.EditRole` and
`DTYPE_ROLE`.
Returns:
None if an invalid index is given, the role is not accepted by the
model or the column is greater than `1`.
The column name will be returned if the given column number equals `0`
and the role is either `Qt.DisplayRole` or `Qt.EditRole`.
The datatype will be returned, if the column number equals `1`. The
`Qt.DisplayRole` or `Qt.EditRole` return a human readable, translated
string, whereas the `DTYPE_ROLE` returns the raw data type.
"""
# an index is invalid, if a row or column does not exist or extends
# the bounds of self.columnCount() or self.rowCount()
# therefor a check for col>1 is unnecessary.
if not index.isValid():
return None
col = index.column()
#row = self._dataFrame.columns[index.column()]
columnName = self._dataFrame.columns[index.row()]
columnDtype = self._dataFrame[columnName].dtype
if role == Qt.DisplayRole or role == Qt.EditRole:
if col == 0:
if columnName == index.row():
return index.row()
return columnName
elif col == 1:
return SupportedDtypes.description(columnDtype)
elif role == DTYPE_ROLE:
if col == 1:
return columnDtype
else:
return None | [
"def",
"data",
"(",
"self",
",",
"index",
",",
"role",
"=",
"Qt",
".",
"DisplayRole",
")",
":",
"# an index is invalid, if a row or column does not exist or extends",
"# the bounds of self.columnCount() or self.rowCount()",
"# therefor a check for col>1 is unnecessary.",
"if",
"n... | Retrieve the data stored in the model at the given `index`.
Args:
index (QtCore.QModelIndex): The model index, which points at a
data object.
role (Qt.ItemDataRole, optional): Defaults to `Qt.DisplayRole`. You
have to use different roles to retrieve different data for an
`index`. Accepted roles are `Qt.DisplayRole`, `Qt.EditRole` and
`DTYPE_ROLE`.
Returns:
None if an invalid index is given, the role is not accepted by the
model or the column is greater than `1`.
The column name will be returned if the given column number equals `0`
and the role is either `Qt.DisplayRole` or `Qt.EditRole`.
The datatype will be returned, if the column number equals `1`. The
`Qt.DisplayRole` or `Qt.EditRole` return a human readable, translated
string, whereas the `DTYPE_ROLE` returns the raw data type. | [
"Retrieve",
"the",
"data",
"stored",
"in",
"the",
"model",
"at",
"the",
"given",
"index",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/models/ColumnDtypeModel.py#L123-L168 | train | 204,343 |
draperjames/qtpandas | qtpandas/models/ColumnDtypeModel.py | ColumnDtypeModel.setData | def setData(self, index, value, role=DTYPE_CHANGE_ROLE):
"""Updates the datatype of a column.
The model must be initated with a dataframe already, since valid
indexes are necessary. The `value` is a translated description of the
data type. The translations can be found at
`qtpandas.translation.DTypeTranslator`.
If a datatype can not be converted, e.g. datetime to integer, a
`NotImplementedError` will be raised.
Args:
index (QtCore.QModelIndex): The index of the column to be changed.
value (str): The description of the new datatype, e.g.
`positive kleine ganze Zahl (16 Bit)`.
role (Qt.ItemDataRole, optional): The role, which accesses and
changes data. Defaults to `DTYPE_CHANGE_ROLE`.
Raises:
NotImplementedError: If an error during conversion occured.
Returns:
bool: `True` if the datatype could be changed, `False` if not or if
the new datatype equals the old one.
"""
if role != DTYPE_CHANGE_ROLE or not index.isValid():
return False
if not self.editable():
return False
self.layoutAboutToBeChanged.emit()
dtype = SupportedDtypes.dtype(value)
currentDtype = np.dtype(index.data(role=DTYPE_ROLE))
if dtype is not None:
if dtype != currentDtype:
# col = index.column()
# row = self._dataFrame.columns[index.column()]
columnName = self._dataFrame.columns[index.row()]
try:
if dtype == np.dtype('<M8[ns]'):
if currentDtype in SupportedDtypes.boolTypes():
raise Exception("Can't convert a boolean value into a datetime value.")
self._dataFrame[columnName] = self._dataFrame[columnName].apply(pandas.to_datetime)
else:
self._dataFrame[columnName] = self._dataFrame[columnName].astype(dtype)
self.dtypeChanged.emit(index.row(), dtype)
self.layoutChanged.emit()
return True
except Exception:
message = 'Could not change datatype %s of column %s to datatype %s' % (currentDtype, columnName, dtype)
self.changeFailed.emit(message, index, dtype)
raise
# self._dataFrame[columnName] = self._dataFrame[columnName].astype(currentDtype)
# self.layoutChanged.emit()
# self.dtypeChanged.emit(columnName)
#raise NotImplementedError, "dtype changing not fully working, original error:\n{}".format(e)
return False | python | def setData(self, index, value, role=DTYPE_CHANGE_ROLE):
"""Updates the datatype of a column.
The model must be initated with a dataframe already, since valid
indexes are necessary. The `value` is a translated description of the
data type. The translations can be found at
`qtpandas.translation.DTypeTranslator`.
If a datatype can not be converted, e.g. datetime to integer, a
`NotImplementedError` will be raised.
Args:
index (QtCore.QModelIndex): The index of the column to be changed.
value (str): The description of the new datatype, e.g.
`positive kleine ganze Zahl (16 Bit)`.
role (Qt.ItemDataRole, optional): The role, which accesses and
changes data. Defaults to `DTYPE_CHANGE_ROLE`.
Raises:
NotImplementedError: If an error during conversion occured.
Returns:
bool: `True` if the datatype could be changed, `False` if not or if
the new datatype equals the old one.
"""
if role != DTYPE_CHANGE_ROLE or not index.isValid():
return False
if not self.editable():
return False
self.layoutAboutToBeChanged.emit()
dtype = SupportedDtypes.dtype(value)
currentDtype = np.dtype(index.data(role=DTYPE_ROLE))
if dtype is not None:
if dtype != currentDtype:
# col = index.column()
# row = self._dataFrame.columns[index.column()]
columnName = self._dataFrame.columns[index.row()]
try:
if dtype == np.dtype('<M8[ns]'):
if currentDtype in SupportedDtypes.boolTypes():
raise Exception("Can't convert a boolean value into a datetime value.")
self._dataFrame[columnName] = self._dataFrame[columnName].apply(pandas.to_datetime)
else:
self._dataFrame[columnName] = self._dataFrame[columnName].astype(dtype)
self.dtypeChanged.emit(index.row(), dtype)
self.layoutChanged.emit()
return True
except Exception:
message = 'Could not change datatype %s of column %s to datatype %s' % (currentDtype, columnName, dtype)
self.changeFailed.emit(message, index, dtype)
raise
# self._dataFrame[columnName] = self._dataFrame[columnName].astype(currentDtype)
# self.layoutChanged.emit()
# self.dtypeChanged.emit(columnName)
#raise NotImplementedError, "dtype changing not fully working, original error:\n{}".format(e)
return False | [
"def",
"setData",
"(",
"self",
",",
"index",
",",
"value",
",",
"role",
"=",
"DTYPE_CHANGE_ROLE",
")",
":",
"if",
"role",
"!=",
"DTYPE_CHANGE_ROLE",
"or",
"not",
"index",
".",
"isValid",
"(",
")",
":",
"return",
"False",
"if",
"not",
"self",
".",
"edit... | Updates the datatype of a column.
The model must be initated with a dataframe already, since valid
indexes are necessary. The `value` is a translated description of the
data type. The translations can be found at
`qtpandas.translation.DTypeTranslator`.
If a datatype can not be converted, e.g. datetime to integer, a
`NotImplementedError` will be raised.
Args:
index (QtCore.QModelIndex): The index of the column to be changed.
value (str): The description of the new datatype, e.g.
`positive kleine ganze Zahl (16 Bit)`.
role (Qt.ItemDataRole, optional): The role, which accesses and
changes data. Defaults to `DTYPE_CHANGE_ROLE`.
Raises:
NotImplementedError: If an error during conversion occured.
Returns:
bool: `True` if the datatype could be changed, `False` if not or if
the new datatype equals the old one. | [
"Updates",
"the",
"datatype",
"of",
"a",
"column",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/models/ColumnDtypeModel.py#L170-L232 | train | 204,344 |
draperjames/qtpandas | qtpandas/models/DataSearch.py | DataSearch.search | def search(self):
"""Applies the filter to the stored dataframe.
A safe environment dictionary will be created, which stores all allowed
functions and attributes, which may be used for the filter.
If any object in the given `filterString` could not be found in the
dictionary, the filter does not apply and returns `False`.
Returns:
tuple: A (indexes, success)-tuple, which indicates identified objects
by applying the filter and if the operation was successful in
general.
"""
# there should be a grammar defined and some lexer/parser.
# instead of this quick-and-dirty implementation.
safeEnvDict = {
'freeSearch': self.freeSearch,
'extentSearch': self.extentSearch,
'indexSearch': self.indexSearch
}
for col in self._dataFrame.columns:
safeEnvDict[col] = self._dataFrame[col]
try:
searchIndex = eval(self._filterString, {
'__builtins__': None}, safeEnvDict)
except NameError:
return [], False
except SyntaxError:
return [], False
except ValueError:
# the use of 'and'/'or' is not valid, need to use binary operators.
return [], False
except TypeError:
# argument must be string or compiled pattern
return [], False
return searchIndex, True | python | def search(self):
"""Applies the filter to the stored dataframe.
A safe environment dictionary will be created, which stores all allowed
functions and attributes, which may be used for the filter.
If any object in the given `filterString` could not be found in the
dictionary, the filter does not apply and returns `False`.
Returns:
tuple: A (indexes, success)-tuple, which indicates identified objects
by applying the filter and if the operation was successful in
general.
"""
# there should be a grammar defined and some lexer/parser.
# instead of this quick-and-dirty implementation.
safeEnvDict = {
'freeSearch': self.freeSearch,
'extentSearch': self.extentSearch,
'indexSearch': self.indexSearch
}
for col in self._dataFrame.columns:
safeEnvDict[col] = self._dataFrame[col]
try:
searchIndex = eval(self._filterString, {
'__builtins__': None}, safeEnvDict)
except NameError:
return [], False
except SyntaxError:
return [], False
except ValueError:
# the use of 'and'/'or' is not valid, need to use binary operators.
return [], False
except TypeError:
# argument must be string or compiled pattern
return [], False
return searchIndex, True | [
"def",
"search",
"(",
"self",
")",
":",
"# there should be a grammar defined and some lexer/parser.",
"# instead of this quick-and-dirty implementation.",
"safeEnvDict",
"=",
"{",
"'freeSearch'",
":",
"self",
".",
"freeSearch",
",",
"'extentSearch'",
":",
"self",
".",
"exte... | Applies the filter to the stored dataframe.
A safe environment dictionary will be created, which stores all allowed
functions and attributes, which may be used for the filter.
If any object in the given `filterString` could not be found in the
dictionary, the filter does not apply and returns `False`.
Returns:
tuple: A (indexes, success)-tuple, which indicates identified objects
by applying the filter and if the operation was successful in
general. | [
"Applies",
"the",
"filter",
"to",
"the",
"stored",
"dataframe",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/models/DataSearch.py#L103-L142 | train | 204,345 |
draperjames/qtpandas | qtpandas/models/DataSearch.py | DataSearch.freeSearch | def freeSearch(self, searchString):
"""Execute a free text search for all columns in the dataframe.
Parameters
----------
searchString (str): Any string which may be contained in a column.
Returns
-------
list: A list containing all indexes with filtered data. Matches
will be `True`, the remaining items will be `False`. If the
dataFrame is empty, an empty list will be returned.
"""
if not self._dataFrame.empty:
# set question to the indexes of data and set everything to false.
question = self._dataFrame.index == -9999
for column in self._dataFrame.columns:
dfColumn = self._dataFrame[column]
dfColumn = dfColumn.apply(str)
question2 = dfColumn.str.contains(searchString,
flags=re.IGNORECASE,
regex=True, na=False)
question = np.logical_or(question, question2)
return question
else:
return [] | python | def freeSearch(self, searchString):
"""Execute a free text search for all columns in the dataframe.
Parameters
----------
searchString (str): Any string which may be contained in a column.
Returns
-------
list: A list containing all indexes with filtered data. Matches
will be `True`, the remaining items will be `False`. If the
dataFrame is empty, an empty list will be returned.
"""
if not self._dataFrame.empty:
# set question to the indexes of data and set everything to false.
question = self._dataFrame.index == -9999
for column in self._dataFrame.columns:
dfColumn = self._dataFrame[column]
dfColumn = dfColumn.apply(str)
question2 = dfColumn.str.contains(searchString,
flags=re.IGNORECASE,
regex=True, na=False)
question = np.logical_or(question, question2)
return question
else:
return [] | [
"def",
"freeSearch",
"(",
"self",
",",
"searchString",
")",
":",
"if",
"not",
"self",
".",
"_dataFrame",
".",
"empty",
":",
"# set question to the indexes of data and set everything to false.",
"question",
"=",
"self",
".",
"_dataFrame",
".",
"index",
"==",
"-",
"... | Execute a free text search for all columns in the dataframe.
Parameters
----------
searchString (str): Any string which may be contained in a column.
Returns
-------
list: A list containing all indexes with filtered data. Matches
will be `True`, the remaining items will be `False`. If the
dataFrame is empty, an empty list will be returned. | [
"Execute",
"a",
"free",
"text",
"search",
"for",
"all",
"columns",
"in",
"the",
"dataframe",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/models/DataSearch.py#L144-L172 | train | 204,346 |
draperjames/qtpandas | qtpandas/models/DataSearch.py | DataSearch.extentSearch | def extentSearch(self, xmin, ymin, xmax, ymax):
"""Filters the data by a geographical bounding box.
The bounding box is given as lower left point coordinates and upper
right point coordinates.
Note:
It's necessary that the dataframe has a `lat` and `lng` column
in order to apply the filter.
Check if the method could be removed in the future. (could be done
via freeSearch)
Returns
-------
list: A list containing all indexes with filtered data. Matches
will be `True`, the remaining items will be `False`. If the
dataFrame is empty, an empty list will be returned.
"""
if not self._dataFrame.empty:
try:
questionMin = (self._dataFrame.lat >= xmin) & (
self._dataFrame.lng >= ymin)
questionMax = (self._dataFrame.lat <= xmax) & (
self._dataFrame.lng <= ymax)
return np.logical_and(questionMin, questionMax)
except AttributeError:
return []
else:
return [] | python | def extentSearch(self, xmin, ymin, xmax, ymax):
"""Filters the data by a geographical bounding box.
The bounding box is given as lower left point coordinates and upper
right point coordinates.
Note:
It's necessary that the dataframe has a `lat` and `lng` column
in order to apply the filter.
Check if the method could be removed in the future. (could be done
via freeSearch)
Returns
-------
list: A list containing all indexes with filtered data. Matches
will be `True`, the remaining items will be `False`. If the
dataFrame is empty, an empty list will be returned.
"""
if not self._dataFrame.empty:
try:
questionMin = (self._dataFrame.lat >= xmin) & (
self._dataFrame.lng >= ymin)
questionMax = (self._dataFrame.lat <= xmax) & (
self._dataFrame.lng <= ymax)
return np.logical_and(questionMin, questionMax)
except AttributeError:
return []
else:
return [] | [
"def",
"extentSearch",
"(",
"self",
",",
"xmin",
",",
"ymin",
",",
"xmax",
",",
"ymax",
")",
":",
"if",
"not",
"self",
".",
"_dataFrame",
".",
"empty",
":",
"try",
":",
"questionMin",
"=",
"(",
"self",
".",
"_dataFrame",
".",
"lat",
">=",
"xmin",
"... | Filters the data by a geographical bounding box.
The bounding box is given as lower left point coordinates and upper
right point coordinates.
Note:
It's necessary that the dataframe has a `lat` and `lng` column
in order to apply the filter.
Check if the method could be removed in the future. (could be done
via freeSearch)
Returns
-------
list: A list containing all indexes with filtered data. Matches
will be `True`, the remaining items will be `False`. If the
dataFrame is empty, an empty list will be returned. | [
"Filters",
"the",
"data",
"by",
"a",
"geographical",
"bounding",
"box",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/models/DataSearch.py#L174-L204 | train | 204,347 |
draperjames/qtpandas | qtpandas/models/DataSearch.py | DataSearch.indexSearch | def indexSearch(self, indexes):
"""Filters the data by a list of indexes.
Args:
indexes (list of int): List of index numbers to return.
Returns:
list: A list containing all indexes with filtered data. Matches
will be `True`, the remaining items will be `False`. If the
dataFrame is empty, an empty list will be returned.
"""
if not self._dataFrame.empty:
filter0 = self._dataFrame.index == -9999
for index in indexes:
filter1 = self._dataFrame.index == index
filter0 = np.logical_or(filter0, filter1)
return filter0
else:
return [] | python | def indexSearch(self, indexes):
"""Filters the data by a list of indexes.
Args:
indexes (list of int): List of index numbers to return.
Returns:
list: A list containing all indexes with filtered data. Matches
will be `True`, the remaining items will be `False`. If the
dataFrame is empty, an empty list will be returned.
"""
if not self._dataFrame.empty:
filter0 = self._dataFrame.index == -9999
for index in indexes:
filter1 = self._dataFrame.index == index
filter0 = np.logical_or(filter0, filter1)
return filter0
else:
return [] | [
"def",
"indexSearch",
"(",
"self",
",",
"indexes",
")",
":",
"if",
"not",
"self",
".",
"_dataFrame",
".",
"empty",
":",
"filter0",
"=",
"self",
".",
"_dataFrame",
".",
"index",
"==",
"-",
"9999",
"for",
"index",
"in",
"indexes",
":",
"filter1",
"=",
... | Filters the data by a list of indexes.
Args:
indexes (list of int): List of index numbers to return.
Returns:
list: A list containing all indexes with filtered data. Matches
will be `True`, the remaining items will be `False`. If the
dataFrame is empty, an empty list will be returned. | [
"Filters",
"the",
"data",
"by",
"a",
"list",
"of",
"indexes",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/models/DataSearch.py#L206-L227 | train | 204,348 |
draperjames/qtpandas | qtpandas/models/DataFrameModel.py | read_file | def read_file(filepath, **kwargs):
"""
Read a data file into a DataFrameModel.
:param filepath: The rows/columns filepath to read.
:param kwargs:
xls/x files - see pandas.read_excel(**kwargs)
.csv/.txt/etc - see pandas.read_csv(**kwargs)
:return: DataFrameModel
"""
return DataFrameModel(dataFrame=superReadFile(filepath, **kwargs),
filePath=filepath) | python | def read_file(filepath, **kwargs):
"""
Read a data file into a DataFrameModel.
:param filepath: The rows/columns filepath to read.
:param kwargs:
xls/x files - see pandas.read_excel(**kwargs)
.csv/.txt/etc - see pandas.read_csv(**kwargs)
:return: DataFrameModel
"""
return DataFrameModel(dataFrame=superReadFile(filepath, **kwargs),
filePath=filepath) | [
"def",
"read_file",
"(",
"filepath",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"DataFrameModel",
"(",
"dataFrame",
"=",
"superReadFile",
"(",
"filepath",
",",
"*",
"*",
"kwargs",
")",
",",
"filePath",
"=",
"filepath",
")"
] | Read a data file into a DataFrameModel.
:param filepath: The rows/columns filepath to read.
:param kwargs:
xls/x files - see pandas.read_excel(**kwargs)
.csv/.txt/etc - see pandas.read_csv(**kwargs)
:return: DataFrameModel | [
"Read",
"a",
"data",
"file",
"into",
"a",
"DataFrameModel",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/models/DataFrameModel.py#L36-L47 | train | 204,349 |
draperjames/qtpandas | qtpandas/models/DataFrameModel.py | DataFrameModel.setDataFrame | def setDataFrame(self, dataFrame, copyDataFrame=False, filePath=None):
"""
Setter function to _dataFrame. Holds all data.
Note:
It's not implemented with python properties to keep Qt conventions.
Raises:
TypeError: if dataFrame is not of type pandas.core.frame.DataFrame.
Args:
dataFrame (pandas.core.frame.DataFrame): assign dataFrame to _dataFrame. Holds all the data displayed.
copyDataFrame (bool, optional): create a copy of dataFrame or use it as is. defaults to False.
If you use it as is, you can change it from outside otherwise you have to reset the dataFrame
after external changes.
"""
if not isinstance(dataFrame, pandas.core.frame.DataFrame):
raise TypeError("not of type pandas.core.frame.DataFrame")
self.layoutAboutToBeChanged.emit()
if copyDataFrame:
self._dataFrame = dataFrame.copy()
else:
self._dataFrame = dataFrame
self._columnDtypeModel = ColumnDtypeModel(dataFrame)
self._columnDtypeModel.dtypeChanged.connect(self.propagateDtypeChanges)
self._columnDtypeModel.changeFailed.connect(
lambda columnName, index, dtype: self.changingDtypeFailed.emit(columnName, index, dtype)
)
if filePath is not None:
self._filePath = filePath
self.layoutChanged.emit()
self.dataChanged.emit()
self.dataFrameChanged.emit() | python | def setDataFrame(self, dataFrame, copyDataFrame=False, filePath=None):
"""
Setter function to _dataFrame. Holds all data.
Note:
It's not implemented with python properties to keep Qt conventions.
Raises:
TypeError: if dataFrame is not of type pandas.core.frame.DataFrame.
Args:
dataFrame (pandas.core.frame.DataFrame): assign dataFrame to _dataFrame. Holds all the data displayed.
copyDataFrame (bool, optional): create a copy of dataFrame or use it as is. defaults to False.
If you use it as is, you can change it from outside otherwise you have to reset the dataFrame
after external changes.
"""
if not isinstance(dataFrame, pandas.core.frame.DataFrame):
raise TypeError("not of type pandas.core.frame.DataFrame")
self.layoutAboutToBeChanged.emit()
if copyDataFrame:
self._dataFrame = dataFrame.copy()
else:
self._dataFrame = dataFrame
self._columnDtypeModel = ColumnDtypeModel(dataFrame)
self._columnDtypeModel.dtypeChanged.connect(self.propagateDtypeChanges)
self._columnDtypeModel.changeFailed.connect(
lambda columnName, index, dtype: self.changingDtypeFailed.emit(columnName, index, dtype)
)
if filePath is not None:
self._filePath = filePath
self.layoutChanged.emit()
self.dataChanged.emit()
self.dataFrameChanged.emit() | [
"def",
"setDataFrame",
"(",
"self",
",",
"dataFrame",
",",
"copyDataFrame",
"=",
"False",
",",
"filePath",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"dataFrame",
",",
"pandas",
".",
"core",
".",
"frame",
".",
"DataFrame",
")",
":",
"raise",
... | Setter function to _dataFrame. Holds all data.
Note:
It's not implemented with python properties to keep Qt conventions.
Raises:
TypeError: if dataFrame is not of type pandas.core.frame.DataFrame.
Args:
dataFrame (pandas.core.frame.DataFrame): assign dataFrame to _dataFrame. Holds all the data displayed.
copyDataFrame (bool, optional): create a copy of dataFrame or use it as is. defaults to False.
If you use it as is, you can change it from outside otherwise you have to reset the dataFrame
after external changes. | [
"Setter",
"function",
"to",
"_dataFrame",
".",
"Holds",
"all",
"data",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/models/DataFrameModel.py#L182-L217 | train | 204,350 |
draperjames/qtpandas | qtpandas/models/DataFrameModel.py | DataFrameModel.timestampFormat | def timestampFormat(self, timestampFormat):
"""
Setter to _timestampFormat. Formatting string for conversion of timestamps to QtCore.QDateTime
Raises:
AssertionError: if timestampFormat is not of type unicode.
Args:
timestampFormat (unicode): assign timestampFormat to _timestampFormat.
Formatting string for conversion of timestamps to QtCore.QDateTime. Used in data method.
"""
if not isinstance(timestampFormat, str):
raise TypeError('not of type unicode')
#assert isinstance(timestampFormat, unicode) or timestampFormat.__class__.__name__ == "DateFormat", "not of type unicode"
self._timestampFormat = timestampFormat | python | def timestampFormat(self, timestampFormat):
"""
Setter to _timestampFormat. Formatting string for conversion of timestamps to QtCore.QDateTime
Raises:
AssertionError: if timestampFormat is not of type unicode.
Args:
timestampFormat (unicode): assign timestampFormat to _timestampFormat.
Formatting string for conversion of timestamps to QtCore.QDateTime. Used in data method.
"""
if not isinstance(timestampFormat, str):
raise TypeError('not of type unicode')
#assert isinstance(timestampFormat, unicode) or timestampFormat.__class__.__name__ == "DateFormat", "not of type unicode"
self._timestampFormat = timestampFormat | [
"def",
"timestampFormat",
"(",
"self",
",",
"timestampFormat",
")",
":",
"if",
"not",
"isinstance",
"(",
"timestampFormat",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"'not of type unicode'",
")",
"#assert isinstance(timestampFormat, unicode) or timestampFormat.__cl... | Setter to _timestampFormat. Formatting string for conversion of timestamps to QtCore.QDateTime
Raises:
AssertionError: if timestampFormat is not of type unicode.
Args:
timestampFormat (unicode): assign timestampFormat to _timestampFormat.
Formatting string for conversion of timestamps to QtCore.QDateTime. Used in data method. | [
"Setter",
"to",
"_timestampFormat",
".",
"Formatting",
"string",
"for",
"conversion",
"of",
"timestamps",
"to",
"QtCore",
".",
"QDateTime"
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/models/DataFrameModel.py#L236-L251 | train | 204,351 |
draperjames/qtpandas | qtpandas/models/DataFrameModel.py | DataFrameModel.sort | def sort(self, columnId, order=Qt.AscendingOrder):
"""
Sorts the model column
After sorting the data in ascending or descending order, a signal
`layoutChanged` is emitted.
:param: columnId (int)
the index of the column to sort on.
:param: order (Qt::SortOrder, optional)
descending(1) or ascending(0). defaults to Qt.AscendingOrder
"""
self.layoutAboutToBeChanged.emit()
self.sortingAboutToStart.emit()
column = self._dataFrame.columns[columnId]
self._dataFrame.sort_values(column, ascending=not bool(order), inplace=True)
self.layoutChanged.emit()
self.sortingFinished.emit() | python | def sort(self, columnId, order=Qt.AscendingOrder):
"""
Sorts the model column
After sorting the data in ascending or descending order, a signal
`layoutChanged` is emitted.
:param: columnId (int)
the index of the column to sort on.
:param: order (Qt::SortOrder, optional)
descending(1) or ascending(0). defaults to Qt.AscendingOrder
"""
self.layoutAboutToBeChanged.emit()
self.sortingAboutToStart.emit()
column = self._dataFrame.columns[columnId]
self._dataFrame.sort_values(column, ascending=not bool(order), inplace=True)
self.layoutChanged.emit()
self.sortingFinished.emit() | [
"def",
"sort",
"(",
"self",
",",
"columnId",
",",
"order",
"=",
"Qt",
".",
"AscendingOrder",
")",
":",
"self",
".",
"layoutAboutToBeChanged",
".",
"emit",
"(",
")",
"self",
".",
"sortingAboutToStart",
".",
"emit",
"(",
")",
"column",
"=",
"self",
".",
... | Sorts the model column
After sorting the data in ascending or descending order, a signal
`layoutChanged` is emitted.
:param: columnId (int)
the index of the column to sort on.
:param: order (Qt::SortOrder, optional)
descending(1) or ascending(0). defaults to Qt.AscendingOrder | [
"Sorts",
"the",
"model",
"column"
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/models/DataFrameModel.py#L541-L559 | train | 204,352 |
draperjames/qtpandas | qtpandas/models/DataFrameModel.py | DataFrameModel.setFilter | def setFilter(self, search):
"""
Apply a filter and hide rows.
The filter must be a `DataSearch` object, which evaluates a python
expression.
If there was an error while parsing the expression, the data will remain
unfiltered.
Args:
search(qtpandas.DataSearch): data search object to use.
Raises:
TypeError: An error is raised, if the given parameter is not a
`DataSearch` object.
"""
if not isinstance(search, DataSearch):
raise TypeError('The given parameter must an `qtpandas.DataSearch` object')
self._search = search
self.layoutAboutToBeChanged.emit()
if self._dataFrameOriginal is not None:
self._dataFrame = self._dataFrameOriginal
self._dataFrameOriginal = self._dataFrame.copy()
self._search.setDataFrame(self._dataFrame)
searchIndex, valid = self._search.search()
if valid:
self._dataFrame = self._dataFrame[searchIndex]
self.layoutChanged.emit()
else:
self.clearFilter()
self.layoutChanged.emit()
self.dataFrameChanged.emit() | python | def setFilter(self, search):
"""
Apply a filter and hide rows.
The filter must be a `DataSearch` object, which evaluates a python
expression.
If there was an error while parsing the expression, the data will remain
unfiltered.
Args:
search(qtpandas.DataSearch): data search object to use.
Raises:
TypeError: An error is raised, if the given parameter is not a
`DataSearch` object.
"""
if not isinstance(search, DataSearch):
raise TypeError('The given parameter must an `qtpandas.DataSearch` object')
self._search = search
self.layoutAboutToBeChanged.emit()
if self._dataFrameOriginal is not None:
self._dataFrame = self._dataFrameOriginal
self._dataFrameOriginal = self._dataFrame.copy()
self._search.setDataFrame(self._dataFrame)
searchIndex, valid = self._search.search()
if valid:
self._dataFrame = self._dataFrame[searchIndex]
self.layoutChanged.emit()
else:
self.clearFilter()
self.layoutChanged.emit()
self.dataFrameChanged.emit() | [
"def",
"setFilter",
"(",
"self",
",",
"search",
")",
":",
"if",
"not",
"isinstance",
"(",
"search",
",",
"DataSearch",
")",
":",
"raise",
"TypeError",
"(",
"'The given parameter must an `qtpandas.DataSearch` object'",
")",
"self",
".",
"_search",
"=",
"search",
... | Apply a filter and hide rows.
The filter must be a `DataSearch` object, which evaluates a python
expression.
If there was an error while parsing the expression, the data will remain
unfiltered.
Args:
search(qtpandas.DataSearch): data search object to use.
Raises:
TypeError: An error is raised, if the given parameter is not a
`DataSearch` object. | [
"Apply",
"a",
"filter",
"and",
"hide",
"rows",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/models/DataFrameModel.py#L561-L599 | train | 204,353 |
draperjames/qtpandas | qtpandas/models/DataFrameModel.py | DataFrameModel.clearFilter | def clearFilter(self):
"""
Clear all filters.
"""
if self._dataFrameOriginal is not None:
self.layoutAboutToBeChanged.emit()
self._dataFrame = self._dataFrameOriginal
self._dataFrameOriginal = None
self.layoutChanged.emit() | python | def clearFilter(self):
"""
Clear all filters.
"""
if self._dataFrameOriginal is not None:
self.layoutAboutToBeChanged.emit()
self._dataFrame = self._dataFrameOriginal
self._dataFrameOriginal = None
self.layoutChanged.emit() | [
"def",
"clearFilter",
"(",
"self",
")",
":",
"if",
"self",
".",
"_dataFrameOriginal",
"is",
"not",
"None",
":",
"self",
".",
"layoutAboutToBeChanged",
".",
"emit",
"(",
")",
"self",
".",
"_dataFrame",
"=",
"self",
".",
"_dataFrameOriginal",
"self",
".",
"_... | Clear all filters. | [
"Clear",
"all",
"filters",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/models/DataFrameModel.py#L601-L609 | train | 204,354 |
draperjames/qtpandas | qtpandas/models/DataFrameModel.py | DataFrameModel.addDataFrameColumn | def addDataFrameColumn(self, columnName, dtype=str, defaultValue=None):
"""
Adds a column to the dataframe as long as
the model's editable property is set to True and the
dtype is supported.
:param columnName: str
name of the column.
:param dtype: qtpandas.models.SupportedDtypes option
:param defaultValue: (object)
to default the column's value to, should be the same as the dtype or None
:return: (bool)
True on success, False otherwise.
"""
if not self.editable or dtype not in SupportedDtypes.allTypes():
return False
elements = self.rowCount()
columnPosition = self.columnCount()
newColumn = pandas.Series([defaultValue]*elements, index=self._dataFrame.index, dtype=dtype)
self.beginInsertColumns(QtCore.QModelIndex(), columnPosition - 1, columnPosition - 1)
try:
self._dataFrame.insert(columnPosition, columnName, newColumn, allow_duplicates=False)
except ValueError as e:
# columnName does already exist
return False
self.endInsertColumns()
self.propagateDtypeChanges(columnPosition, newColumn.dtype)
return True | python | def addDataFrameColumn(self, columnName, dtype=str, defaultValue=None):
"""
Adds a column to the dataframe as long as
the model's editable property is set to True and the
dtype is supported.
:param columnName: str
name of the column.
:param dtype: qtpandas.models.SupportedDtypes option
:param defaultValue: (object)
to default the column's value to, should be the same as the dtype or None
:return: (bool)
True on success, False otherwise.
"""
if not self.editable or dtype not in SupportedDtypes.allTypes():
return False
elements = self.rowCount()
columnPosition = self.columnCount()
newColumn = pandas.Series([defaultValue]*elements, index=self._dataFrame.index, dtype=dtype)
self.beginInsertColumns(QtCore.QModelIndex(), columnPosition - 1, columnPosition - 1)
try:
self._dataFrame.insert(columnPosition, columnName, newColumn, allow_duplicates=False)
except ValueError as e:
# columnName does already exist
return False
self.endInsertColumns()
self.propagateDtypeChanges(columnPosition, newColumn.dtype)
return True | [
"def",
"addDataFrameColumn",
"(",
"self",
",",
"columnName",
",",
"dtype",
"=",
"str",
",",
"defaultValue",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"editable",
"or",
"dtype",
"not",
"in",
"SupportedDtypes",
".",
"allTypes",
"(",
")",
":",
"retur... | Adds a column to the dataframe as long as
the model's editable property is set to True and the
dtype is supported.
:param columnName: str
name of the column.
:param dtype: qtpandas.models.SupportedDtypes option
:param defaultValue: (object)
to default the column's value to, should be the same as the dtype or None
:return: (bool)
True on success, False otherwise. | [
"Adds",
"a",
"column",
"to",
"the",
"dataframe",
"as",
"long",
"as",
"the",
"model",
"s",
"editable",
"property",
"is",
"set",
"to",
"True",
"and",
"the",
"dtype",
"is",
"supported",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/models/DataFrameModel.py#L640-L673 | train | 204,355 |
draperjames/qtpandas | qtpandas/models/DataFrameModel.py | DataFrameModel.removeDataFrameRows | def removeDataFrameRows(self, rows):
"""
Removes rows from the dataframe.
:param rows: (list)
of row indexes to removes.
:return: (bool)
True on success, False on failure.
"""
if not self.editable:
return False
if rows:
position = min(rows)
count = len(rows)
self.beginRemoveRows(QtCore.QModelIndex(), position, position + count - 1)
removedAny = False
for idx, line in self._dataFrame.iterrows():
if idx in rows:
removedAny = True
self._dataFrame.drop(idx, inplace=True)
if not removedAny:
return False
self._dataFrame.reset_index(inplace=True, drop=True)
self.endRemoveRows()
return True
return False | python | def removeDataFrameRows(self, rows):
"""
Removes rows from the dataframe.
:param rows: (list)
of row indexes to removes.
:return: (bool)
True on success, False on failure.
"""
if not self.editable:
return False
if rows:
position = min(rows)
count = len(rows)
self.beginRemoveRows(QtCore.QModelIndex(), position, position + count - 1)
removedAny = False
for idx, line in self._dataFrame.iterrows():
if idx in rows:
removedAny = True
self._dataFrame.drop(idx, inplace=True)
if not removedAny:
return False
self._dataFrame.reset_index(inplace=True, drop=True)
self.endRemoveRows()
return True
return False | [
"def",
"removeDataFrameRows",
"(",
"self",
",",
"rows",
")",
":",
"if",
"not",
"self",
".",
"editable",
":",
"return",
"False",
"if",
"rows",
":",
"position",
"=",
"min",
"(",
"rows",
")",
"count",
"=",
"len",
"(",
"rows",
")",
"self",
".",
"beginRem... | Removes rows from the dataframe.
:param rows: (list)
of row indexes to removes.
:return: (bool)
True on success, False on failure. | [
"Removes",
"rows",
"from",
"the",
"dataframe",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/models/DataFrameModel.py#L755-L785 | train | 204,356 |
draperjames/qtpandas | qtpandas/ui/fallback/easygui/boxes/egstore.py | EgStore.restore | def restore(self):
"""
Set the values of whatever attributes are recoverable
from the pickle file.
Populate the attributes (the __dict__) of the EgStore object
from the attributes (the __dict__) of the pickled object.
If the pickled object has attributes that have been initialized
in the EgStore object, then those attributes of the EgStore object
will be replaced by the values of the corresponding attributes
in the pickled object.
If the pickled object is missing some attributes that have
been initialized in the EgStore object, then those attributes
of the EgStore object will retain the values that they were
initialized with.
If the pickled object has some attributes that were not
initialized in the EgStore object, then those attributes
will be ignored.
IN SUMMARY:
After the recover() operation, the EgStore object will have all,
and only, the attributes that it had when it was initialized.
Where possible, those attributes will have values recovered
from the pickled object.
"""
if not os.path.exists(self.filename):
return self
if not os.path.isfile(self.filename):
return self
try:
with open(self.filename, "rb") as f:
unpickledObject = pickle.load(f)
for key in list(self.__dict__.keys()):
default = self.__dict__[key]
self.__dict__[key] = unpickledObject.__dict__.get(key, default)
except:
pass
return self | python | def restore(self):
"""
Set the values of whatever attributes are recoverable
from the pickle file.
Populate the attributes (the __dict__) of the EgStore object
from the attributes (the __dict__) of the pickled object.
If the pickled object has attributes that have been initialized
in the EgStore object, then those attributes of the EgStore object
will be replaced by the values of the corresponding attributes
in the pickled object.
If the pickled object is missing some attributes that have
been initialized in the EgStore object, then those attributes
of the EgStore object will retain the values that they were
initialized with.
If the pickled object has some attributes that were not
initialized in the EgStore object, then those attributes
will be ignored.
IN SUMMARY:
After the recover() operation, the EgStore object will have all,
and only, the attributes that it had when it was initialized.
Where possible, those attributes will have values recovered
from the pickled object.
"""
if not os.path.exists(self.filename):
return self
if not os.path.isfile(self.filename):
return self
try:
with open(self.filename, "rb") as f:
unpickledObject = pickle.load(f)
for key in list(self.__dict__.keys()):
default = self.__dict__[key]
self.__dict__[key] = unpickledObject.__dict__.get(key, default)
except:
pass
return self | [
"def",
"restore",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"filename",
")",
":",
"return",
"self",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"filename",
")",
":",
"return",
"se... | Set the values of whatever attributes are recoverable
from the pickle file.
Populate the attributes (the __dict__) of the EgStore object
from the attributes (the __dict__) of the pickled object.
If the pickled object has attributes that have been initialized
in the EgStore object, then those attributes of the EgStore object
will be replaced by the values of the corresponding attributes
in the pickled object.
If the pickled object is missing some attributes that have
been initialized in the EgStore object, then those attributes
of the EgStore object will retain the values that they were
initialized with.
If the pickled object has some attributes that were not
initialized in the EgStore object, then those attributes
will be ignored.
IN SUMMARY:
After the recover() operation, the EgStore object will have all,
and only, the attributes that it had when it was initialized.
Where possible, those attributes will have values recovered
from the pickled object. | [
"Set",
"the",
"values",
"of",
"whatever",
"attributes",
"are",
"recoverable",
"from",
"the",
"pickle",
"file",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/ui/fallback/easygui/boxes/egstore.py#L85-L130 | train | 204,357 |
draperjames/qtpandas | qtpandas/ui/fallback/easygui/boxes/egstore.py | EgStore.store | def store(self):
"""
Save the attributes of the EgStore object to a pickle file.
Note that if the directory for the pickle file does not already exist,
the store operation will fail.
"""
with open(self.filename, "wb") as f:
pickle.dump(self, f) | python | def store(self):
"""
Save the attributes of the EgStore object to a pickle file.
Note that if the directory for the pickle file does not already exist,
the store operation will fail.
"""
with open(self.filename, "wb") as f:
pickle.dump(self, f) | [
"def",
"store",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"filename",
",",
"\"wb\"",
")",
"as",
"f",
":",
"pickle",
".",
"dump",
"(",
"self",
",",
"f",
")"
] | Save the attributes of the EgStore object to a pickle file.
Note that if the directory for the pickle file does not already exist,
the store operation will fail. | [
"Save",
"the",
"attributes",
"of",
"the",
"EgStore",
"object",
"to",
"a",
"pickle",
"file",
".",
"Note",
"that",
"if",
"the",
"directory",
"for",
"the",
"pickle",
"file",
"does",
"not",
"already",
"exist",
"the",
"store",
"operation",
"will",
"fail",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/ui/fallback/easygui/boxes/egstore.py#L132-L139 | train | 204,358 |
draperjames/qtpandas | qtpandas/ui/fallback/easygui/boxes/base_boxes.py | buttonbox | def buttonbox(msg="", title=" ", choices=("Button[1]", "Button[2]", "Button[3]"), image=None, root=None, default_choice=None, cancel_choice=None):
"""
Display a msg, a title, an image, and a set of buttons.
The buttons are defined by the members of the choices list.
:param str msg: the msg to be displayed
:param str title: the window title
:param list choices: a list or tuple of the choices to be displayed
:param str image: Filename of image to display
:param str default_choice: The choice you want highlighted when the gui appears
:param str cancel_choice: If the user presses the 'X' close, which button should be pressed
:return: the text of the button that the user selected
"""
global boxRoot, __replyButtonText, buttonsFrame
# If default is not specified, select the first button. This matches old
# behavior.
if default_choice is None:
default_choice = choices[0]
# Initialize __replyButtonText to the first choice.
# This is what will be used if the window is closed by the close button.
__replyButtonText = choices[0]
if root:
root.withdraw()
boxRoot = Toplevel(master=root)
boxRoot.withdraw()
else:
boxRoot = Tk()
boxRoot.withdraw()
boxRoot.title(title)
boxRoot.iconname('Dialog')
boxRoot.geometry(st.rootWindowPosition)
boxRoot.minsize(400, 100)
# ------------- define the messageFrame ---------------------------------
messageFrame = Frame(master=boxRoot)
messageFrame.pack(side=TOP, fill=BOTH)
# ------------- define the imageFrame ---------------------------------
if image:
tk_Image = None
try:
tk_Image = ut.load_tk_image(image)
except Exception as inst:
print(inst)
if tk_Image:
imageFrame = Frame(master=boxRoot)
imageFrame.pack(side=TOP, fill=BOTH)
label = Label(imageFrame, image=tk_Image)
label.image = tk_Image # keep a reference!
label.pack(side=TOP, expand=YES, fill=X, padx='1m', pady='1m')
# ------------- define the buttonsFrame ---------------------------------
buttonsFrame = Frame(master=boxRoot)
buttonsFrame.pack(side=TOP, fill=BOTH)
# -------------------- place the widgets in the frames -------------------
messageWidget = Message(messageFrame, text=msg, width=400)
messageWidget.configure(
font=(st.PROPORTIONAL_FONT_FAMILY, st.PROPORTIONAL_FONT_SIZE))
messageWidget.pack(side=TOP, expand=YES, fill=X, padx='3m', pady='3m')
__put_buttons_in_buttonframe(choices, default_choice, cancel_choice)
# -------------- the action begins -----------
boxRoot.deiconify()
boxRoot.mainloop()
boxRoot.destroy()
if root:
root.deiconify()
return __replyButtonText | python | def buttonbox(msg="", title=" ", choices=("Button[1]", "Button[2]", "Button[3]"), image=None, root=None, default_choice=None, cancel_choice=None):
"""
Display a msg, a title, an image, and a set of buttons.
The buttons are defined by the members of the choices list.
:param str msg: the msg to be displayed
:param str title: the window title
:param list choices: a list or tuple of the choices to be displayed
:param str image: Filename of image to display
:param str default_choice: The choice you want highlighted when the gui appears
:param str cancel_choice: If the user presses the 'X' close, which button should be pressed
:return: the text of the button that the user selected
"""
global boxRoot, __replyButtonText, buttonsFrame
# If default is not specified, select the first button. This matches old
# behavior.
if default_choice is None:
default_choice = choices[0]
# Initialize __replyButtonText to the first choice.
# This is what will be used if the window is closed by the close button.
__replyButtonText = choices[0]
if root:
root.withdraw()
boxRoot = Toplevel(master=root)
boxRoot.withdraw()
else:
boxRoot = Tk()
boxRoot.withdraw()
boxRoot.title(title)
boxRoot.iconname('Dialog')
boxRoot.geometry(st.rootWindowPosition)
boxRoot.minsize(400, 100)
# ------------- define the messageFrame ---------------------------------
messageFrame = Frame(master=boxRoot)
messageFrame.pack(side=TOP, fill=BOTH)
# ------------- define the imageFrame ---------------------------------
if image:
tk_Image = None
try:
tk_Image = ut.load_tk_image(image)
except Exception as inst:
print(inst)
if tk_Image:
imageFrame = Frame(master=boxRoot)
imageFrame.pack(side=TOP, fill=BOTH)
label = Label(imageFrame, image=tk_Image)
label.image = tk_Image # keep a reference!
label.pack(side=TOP, expand=YES, fill=X, padx='1m', pady='1m')
# ------------- define the buttonsFrame ---------------------------------
buttonsFrame = Frame(master=boxRoot)
buttonsFrame.pack(side=TOP, fill=BOTH)
# -------------------- place the widgets in the frames -------------------
messageWidget = Message(messageFrame, text=msg, width=400)
messageWidget.configure(
font=(st.PROPORTIONAL_FONT_FAMILY, st.PROPORTIONAL_FONT_SIZE))
messageWidget.pack(side=TOP, expand=YES, fill=X, padx='3m', pady='3m')
__put_buttons_in_buttonframe(choices, default_choice, cancel_choice)
# -------------- the action begins -----------
boxRoot.deiconify()
boxRoot.mainloop()
boxRoot.destroy()
if root:
root.deiconify()
return __replyButtonText | [
"def",
"buttonbox",
"(",
"msg",
"=",
"\"\"",
",",
"title",
"=",
"\" \"",
",",
"choices",
"=",
"(",
"\"Button[1]\"",
",",
"\"Button[2]\"",
",",
"\"Button[3]\"",
")",
",",
"image",
"=",
"None",
",",
"root",
"=",
"None",
",",
"default_choice",
"=",
"None",
... | Display a msg, a title, an image, and a set of buttons.
The buttons are defined by the members of the choices list.
:param str msg: the msg to be displayed
:param str title: the window title
:param list choices: a list or tuple of the choices to be displayed
:param str image: Filename of image to display
:param str default_choice: The choice you want highlighted when the gui appears
:param str cancel_choice: If the user presses the 'X' close, which button should be pressed
:return: the text of the button that the user selected | [
"Display",
"a",
"msg",
"a",
"title",
"an",
"image",
"and",
"a",
"set",
"of",
"buttons",
".",
"The",
"buttons",
"are",
"defined",
"by",
"the",
"members",
"of",
"the",
"choices",
"list",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/ui/fallback/easygui/boxes/base_boxes.py#L49-L122 | train | 204,359 |
draperjames/qtpandas | qtpandas/ui/fallback/easygui/boxes/base_boxes.py | __buttonEvent | def __buttonEvent(event=None, buttons=None, virtual_event=None):
"""
Handle an event that is generated by a person interacting with a button. It may be a button press
or a key press.
"""
# TODO: Replace globals with tkinter variables
global boxRoot, __replyButtonText
# Determine window location and save to global
m = re.match("(\d+)x(\d+)([-+]\d+)([-+]\d+)", boxRoot.geometry())
if not m:
raise ValueError(
"failed to parse geometry string: {}".format(boxRoot.geometry()))
width, height, xoffset, yoffset = [int(s) for s in m.groups()]
st.rootWindowPosition = '{0:+g}{1:+g}'.format(xoffset, yoffset)
# print('{0}:{1}:{2}'.format(event, buttons, virtual_event))
if virtual_event == 'cancel':
for button_name, button in list(buttons.items()):
if 'cancel_choice' in button:
__replyButtonText = button['original_text']
__replyButtonText = None
boxRoot.quit()
return
if virtual_event == 'select':
text = event.widget.config('text')[-1]
if not isinstance(text, ut.str):
text = ' '.join(text)
for button_name, button in list(buttons.items()):
if button['clean_text'] == text:
__replyButtonText = button['original_text']
boxRoot.quit()
return
# Hotkeys
if buttons:
for button_name, button in list(buttons.items()):
hotkey_pressed = event.keysym
if event.keysym != event.char: # A special character
hotkey_pressed = '<{}>'.format(event.keysym)
if button['hotkey'] == hotkey_pressed:
__replyButtonText = button_name
boxRoot.quit()
return
print("Event not understood") | python | def __buttonEvent(event=None, buttons=None, virtual_event=None):
"""
Handle an event that is generated by a person interacting with a button. It may be a button press
or a key press.
"""
# TODO: Replace globals with tkinter variables
global boxRoot, __replyButtonText
# Determine window location and save to global
m = re.match("(\d+)x(\d+)([-+]\d+)([-+]\d+)", boxRoot.geometry())
if not m:
raise ValueError(
"failed to parse geometry string: {}".format(boxRoot.geometry()))
width, height, xoffset, yoffset = [int(s) for s in m.groups()]
st.rootWindowPosition = '{0:+g}{1:+g}'.format(xoffset, yoffset)
# print('{0}:{1}:{2}'.format(event, buttons, virtual_event))
if virtual_event == 'cancel':
for button_name, button in list(buttons.items()):
if 'cancel_choice' in button:
__replyButtonText = button['original_text']
__replyButtonText = None
boxRoot.quit()
return
if virtual_event == 'select':
text = event.widget.config('text')[-1]
if not isinstance(text, ut.str):
text = ' '.join(text)
for button_name, button in list(buttons.items()):
if button['clean_text'] == text:
__replyButtonText = button['original_text']
boxRoot.quit()
return
# Hotkeys
if buttons:
for button_name, button in list(buttons.items()):
hotkey_pressed = event.keysym
if event.keysym != event.char: # A special character
hotkey_pressed = '<{}>'.format(event.keysym)
if button['hotkey'] == hotkey_pressed:
__replyButtonText = button_name
boxRoot.quit()
return
print("Event not understood") | [
"def",
"__buttonEvent",
"(",
"event",
"=",
"None",
",",
"buttons",
"=",
"None",
",",
"virtual_event",
"=",
"None",
")",
":",
"# TODO: Replace globals with tkinter variables",
"global",
"boxRoot",
",",
"__replyButtonText",
"# Determine window location and save to global",
... | Handle an event that is generated by a person interacting with a button. It may be a button press
or a key press. | [
"Handle",
"an",
"event",
"that",
"is",
"generated",
"by",
"a",
"person",
"interacting",
"with",
"a",
"button",
".",
"It",
"may",
"be",
"a",
"button",
"press",
"or",
"a",
"key",
"press",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/ui/fallback/easygui/boxes/base_boxes.py#L1019-L1065 | train | 204,360 |
draperjames/qtpandas | qtpandas/ui/fallback/easygui/boxes/derived_boxes.py | indexbox | def indexbox(msg="Shall I continue?", title=" ",
choices=("Yes", "No"), image=None,
default_choice='Yes', cancel_choice='No'):
"""
Display a buttonbox with the specified choices.
:param str msg: the msg to be displayed
:param str title: the window title
:param list choices: a list or tuple of the choices to be displayed
:param str image: Filename of image to display
:param str default_choice: The choice you want highlighted
when the gui appears
:param str cancel_choice: If the user presses the 'X' close,
which button should be pressed
:return: the index of the choice selected, starting from 0
"""
reply = bb.buttonbox(msg=msg,
title=title,
choices=choices,
image=image,
default_choice=default_choice,
cancel_choice=cancel_choice)
if reply is None:
return None
for i, choice in enumerate(choices):
if reply == choice:
return i
msg = ("There is a program logic error in the EasyGui code "
"for indexbox.\nreply={0}, choices={1}".format(
reply, choices))
raise AssertionError(msg) | python | def indexbox(msg="Shall I continue?", title=" ",
choices=("Yes", "No"), image=None,
default_choice='Yes', cancel_choice='No'):
"""
Display a buttonbox with the specified choices.
:param str msg: the msg to be displayed
:param str title: the window title
:param list choices: a list or tuple of the choices to be displayed
:param str image: Filename of image to display
:param str default_choice: The choice you want highlighted
when the gui appears
:param str cancel_choice: If the user presses the 'X' close,
which button should be pressed
:return: the index of the choice selected, starting from 0
"""
reply = bb.buttonbox(msg=msg,
title=title,
choices=choices,
image=image,
default_choice=default_choice,
cancel_choice=cancel_choice)
if reply is None:
return None
for i, choice in enumerate(choices):
if reply == choice:
return i
msg = ("There is a program logic error in the EasyGui code "
"for indexbox.\nreply={0}, choices={1}".format(
reply, choices))
raise AssertionError(msg) | [
"def",
"indexbox",
"(",
"msg",
"=",
"\"Shall I continue?\"",
",",
"title",
"=",
"\" \"",
",",
"choices",
"=",
"(",
"\"Yes\"",
",",
"\"No\"",
")",
",",
"image",
"=",
"None",
",",
"default_choice",
"=",
"'Yes'",
",",
"cancel_choice",
"=",
"'No'",
")",
":",... | Display a buttonbox with the specified choices.
:param str msg: the msg to be displayed
:param str title: the window title
:param list choices: a list or tuple of the choices to be displayed
:param str image: Filename of image to display
:param str default_choice: The choice you want highlighted
when the gui appears
:param str cancel_choice: If the user presses the 'X' close,
which button should be pressed
:return: the index of the choice selected, starting from 0 | [
"Display",
"a",
"buttonbox",
"with",
"the",
"specified",
"choices",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/ui/fallback/easygui/boxes/derived_boxes.py#L166-L196 | train | 204,361 |
draperjames/qtpandas | qtpandas/ui/fallback/easygui/boxes/derived_boxes.py | msgbox | def msgbox(msg="(Your message goes here)", title=" ",
ok_button="OK", image=None, root=None):
"""
Display a message box
:param str msg: the msg to be displayed
:param str title: the window title
:param str ok_button: text to show in the button
:param str image: Filename of image to display
:param tk_widget root: Top-level Tk widget
:return: the text of the ok_button
"""
if not isinstance(ok_button, ut.str):
raise AssertionError(
"The 'ok_button' argument to msgbox must be a string.")
return bb.buttonbox(msg=msg,
title=title,
choices=[ok_button],
image=image,
root=root,
default_choice=ok_button,
cancel_choice=ok_button) | python | def msgbox(msg="(Your message goes here)", title=" ",
ok_button="OK", image=None, root=None):
"""
Display a message box
:param str msg: the msg to be displayed
:param str title: the window title
:param str ok_button: text to show in the button
:param str image: Filename of image to display
:param tk_widget root: Top-level Tk widget
:return: the text of the ok_button
"""
if not isinstance(ok_button, ut.str):
raise AssertionError(
"The 'ok_button' argument to msgbox must be a string.")
return bb.buttonbox(msg=msg,
title=title,
choices=[ok_button],
image=image,
root=root,
default_choice=ok_button,
cancel_choice=ok_button) | [
"def",
"msgbox",
"(",
"msg",
"=",
"\"(Your message goes here)\"",
",",
"title",
"=",
"\" \"",
",",
"ok_button",
"=",
"\"OK\"",
",",
"image",
"=",
"None",
",",
"root",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"ok_button",
",",
"ut",
".",
"... | Display a message box
:param str msg: the msg to be displayed
:param str title: the window title
:param str ok_button: text to show in the button
:param str image: Filename of image to display
:param tk_widget root: Top-level Tk widget
:return: the text of the ok_button | [
"Display",
"a",
"message",
"box"
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/ui/fallback/easygui/boxes/derived_boxes.py#L202-L224 | train | 204,362 |
draperjames/qtpandas | qtpandas/ui/fallback/easygui/boxes/derived_boxes.py | multenterbox | def multenterbox(msg="Fill in values for the fields.", title=" ",
fields=(), values=()):
r"""
Show screen with multiple data entry fields.
If there are fewer values than names, the list of values is padded with
empty strings until the number of values is the same as the number
of names.
If there are more values than names, the list of values
is truncated so that there are as many values as names.
Returns a list of the values of the fields,
or None if the user cancels the operation.
Here is some example code, that shows how values returned from
multenterbox can be checked for validity before they are accepted::
msg = "Enter your personal information"
title = "Credit Card Application"
fieldNames = ["Name","Street Address","City","State","ZipCode"]
fieldValues = [] # we start with blanks for the values
fieldValues = multenterbox(msg,title, fieldNames)
# make sure that none of the fields was left blank
while 1:
if fieldValues is None: break
errmsg = ""
for i in range(len(fieldNames)):
if fieldValues[i].strip() == "":
errmsg += ('"%s" is a required field.\n\n' % fieldNames[i])
if errmsg == "":
break # no problems found
fieldValues = multenterbox(errmsg, title, fieldNames, fieldValues)
print("Reply was: %s" % str(fieldValues))
:param str msg: the msg to be displayed.
:param str title: the window title
:param list fields: a list of fieldnames.
:param list values: a list of field values
:return: String
"""
return bb.__multfillablebox(msg, title, fields, values, None) | python | def multenterbox(msg="Fill in values for the fields.", title=" ",
fields=(), values=()):
r"""
Show screen with multiple data entry fields.
If there are fewer values than names, the list of values is padded with
empty strings until the number of values is the same as the number
of names.
If there are more values than names, the list of values
is truncated so that there are as many values as names.
Returns a list of the values of the fields,
or None if the user cancels the operation.
Here is some example code, that shows how values returned from
multenterbox can be checked for validity before they are accepted::
msg = "Enter your personal information"
title = "Credit Card Application"
fieldNames = ["Name","Street Address","City","State","ZipCode"]
fieldValues = [] # we start with blanks for the values
fieldValues = multenterbox(msg,title, fieldNames)
# make sure that none of the fields was left blank
while 1:
if fieldValues is None: break
errmsg = ""
for i in range(len(fieldNames)):
if fieldValues[i].strip() == "":
errmsg += ('"%s" is a required field.\n\n' % fieldNames[i])
if errmsg == "":
break # no problems found
fieldValues = multenterbox(errmsg, title, fieldNames, fieldValues)
print("Reply was: %s" % str(fieldValues))
:param str msg: the msg to be displayed.
:param str title: the window title
:param list fields: a list of fieldnames.
:param list values: a list of field values
:return: String
"""
return bb.__multfillablebox(msg, title, fields, values, None) | [
"def",
"multenterbox",
"(",
"msg",
"=",
"\"Fill in values for the fields.\"",
",",
"title",
"=",
"\" \"",
",",
"fields",
"=",
"(",
")",
",",
"values",
"=",
"(",
")",
")",
":",
"return",
"bb",
".",
"__multfillablebox",
"(",
"msg",
",",
"title",
",",
"fiel... | r"""
Show screen with multiple data entry fields.
If there are fewer values than names, the list of values is padded with
empty strings until the number of values is the same as the number
of names.
If there are more values than names, the list of values
is truncated so that there are as many values as names.
Returns a list of the values of the fields,
or None if the user cancels the operation.
Here is some example code, that shows how values returned from
multenterbox can be checked for validity before they are accepted::
msg = "Enter your personal information"
title = "Credit Card Application"
fieldNames = ["Name","Street Address","City","State","ZipCode"]
fieldValues = [] # we start with blanks for the values
fieldValues = multenterbox(msg,title, fieldNames)
# make sure that none of the fields was left blank
while 1:
if fieldValues is None: break
errmsg = ""
for i in range(len(fieldNames)):
if fieldValues[i].strip() == "":
errmsg += ('"%s" is a required field.\n\n' % fieldNames[i])
if errmsg == "":
break # no problems found
fieldValues = multenterbox(errmsg, title, fieldNames, fieldValues)
print("Reply was: %s" % str(fieldValues))
:param str msg: the msg to be displayed.
:param str title: the window title
:param list fields: a list of fieldnames.
:param list values: a list of field values
:return: String | [
"r",
"Show",
"screen",
"with",
"multiple",
"data",
"entry",
"fields",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/ui/fallback/easygui/boxes/derived_boxes.py#L319-L362 | train | 204,363 |
draperjames/qtpandas | qtpandas/ui/fallback/easygui/boxes/derived_boxes.py | exceptionbox | def exceptionbox(msg=None, title=None):
"""
Display a box that gives information about
an exception that has just been raised.
The caller may optionally pass in a title for the window, or a
msg to accompany the error information.
Note that you do not need to (and cannot) pass an exception object
as an argument. The latest exception will automatically be used.
:param str msg: the msg to be displayed
:param str title: the window title
:return: None
"""
if title is None:
title = "Error Report"
if msg is None:
msg = "An error (exception) has occurred in the program."
codebox(msg, title, ut.exception_format()) | python | def exceptionbox(msg=None, title=None):
"""
Display a box that gives information about
an exception that has just been raised.
The caller may optionally pass in a title for the window, or a
msg to accompany the error information.
Note that you do not need to (and cannot) pass an exception object
as an argument. The latest exception will automatically be used.
:param str msg: the msg to be displayed
:param str title: the window title
:return: None
"""
if title is None:
title = "Error Report"
if msg is None:
msg = "An error (exception) has occurred in the program."
codebox(msg, title, ut.exception_format()) | [
"def",
"exceptionbox",
"(",
"msg",
"=",
"None",
",",
"title",
"=",
"None",
")",
":",
"if",
"title",
"is",
"None",
":",
"title",
"=",
"\"Error Report\"",
"if",
"msg",
"is",
"None",
":",
"msg",
"=",
"\"An error (exception) has occurred in the program.\"",
"codeb... | Display a box that gives information about
an exception that has just been raised.
The caller may optionally pass in a title for the window, or a
msg to accompany the error information.
Note that you do not need to (and cannot) pass an exception object
as an argument. The latest exception will automatically be used.
:param str msg: the msg to be displayed
:param str title: the window title
:return: None | [
"Display",
"a",
"box",
"that",
"gives",
"information",
"about",
"an",
"exception",
"that",
"has",
"just",
"been",
"raised",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/ui/fallback/easygui/boxes/derived_boxes.py#L509-L530 | train | 204,364 |
draperjames/qtpandas | qtpandas/ui/fallback/easygui/boxes/derived_boxes.py | codebox | def codebox(msg="", title=" ", text=""):
"""
Display some text in a monospaced font, with no line wrapping.
This function is suitable for displaying code and text that is
formatted using spaces.
The text parameter should be a string, or a list or tuple of lines to be
displayed in the textbox.
:param str msg: the msg to be displayed
:param str title: the window title
:param str text: what to display in the textbox
"""
return tb.textbox(msg, title, text, codebox=1) | python | def codebox(msg="", title=" ", text=""):
"""
Display some text in a monospaced font, with no line wrapping.
This function is suitable for displaying code and text that is
formatted using spaces.
The text parameter should be a string, or a list or tuple of lines to be
displayed in the textbox.
:param str msg: the msg to be displayed
:param str title: the window title
:param str text: what to display in the textbox
"""
return tb.textbox(msg, title, text, codebox=1) | [
"def",
"codebox",
"(",
"msg",
"=",
"\"\"",
",",
"title",
"=",
"\" \"",
",",
"text",
"=",
"\"\"",
")",
":",
"return",
"tb",
".",
"textbox",
"(",
"msg",
",",
"title",
",",
"text",
",",
"codebox",
"=",
"1",
")"
] | Display some text in a monospaced font, with no line wrapping.
This function is suitable for displaying code and text that is
formatted using spaces.
The text parameter should be a string, or a list or tuple of lines to be
displayed in the textbox.
:param str msg: the msg to be displayed
:param str title: the window title
:param str text: what to display in the textbox | [
"Display",
"some",
"text",
"in",
"a",
"monospaced",
"font",
"with",
"no",
"line",
"wrapping",
".",
"This",
"function",
"is",
"suitable",
"for",
"displaying",
"code",
"and",
"text",
"that",
"is",
"formatted",
"using",
"spaces",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/ui/fallback/easygui/boxes/derived_boxes.py#L537-L550 | train | 204,365 |
draperjames/qtpandas | qtpandas/views/CSVDialogs.py | _calculateEncodingKey | def _calculateEncodingKey(comparator):
"""Gets the first key of all available encodings where the corresponding
value matches the comparator.
Args:
comparator (string): A view name for an encoding.
Returns:
str: A key for a specific encoding used by python.
"""
encodingName = None
for k, v in list(_encodings.items()):
if v == comparator:
encodingName = k
break
return encodingName | python | def _calculateEncodingKey(comparator):
"""Gets the first key of all available encodings where the corresponding
value matches the comparator.
Args:
comparator (string): A view name for an encoding.
Returns:
str: A key for a specific encoding used by python.
"""
encodingName = None
for k, v in list(_encodings.items()):
if v == comparator:
encodingName = k
break
return encodingName | [
"def",
"_calculateEncodingKey",
"(",
"comparator",
")",
":",
"encodingName",
"=",
"None",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"_encodings",
".",
"items",
"(",
")",
")",
":",
"if",
"v",
"==",
"comparator",
":",
"encodingName",
"=",
"k",
"break",
"r... | Gets the first key of all available encodings where the corresponding
value matches the comparator.
Args:
comparator (string): A view name for an encoding.
Returns:
str: A key for a specific encoding used by python. | [
"Gets",
"the",
"first",
"key",
"of",
"all",
"available",
"encodings",
"where",
"the",
"corresponding",
"value",
"matches",
"the",
"comparator",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/CSVDialogs.py#L675-L691 | train | 204,366 |
draperjames/qtpandas | qtpandas/views/CSVDialogs.py | DelimiterSelectionWidget._initUI | def _initUI(self):
"""Creates the inital layout with all subwidgets.
The layout is a `QHBoxLayout`. Each time a radio button is
selected or unselected, a slot
`DelimiterSelectionWidget._delimiter` is called.
Furthermore the `QLineEdit` widget has a custom regex validator
`DelimiterValidator` enabled.
"""
#layout = QtGui.QHBoxLayout(self)
self.semicolonRadioButton = QtGui.QRadioButton('Semicolon')
self.commaRadioButton = QtGui.QRadioButton('Comma')
self.tabRadioButton = QtGui.QRadioButton('Tab')
self.otherRadioButton = QtGui.QRadioButton('Other')
self.commaRadioButton.setChecked(True)
self.otherSeparatorLineEdit = QtGui.QLineEdit(self)
#TODO: Enable this or add BAR radio and option.
self.otherSeparatorLineEdit.setEnabled(False)
self.semicolonRadioButton.toggled.connect(self._delimiter)
self.commaRadioButton.toggled.connect(self._delimiter)
self.tabRadioButton.toggled.connect(self._delimiter)
self.otherRadioButton.toggled.connect(self._enableLine)
self.otherSeparatorLineEdit.textChanged.connect(lambda: self._delimiter(True))
self.otherSeparatorLineEdit.setValidator(DelimiterValidator(self))
currentLayout = self.layout()
# unset and delete the current layout in order to set a new one
if currentLayout is not None:
del currentLayout
layout = QtGui.QHBoxLayout()
layout.addWidget(self.semicolonRadioButton)
layout.addWidget(self.commaRadioButton)
layout.addWidget(self.tabRadioButton)
layout.addWidget(self.otherRadioButton)
layout.addWidget(self.otherSeparatorLineEdit)
self.setLayout(layout) | python | def _initUI(self):
"""Creates the inital layout with all subwidgets.
The layout is a `QHBoxLayout`. Each time a radio button is
selected or unselected, a slot
`DelimiterSelectionWidget._delimiter` is called.
Furthermore the `QLineEdit` widget has a custom regex validator
`DelimiterValidator` enabled.
"""
#layout = QtGui.QHBoxLayout(self)
self.semicolonRadioButton = QtGui.QRadioButton('Semicolon')
self.commaRadioButton = QtGui.QRadioButton('Comma')
self.tabRadioButton = QtGui.QRadioButton('Tab')
self.otherRadioButton = QtGui.QRadioButton('Other')
self.commaRadioButton.setChecked(True)
self.otherSeparatorLineEdit = QtGui.QLineEdit(self)
#TODO: Enable this or add BAR radio and option.
self.otherSeparatorLineEdit.setEnabled(False)
self.semicolonRadioButton.toggled.connect(self._delimiter)
self.commaRadioButton.toggled.connect(self._delimiter)
self.tabRadioButton.toggled.connect(self._delimiter)
self.otherRadioButton.toggled.connect(self._enableLine)
self.otherSeparatorLineEdit.textChanged.connect(lambda: self._delimiter(True))
self.otherSeparatorLineEdit.setValidator(DelimiterValidator(self))
currentLayout = self.layout()
# unset and delete the current layout in order to set a new one
if currentLayout is not None:
del currentLayout
layout = QtGui.QHBoxLayout()
layout.addWidget(self.semicolonRadioButton)
layout.addWidget(self.commaRadioButton)
layout.addWidget(self.tabRadioButton)
layout.addWidget(self.otherRadioButton)
layout.addWidget(self.otherSeparatorLineEdit)
self.setLayout(layout) | [
"def",
"_initUI",
"(",
"self",
")",
":",
"#layout = QtGui.QHBoxLayout(self)",
"self",
".",
"semicolonRadioButton",
"=",
"QtGui",
".",
"QRadioButton",
"(",
"'Semicolon'",
")",
"self",
".",
"commaRadioButton",
"=",
"QtGui",
".",
"QRadioButton",
"(",
"'Comma'",
")",
... | Creates the inital layout with all subwidgets.
The layout is a `QHBoxLayout`. Each time a radio button is
selected or unselected, a slot
`DelimiterSelectionWidget._delimiter` is called.
Furthermore the `QLineEdit` widget has a custom regex validator
`DelimiterValidator` enabled. | [
"Creates",
"the",
"inital",
"layout",
"with",
"all",
"subwidgets",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/CSVDialogs.py#L89-L130 | train | 204,367 |
draperjames/qtpandas | qtpandas/views/CSVDialogs.py | DelimiterSelectionWidget.currentSelected | def currentSelected(self):
"""Returns the currently selected delimiter character.
Returns:
str: One of `,`, `;`, `\t`, `*other*`.
"""
if self.commaRadioButton.isChecked():
return ','
elif self.semicolonRadioButton.isChecked():
return ';'
elif self.tabRadioButton.isChecked():
return '\t'
elif self.otherRadioButton.isChecked():
return self.otherSeparatorLineEdit.text()
return | python | def currentSelected(self):
"""Returns the currently selected delimiter character.
Returns:
str: One of `,`, `;`, `\t`, `*other*`.
"""
if self.commaRadioButton.isChecked():
return ','
elif self.semicolonRadioButton.isChecked():
return ';'
elif self.tabRadioButton.isChecked():
return '\t'
elif self.otherRadioButton.isChecked():
return self.otherSeparatorLineEdit.text()
return | [
"def",
"currentSelected",
"(",
"self",
")",
":",
"if",
"self",
".",
"commaRadioButton",
".",
"isChecked",
"(",
")",
":",
"return",
"','",
"elif",
"self",
".",
"semicolonRadioButton",
".",
"isChecked",
"(",
")",
":",
"return",
"';'",
"elif",
"self",
".",
... | Returns the currently selected delimiter character.
Returns:
str: One of `,`, `;`, `\t`, `*other*`. | [
"Returns",
"the",
"currently",
"selected",
"delimiter",
"character",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/CSVDialogs.py#L136-L151 | train | 204,368 |
draperjames/qtpandas | qtpandas/views/CSVDialogs.py | CSVImportDialog._openFile | def _openFile(self):
"""Opens a file dialog and sets a value for the QLineEdit widget.
This method is also a `SLOT`.
"""
file_types = "Comma Separated Values (*.csv);;Text files (*.txt);;All Files (*)"
ret = QtGui.QFileDialog.getOpenFileName(self,
self.tr('open file'),
filter=file_types)
if isinstance(ret, tuple):
ret = ret[0] #PySide compatibility maybe?
if ret:
self._filenameLineEdit.setText(ret)
self._updateFilename() | python | def _openFile(self):
"""Opens a file dialog and sets a value for the QLineEdit widget.
This method is also a `SLOT`.
"""
file_types = "Comma Separated Values (*.csv);;Text files (*.txt);;All Files (*)"
ret = QtGui.QFileDialog.getOpenFileName(self,
self.tr('open file'),
filter=file_types)
if isinstance(ret, tuple):
ret = ret[0] #PySide compatibility maybe?
if ret:
self._filenameLineEdit.setText(ret)
self._updateFilename() | [
"def",
"_openFile",
"(",
"self",
")",
":",
"file_types",
"=",
"\"Comma Separated Values (*.csv);;Text files (*.txt);;All Files (*)\"",
"ret",
"=",
"QtGui",
".",
"QFileDialog",
".",
"getOpenFileName",
"(",
"self",
",",
"self",
".",
"tr",
"(",
"'open file'",
")",
",",... | Opens a file dialog and sets a value for the QLineEdit widget.
This method is also a `SLOT`. | [
"Opens",
"a",
"file",
"dialog",
"and",
"sets",
"a",
"value",
"for",
"the",
"QLineEdit",
"widget",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/CSVDialogs.py#L312-L329 | train | 204,369 |
draperjames/qtpandas | qtpandas/views/CSVDialogs.py | CSVImportDialog._updateFilename | def _updateFilename(self):
"""Calls several methods after the filename changed.
This method is also a `SLOT`.
It checks the encoding of the changed filename and generates a
preview of the data.
"""
self._filename = self._filenameLineEdit.text()
self._guessEncoding(self._filename)
self._previewFile() | python | def _updateFilename(self):
"""Calls several methods after the filename changed.
This method is also a `SLOT`.
It checks the encoding of the changed filename and generates a
preview of the data.
"""
self._filename = self._filenameLineEdit.text()
self._guessEncoding(self._filename)
self._previewFile() | [
"def",
"_updateFilename",
"(",
"self",
")",
":",
"self",
".",
"_filename",
"=",
"self",
".",
"_filenameLineEdit",
".",
"text",
"(",
")",
"self",
".",
"_guessEncoding",
"(",
"self",
".",
"_filename",
")",
"self",
".",
"_previewFile",
"(",
")"
] | Calls several methods after the filename changed.
This method is also a `SLOT`.
It checks the encoding of the changed filename and generates a
preview of the data. | [
"Calls",
"several",
"methods",
"after",
"the",
"filename",
"changed",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/CSVDialogs.py#L349-L359 | train | 204,370 |
draperjames/qtpandas | qtpandas/views/CSVDialogs.py | CSVImportDialog._guessEncoding | def _guessEncoding(self, path):
"""Opens a file from the given `path` and checks the file encoding.
The file must exists on the file system and end with the extension
`.csv`. The file is read line by line until the encoding could be
guessed.
On a successfull identification, the widgets of this dialog will be
updated.
Args:
path (string): Path to a csv file on the file system.
"""
if os.path.exists(path) and path.lower().endswith('csv'):
# encoding = self._detector.detect(path)
encoding = None
if encoding is not None:
if encoding.startswith('utf'):
encoding = encoding.replace('-', '')
encoding = encoding.replace('-','_')
viewValue = _encodings.get(encoding)
self._encodingKey = encoding
index = self._encodingComboBox.findText(viewValue.upper())
self._encodingComboBox.setCurrentIndex(index) | python | def _guessEncoding(self, path):
"""Opens a file from the given `path` and checks the file encoding.
The file must exists on the file system and end with the extension
`.csv`. The file is read line by line until the encoding could be
guessed.
On a successfull identification, the widgets of this dialog will be
updated.
Args:
path (string): Path to a csv file on the file system.
"""
if os.path.exists(path) and path.lower().endswith('csv'):
# encoding = self._detector.detect(path)
encoding = None
if encoding is not None:
if encoding.startswith('utf'):
encoding = encoding.replace('-', '')
encoding = encoding.replace('-','_')
viewValue = _encodings.get(encoding)
self._encodingKey = encoding
index = self._encodingComboBox.findText(viewValue.upper())
self._encodingComboBox.setCurrentIndex(index) | [
"def",
"_guessEncoding",
"(",
"self",
",",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
"and",
"path",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'csv'",
")",
":",
"# encoding = self._detector.detect(path)",
"encoding",
... | Opens a file from the given `path` and checks the file encoding.
The file must exists on the file system and end with the extension
`.csv`. The file is read line by line until the encoding could be
guessed.
On a successfull identification, the widgets of this dialog will be
updated.
Args:
path (string): Path to a csv file on the file system. | [
"Opens",
"a",
"file",
"from",
"the",
"given",
"path",
"and",
"checks",
"the",
"file",
"encoding",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/CSVDialogs.py#L361-L388 | train | 204,371 |
draperjames/qtpandas | qtpandas/views/CSVDialogs.py | CSVImportDialog._updateEncoding | def _updateEncoding(self, index):
"""Changes the value of the encoding combo box to the value of given index.
This method is also a `SLOT`.
After the encoding is changed, the file will be reloaded and previewed.
Args:
index (int): An valid index of the combo box.
"""
encoding = self._encodingComboBox.itemText(index)
encoding = encoding.lower()
self._encodingKey = _calculateEncodingKey(encoding)
self._previewFile() | python | def _updateEncoding(self, index):
"""Changes the value of the encoding combo box to the value of given index.
This method is also a `SLOT`.
After the encoding is changed, the file will be reloaded and previewed.
Args:
index (int): An valid index of the combo box.
"""
encoding = self._encodingComboBox.itemText(index)
encoding = encoding.lower()
self._encodingKey = _calculateEncodingKey(encoding)
self._previewFile() | [
"def",
"_updateEncoding",
"(",
"self",
",",
"index",
")",
":",
"encoding",
"=",
"self",
".",
"_encodingComboBox",
".",
"itemText",
"(",
"index",
")",
"encoding",
"=",
"encoding",
".",
"lower",
"(",
")",
"self",
".",
"_encodingKey",
"=",
"_calculateEncodingKe... | Changes the value of the encoding combo box to the value of given index.
This method is also a `SLOT`.
After the encoding is changed, the file will be reloaded and previewed.
Args:
index (int): An valid index of the combo box. | [
"Changes",
"the",
"value",
"of",
"the",
"encoding",
"combo",
"box",
"to",
"the",
"value",
"of",
"given",
"index",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/CSVDialogs.py#L391-L405 | train | 204,372 |
draperjames/qtpandas | qtpandas/views/CSVDialogs.py | CSVImportDialog._previewFile | def _previewFile(self):
"""Updates the preview widgets with new models for both tab panes.
"""
dataFrame = self._loadCSVDataFrame()
dataFrameModel = DataFrameModel(dataFrame, filePath=self._filename)
dataFrameModel.enableEditing(True)
self._previewTableView.setModel(dataFrameModel)
columnModel = dataFrameModel.columnDtypeModel()
columnModel.changeFailed.connect(self.updateStatusBar)
self._datatypeTableView.setModel(columnModel) | python | def _previewFile(self):
"""Updates the preview widgets with new models for both tab panes.
"""
dataFrame = self._loadCSVDataFrame()
dataFrameModel = DataFrameModel(dataFrame, filePath=self._filename)
dataFrameModel.enableEditing(True)
self._previewTableView.setModel(dataFrameModel)
columnModel = dataFrameModel.columnDtypeModel()
columnModel.changeFailed.connect(self.updateStatusBar)
self._datatypeTableView.setModel(columnModel) | [
"def",
"_previewFile",
"(",
"self",
")",
":",
"dataFrame",
"=",
"self",
".",
"_loadCSVDataFrame",
"(",
")",
"dataFrameModel",
"=",
"DataFrameModel",
"(",
"dataFrame",
",",
"filePath",
"=",
"self",
".",
"_filename",
")",
"dataFrameModel",
".",
"enableEditing",
... | Updates the preview widgets with new models for both tab panes. | [
"Updates",
"the",
"preview",
"widgets",
"with",
"new",
"models",
"for",
"both",
"tab",
"panes",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/CSVDialogs.py#L420-L430 | train | 204,373 |
draperjames/qtpandas | qtpandas/views/CSVDialogs.py | CSVImportDialog._loadCSVDataFrame | def _loadCSVDataFrame(self):
"""Loads the given csv file with pandas and generate a new dataframe.
The file will be loaded with the configured encoding, delimiter
and header.git
If any execptions will occur, an empty Dataframe is generated
and a message will appear in the status bar.
Returns:
pandas.DataFrame: A dataframe containing all the available
information of the csv file.
"""
if self._filename and os.path.exists(self._filename):
# default fallback if no encoding was found/selected
encoding = self._encodingKey or 'UTF_8'
try:
dataFrame = superReadFile(self._filename,
sep=self._delimiter, first_codec=encoding,
header=self._header)
dataFrame = dataFrame.apply(fillNoneValues)
dataFrame = dataFrame.apply(convertTimestamps)
except Exception as err:
self.updateStatusBar(str(err))
print(err)
return pandas.DataFrame()
self.updateStatusBar('Preview generated.')
return dataFrame
self.updateStatusBar('File could not be read.')
return pandas.DataFrame() | python | def _loadCSVDataFrame(self):
"""Loads the given csv file with pandas and generate a new dataframe.
The file will be loaded with the configured encoding, delimiter
and header.git
If any execptions will occur, an empty Dataframe is generated
and a message will appear in the status bar.
Returns:
pandas.DataFrame: A dataframe containing all the available
information of the csv file.
"""
if self._filename and os.path.exists(self._filename):
# default fallback if no encoding was found/selected
encoding = self._encodingKey or 'UTF_8'
try:
dataFrame = superReadFile(self._filename,
sep=self._delimiter, first_codec=encoding,
header=self._header)
dataFrame = dataFrame.apply(fillNoneValues)
dataFrame = dataFrame.apply(convertTimestamps)
except Exception as err:
self.updateStatusBar(str(err))
print(err)
return pandas.DataFrame()
self.updateStatusBar('Preview generated.')
return dataFrame
self.updateStatusBar('File could not be read.')
return pandas.DataFrame() | [
"def",
"_loadCSVDataFrame",
"(",
"self",
")",
":",
"if",
"self",
".",
"_filename",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_filename",
")",
":",
"# default fallback if no encoding was found/selected",
"encoding",
"=",
"self",
".",
"_encodingK... | Loads the given csv file with pandas and generate a new dataframe.
The file will be loaded with the configured encoding, delimiter
and header.git
If any execptions will occur, an empty Dataframe is generated
and a message will appear in the status bar.
Returns:
pandas.DataFrame: A dataframe containing all the available
information of the csv file. | [
"Loads",
"the",
"given",
"csv",
"file",
"with",
"pandas",
"and",
"generate",
"a",
"new",
"dataframe",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/CSVDialogs.py#L432-L462 | train | 204,374 |
draperjames/qtpandas | qtpandas/views/CSVDialogs.py | CSVImportDialog.accepted | def accepted(self):
"""Successfully close the widget and return the loaded model.
This method is also a `SLOT`.
The dialog will be closed, when the `ok` button is pressed. If
a `DataFrame` was loaded, it will be emitted by the signal `load`.
"""
model = self._previewTableView.model()
if model is not None:
df = model.dataFrame().copy()
dfModel = DataFrameModel(df)
self.load.emit(dfModel, self._filename)
print(("Emitted model for {}".format(self._filename)))
self._resetWidgets()
self.accept() | python | def accepted(self):
"""Successfully close the widget and return the loaded model.
This method is also a `SLOT`.
The dialog will be closed, when the `ok` button is pressed. If
a `DataFrame` was loaded, it will be emitted by the signal `load`.
"""
model = self._previewTableView.model()
if model is not None:
df = model.dataFrame().copy()
dfModel = DataFrameModel(df)
self.load.emit(dfModel, self._filename)
print(("Emitted model for {}".format(self._filename)))
self._resetWidgets()
self.accept() | [
"def",
"accepted",
"(",
"self",
")",
":",
"model",
"=",
"self",
".",
"_previewTableView",
".",
"model",
"(",
")",
"if",
"model",
"is",
"not",
"None",
":",
"df",
"=",
"model",
".",
"dataFrame",
"(",
")",
".",
"copy",
"(",
")",
"dfModel",
"=",
"DataF... | Successfully close the widget and return the loaded model.
This method is also a `SLOT`.
The dialog will be closed, when the `ok` button is pressed. If
a `DataFrame` was loaded, it will be emitted by the signal `load`. | [
"Successfully",
"close",
"the",
"widget",
"and",
"return",
"the",
"loaded",
"model",
"."
] | 64294fb69f1839e53dee5ea453337266bfaf24f4 | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/CSVDialogs.py#L477-L492 | train | 204,375 |
trezor/python-trezor | trezorlib/debuglink.py | DebugLink.encode_pin | def encode_pin(self, pin, matrix=None):
"""Transform correct PIN according to the displayed matrix."""
if matrix is None:
_, matrix = self.read_pin()
return "".join([str(matrix.index(p) + 1) for p in pin]) | python | def encode_pin(self, pin, matrix=None):
"""Transform correct PIN according to the displayed matrix."""
if matrix is None:
_, matrix = self.read_pin()
return "".join([str(matrix.index(p) + 1) for p in pin]) | [
"def",
"encode_pin",
"(",
"self",
",",
"pin",
",",
"matrix",
"=",
"None",
")",
":",
"if",
"matrix",
"is",
"None",
":",
"_",
",",
"matrix",
"=",
"self",
".",
"read_pin",
"(",
")",
"return",
"\"\"",
".",
"join",
"(",
"[",
"str",
"(",
"matrix",
".",... | Transform correct PIN according to the displayed matrix. | [
"Transform",
"correct",
"PIN",
"according",
"to",
"the",
"displayed",
"matrix",
"."
] | 2813522b05cef4e0e545a101f8b3559a3183b45b | https://github.com/trezor/python-trezor/blob/2813522b05cef4e0e545a101f8b3559a3183b45b/trezorlib/debuglink.py#L56-L60 | train | 204,376 |
trezor/python-trezor | trezorlib/stellar.py | _xdr_read_asset | def _xdr_read_asset(unpacker):
"""Reads a stellar Asset from unpacker"""
asset = messages.StellarAssetType(type=unpacker.unpack_uint())
if asset.type == ASSET_TYPE_ALPHA4:
asset.code = unpacker.unpack_fstring(4)
asset.issuer = _xdr_read_address(unpacker)
if asset.type == ASSET_TYPE_ALPHA12:
asset.code = unpacker.unpack_fstring(12)
asset.issuer = _xdr_read_address(unpacker)
return asset | python | def _xdr_read_asset(unpacker):
"""Reads a stellar Asset from unpacker"""
asset = messages.StellarAssetType(type=unpacker.unpack_uint())
if asset.type == ASSET_TYPE_ALPHA4:
asset.code = unpacker.unpack_fstring(4)
asset.issuer = _xdr_read_address(unpacker)
if asset.type == ASSET_TYPE_ALPHA12:
asset.code = unpacker.unpack_fstring(12)
asset.issuer = _xdr_read_address(unpacker)
return asset | [
"def",
"_xdr_read_asset",
"(",
"unpacker",
")",
":",
"asset",
"=",
"messages",
".",
"StellarAssetType",
"(",
"type",
"=",
"unpacker",
".",
"unpack_uint",
"(",
")",
")",
"if",
"asset",
".",
"type",
"==",
"ASSET_TYPE_ALPHA4",
":",
"asset",
".",
"code",
"=",
... | Reads a stellar Asset from unpacker | [
"Reads",
"a",
"stellar",
"Asset",
"from",
"unpacker"
] | 2813522b05cef4e0e545a101f8b3559a3183b45b | https://github.com/trezor/python-trezor/blob/2813522b05cef4e0e545a101f8b3559a3183b45b/trezorlib/stellar.py#L294-L306 | train | 204,377 |
trezor/python-trezor | trezorlib/stellar.py | _crc16_checksum | def _crc16_checksum(bytes):
"""Returns the CRC-16 checksum of bytearray bytes
Ported from Java implementation at: http://introcs.cs.princeton.edu/java/61data/CRC16CCITT.java.html
Initial value changed to 0x0000 to match Stellar configuration.
"""
crc = 0x0000
polynomial = 0x1021
for byte in bytes:
for i in range(8):
bit = (byte >> (7 - i) & 1) == 1
c15 = (crc >> 15 & 1) == 1
crc <<= 1
if c15 ^ bit:
crc ^= polynomial
return crc & 0xFFFF | python | def _crc16_checksum(bytes):
"""Returns the CRC-16 checksum of bytearray bytes
Ported from Java implementation at: http://introcs.cs.princeton.edu/java/61data/CRC16CCITT.java.html
Initial value changed to 0x0000 to match Stellar configuration.
"""
crc = 0x0000
polynomial = 0x1021
for byte in bytes:
for i in range(8):
bit = (byte >> (7 - i) & 1) == 1
c15 = (crc >> 15 & 1) == 1
crc <<= 1
if c15 ^ bit:
crc ^= polynomial
return crc & 0xFFFF | [
"def",
"_crc16_checksum",
"(",
"bytes",
")",
":",
"crc",
"=",
"0x0000",
"polynomial",
"=",
"0x1021",
"for",
"byte",
"in",
"bytes",
":",
"for",
"i",
"in",
"range",
"(",
"8",
")",
":",
"bit",
"=",
"(",
"byte",
">>",
"(",
"7",
"-",
"i",
")",
"&",
... | Returns the CRC-16 checksum of bytearray bytes
Ported from Java implementation at: http://introcs.cs.princeton.edu/java/61data/CRC16CCITT.java.html
Initial value changed to 0x0000 to match Stellar configuration. | [
"Returns",
"the",
"CRC",
"-",
"16",
"checksum",
"of",
"bytearray",
"bytes"
] | 2813522b05cef4e0e545a101f8b3559a3183b45b | https://github.com/trezor/python-trezor/blob/2813522b05cef4e0e545a101f8b3559a3183b45b/trezorlib/stellar.py#L321-L339 | train | 204,378 |
trezor/python-trezor | trezorlib/tools.py | b58encode | def b58encode(v):
""" encode v, which is a string of bytes, to base58."""
long_value = 0
for c in v:
long_value = long_value * 256 + c
result = ""
while long_value >= __b58base:
div, mod = divmod(long_value, __b58base)
result = __b58chars[mod] + result
long_value = div
result = __b58chars[long_value] + result
# Bitcoin does a little leading-zero-compression:
# leading 0-bytes in the input become leading-1s
nPad = 0
for c in v:
if c == 0:
nPad += 1
else:
break
return (__b58chars[0] * nPad) + result | python | def b58encode(v):
""" encode v, which is a string of bytes, to base58."""
long_value = 0
for c in v:
long_value = long_value * 256 + c
result = ""
while long_value >= __b58base:
div, mod = divmod(long_value, __b58base)
result = __b58chars[mod] + result
long_value = div
result = __b58chars[long_value] + result
# Bitcoin does a little leading-zero-compression:
# leading 0-bytes in the input become leading-1s
nPad = 0
for c in v:
if c == 0:
nPad += 1
else:
break
return (__b58chars[0] * nPad) + result | [
"def",
"b58encode",
"(",
"v",
")",
":",
"long_value",
"=",
"0",
"for",
"c",
"in",
"v",
":",
"long_value",
"=",
"long_value",
"*",
"256",
"+",
"c",
"result",
"=",
"\"\"",
"while",
"long_value",
">=",
"__b58base",
":",
"div",
",",
"mod",
"=",
"divmod",... | encode v, which is a string of bytes, to base58. | [
"encode",
"v",
"which",
"is",
"a",
"string",
"of",
"bytes",
"to",
"base58",
"."
] | 2813522b05cef4e0e545a101f8b3559a3183b45b | https://github.com/trezor/python-trezor/blob/2813522b05cef4e0e545a101f8b3559a3183b45b/trezorlib/tools.py#L79-L102 | train | 204,379 |
trezor/python-trezor | trezorlib/tools.py | normalize_nfc | def normalize_nfc(txt):
"""
Normalize message to NFC and return bytes suitable for protobuf.
This seems to be bitcoin-qt standard of doing things.
"""
if isinstance(txt, bytes):
txt = txt.decode()
return unicodedata.normalize("NFC", txt).encode() | python | def normalize_nfc(txt):
"""
Normalize message to NFC and return bytes suitable for protobuf.
This seems to be bitcoin-qt standard of doing things.
"""
if isinstance(txt, bytes):
txt = txt.decode()
return unicodedata.normalize("NFC", txt).encode() | [
"def",
"normalize_nfc",
"(",
"txt",
")",
":",
"if",
"isinstance",
"(",
"txt",
",",
"bytes",
")",
":",
"txt",
"=",
"txt",
".",
"decode",
"(",
")",
"return",
"unicodedata",
".",
"normalize",
"(",
"\"NFC\"",
",",
"txt",
")",
".",
"encode",
"(",
")"
] | Normalize message to NFC and return bytes suitable for protobuf.
This seems to be bitcoin-qt standard of doing things. | [
"Normalize",
"message",
"to",
"NFC",
"and",
"return",
"bytes",
"suitable",
"for",
"protobuf",
".",
"This",
"seems",
"to",
"be",
"bitcoin",
"-",
"qt",
"standard",
"of",
"doing",
"things",
"."
] | 2813522b05cef4e0e545a101f8b3559a3183b45b | https://github.com/trezor/python-trezor/blob/2813522b05cef4e0e545a101f8b3559a3183b45b/trezorlib/tools.py#L190-L197 | train | 204,380 |
trezor/python-trezor | trezorlib/transport/protocol.py | get_protocol | def get_protocol(handle: Handle, want_v2: bool) -> Protocol:
"""Make a Protocol instance for the given handle.
Each transport can have a preference for using a particular protocol version.
This preference is overridable through `TREZOR_PROTOCOL_V1` environment variable,
which forces the library to use V1 anyways.
As of 11/2018, no devices support V2, so we enforce V1 here. It is still possible
to set `TREZOR_PROTOCOL_V1=0` and thus enable V2 protocol for transports that ask
for it (i.e., USB transports for Trezor T).
"""
force_v1 = int(os.environ.get("TREZOR_PROTOCOL_V1", 1))
if want_v2 and not force_v1:
return ProtocolV2(handle)
else:
return ProtocolV1(handle) | python | def get_protocol(handle: Handle, want_v2: bool) -> Protocol:
"""Make a Protocol instance for the given handle.
Each transport can have a preference for using a particular protocol version.
This preference is overridable through `TREZOR_PROTOCOL_V1` environment variable,
which forces the library to use V1 anyways.
As of 11/2018, no devices support V2, so we enforce V1 here. It is still possible
to set `TREZOR_PROTOCOL_V1=0` and thus enable V2 protocol for transports that ask
for it (i.e., USB transports for Trezor T).
"""
force_v1 = int(os.environ.get("TREZOR_PROTOCOL_V1", 1))
if want_v2 and not force_v1:
return ProtocolV2(handle)
else:
return ProtocolV1(handle) | [
"def",
"get_protocol",
"(",
"handle",
":",
"Handle",
",",
"want_v2",
":",
"bool",
")",
"->",
"Protocol",
":",
"force_v1",
"=",
"int",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"\"TREZOR_PROTOCOL_V1\"",
",",
"1",
")",
")",
"if",
"want_v2",
"and",
"not... | Make a Protocol instance for the given handle.
Each transport can have a preference for using a particular protocol version.
This preference is overridable through `TREZOR_PROTOCOL_V1` environment variable,
which forces the library to use V1 anyways.
As of 11/2018, no devices support V2, so we enforce V1 here. It is still possible
to set `TREZOR_PROTOCOL_V1=0` and thus enable V2 protocol for transports that ask
for it (i.e., USB transports for Trezor T). | [
"Make",
"a",
"Protocol",
"instance",
"for",
"the",
"given",
"handle",
"."
] | 2813522b05cef4e0e545a101f8b3559a3183b45b | https://github.com/trezor/python-trezor/blob/2813522b05cef4e0e545a101f8b3559a3183b45b/trezorlib/transport/protocol.py#L334-L349 | train | 204,381 |
trezor/python-trezor | trezorlib/transport/udp.py | UdpTransport._ping | def _ping(self) -> bool:
"""Test if the device is listening."""
assert self.socket is not None
resp = None
try:
self.socket.sendall(b"PINGPING")
resp = self.socket.recv(8)
except Exception:
pass
return resp == b"PONGPONG" | python | def _ping(self) -> bool:
"""Test if the device is listening."""
assert self.socket is not None
resp = None
try:
self.socket.sendall(b"PINGPING")
resp = self.socket.recv(8)
except Exception:
pass
return resp == b"PONGPONG" | [
"def",
"_ping",
"(",
"self",
")",
"->",
"bool",
":",
"assert",
"self",
".",
"socket",
"is",
"not",
"None",
"resp",
"=",
"None",
"try",
":",
"self",
".",
"socket",
".",
"sendall",
"(",
"b\"PINGPING\"",
")",
"resp",
"=",
"self",
".",
"socket",
".",
"... | Test if the device is listening. | [
"Test",
"if",
"the",
"device",
"is",
"listening",
"."
] | 2813522b05cef4e0e545a101f8b3559a3183b45b | https://github.com/trezor/python-trezor/blob/2813522b05cef4e0e545a101f8b3559a3183b45b/trezorlib/transport/udp.py#L95-L104 | train | 204,382 |
trezor/python-trezor | trezorlib/cosi.py | combine_keys | def combine_keys(pks: Iterable[Ed25519PublicPoint]) -> Ed25519PublicPoint:
"""Combine a list of Ed25519 points into a "global" CoSi key."""
P = [_ed25519.decodepoint(pk) for pk in pks]
combine = reduce(_ed25519.edwards_add, P)
return Ed25519PublicPoint(_ed25519.encodepoint(combine)) | python | def combine_keys(pks: Iterable[Ed25519PublicPoint]) -> Ed25519PublicPoint:
"""Combine a list of Ed25519 points into a "global" CoSi key."""
P = [_ed25519.decodepoint(pk) for pk in pks]
combine = reduce(_ed25519.edwards_add, P)
return Ed25519PublicPoint(_ed25519.encodepoint(combine)) | [
"def",
"combine_keys",
"(",
"pks",
":",
"Iterable",
"[",
"Ed25519PublicPoint",
"]",
")",
"->",
"Ed25519PublicPoint",
":",
"P",
"=",
"[",
"_ed25519",
".",
"decodepoint",
"(",
"pk",
")",
"for",
"pk",
"in",
"pks",
"]",
"combine",
"=",
"reduce",
"(",
"_ed255... | Combine a list of Ed25519 points into a "global" CoSi key. | [
"Combine",
"a",
"list",
"of",
"Ed25519",
"points",
"into",
"a",
"global",
"CoSi",
"key",
"."
] | 2813522b05cef4e0e545a101f8b3559a3183b45b | https://github.com/trezor/python-trezor/blob/2813522b05cef4e0e545a101f8b3559a3183b45b/trezorlib/cosi.py#L30-L34 | train | 204,383 |
trezor/python-trezor | trezorlib/cosi.py | combine_sig | def combine_sig(
global_R: Ed25519PublicPoint, sigs: Iterable[Ed25519Signature]
) -> Ed25519Signature:
"""Combine a list of signatures into a single CoSi signature."""
S = [_ed25519.decodeint(si) for si in sigs]
s = sum(S) % _ed25519.l
sig = global_R + _ed25519.encodeint(s)
return Ed25519Signature(sig) | python | def combine_sig(
global_R: Ed25519PublicPoint, sigs: Iterable[Ed25519Signature]
) -> Ed25519Signature:
"""Combine a list of signatures into a single CoSi signature."""
S = [_ed25519.decodeint(si) for si in sigs]
s = sum(S) % _ed25519.l
sig = global_R + _ed25519.encodeint(s)
return Ed25519Signature(sig) | [
"def",
"combine_sig",
"(",
"global_R",
":",
"Ed25519PublicPoint",
",",
"sigs",
":",
"Iterable",
"[",
"Ed25519Signature",
"]",
")",
"->",
"Ed25519Signature",
":",
"S",
"=",
"[",
"_ed25519",
".",
"decodeint",
"(",
"si",
")",
"for",
"si",
"in",
"sigs",
"]",
... | Combine a list of signatures into a single CoSi signature. | [
"Combine",
"a",
"list",
"of",
"signatures",
"into",
"a",
"single",
"CoSi",
"signature",
"."
] | 2813522b05cef4e0e545a101f8b3559a3183b45b | https://github.com/trezor/python-trezor/blob/2813522b05cef4e0e545a101f8b3559a3183b45b/trezorlib/cosi.py#L37-L44 | train | 204,384 |
trezor/python-trezor | trezorlib/cosi.py | get_nonce | def get_nonce(
sk: Ed25519PrivateKey, data: bytes, ctr: int = 0
) -> Tuple[int, Ed25519PublicPoint]:
"""Calculate CoSi nonces for given data.
These differ from Ed25519 deterministic nonces in that there is a counter appended at end.
Returns both the private point `r` and the partial signature `R`.
`r` is returned for performance reasons: :func:`sign_with_privkey`
takes it as its `nonce` argument so that it doesn't repeat the `get_nonce` call.
`R` should be combined with other partial signatures through :func:`combine_keys`
to obtain a "global commitment".
"""
# r = hash(hash(sk)[b .. 2b] + M + ctr)
# R = rB
h = _ed25519.H(sk)
bytesize = _ed25519.b // 8
assert len(h) == bytesize * 2
r = _ed25519.Hint(h[bytesize:] + data + ctr.to_bytes(4, "big"))
R = _ed25519.scalarmult(_ed25519.B, r)
return r, Ed25519PublicPoint(_ed25519.encodepoint(R)) | python | def get_nonce(
sk: Ed25519PrivateKey, data: bytes, ctr: int = 0
) -> Tuple[int, Ed25519PublicPoint]:
"""Calculate CoSi nonces for given data.
These differ from Ed25519 deterministic nonces in that there is a counter appended at end.
Returns both the private point `r` and the partial signature `R`.
`r` is returned for performance reasons: :func:`sign_with_privkey`
takes it as its `nonce` argument so that it doesn't repeat the `get_nonce` call.
`R` should be combined with other partial signatures through :func:`combine_keys`
to obtain a "global commitment".
"""
# r = hash(hash(sk)[b .. 2b] + M + ctr)
# R = rB
h = _ed25519.H(sk)
bytesize = _ed25519.b // 8
assert len(h) == bytesize * 2
r = _ed25519.Hint(h[bytesize:] + data + ctr.to_bytes(4, "big"))
R = _ed25519.scalarmult(_ed25519.B, r)
return r, Ed25519PublicPoint(_ed25519.encodepoint(R)) | [
"def",
"get_nonce",
"(",
"sk",
":",
"Ed25519PrivateKey",
",",
"data",
":",
"bytes",
",",
"ctr",
":",
"int",
"=",
"0",
")",
"->",
"Tuple",
"[",
"int",
",",
"Ed25519PublicPoint",
"]",
":",
"# r = hash(hash(sk)[b .. 2b] + M + ctr)",
"# R = rB",
"h",
"=",
"_ed25... | Calculate CoSi nonces for given data.
These differ from Ed25519 deterministic nonces in that there is a counter appended at end.
Returns both the private point `r` and the partial signature `R`.
`r` is returned for performance reasons: :func:`sign_with_privkey`
takes it as its `nonce` argument so that it doesn't repeat the `get_nonce` call.
`R` should be combined with other partial signatures through :func:`combine_keys`
to obtain a "global commitment". | [
"Calculate",
"CoSi",
"nonces",
"for",
"given",
"data",
".",
"These",
"differ",
"from",
"Ed25519",
"deterministic",
"nonces",
"in",
"that",
"there",
"is",
"a",
"counter",
"appended",
"at",
"end",
"."
] | 2813522b05cef4e0e545a101f8b3559a3183b45b | https://github.com/trezor/python-trezor/blob/2813522b05cef4e0e545a101f8b3559a3183b45b/trezorlib/cosi.py#L47-L67 | train | 204,385 |
trezor/python-trezor | trezorlib/cosi.py | verify | def verify(
signature: Ed25519Signature, digest: bytes, pub_key: Ed25519PublicPoint
) -> None:
"""Verify Ed25519 signature. Raise exception if the signature is invalid."""
# XXX this *might* change to bool function
_ed25519.checkvalid(signature, digest, pub_key) | python | def verify(
signature: Ed25519Signature, digest: bytes, pub_key: Ed25519PublicPoint
) -> None:
"""Verify Ed25519 signature. Raise exception if the signature is invalid."""
# XXX this *might* change to bool function
_ed25519.checkvalid(signature, digest, pub_key) | [
"def",
"verify",
"(",
"signature",
":",
"Ed25519Signature",
",",
"digest",
":",
"bytes",
",",
"pub_key",
":",
"Ed25519PublicPoint",
")",
"->",
"None",
":",
"# XXX this *might* change to bool function",
"_ed25519",
".",
"checkvalid",
"(",
"signature",
",",
"digest",
... | Verify Ed25519 signature. Raise exception if the signature is invalid. | [
"Verify",
"Ed25519",
"signature",
".",
"Raise",
"exception",
"if",
"the",
"signature",
"is",
"invalid",
"."
] | 2813522b05cef4e0e545a101f8b3559a3183b45b | https://github.com/trezor/python-trezor/blob/2813522b05cef4e0e545a101f8b3559a3183b45b/trezorlib/cosi.py#L70-L75 | train | 204,386 |
trezor/python-trezor | trezorlib/cosi.py | sign_with_privkey | def sign_with_privkey(
digest: bytes,
privkey: Ed25519PrivateKey,
global_pubkey: Ed25519PublicPoint,
nonce: int,
global_commit: Ed25519PublicPoint,
) -> Ed25519Signature:
"""Create a CoSi signature of `digest` with the supplied private key.
This function needs to know the global public key and global commitment.
"""
h = _ed25519.H(privkey)
a = _ed25519.decodecoord(h)
S = (nonce + _ed25519.Hint(global_commit + global_pubkey + digest) * a) % _ed25519.l
return Ed25519Signature(_ed25519.encodeint(S)) | python | def sign_with_privkey(
digest: bytes,
privkey: Ed25519PrivateKey,
global_pubkey: Ed25519PublicPoint,
nonce: int,
global_commit: Ed25519PublicPoint,
) -> Ed25519Signature:
"""Create a CoSi signature of `digest` with the supplied private key.
This function needs to know the global public key and global commitment.
"""
h = _ed25519.H(privkey)
a = _ed25519.decodecoord(h)
S = (nonce + _ed25519.Hint(global_commit + global_pubkey + digest) * a) % _ed25519.l
return Ed25519Signature(_ed25519.encodeint(S)) | [
"def",
"sign_with_privkey",
"(",
"digest",
":",
"bytes",
",",
"privkey",
":",
"Ed25519PrivateKey",
",",
"global_pubkey",
":",
"Ed25519PublicPoint",
",",
"nonce",
":",
"int",
",",
"global_commit",
":",
"Ed25519PublicPoint",
",",
")",
"->",
"Ed25519Signature",
":",
... | Create a CoSi signature of `digest` with the supplied private key.
This function needs to know the global public key and global commitment. | [
"Create",
"a",
"CoSi",
"signature",
"of",
"digest",
"with",
"the",
"supplied",
"private",
"key",
".",
"This",
"function",
"needs",
"to",
"know",
"the",
"global",
"public",
"key",
"and",
"global",
"commitment",
"."
] | 2813522b05cef4e0e545a101f8b3559a3183b45b | https://github.com/trezor/python-trezor/blob/2813522b05cef4e0e545a101f8b3559a3183b45b/trezorlib/cosi.py#L104-L118 | train | 204,387 |
trezor/python-trezor | setup.py | _patch_prebuild | def _patch_prebuild(cls):
"""Patch a setuptools command to depend on `prebuild`"""
orig_run = cls.run
def new_run(self):
self.run_command("prebuild")
orig_run(self)
cls.run = new_run | python | def _patch_prebuild(cls):
"""Patch a setuptools command to depend on `prebuild`"""
orig_run = cls.run
def new_run(self):
self.run_command("prebuild")
orig_run(self)
cls.run = new_run | [
"def",
"_patch_prebuild",
"(",
"cls",
")",
":",
"orig_run",
"=",
"cls",
".",
"run",
"def",
"new_run",
"(",
"self",
")",
":",
"self",
".",
"run_command",
"(",
"\"prebuild\"",
")",
"orig_run",
"(",
"self",
")",
"cls",
".",
"run",
"=",
"new_run"
] | Patch a setuptools command to depend on `prebuild` | [
"Patch",
"a",
"setuptools",
"command",
"to",
"depend",
"on",
"prebuild"
] | 2813522b05cef4e0e545a101f8b3559a3183b45b | https://github.com/trezor/python-trezor/blob/2813522b05cef4e0e545a101f8b3559a3183b45b/setup.py#L104-L112 | train | 204,388 |
trezor/python-trezor | trezorlib/client.py | get_default_client | def get_default_client(path=None, ui=None, **kwargs):
"""Get a client for a connected Trezor device.
Returns a TrezorClient instance with minimum fuss.
If no path is specified, finds first connected Trezor. Otherwise performs
a prefix-search for the specified device. If no UI is supplied, instantiates
the default CLI UI.
"""
from .transport import get_transport
from .ui import ClickUI
transport = get_transport(path, prefix_search=True)
if ui is None:
ui = ClickUI()
return TrezorClient(transport, ui, **kwargs) | python | def get_default_client(path=None, ui=None, **kwargs):
"""Get a client for a connected Trezor device.
Returns a TrezorClient instance with minimum fuss.
If no path is specified, finds first connected Trezor. Otherwise performs
a prefix-search for the specified device. If no UI is supplied, instantiates
the default CLI UI.
"""
from .transport import get_transport
from .ui import ClickUI
transport = get_transport(path, prefix_search=True)
if ui is None:
ui = ClickUI()
return TrezorClient(transport, ui, **kwargs) | [
"def",
"get_default_client",
"(",
"path",
"=",
"None",
",",
"ui",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"transport",
"import",
"get_transport",
"from",
".",
"ui",
"import",
"ClickUI",
"transport",
"=",
"get_transport",
"(",
"path",
... | Get a client for a connected Trezor device.
Returns a TrezorClient instance with minimum fuss.
If no path is specified, finds first connected Trezor. Otherwise performs
a prefix-search for the specified device. If no UI is supplied, instantiates
the default CLI UI. | [
"Get",
"a",
"client",
"for",
"a",
"connected",
"Trezor",
"device",
"."
] | 2813522b05cef4e0e545a101f8b3559a3183b45b | https://github.com/trezor/python-trezor/blob/2813522b05cef4e0e545a101f8b3559a3183b45b/trezorlib/client.py#L55-L71 | train | 204,389 |
kontron/python-ipmi | pyipmi/sel.py | Sel.sel_entries | def sel_entries(self):
"""Generator which returns all SEL entries."""
ENTIRE_RECORD = 0xff
rsp = self.send_message_with_name('GetSelInfo')
if rsp.entries == 0:
return
reservation_id = self.get_sel_reservation_id()
next_record_id = 0
while True:
req = create_request_by_name('GetSelEntry')
req.reservation_id = reservation_id
req.record_id = next_record_id
req.offset = 0
self.max_req_len = ENTIRE_RECORD
record_data = ByteBuffer()
while True:
req.length = self.max_req_len
if (self.max_req_len != 0xff
and (req.offset + req.length) > 16):
req.length = 16 - req.offset
rsp = self.send_message(req)
if rsp.completion_code == constants.CC_CANT_RET_NUM_REQ_BYTES:
if self.max_req_len == 0xff:
self.max_req_len = 16
else:
self.max_req_len -= 1
continue
else:
check_completion_code(rsp.completion_code)
record_data.extend(rsp.record_data)
req.offset = len(record_data)
if len(record_data) >= 16:
break
next_record_id = rsp.next_record_id
yield SelEntry(record_data)
if next_record_id == 0xffff:
break | python | def sel_entries(self):
"""Generator which returns all SEL entries."""
ENTIRE_RECORD = 0xff
rsp = self.send_message_with_name('GetSelInfo')
if rsp.entries == 0:
return
reservation_id = self.get_sel_reservation_id()
next_record_id = 0
while True:
req = create_request_by_name('GetSelEntry')
req.reservation_id = reservation_id
req.record_id = next_record_id
req.offset = 0
self.max_req_len = ENTIRE_RECORD
record_data = ByteBuffer()
while True:
req.length = self.max_req_len
if (self.max_req_len != 0xff
and (req.offset + req.length) > 16):
req.length = 16 - req.offset
rsp = self.send_message(req)
if rsp.completion_code == constants.CC_CANT_RET_NUM_REQ_BYTES:
if self.max_req_len == 0xff:
self.max_req_len = 16
else:
self.max_req_len -= 1
continue
else:
check_completion_code(rsp.completion_code)
record_data.extend(rsp.record_data)
req.offset = len(record_data)
if len(record_data) >= 16:
break
next_record_id = rsp.next_record_id
yield SelEntry(record_data)
if next_record_id == 0xffff:
break | [
"def",
"sel_entries",
"(",
"self",
")",
":",
"ENTIRE_RECORD",
"=",
"0xff",
"rsp",
"=",
"self",
".",
"send_message_with_name",
"(",
"'GetSelInfo'",
")",
"if",
"rsp",
".",
"entries",
"==",
"0",
":",
"return",
"reservation_id",
"=",
"self",
".",
"get_sel_reserv... | Generator which returns all SEL entries. | [
"Generator",
"which",
"returns",
"all",
"SEL",
"entries",
"."
] | ce46da47a37dd683615f32d04a10eda069aa569a | https://github.com/kontron/python-ipmi/blob/ce46da47a37dd683615f32d04a10eda069aa569a/pyipmi/sel.py#L49-L91 | train | 204,390 |
kontron/python-ipmi | pyipmi/hpm.py | Hpm.initiate_upgrade_action_and_wait | def initiate_upgrade_action_and_wait(self, components_mask, action,
timeout=2, interval=0.1):
""" Initiate Upgrade Action and wait for
long running command. """
try:
self.initiate_upgrade_action(components_mask, action)
except CompletionCodeError as e:
if e.cc == CC_LONG_DURATION_CMD_IN_PROGRESS:
self.wait_for_long_duration_command(
constants.CMDID_HPM_INITIATE_UPGRADE_ACTION,
timeout, interval)
else:
raise HpmError('initiate_upgrade_action CC=0x%02x' % e.cc) | python | def initiate_upgrade_action_and_wait(self, components_mask, action,
timeout=2, interval=0.1):
""" Initiate Upgrade Action and wait for
long running command. """
try:
self.initiate_upgrade_action(components_mask, action)
except CompletionCodeError as e:
if e.cc == CC_LONG_DURATION_CMD_IN_PROGRESS:
self.wait_for_long_duration_command(
constants.CMDID_HPM_INITIATE_UPGRADE_ACTION,
timeout, interval)
else:
raise HpmError('initiate_upgrade_action CC=0x%02x' % e.cc) | [
"def",
"initiate_upgrade_action_and_wait",
"(",
"self",
",",
"components_mask",
",",
"action",
",",
"timeout",
"=",
"2",
",",
"interval",
"=",
"0.1",
")",
":",
"try",
":",
"self",
".",
"initiate_upgrade_action",
"(",
"components_mask",
",",
"action",
")",
"exc... | Initiate Upgrade Action and wait for
long running command. | [
"Initiate",
"Upgrade",
"Action",
"and",
"wait",
"for",
"long",
"running",
"command",
"."
] | ce46da47a37dd683615f32d04a10eda069aa569a | https://github.com/kontron/python-ipmi/blob/ce46da47a37dd683615f32d04a10eda069aa569a/pyipmi/hpm.py#L128-L140 | train | 204,391 |
kontron/python-ipmi | pyipmi/hpm.py | Hpm.upload_binary | def upload_binary(self, binary, timeout=2, interval=0.1):
""" Upload all firmware blocks from binary and wait for
long running command. """
block_number = 0
block_size = self._determine_max_block_size()
for chunk in chunks(binary, block_size):
try:
self.upload_firmware_block(block_number, chunk)
except CompletionCodeError as e:
if e.cc == CC_LONG_DURATION_CMD_IN_PROGRESS:
self.wait_for_long_duration_command(
constants.CMDID_HPM_UPLOAD_FIRMWARE_BLOCK,
timeout, interval)
else:
raise HpmError('upload_firmware_block CC=0x%02x' % e.cc)
block_number += 1
block_number &= 0xff | python | def upload_binary(self, binary, timeout=2, interval=0.1):
""" Upload all firmware blocks from binary and wait for
long running command. """
block_number = 0
block_size = self._determine_max_block_size()
for chunk in chunks(binary, block_size):
try:
self.upload_firmware_block(block_number, chunk)
except CompletionCodeError as e:
if e.cc == CC_LONG_DURATION_CMD_IN_PROGRESS:
self.wait_for_long_duration_command(
constants.CMDID_HPM_UPLOAD_FIRMWARE_BLOCK,
timeout, interval)
else:
raise HpmError('upload_firmware_block CC=0x%02x' % e.cc)
block_number += 1
block_number &= 0xff | [
"def",
"upload_binary",
"(",
"self",
",",
"binary",
",",
"timeout",
"=",
"2",
",",
"interval",
"=",
"0.1",
")",
":",
"block_number",
"=",
"0",
"block_size",
"=",
"self",
".",
"_determine_max_block_size",
"(",
")",
"for",
"chunk",
"in",
"chunks",
"(",
"bi... | Upload all firmware blocks from binary and wait for
long running command. | [
"Upload",
"all",
"firmware",
"blocks",
"from",
"binary",
"and",
"wait",
"for",
"long",
"running",
"command",
"."
] | ce46da47a37dd683615f32d04a10eda069aa569a | https://github.com/kontron/python-ipmi/blob/ce46da47a37dd683615f32d04a10eda069aa569a/pyipmi/hpm.py#L151-L168 | train | 204,392 |
kontron/python-ipmi | pyipmi/hpm.py | Hpm.finish_upload_and_wait | def finish_upload_and_wait(self, component, length,
timeout=2, interval=0.1):
""" Finish the firmware upload process and wait for
long running command. """
try:
rsp = self.finish_firmware_upload(component, length)
check_completion_code(rsp.completion_code)
except CompletionCodeError as e:
if e.cc == CC_LONG_DURATION_CMD_IN_PROGRESS:
self.wait_for_long_duration_command(
constants.CMDID_HPM_FINISH_FIRMWARE_UPLOAD,
timeout, interval)
else:
raise HpmError('finish_firmware_upload CC=0x%02x' % e.cc) | python | def finish_upload_and_wait(self, component, length,
timeout=2, interval=0.1):
""" Finish the firmware upload process and wait for
long running command. """
try:
rsp = self.finish_firmware_upload(component, length)
check_completion_code(rsp.completion_code)
except CompletionCodeError as e:
if e.cc == CC_LONG_DURATION_CMD_IN_PROGRESS:
self.wait_for_long_duration_command(
constants.CMDID_HPM_FINISH_FIRMWARE_UPLOAD,
timeout, interval)
else:
raise HpmError('finish_firmware_upload CC=0x%02x' % e.cc) | [
"def",
"finish_upload_and_wait",
"(",
"self",
",",
"component",
",",
"length",
",",
"timeout",
"=",
"2",
",",
"interval",
"=",
"0.1",
")",
":",
"try",
":",
"rsp",
"=",
"self",
".",
"finish_firmware_upload",
"(",
"component",
",",
"length",
")",
"check_comp... | Finish the firmware upload process and wait for
long running command. | [
"Finish",
"the",
"firmware",
"upload",
"process",
"and",
"wait",
"for",
"long",
"running",
"command",
"."
] | ce46da47a37dd683615f32d04a10eda069aa569a | https://github.com/kontron/python-ipmi/blob/ce46da47a37dd683615f32d04a10eda069aa569a/pyipmi/hpm.py#L175-L188 | train | 204,393 |
kontron/python-ipmi | pyipmi/hpm.py | Hpm.activate_firmware_and_wait | def activate_firmware_and_wait(self, rollback_override=None,
timeout=2, interval=1):
""" Activate the new uploaded firmware and wait for
long running command. """
try:
self.activate_firmware(rollback_override)
except CompletionCodeError as e:
if e.cc == CC_LONG_DURATION_CMD_IN_PROGRESS:
self.wait_for_long_duration_command(
constants.CMDID_HPM_ACTIVATE_FIRMWARE,
timeout, interval)
else:
raise HpmError('activate_firmware CC=0x%02x' % e.cc)
except IpmiTimeoutError:
# controller is in reset and flashed new firmware
pass | python | def activate_firmware_and_wait(self, rollback_override=None,
timeout=2, interval=1):
""" Activate the new uploaded firmware and wait for
long running command. """
try:
self.activate_firmware(rollback_override)
except CompletionCodeError as e:
if e.cc == CC_LONG_DURATION_CMD_IN_PROGRESS:
self.wait_for_long_duration_command(
constants.CMDID_HPM_ACTIVATE_FIRMWARE,
timeout, interval)
else:
raise HpmError('activate_firmware CC=0x%02x' % e.cc)
except IpmiTimeoutError:
# controller is in reset and flashed new firmware
pass | [
"def",
"activate_firmware_and_wait",
"(",
"self",
",",
"rollback_override",
"=",
"None",
",",
"timeout",
"=",
"2",
",",
"interval",
"=",
"1",
")",
":",
"try",
":",
"self",
".",
"activate_firmware",
"(",
"rollback_override",
")",
"except",
"CompletionCodeError",
... | Activate the new uploaded firmware and wait for
long running command. | [
"Activate",
"the",
"new",
"uploaded",
"firmware",
"and",
"wait",
"for",
"long",
"running",
"command",
"."
] | ce46da47a37dd683615f32d04a10eda069aa569a | https://github.com/kontron/python-ipmi/blob/ce46da47a37dd683615f32d04a10eda069aa569a/pyipmi/hpm.py#L219-L234 | train | 204,394 |
kontron/python-ipmi | pyipmi/fields.py | VersionField._decode_data | def _decode_data(self, data):
"""`data` is array.array"""
self.major = data[0]
if data[1] is 0xff:
self.minor = data[1]
elif data[1] <= 0x99:
self.minor = int(data[1:2].tostring().decode('bcd+'))
else:
raise DecodingError() | python | def _decode_data(self, data):
"""`data` is array.array"""
self.major = data[0]
if data[1] is 0xff:
self.minor = data[1]
elif data[1] <= 0x99:
self.minor = int(data[1:2].tostring().decode('bcd+'))
else:
raise DecodingError() | [
"def",
"_decode_data",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"major",
"=",
"data",
"[",
"0",
"]",
"if",
"data",
"[",
"1",
"]",
"is",
"0xff",
":",
"self",
".",
"minor",
"=",
"data",
"[",
"1",
"]",
"elif",
"data",
"[",
"1",
"]",
"<="... | `data` is array.array | [
"data",
"is",
"array",
".",
"array"
] | ce46da47a37dd683615f32d04a10eda069aa569a | https://github.com/kontron/python-ipmi/blob/ce46da47a37dd683615f32d04a10eda069aa569a/pyipmi/fields.py#L37-L46 | train | 204,395 |
kontron/python-ipmi | pyipmi/__init__.py | Target.set_routing | def set_routing(self, routing):
"""Set the path over which a target is reachable.
The path is given as a list of tuples in the form (address,
bridge_channel).
Example #1: access to an ATCA blade in a chassis
slave = 0x81, target = 0x82
routing = [(0x81,0x20,0),(0x20,0x82,None)]
Example #2: access to an AMC in a uTCA chassis
slave = 0x81, target = 0x72
routing = [(0x81,0x20,0),(0x20,0x82,7),(0x20,0x72,None)]
uTCA - MCH AMC
.-------------------. .--------.
| .-----------| | |
| ShMC | CM | | MMC |
channel=0 | | | channel=7 | |
81 ------------| 0x20 |0x82 0x20 |-------------| 0x72 |
| | | | |
| | | | |
| `-----------| | |
`-------------------´ `--------´
`------------´ `---´ `---------------´
Example #3: access to an AMC in a ATCA AMC carrier
slave = 0x81, target = 0x72
routing = [(0x81,0x20,0),(0x20,0x8e,7),(0x20,0x80,None)]
"""
if is_string(routing):
# if type(routing) in [unicode, str]:
routing = ast.literal_eval(routing)
self.routing = [Routing(*route) for route in routing] | python | def set_routing(self, routing):
"""Set the path over which a target is reachable.
The path is given as a list of tuples in the form (address,
bridge_channel).
Example #1: access to an ATCA blade in a chassis
slave = 0x81, target = 0x82
routing = [(0x81,0x20,0),(0x20,0x82,None)]
Example #2: access to an AMC in a uTCA chassis
slave = 0x81, target = 0x72
routing = [(0x81,0x20,0),(0x20,0x82,7),(0x20,0x72,None)]
uTCA - MCH AMC
.-------------------. .--------.
| .-----------| | |
| ShMC | CM | | MMC |
channel=0 | | | channel=7 | |
81 ------------| 0x20 |0x82 0x20 |-------------| 0x72 |
| | | | |
| | | | |
| `-----------| | |
`-------------------´ `--------´
`------------´ `---´ `---------------´
Example #3: access to an AMC in a ATCA AMC carrier
slave = 0x81, target = 0x72
routing = [(0x81,0x20,0),(0x20,0x8e,7),(0x20,0x80,None)]
"""
if is_string(routing):
# if type(routing) in [unicode, str]:
routing = ast.literal_eval(routing)
self.routing = [Routing(*route) for route in routing] | [
"def",
"set_routing",
"(",
"self",
",",
"routing",
")",
":",
"if",
"is_string",
"(",
"routing",
")",
":",
"# if type(routing) in [unicode, str]:",
"routing",
"=",
"ast",
".",
"literal_eval",
"(",
"routing",
")",
"self",
".",
"routing",
"=",
"[",
"Routing",
"... | Set the path over which a target is reachable.
The path is given as a list of tuples in the form (address,
bridge_channel).
Example #1: access to an ATCA blade in a chassis
slave = 0x81, target = 0x82
routing = [(0x81,0x20,0),(0x20,0x82,None)]
Example #2: access to an AMC in a uTCA chassis
slave = 0x81, target = 0x72
routing = [(0x81,0x20,0),(0x20,0x82,7),(0x20,0x72,None)]
uTCA - MCH AMC
.-------------------. .--------.
| .-----------| | |
| ShMC | CM | | MMC |
channel=0 | | | channel=7 | |
81 ------------| 0x20 |0x82 0x20 |-------------| 0x72 |
| | | | |
| | | | |
| `-----------| | |
`-------------------´ `--------´
`------------´ `---´ `---------------´
Example #3: access to an AMC in a ATCA AMC carrier
slave = 0x81, target = 0x72
routing = [(0x81,0x20,0),(0x20,0x8e,7),(0x20,0x80,None)] | [
"Set",
"the",
"path",
"over",
"which",
"a",
"target",
"is",
"reachable",
"."
] | ce46da47a37dd683615f32d04a10eda069aa569a | https://github.com/kontron/python-ipmi/blob/ce46da47a37dd683615f32d04a10eda069aa569a/pyipmi/__init__.py#L111-L147 | train | 204,396 |
kontron/python-ipmi | pyipmi/__init__.py | Ipmi.raw_command | def raw_command(self, lun, netfn, raw_bytes):
"""Send the raw command data and return the raw response.
lun: the logical unit number
netfn: the network function
raw_bytes: the raw message as bytestring
Returns the response as bytestring.
"""
return self.interface.send_and_receive_raw(self.target, lun, netfn,
raw_bytes) | python | def raw_command(self, lun, netfn, raw_bytes):
"""Send the raw command data and return the raw response.
lun: the logical unit number
netfn: the network function
raw_bytes: the raw message as bytestring
Returns the response as bytestring.
"""
return self.interface.send_and_receive_raw(self.target, lun, netfn,
raw_bytes) | [
"def",
"raw_command",
"(",
"self",
",",
"lun",
",",
"netfn",
",",
"raw_bytes",
")",
":",
"return",
"self",
".",
"interface",
".",
"send_and_receive_raw",
"(",
"self",
".",
"target",
",",
"lun",
",",
"netfn",
",",
"raw_bytes",
")"
] | Send the raw command data and return the raw response.
lun: the logical unit number
netfn: the network function
raw_bytes: the raw message as bytestring
Returns the response as bytestring. | [
"Send",
"the",
"raw",
"command",
"data",
"and",
"return",
"the",
"raw",
"response",
"."
] | ce46da47a37dd683615f32d04a10eda069aa569a | https://github.com/kontron/python-ipmi/blob/ce46da47a37dd683615f32d04a10eda069aa569a/pyipmi/__init__.py#L210-L220 | train | 204,397 |
kontron/python-ipmi | pyipmi/interfaces/rmcp.py | Rmcp._send_and_receive | def _send_and_receive(self, target, lun, netfn, cmdid, payload):
"""Send and receive data using RMCP interface.
target:
lun:
netfn:
cmdid:
raw_bytes: IPMI message payload as bytestring
Returns the received data as array.
"""
self._inc_sequence_number()
header = IpmbHeaderReq()
header.netfn = netfn
header.rs_lun = lun
header.rs_sa = target.ipmb_address
header.rq_seq = self.next_sequence_number
header.rq_lun = 0
header.rq_sa = self.slave_address
header.cmd_id = cmdid
# Bridge message
if target.routing:
tx_data = encode_bridged_message(target.routing, header, payload,
self.next_sequence_number)
else:
tx_data = encode_ipmb_msg(header, payload)
self._send_ipmi_msg(tx_data)
received = False
while received is False:
if not self._q.empty():
rx_data = self._q.get()
else:
rx_data = self._receive_ipmi_msg()
if array('B', rx_data)[5] == constants.CMDID_SEND_MESSAGE:
rx_data = decode_bridged_message(rx_data)
received = rx_filter(header, rx_data)
if not received:
self._q.put(rx_data)
return rx_data[6:-1] | python | def _send_and_receive(self, target, lun, netfn, cmdid, payload):
"""Send and receive data using RMCP interface.
target:
lun:
netfn:
cmdid:
raw_bytes: IPMI message payload as bytestring
Returns the received data as array.
"""
self._inc_sequence_number()
header = IpmbHeaderReq()
header.netfn = netfn
header.rs_lun = lun
header.rs_sa = target.ipmb_address
header.rq_seq = self.next_sequence_number
header.rq_lun = 0
header.rq_sa = self.slave_address
header.cmd_id = cmdid
# Bridge message
if target.routing:
tx_data = encode_bridged_message(target.routing, header, payload,
self.next_sequence_number)
else:
tx_data = encode_ipmb_msg(header, payload)
self._send_ipmi_msg(tx_data)
received = False
while received is False:
if not self._q.empty():
rx_data = self._q.get()
else:
rx_data = self._receive_ipmi_msg()
if array('B', rx_data)[5] == constants.CMDID_SEND_MESSAGE:
rx_data = decode_bridged_message(rx_data)
received = rx_filter(header, rx_data)
if not received:
self._q.put(rx_data)
return rx_data[6:-1] | [
"def",
"_send_and_receive",
"(",
"self",
",",
"target",
",",
"lun",
",",
"netfn",
",",
"cmdid",
",",
"payload",
")",
":",
"self",
".",
"_inc_sequence_number",
"(",
")",
"header",
"=",
"IpmbHeaderReq",
"(",
")",
"header",
".",
"netfn",
"=",
"netfn",
"head... | Send and receive data using RMCP interface.
target:
lun:
netfn:
cmdid:
raw_bytes: IPMI message payload as bytestring
Returns the received data as array. | [
"Send",
"and",
"receive",
"data",
"using",
"RMCP",
"interface",
"."
] | ce46da47a37dd683615f32d04a10eda069aa569a | https://github.com/kontron/python-ipmi/blob/ce46da47a37dd683615f32d04a10eda069aa569a/pyipmi/interfaces/rmcp.py#L493-L539 | train | 204,398 |
kontron/python-ipmi | pyipmi/interfaces/rmcp.py | Rmcp.send_and_receive_raw | def send_and_receive_raw(self, target, lun, netfn, raw_bytes):
"""Interface function to send and receive raw message.
target: IPMI target
lun: logical unit number
netfn: network function
raw_bytes: RAW bytes as bytestring
Returns the IPMI message response bytestring.
"""
return self._send_and_receive(target=target,
lun=lun,
netfn=netfn,
cmdid=array('B', raw_bytes)[0],
payload=raw_bytes[1:]) | python | def send_and_receive_raw(self, target, lun, netfn, raw_bytes):
"""Interface function to send and receive raw message.
target: IPMI target
lun: logical unit number
netfn: network function
raw_bytes: RAW bytes as bytestring
Returns the IPMI message response bytestring.
"""
return self._send_and_receive(target=target,
lun=lun,
netfn=netfn,
cmdid=array('B', raw_bytes)[0],
payload=raw_bytes[1:]) | [
"def",
"send_and_receive_raw",
"(",
"self",
",",
"target",
",",
"lun",
",",
"netfn",
",",
"raw_bytes",
")",
":",
"return",
"self",
".",
"_send_and_receive",
"(",
"target",
"=",
"target",
",",
"lun",
"=",
"lun",
",",
"netfn",
"=",
"netfn",
",",
"cmdid",
... | Interface function to send and receive raw message.
target: IPMI target
lun: logical unit number
netfn: network function
raw_bytes: RAW bytes as bytestring
Returns the IPMI message response bytestring. | [
"Interface",
"function",
"to",
"send",
"and",
"receive",
"raw",
"message",
"."
] | ce46da47a37dd683615f32d04a10eda069aa569a | https://github.com/kontron/python-ipmi/blob/ce46da47a37dd683615f32d04a10eda069aa569a/pyipmi/interfaces/rmcp.py#L541-L555 | train | 204,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.