partition
stringclasses 3
values | func_name
stringlengths 1
134
| docstring
stringlengths 1
46.9k
| path
stringlengths 4
223
| original_string
stringlengths 75
104k
| code
stringlengths 75
104k
| docstring_tokens
listlengths 1
1.97k
| repo
stringlengths 7
55
| language
stringclasses 1
value | url
stringlengths 87
315
| code_tokens
listlengths 19
28.4k
| sha
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|
valid
|
authenticate
|
Returns True if the given username and password authenticate for the
given service. Returns False otherwise.
``username``: the username to authenticate
``password``: the password in plain text
``service``: the PAM service to authenticate against.
Defaults to 'login'
The above parameters can be strings or bytes. If they are strings,
they will be encoded using the encoding given by:
``encoding``: the encoding to use for the above parameters if they
are given as strings. Defaults to 'utf-8'
``resetcred``: Use the pam_setcred() function to
reinitialize the credentials.
Defaults to 'True'.
|
simplepam.py
|
def authenticate(username, password, service='login', encoding='utf-8',
resetcred=True):
"""Returns True if the given username and password authenticate for the
given service. Returns False otherwise.
``username``: the username to authenticate
``password``: the password in plain text
``service``: the PAM service to authenticate against.
Defaults to 'login'
The above parameters can be strings or bytes. If they are strings,
they will be encoded using the encoding given by:
``encoding``: the encoding to use for the above parameters if they
are given as strings. Defaults to 'utf-8'
``resetcred``: Use the pam_setcred() function to
reinitialize the credentials.
Defaults to 'True'.
"""
if sys.version_info >= (3,):
if isinstance(username, str):
username = username.encode(encoding)
if isinstance(password, str):
password = password.encode(encoding)
if isinstance(service, str):
service = service.encode(encoding)
@conv_func
def my_conv(n_messages, messages, p_response, app_data):
"""Simple conversation function that responds to any
prompt where the echo is off with the supplied password"""
# Create an array of n_messages response objects
addr = calloc(n_messages, sizeof(PamResponse))
p_response[0] = cast(addr, POINTER(PamResponse))
for i in range(n_messages):
if messages[i].contents.msg_style == PAM_PROMPT_ECHO_OFF:
pw_copy = strdup(password)
p_response.contents[i].resp = cast(pw_copy, c_char_p)
p_response.contents[i].resp_retcode = 0
return 0
handle = PamHandle()
conv = PamConv(my_conv, 0)
retval = pam_start(service, username, byref(conv), byref(handle))
if retval != 0:
# TODO: This is not an authentication error, something
# has gone wrong starting up PAM
return False
retval = pam_authenticate(handle, 0)
auth_success = (retval == 0)
# Re-initialize credentials (for Kerberos users, etc)
# Don't check return code of pam_setcred(), it shouldn't matter
# if this fails
if auth_success and resetcred:
retval = pam_setcred(handle, PAM_REINITIALIZE_CRED)
pam_end(handle, retval)
return auth_success
|
def authenticate(username, password, service='login', encoding='utf-8',
resetcred=True):
"""Returns True if the given username and password authenticate for the
given service. Returns False otherwise.
``username``: the username to authenticate
``password``: the password in plain text
``service``: the PAM service to authenticate against.
Defaults to 'login'
The above parameters can be strings or bytes. If they are strings,
they will be encoded using the encoding given by:
``encoding``: the encoding to use for the above parameters if they
are given as strings. Defaults to 'utf-8'
``resetcred``: Use the pam_setcred() function to
reinitialize the credentials.
Defaults to 'True'.
"""
if sys.version_info >= (3,):
if isinstance(username, str):
username = username.encode(encoding)
if isinstance(password, str):
password = password.encode(encoding)
if isinstance(service, str):
service = service.encode(encoding)
@conv_func
def my_conv(n_messages, messages, p_response, app_data):
"""Simple conversation function that responds to any
prompt where the echo is off with the supplied password"""
# Create an array of n_messages response objects
addr = calloc(n_messages, sizeof(PamResponse))
p_response[0] = cast(addr, POINTER(PamResponse))
for i in range(n_messages):
if messages[i].contents.msg_style == PAM_PROMPT_ECHO_OFF:
pw_copy = strdup(password)
p_response.contents[i].resp = cast(pw_copy, c_char_p)
p_response.contents[i].resp_retcode = 0
return 0
handle = PamHandle()
conv = PamConv(my_conv, 0)
retval = pam_start(service, username, byref(conv), byref(handle))
if retval != 0:
# TODO: This is not an authentication error, something
# has gone wrong starting up PAM
return False
retval = pam_authenticate(handle, 0)
auth_success = (retval == 0)
# Re-initialize credentials (for Kerberos users, etc)
# Don't check return code of pam_setcred(), it shouldn't matter
# if this fails
if auth_success and resetcred:
retval = pam_setcred(handle, PAM_REINITIALIZE_CRED)
pam_end(handle, retval)
return auth_success
|
[
"Returns",
"True",
"if",
"the",
"given",
"username",
"and",
"password",
"authenticate",
"for",
"the",
"given",
"service",
".",
"Returns",
"False",
"otherwise",
"."
] |
leonnnn/python3-simplepam
|
python
|
https://github.com/leonnnn/python3-simplepam/blob/b81a806e3215b95f8c2c19d091214c4609a1f12d/simplepam.py#L104-L169
|
[
"def",
"authenticate",
"(",
"username",
",",
"password",
",",
"service",
"=",
"'login'",
",",
"encoding",
"=",
"'utf-8'",
",",
"resetcred",
"=",
"True",
")",
":",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
")",
":",
"if",
"isinstance",
"(",
"username",
",",
"str",
")",
":",
"username",
"=",
"username",
".",
"encode",
"(",
"encoding",
")",
"if",
"isinstance",
"(",
"password",
",",
"str",
")",
":",
"password",
"=",
"password",
".",
"encode",
"(",
"encoding",
")",
"if",
"isinstance",
"(",
"service",
",",
"str",
")",
":",
"service",
"=",
"service",
".",
"encode",
"(",
"encoding",
")",
"@",
"conv_func",
"def",
"my_conv",
"(",
"n_messages",
",",
"messages",
",",
"p_response",
",",
"app_data",
")",
":",
"\"\"\"Simple conversation function that responds to any\n prompt where the echo is off with the supplied password\"\"\"",
"# Create an array of n_messages response objects",
"addr",
"=",
"calloc",
"(",
"n_messages",
",",
"sizeof",
"(",
"PamResponse",
")",
")",
"p_response",
"[",
"0",
"]",
"=",
"cast",
"(",
"addr",
",",
"POINTER",
"(",
"PamResponse",
")",
")",
"for",
"i",
"in",
"range",
"(",
"n_messages",
")",
":",
"if",
"messages",
"[",
"i",
"]",
".",
"contents",
".",
"msg_style",
"==",
"PAM_PROMPT_ECHO_OFF",
":",
"pw_copy",
"=",
"strdup",
"(",
"password",
")",
"p_response",
".",
"contents",
"[",
"i",
"]",
".",
"resp",
"=",
"cast",
"(",
"pw_copy",
",",
"c_char_p",
")",
"p_response",
".",
"contents",
"[",
"i",
"]",
".",
"resp_retcode",
"=",
"0",
"return",
"0",
"handle",
"=",
"PamHandle",
"(",
")",
"conv",
"=",
"PamConv",
"(",
"my_conv",
",",
"0",
")",
"retval",
"=",
"pam_start",
"(",
"service",
",",
"username",
",",
"byref",
"(",
"conv",
")",
",",
"byref",
"(",
"handle",
")",
")",
"if",
"retval",
"!=",
"0",
":",
"# TODO: This is not an authentication error, something",
"# has gone wrong starting up PAM",
"return",
"False",
"retval",
"=",
"pam_authenticate",
"(",
"handle",
",",
"0",
")",
"auth_success",
"=",
"(",
"retval",
"==",
"0",
")",
"# Re-initialize credentials (for Kerberos users, etc)",
"# Don't check return code of pam_setcred(), it shouldn't matter",
"# if this fails",
"if",
"auth_success",
"and",
"resetcred",
":",
"retval",
"=",
"pam_setcred",
"(",
"handle",
",",
"PAM_REINITIALIZE_CRED",
")",
"pam_end",
"(",
"handle",
",",
"retval",
")",
"return",
"auth_success"
] |
b81a806e3215b95f8c2c19d091214c4609a1f12d
|
valid
|
SerializerSaveView.post
|
Save the provided data using the class' serializer.
Args:
request:
The request being made.
Returns:
An ``APIResponse`` instance. If the request was successful
the response will have a 200 status code and contain the
serializer's data. Otherwise a 400 status code and the
request's errors will be returned.
|
rest_email_auth/generics.py
|
def post(self, request):
"""
Save the provided data using the class' serializer.
Args:
request:
The request being made.
Returns:
An ``APIResponse`` instance. If the request was successful
the response will have a 200 status code and contain the
serializer's data. Otherwise a 400 status code and the
request's errors will be returned.
"""
serializer = self.get_serializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
def post(self, request):
"""
Save the provided data using the class' serializer.
Args:
request:
The request being made.
Returns:
An ``APIResponse`` instance. If the request was successful
the response will have a 200 status code and contain the
serializer's data. Otherwise a 400 status code and the
request's errors will be returned.
"""
serializer = self.get_serializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
[
"Save",
"the",
"provided",
"data",
"using",
"the",
"class",
"serializer",
"."
] |
cdriehuys/django-rest-email-auth
|
python
|
https://github.com/cdriehuys/django-rest-email-auth/blob/7e752c4d77ae02d2d046f214f56e743aa12ab23f/rest_email_auth/generics.py#L14-L35
|
[
"def",
"post",
"(",
"self",
",",
"request",
")",
":",
"serializer",
"=",
"self",
".",
"get_serializer",
"(",
"data",
"=",
"request",
".",
"data",
")",
"if",
"serializer",
".",
"is_valid",
"(",
")",
":",
"serializer",
".",
"save",
"(",
")",
"return",
"Response",
"(",
"serializer",
".",
"data",
")",
"return",
"Response",
"(",
"serializer",
".",
"errors",
",",
"status",
"=",
"status",
".",
"HTTP_400_BAD_REQUEST",
")"
] |
7e752c4d77ae02d2d046f214f56e743aa12ab23f
|
valid
|
ReferrerTree.get_repr
|
Return an HTML tree block describing the given object.
|
django_dowser/views.py
|
def get_repr(self, obj, referent=None):
"""Return an HTML tree block describing the given object."""
objtype = type(obj)
typename = str(objtype.__module__) + "." + objtype.__name__
prettytype = typename.replace("__builtin__.", "")
name = getattr(obj, "__name__", "")
if name:
prettytype = "%s %r" % (prettytype, name)
key = ""
if referent:
key = self.get_refkey(obj, referent)
url = reverse('dowser_trace_object', args=(
typename,
id(obj)
))
return ('<a class="objectid" href="%s">%s</a> '
'<span class="typename">%s</span>%s<br />'
'<span class="repr">%s</span>'
% (url, id(obj), prettytype, key, get_repr(obj, 100))
)
|
def get_repr(self, obj, referent=None):
"""Return an HTML tree block describing the given object."""
objtype = type(obj)
typename = str(objtype.__module__) + "." + objtype.__name__
prettytype = typename.replace("__builtin__.", "")
name = getattr(obj, "__name__", "")
if name:
prettytype = "%s %r" % (prettytype, name)
key = ""
if referent:
key = self.get_refkey(obj, referent)
url = reverse('dowser_trace_object', args=(
typename,
id(obj)
))
return ('<a class="objectid" href="%s">%s</a> '
'<span class="typename">%s</span>%s<br />'
'<span class="repr">%s</span>'
% (url, id(obj), prettytype, key, get_repr(obj, 100))
)
|
[
"Return",
"an",
"HTML",
"tree",
"block",
"describing",
"the",
"given",
"object",
"."
] |
munhitsu/django-dowser
|
python
|
https://github.com/munhitsu/django-dowser/blob/3030be07cd3cf183adea634b066337bcd07074d6/django_dowser/views.py#L222-L243
|
[
"def",
"get_repr",
"(",
"self",
",",
"obj",
",",
"referent",
"=",
"None",
")",
":",
"objtype",
"=",
"type",
"(",
"obj",
")",
"typename",
"=",
"str",
"(",
"objtype",
".",
"__module__",
")",
"+",
"\".\"",
"+",
"objtype",
".",
"__name__",
"prettytype",
"=",
"typename",
".",
"replace",
"(",
"\"__builtin__.\"",
",",
"\"\"",
")",
"name",
"=",
"getattr",
"(",
"obj",
",",
"\"__name__\"",
",",
"\"\"",
")",
"if",
"name",
":",
"prettytype",
"=",
"\"%s %r\"",
"%",
"(",
"prettytype",
",",
"name",
")",
"key",
"=",
"\"\"",
"if",
"referent",
":",
"key",
"=",
"self",
".",
"get_refkey",
"(",
"obj",
",",
"referent",
")",
"url",
"=",
"reverse",
"(",
"'dowser_trace_object'",
",",
"args",
"=",
"(",
"typename",
",",
"id",
"(",
"obj",
")",
")",
")",
"return",
"(",
"'<a class=\"objectid\" href=\"%s\">%s</a> '",
"'<span class=\"typename\">%s</span>%s<br />'",
"'<span class=\"repr\">%s</span>'",
"%",
"(",
"url",
",",
"id",
"(",
"obj",
")",
",",
"prettytype",
",",
"key",
",",
"get_repr",
"(",
"obj",
",",
"100",
")",
")",
")"
] |
3030be07cd3cf183adea634b066337bcd07074d6
|
valid
|
ReferrerTree.get_refkey
|
Return the dict key or attribute name of obj which refers to
referent.
|
django_dowser/views.py
|
def get_refkey(self, obj, referent):
"""Return the dict key or attribute name of obj which refers to
referent."""
if isinstance(obj, dict):
for k, v in obj.items():
if v is referent:
return " (via its %r key)" % k
for k in dir(obj) + ['__dict__']:
if getattr(obj, k, None) is referent:
return " (via its %r attribute)" % k
return ""
|
def get_refkey(self, obj, referent):
"""Return the dict key or attribute name of obj which refers to
referent."""
if isinstance(obj, dict):
for k, v in obj.items():
if v is referent:
return " (via its %r key)" % k
for k in dir(obj) + ['__dict__']:
if getattr(obj, k, None) is referent:
return " (via its %r attribute)" % k
return ""
|
[
"Return",
"the",
"dict",
"key",
"or",
"attribute",
"name",
"of",
"obj",
"which",
"refers",
"to",
"referent",
"."
] |
munhitsu/django-dowser
|
python
|
https://github.com/munhitsu/django-dowser/blob/3030be07cd3cf183adea634b066337bcd07074d6/django_dowser/views.py#L245-L256
|
[
"def",
"get_refkey",
"(",
"self",
",",
"obj",
",",
"referent",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"for",
"k",
",",
"v",
"in",
"obj",
".",
"items",
"(",
")",
":",
"if",
"v",
"is",
"referent",
":",
"return",
"\" (via its %r key)\"",
"%",
"k",
"for",
"k",
"in",
"dir",
"(",
"obj",
")",
"+",
"[",
"'__dict__'",
"]",
":",
"if",
"getattr",
"(",
"obj",
",",
"k",
",",
"None",
")",
"is",
"referent",
":",
"return",
"\" (via its %r attribute)\"",
"%",
"k",
"return",
"\"\""
] |
3030be07cd3cf183adea634b066337bcd07074d6
|
valid
|
Tree.walk
|
Walk the object tree, ignoring duplicates and circular refs.
|
django_dowser/reftree.py
|
def walk(self, maxresults=100, maxdepth=None):
"""Walk the object tree, ignoring duplicates and circular refs."""
log.debug("step")
self.seen = {}
self.ignore(self, self.__dict__, self.obj, self.seen, self._ignore)
# Ignore the calling frame, its builtins, globals and locals
self.ignore_caller()
self.maxdepth = maxdepth
count = 0
log.debug("will iterate results")
for result in self._gen(self.obj):
log.debug("will yeld")
yield result
count += 1
if maxresults and count >= maxresults:
yield 0, 0, "==== Max results reached ===="
return
|
def walk(self, maxresults=100, maxdepth=None):
"""Walk the object tree, ignoring duplicates and circular refs."""
log.debug("step")
self.seen = {}
self.ignore(self, self.__dict__, self.obj, self.seen, self._ignore)
# Ignore the calling frame, its builtins, globals and locals
self.ignore_caller()
self.maxdepth = maxdepth
count = 0
log.debug("will iterate results")
for result in self._gen(self.obj):
log.debug("will yeld")
yield result
count += 1
if maxresults and count >= maxresults:
yield 0, 0, "==== Max results reached ===="
return
|
[
"Walk",
"the",
"object",
"tree",
"ignoring",
"duplicates",
"and",
"circular",
"refs",
"."
] |
munhitsu/django-dowser
|
python
|
https://github.com/munhitsu/django-dowser/blob/3030be07cd3cf183adea634b066337bcd07074d6/django_dowser/reftree.py#L28-L45
|
[
"def",
"walk",
"(",
"self",
",",
"maxresults",
"=",
"100",
",",
"maxdepth",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"\"step\"",
")",
"self",
".",
"seen",
"=",
"{",
"}",
"self",
".",
"ignore",
"(",
"self",
",",
"self",
".",
"__dict__",
",",
"self",
".",
"obj",
",",
"self",
".",
"seen",
",",
"self",
".",
"_ignore",
")",
"# Ignore the calling frame, its builtins, globals and locals",
"self",
".",
"ignore_caller",
"(",
")",
"self",
".",
"maxdepth",
"=",
"maxdepth",
"count",
"=",
"0",
"log",
".",
"debug",
"(",
"\"will iterate results\"",
")",
"for",
"result",
"in",
"self",
".",
"_gen",
"(",
"self",
".",
"obj",
")",
":",
"log",
".",
"debug",
"(",
"\"will yeld\"",
")",
"yield",
"result",
"count",
"+=",
"1",
"if",
"maxresults",
"and",
"count",
">=",
"maxresults",
":",
"yield",
"0",
",",
"0",
",",
"\"==== Max results reached ====\"",
"return"
] |
3030be07cd3cf183adea634b066337bcd07074d6
|
valid
|
Tree.print_tree
|
Walk the object tree, pretty-printing each branch.
|
django_dowser/reftree.py
|
def print_tree(self, maxresults=100, maxdepth=None):
"""Walk the object tree, pretty-printing each branch."""
self.ignore_caller()
for depth, refid, rep in self.walk(maxresults, maxdepth):
print(("%9d" % refid), (" " * depth * 2), rep)
|
def print_tree(self, maxresults=100, maxdepth=None):
"""Walk the object tree, pretty-printing each branch."""
self.ignore_caller()
for depth, refid, rep in self.walk(maxresults, maxdepth):
print(("%9d" % refid), (" " * depth * 2), rep)
|
[
"Walk",
"the",
"object",
"tree",
"pretty",
"-",
"printing",
"each",
"branch",
"."
] |
munhitsu/django-dowser
|
python
|
https://github.com/munhitsu/django-dowser/blob/3030be07cd3cf183adea634b066337bcd07074d6/django_dowser/reftree.py#L47-L51
|
[
"def",
"print_tree",
"(",
"self",
",",
"maxresults",
"=",
"100",
",",
"maxdepth",
"=",
"None",
")",
":",
"self",
".",
"ignore_caller",
"(",
")",
"for",
"depth",
",",
"refid",
",",
"rep",
"in",
"self",
".",
"walk",
"(",
"maxresults",
",",
"maxdepth",
")",
":",
"print",
"(",
"(",
"\"%9d\"",
"%",
"refid",
")",
",",
"(",
"\" \"",
"*",
"depth",
"*",
"2",
")",
",",
"rep",
")"
] |
3030be07cd3cf183adea634b066337bcd07074d6
|
valid
|
CircularReferents.print_tree
|
Walk the object tree, pretty-printing each branch.
|
django_dowser/reftree.py
|
def print_tree(self, maxresults=100, maxdepth=None):
"""Walk the object tree, pretty-printing each branch."""
self.ignore_caller()
for trail in self.walk(maxresults, maxdepth):
print(trail)
if self.stops:
print("%s paths stopped because max depth reached" % self.stops)
|
def print_tree(self, maxresults=100, maxdepth=None):
"""Walk the object tree, pretty-printing each branch."""
self.ignore_caller()
for trail in self.walk(maxresults, maxdepth):
print(trail)
if self.stops:
print("%s paths stopped because max depth reached" % self.stops)
|
[
"Walk",
"the",
"object",
"tree",
"pretty",
"-",
"printing",
"each",
"branch",
"."
] |
munhitsu/django-dowser
|
python
|
https://github.com/munhitsu/django-dowser/blob/3030be07cd3cf183adea634b066337bcd07074d6/django_dowser/reftree.py#L173-L179
|
[
"def",
"print_tree",
"(",
"self",
",",
"maxresults",
"=",
"100",
",",
"maxdepth",
"=",
"None",
")",
":",
"self",
".",
"ignore_caller",
"(",
")",
"for",
"trail",
"in",
"self",
".",
"walk",
"(",
"maxresults",
",",
"maxdepth",
")",
":",
"print",
"(",
"trail",
")",
"if",
"self",
".",
"stops",
":",
"print",
"(",
"\"%s paths stopped because max depth reached\"",
"%",
"self",
".",
"stops",
")"
] |
3030be07cd3cf183adea634b066337bcd07074d6
|
valid
|
get_finders
|
Set the media fixtures finders on settings.py.
Example:
MEDIA_FIXTURES_FILES_FINDERS = (
'django_media_fixtures.finders.FileSystemFinder',
'django_media_fixtures.finders.AppDirectoriesFinder', # default
)
|
django_media_fixtures/finders.py
|
def get_finders():
"""
Set the media fixtures finders on settings.py.
Example:
MEDIA_FIXTURES_FILES_FINDERS = (
'django_media_fixtures.finders.FileSystemFinder',
'django_media_fixtures.finders.AppDirectoriesFinder', # default
)
"""
if hasattr(settings, 'MEDIA_FIXTURES_FILES_FINDERS'):
finders = settings.MEDIA_FIXTURES_FILES_FINDERS
else:
finders = (
'django_media_fixtures.finders.AppDirectoriesFinder',
)
for finder_path in finders:
yield get_finder(finder_path)
|
def get_finders():
"""
Set the media fixtures finders on settings.py.
Example:
MEDIA_FIXTURES_FILES_FINDERS = (
'django_media_fixtures.finders.FileSystemFinder',
'django_media_fixtures.finders.AppDirectoriesFinder', # default
)
"""
if hasattr(settings, 'MEDIA_FIXTURES_FILES_FINDERS'):
finders = settings.MEDIA_FIXTURES_FILES_FINDERS
else:
finders = (
'django_media_fixtures.finders.AppDirectoriesFinder',
)
for finder_path in finders:
yield get_finder(finder_path)
|
[
"Set",
"the",
"media",
"fixtures",
"finders",
"on",
"settings",
".",
"py",
".",
"Example",
":",
"MEDIA_FIXTURES_FILES_FINDERS",
"=",
"(",
"django_media_fixtures",
".",
"finders",
".",
"FileSystemFinder",
"django_media_fixtures",
".",
"finders",
".",
"AppDirectoriesFinder",
"#",
"default",
")"
] |
adrianoveiga/django-media-fixtures
|
python
|
https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/finders.py#L159-L176
|
[
"def",
"get_finders",
"(",
")",
":",
"if",
"hasattr",
"(",
"settings",
",",
"'MEDIA_FIXTURES_FILES_FINDERS'",
")",
":",
"finders",
"=",
"settings",
".",
"MEDIA_FIXTURES_FILES_FINDERS",
"else",
":",
"finders",
"=",
"(",
"'django_media_fixtures.finders.AppDirectoriesFinder'",
",",
")",
"for",
"finder_path",
"in",
"finders",
":",
"yield",
"get_finder",
"(",
"finder_path",
")"
] |
a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54
|
valid
|
get_finder
|
Imports the media fixtures files finder class described by import_path, where
import_path is the full Python path to the class.
|
django_media_fixtures/finders.py
|
def get_finder(import_path):
"""
Imports the media fixtures files finder class described by import_path, where
import_path is the full Python path to the class.
"""
Finder = import_string(import_path)
if not issubclass(Finder, BaseFinder):
raise ImproperlyConfigured('Finder "%s" is not a subclass of "%s"' %
(Finder, BaseFinder))
return Finder()
|
def get_finder(import_path):
"""
Imports the media fixtures files finder class described by import_path, where
import_path is the full Python path to the class.
"""
Finder = import_string(import_path)
if not issubclass(Finder, BaseFinder):
raise ImproperlyConfigured('Finder "%s" is not a subclass of "%s"' %
(Finder, BaseFinder))
return Finder()
|
[
"Imports",
"the",
"media",
"fixtures",
"files",
"finder",
"class",
"described",
"by",
"import_path",
"where",
"import_path",
"is",
"the",
"full",
"Python",
"path",
"to",
"the",
"class",
"."
] |
adrianoveiga/django-media-fixtures
|
python
|
https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/finders.py#L180-L189
|
[
"def",
"get_finder",
"(",
"import_path",
")",
":",
"Finder",
"=",
"import_string",
"(",
"import_path",
")",
"if",
"not",
"issubclass",
"(",
"Finder",
",",
"BaseFinder",
")",
":",
"raise",
"ImproperlyConfigured",
"(",
"'Finder \"%s\" is not a subclass of \"%s\"'",
"%",
"(",
"Finder",
",",
"BaseFinder",
")",
")",
"return",
"Finder",
"(",
")"
] |
a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54
|
valid
|
FileSystemFinder.find
|
Looks for files in the extra locations
as defined in ``MEDIA_FIXTURES_FILES_DIRS``.
|
django_media_fixtures/finders.py
|
def find(self, path, all=False):
"""
Looks for files in the extra locations
as defined in ``MEDIA_FIXTURES_FILES_DIRS``.
"""
matches = []
for prefix, root in self.locations:
if root not in searched_locations:
searched_locations.append(root)
matched_path = self.find_location(root, path, prefix)
if matched_path:
if not all:
return matched_path
matches.append(matched_path)
return matches
|
def find(self, path, all=False):
"""
Looks for files in the extra locations
as defined in ``MEDIA_FIXTURES_FILES_DIRS``.
"""
matches = []
for prefix, root in self.locations:
if root not in searched_locations:
searched_locations.append(root)
matched_path = self.find_location(root, path, prefix)
if matched_path:
if not all:
return matched_path
matches.append(matched_path)
return matches
|
[
"Looks",
"for",
"files",
"in",
"the",
"extra",
"locations",
"as",
"defined",
"in",
"MEDIA_FIXTURES_FILES_DIRS",
"."
] |
adrianoveiga/django-media-fixtures
|
python
|
https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/finders.py#L52-L66
|
[
"def",
"find",
"(",
"self",
",",
"path",
",",
"all",
"=",
"False",
")",
":",
"matches",
"=",
"[",
"]",
"for",
"prefix",
",",
"root",
"in",
"self",
".",
"locations",
":",
"if",
"root",
"not",
"in",
"searched_locations",
":",
"searched_locations",
".",
"append",
"(",
"root",
")",
"matched_path",
"=",
"self",
".",
"find_location",
"(",
"root",
",",
"path",
",",
"prefix",
")",
"if",
"matched_path",
":",
"if",
"not",
"all",
":",
"return",
"matched_path",
"matches",
".",
"append",
"(",
"matched_path",
")",
"return",
"matches"
] |
a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54
|
valid
|
FileSystemFinder.find_location
|
Finds a requested media file in a location, returning the found
absolute path (or ``None`` if no match).
|
django_media_fixtures/finders.py
|
def find_location(self, root, path, prefix=None):
"""
Finds a requested media file in a location, returning the found
absolute path (or ``None`` if no match).
"""
if prefix:
prefix = '%s%s' % (prefix, os.sep)
if not path.startswith(prefix):
return None
path = path[len(prefix):]
path = safe_join(root, path)
if os.path.exists(path):
return path
|
def find_location(self, root, path, prefix=None):
"""
Finds a requested media file in a location, returning the found
absolute path (or ``None`` if no match).
"""
if prefix:
prefix = '%s%s' % (prefix, os.sep)
if not path.startswith(prefix):
return None
path = path[len(prefix):]
path = safe_join(root, path)
if os.path.exists(path):
return path
|
[
"Finds",
"a",
"requested",
"media",
"file",
"in",
"a",
"location",
"returning",
"the",
"found",
"absolute",
"path",
"(",
"or",
"None",
"if",
"no",
"match",
")",
"."
] |
adrianoveiga/django-media-fixtures
|
python
|
https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/finders.py#L68-L80
|
[
"def",
"find_location",
"(",
"self",
",",
"root",
",",
"path",
",",
"prefix",
"=",
"None",
")",
":",
"if",
"prefix",
":",
"prefix",
"=",
"'%s%s'",
"%",
"(",
"prefix",
",",
"os",
".",
"sep",
")",
"if",
"not",
"path",
".",
"startswith",
"(",
"prefix",
")",
":",
"return",
"None",
"path",
"=",
"path",
"[",
"len",
"(",
"prefix",
")",
":",
"]",
"path",
"=",
"safe_join",
"(",
"root",
",",
"path",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"path"
] |
a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54
|
valid
|
FileSystemFinder.list
|
List all files in all locations.
|
django_media_fixtures/finders.py
|
def list(self, ignore_patterns):
"""
List all files in all locations.
"""
for prefix, root in self.locations:
storage = self.storages[root]
for path in utils.get_files(storage, ignore_patterns):
yield path, storage
|
def list(self, ignore_patterns):
"""
List all files in all locations.
"""
for prefix, root in self.locations:
storage = self.storages[root]
for path in utils.get_files(storage, ignore_patterns):
yield path, storage
|
[
"List",
"all",
"files",
"in",
"all",
"locations",
"."
] |
adrianoveiga/django-media-fixtures
|
python
|
https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/finders.py#L82-L89
|
[
"def",
"list",
"(",
"self",
",",
"ignore_patterns",
")",
":",
"for",
"prefix",
",",
"root",
"in",
"self",
".",
"locations",
":",
"storage",
"=",
"self",
".",
"storages",
"[",
"root",
"]",
"for",
"path",
"in",
"utils",
".",
"get_files",
"(",
"storage",
",",
"ignore_patterns",
")",
":",
"yield",
"path",
",",
"storage"
] |
a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54
|
valid
|
AppDirectoriesFinder.list
|
List all files in all app storages.
|
django_media_fixtures/finders.py
|
def list(self, ignore_patterns):
"""
List all files in all app storages.
"""
for storage in six.itervalues(self.storages):
if storage.exists(''): # check if storage location exists
for path in utils.get_files(storage, ignore_patterns):
yield path, storage
|
def list(self, ignore_patterns):
"""
List all files in all app storages.
"""
for storage in six.itervalues(self.storages):
if storage.exists(''): # check if storage location exists
for path in utils.get_files(storage, ignore_patterns):
yield path, storage
|
[
"List",
"all",
"files",
"in",
"all",
"app",
"storages",
"."
] |
adrianoveiga/django-media-fixtures
|
python
|
https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/finders.py#L121-L128
|
[
"def",
"list",
"(",
"self",
",",
"ignore_patterns",
")",
":",
"for",
"storage",
"in",
"six",
".",
"itervalues",
"(",
"self",
".",
"storages",
")",
":",
"if",
"storage",
".",
"exists",
"(",
"''",
")",
":",
"# check if storage location exists",
"for",
"path",
"in",
"utils",
".",
"get_files",
"(",
"storage",
",",
"ignore_patterns",
")",
":",
"yield",
"path",
",",
"storage"
] |
a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54
|
valid
|
AppDirectoriesFinder.find
|
Looks for files in the app directories.
|
django_media_fixtures/finders.py
|
def find(self, path, all=False):
"""
Looks for files in the app directories.
"""
matches = []
for app in self.apps:
app_location = self.storages[app].location
if app_location not in searched_locations:
searched_locations.append(app_location)
match = self.find_in_app(app, path)
if match:
if not all:
return match
matches.append(match)
return matches
|
def find(self, path, all=False):
"""
Looks for files in the app directories.
"""
matches = []
for app in self.apps:
app_location = self.storages[app].location
if app_location not in searched_locations:
searched_locations.append(app_location)
match = self.find_in_app(app, path)
if match:
if not all:
return match
matches.append(match)
return matches
|
[
"Looks",
"for",
"files",
"in",
"the",
"app",
"directories",
"."
] |
adrianoveiga/django-media-fixtures
|
python
|
https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/finders.py#L130-L144
|
[
"def",
"find",
"(",
"self",
",",
"path",
",",
"all",
"=",
"False",
")",
":",
"matches",
"=",
"[",
"]",
"for",
"app",
"in",
"self",
".",
"apps",
":",
"app_location",
"=",
"self",
".",
"storages",
"[",
"app",
"]",
".",
"location",
"if",
"app_location",
"not",
"in",
"searched_locations",
":",
"searched_locations",
".",
"append",
"(",
"app_location",
")",
"match",
"=",
"self",
".",
"find_in_app",
"(",
"app",
",",
"path",
")",
"if",
"match",
":",
"if",
"not",
"all",
":",
"return",
"match",
"matches",
".",
"append",
"(",
"match",
")",
"return",
"matches"
] |
a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54
|
valid
|
AppDirectoriesFinder.find_in_app
|
Find a requested media file in an app's media fixtures locations.
|
django_media_fixtures/finders.py
|
def find_in_app(self, app, path):
"""
Find a requested media file in an app's media fixtures locations.
"""
storage = self.storages.get(app, None)
if storage:
# only try to find a file if the source dir actually exists
if storage.exists(path):
matched_path = storage.path(path)
if matched_path:
return matched_path
|
def find_in_app(self, app, path):
"""
Find a requested media file in an app's media fixtures locations.
"""
storage = self.storages.get(app, None)
if storage:
# only try to find a file if the source dir actually exists
if storage.exists(path):
matched_path = storage.path(path)
if matched_path:
return matched_path
|
[
"Find",
"a",
"requested",
"media",
"file",
"in",
"an",
"app",
"s",
"media",
"fixtures",
"locations",
"."
] |
adrianoveiga/django-media-fixtures
|
python
|
https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/finders.py#L146-L156
|
[
"def",
"find_in_app",
"(",
"self",
",",
"app",
",",
"path",
")",
":",
"storage",
"=",
"self",
".",
"storages",
".",
"get",
"(",
"app",
",",
"None",
")",
"if",
"storage",
":",
"# only try to find a file if the source dir actually exists",
"if",
"storage",
".",
"exists",
"(",
"path",
")",
":",
"matched_path",
"=",
"storage",
".",
"path",
"(",
"path",
")",
"if",
"matched_path",
":",
"return",
"matched_path"
] |
a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54
|
valid
|
Command.set_options
|
Set instance variables based on an options dict
|
django_media_fixtures/management/commands/collectmedia.py
|
def set_options(self, **options):
"""
Set instance variables based on an options dict
"""
self.interactive = options['interactive']
self.verbosity = options['verbosity']
self.symlink = options['link']
self.clear = options['clear']
self.dry_run = options['dry_run']
ignore_patterns = options['ignore_patterns']
if options['use_default_ignore_patterns']:
ignore_patterns += ['CVS', '.*', '*~']
self.ignore_patterns = list(set(ignore_patterns))
self.post_process = options['post_process']
|
def set_options(self, **options):
"""
Set instance variables based on an options dict
"""
self.interactive = options['interactive']
self.verbosity = options['verbosity']
self.symlink = options['link']
self.clear = options['clear']
self.dry_run = options['dry_run']
ignore_patterns = options['ignore_patterns']
if options['use_default_ignore_patterns']:
ignore_patterns += ['CVS', '.*', '*~']
self.ignore_patterns = list(set(ignore_patterns))
self.post_process = options['post_process']
|
[
"Set",
"instance",
"variables",
"based",
"on",
"an",
"options",
"dict"
] |
adrianoveiga/django-media-fixtures
|
python
|
https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/management/commands/collectmedia.py#L70-L83
|
[
"def",
"set_options",
"(",
"self",
",",
"*",
"*",
"options",
")",
":",
"self",
".",
"interactive",
"=",
"options",
"[",
"'interactive'",
"]",
"self",
".",
"verbosity",
"=",
"options",
"[",
"'verbosity'",
"]",
"self",
".",
"symlink",
"=",
"options",
"[",
"'link'",
"]",
"self",
".",
"clear",
"=",
"options",
"[",
"'clear'",
"]",
"self",
".",
"dry_run",
"=",
"options",
"[",
"'dry_run'",
"]",
"ignore_patterns",
"=",
"options",
"[",
"'ignore_patterns'",
"]",
"if",
"options",
"[",
"'use_default_ignore_patterns'",
"]",
":",
"ignore_patterns",
"+=",
"[",
"'CVS'",
",",
"'.*'",
",",
"'*~'",
"]",
"self",
".",
"ignore_patterns",
"=",
"list",
"(",
"set",
"(",
"ignore_patterns",
")",
")",
"self",
".",
"post_process",
"=",
"options",
"[",
"'post_process'",
"]"
] |
a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54
|
valid
|
Command.collect
|
Perform the bulk of the work of collectmedia.
Split off from handle() to facilitate testing.
|
django_media_fixtures/management/commands/collectmedia.py
|
def collect(self):
"""
Perform the bulk of the work of collectmedia.
Split off from handle() to facilitate testing.
"""
if self.symlink and not self.local:
raise CommandError("Can't symlink to a remote destination.")
if self.clear:
self.clear_dir('')
if self.symlink:
handler = self.link_file
else:
handler = self.copy_file
found_files = OrderedDict()
for finder in get_finders():
for path, storage in finder.list(self.ignore_patterns):
# Prefix the relative path if the source storage contains it
if getattr(storage, 'prefix', None):
prefixed_path = os.path.join(storage.prefix, path)
else:
prefixed_path = path
if prefixed_path not in found_files:
found_files[prefixed_path] = (storage, path)
handler(path, prefixed_path, storage)
# Here we check if the storage backend has a post_process
# method and pass it the list of modified files.
if self.post_process and hasattr(self.storage, 'post_process'):
processor = self.storage.post_process(found_files,
dry_run=self.dry_run)
for original_path, processed_path, processed in processor:
if isinstance(processed, Exception):
self.stderr.write("Post-processing '%s' failed!" % original_path)
# Add a blank line before the traceback, otherwise it's
# too easy to miss the relevant part of the error message.
self.stderr.write("")
raise processed
if processed:
self.log("Post-processed '%s' as '%s'" %
(original_path, processed_path), level=1)
self.post_processed_files.append(original_path)
else:
self.log("Skipped post-processing '%s'" % original_path)
return {
'modified': self.copied_files + self.symlinked_files,
'unmodified': self.unmodified_files,
'post_processed': self.post_processed_files,
}
|
def collect(self):
"""
Perform the bulk of the work of collectmedia.
Split off from handle() to facilitate testing.
"""
if self.symlink and not self.local:
raise CommandError("Can't symlink to a remote destination.")
if self.clear:
self.clear_dir('')
if self.symlink:
handler = self.link_file
else:
handler = self.copy_file
found_files = OrderedDict()
for finder in get_finders():
for path, storage in finder.list(self.ignore_patterns):
# Prefix the relative path if the source storage contains it
if getattr(storage, 'prefix', None):
prefixed_path = os.path.join(storage.prefix, path)
else:
prefixed_path = path
if prefixed_path not in found_files:
found_files[prefixed_path] = (storage, path)
handler(path, prefixed_path, storage)
# Here we check if the storage backend has a post_process
# method and pass it the list of modified files.
if self.post_process and hasattr(self.storage, 'post_process'):
processor = self.storage.post_process(found_files,
dry_run=self.dry_run)
for original_path, processed_path, processed in processor:
if isinstance(processed, Exception):
self.stderr.write("Post-processing '%s' failed!" % original_path)
# Add a blank line before the traceback, otherwise it's
# too easy to miss the relevant part of the error message.
self.stderr.write("")
raise processed
if processed:
self.log("Post-processed '%s' as '%s'" %
(original_path, processed_path), level=1)
self.post_processed_files.append(original_path)
else:
self.log("Skipped post-processing '%s'" % original_path)
return {
'modified': self.copied_files + self.symlinked_files,
'unmodified': self.unmodified_files,
'post_processed': self.post_processed_files,
}
|
[
"Perform",
"the",
"bulk",
"of",
"the",
"work",
"of",
"collectmedia",
"."
] |
adrianoveiga/django-media-fixtures
|
python
|
https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/management/commands/collectmedia.py#L85-L138
|
[
"def",
"collect",
"(",
"self",
")",
":",
"if",
"self",
".",
"symlink",
"and",
"not",
"self",
".",
"local",
":",
"raise",
"CommandError",
"(",
"\"Can't symlink to a remote destination.\"",
")",
"if",
"self",
".",
"clear",
":",
"self",
".",
"clear_dir",
"(",
"''",
")",
"if",
"self",
".",
"symlink",
":",
"handler",
"=",
"self",
".",
"link_file",
"else",
":",
"handler",
"=",
"self",
".",
"copy_file",
"found_files",
"=",
"OrderedDict",
"(",
")",
"for",
"finder",
"in",
"get_finders",
"(",
")",
":",
"for",
"path",
",",
"storage",
"in",
"finder",
".",
"list",
"(",
"self",
".",
"ignore_patterns",
")",
":",
"# Prefix the relative path if the source storage contains it",
"if",
"getattr",
"(",
"storage",
",",
"'prefix'",
",",
"None",
")",
":",
"prefixed_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"storage",
".",
"prefix",
",",
"path",
")",
"else",
":",
"prefixed_path",
"=",
"path",
"if",
"prefixed_path",
"not",
"in",
"found_files",
":",
"found_files",
"[",
"prefixed_path",
"]",
"=",
"(",
"storage",
",",
"path",
")",
"handler",
"(",
"path",
",",
"prefixed_path",
",",
"storage",
")",
"# Here we check if the storage backend has a post_process",
"# method and pass it the list of modified files.",
"if",
"self",
".",
"post_process",
"and",
"hasattr",
"(",
"self",
".",
"storage",
",",
"'post_process'",
")",
":",
"processor",
"=",
"self",
".",
"storage",
".",
"post_process",
"(",
"found_files",
",",
"dry_run",
"=",
"self",
".",
"dry_run",
")",
"for",
"original_path",
",",
"processed_path",
",",
"processed",
"in",
"processor",
":",
"if",
"isinstance",
"(",
"processed",
",",
"Exception",
")",
":",
"self",
".",
"stderr",
".",
"write",
"(",
"\"Post-processing '%s' failed!\"",
"%",
"original_path",
")",
"# Add a blank line before the traceback, otherwise it's",
"# too easy to miss the relevant part of the error message.",
"self",
".",
"stderr",
".",
"write",
"(",
"\"\"",
")",
"raise",
"processed",
"if",
"processed",
":",
"self",
".",
"log",
"(",
"\"Post-processed '%s' as '%s'\"",
"%",
"(",
"original_path",
",",
"processed_path",
")",
",",
"level",
"=",
"1",
")",
"self",
".",
"post_processed_files",
".",
"append",
"(",
"original_path",
")",
"else",
":",
"self",
".",
"log",
"(",
"\"Skipped post-processing '%s'\"",
"%",
"original_path",
")",
"return",
"{",
"'modified'",
":",
"self",
".",
"copied_files",
"+",
"self",
".",
"symlinked_files",
",",
"'unmodified'",
":",
"self",
".",
"unmodified_files",
",",
"'post_processed'",
":",
"self",
".",
"post_processed_files",
",",
"}"
] |
a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54
|
valid
|
Command.clear_dir
|
Deletes the given relative path using the destination storage backend.
|
django_media_fixtures/management/commands/collectmedia.py
|
def clear_dir(self, path):
"""
Deletes the given relative path using the destination storage backend.
"""
dirs, files = self.storage.listdir(path)
for f in files:
fpath = os.path.join(path, f)
if self.dry_run:
self.log("Pretending to delete '%s'" %
smart_text(fpath), level=1)
else:
self.log("Deleting '%s'" % smart_text(fpath), level=1)
self.storage.delete(fpath)
for d in dirs:
self.clear_dir(os.path.join(path, d))
|
def clear_dir(self, path):
"""
Deletes the given relative path using the destination storage backend.
"""
dirs, files = self.storage.listdir(path)
for f in files:
fpath = os.path.join(path, f)
if self.dry_run:
self.log("Pretending to delete '%s'" %
smart_text(fpath), level=1)
else:
self.log("Deleting '%s'" % smart_text(fpath), level=1)
self.storage.delete(fpath)
for d in dirs:
self.clear_dir(os.path.join(path, d))
|
[
"Deletes",
"the",
"given",
"relative",
"path",
"using",
"the",
"destination",
"storage",
"backend",
"."
] |
adrianoveiga/django-media-fixtures
|
python
|
https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/management/commands/collectmedia.py#L206-L220
|
[
"def",
"clear_dir",
"(",
"self",
",",
"path",
")",
":",
"dirs",
",",
"files",
"=",
"self",
".",
"storage",
".",
"listdir",
"(",
"path",
")",
"for",
"f",
"in",
"files",
":",
"fpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"f",
")",
"if",
"self",
".",
"dry_run",
":",
"self",
".",
"log",
"(",
"\"Pretending to delete '%s'\"",
"%",
"smart_text",
"(",
"fpath",
")",
",",
"level",
"=",
"1",
")",
"else",
":",
"self",
".",
"log",
"(",
"\"Deleting '%s'\"",
"%",
"smart_text",
"(",
"fpath",
")",
",",
"level",
"=",
"1",
")",
"self",
".",
"storage",
".",
"delete",
"(",
"fpath",
")",
"for",
"d",
"in",
"dirs",
":",
"self",
".",
"clear_dir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"d",
")",
")"
] |
a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54
|
valid
|
Command.delete_file
|
Checks if the target file should be deleted if it already exists
|
django_media_fixtures/management/commands/collectmedia.py
|
def delete_file(self, path, prefixed_path, source_storage):
"""
Checks if the target file should be deleted if it already exists
"""
if self.storage.exists(prefixed_path):
try:
# When was the target file modified last time?
target_last_modified = \
self.storage.modified_time(prefixed_path)
except (OSError, NotImplementedError, AttributeError):
# The storage doesn't support ``modified_time`` or failed
pass
else:
try:
# When was the source file modified last time?
source_last_modified = source_storage.modified_time(path)
except (OSError, NotImplementedError, AttributeError):
pass
else:
# The full path of the target file
if self.local:
full_path = self.storage.path(prefixed_path)
else:
full_path = None
# Skip the file if the source file is younger
# Avoid sub-second precision (see #14665, #19540)
if (target_last_modified.replace(microsecond=0)
>= source_last_modified.replace(microsecond=0)):
if not ((self.symlink and full_path
and not os.path.islink(full_path)) or
(not self.symlink and full_path
and os.path.islink(full_path))):
if prefixed_path not in self.unmodified_files:
self.unmodified_files.append(prefixed_path)
self.log("Skipping '%s' (not modified)" % path)
return False
# Then delete the existing file if really needed
if self.dry_run:
self.log("Pretending to delete '%s'" % path)
else:
self.log("Deleting '%s'" % path)
self.storage.delete(prefixed_path)
return True
|
def delete_file(self, path, prefixed_path, source_storage):
"""
Checks if the target file should be deleted if it already exists
"""
if self.storage.exists(prefixed_path):
try:
# When was the target file modified last time?
target_last_modified = \
self.storage.modified_time(prefixed_path)
except (OSError, NotImplementedError, AttributeError):
# The storage doesn't support ``modified_time`` or failed
pass
else:
try:
# When was the source file modified last time?
source_last_modified = source_storage.modified_time(path)
except (OSError, NotImplementedError, AttributeError):
pass
else:
# The full path of the target file
if self.local:
full_path = self.storage.path(prefixed_path)
else:
full_path = None
# Skip the file if the source file is younger
# Avoid sub-second precision (see #14665, #19540)
if (target_last_modified.replace(microsecond=0)
>= source_last_modified.replace(microsecond=0)):
if not ((self.symlink and full_path
and not os.path.islink(full_path)) or
(not self.symlink and full_path
and os.path.islink(full_path))):
if prefixed_path not in self.unmodified_files:
self.unmodified_files.append(prefixed_path)
self.log("Skipping '%s' (not modified)" % path)
return False
# Then delete the existing file if really needed
if self.dry_run:
self.log("Pretending to delete '%s'" % path)
else:
self.log("Deleting '%s'" % path)
self.storage.delete(prefixed_path)
return True
|
[
"Checks",
"if",
"the",
"target",
"file",
"should",
"be",
"deleted",
"if",
"it",
"already",
"exists"
] |
adrianoveiga/django-media-fixtures
|
python
|
https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/management/commands/collectmedia.py#L222-L264
|
[
"def",
"delete_file",
"(",
"self",
",",
"path",
",",
"prefixed_path",
",",
"source_storage",
")",
":",
"if",
"self",
".",
"storage",
".",
"exists",
"(",
"prefixed_path",
")",
":",
"try",
":",
"# When was the target file modified last time?",
"target_last_modified",
"=",
"self",
".",
"storage",
".",
"modified_time",
"(",
"prefixed_path",
")",
"except",
"(",
"OSError",
",",
"NotImplementedError",
",",
"AttributeError",
")",
":",
"# The storage doesn't support ``modified_time`` or failed",
"pass",
"else",
":",
"try",
":",
"# When was the source file modified last time?",
"source_last_modified",
"=",
"source_storage",
".",
"modified_time",
"(",
"path",
")",
"except",
"(",
"OSError",
",",
"NotImplementedError",
",",
"AttributeError",
")",
":",
"pass",
"else",
":",
"# The full path of the target file",
"if",
"self",
".",
"local",
":",
"full_path",
"=",
"self",
".",
"storage",
".",
"path",
"(",
"prefixed_path",
")",
"else",
":",
"full_path",
"=",
"None",
"# Skip the file if the source file is younger",
"# Avoid sub-second precision (see #14665, #19540)",
"if",
"(",
"target_last_modified",
".",
"replace",
"(",
"microsecond",
"=",
"0",
")",
">=",
"source_last_modified",
".",
"replace",
"(",
"microsecond",
"=",
"0",
")",
")",
":",
"if",
"not",
"(",
"(",
"self",
".",
"symlink",
"and",
"full_path",
"and",
"not",
"os",
".",
"path",
".",
"islink",
"(",
"full_path",
")",
")",
"or",
"(",
"not",
"self",
".",
"symlink",
"and",
"full_path",
"and",
"os",
".",
"path",
".",
"islink",
"(",
"full_path",
")",
")",
")",
":",
"if",
"prefixed_path",
"not",
"in",
"self",
".",
"unmodified_files",
":",
"self",
".",
"unmodified_files",
".",
"append",
"(",
"prefixed_path",
")",
"self",
".",
"log",
"(",
"\"Skipping '%s' (not modified)\"",
"%",
"path",
")",
"return",
"False",
"# Then delete the existing file if really needed",
"if",
"self",
".",
"dry_run",
":",
"self",
".",
"log",
"(",
"\"Pretending to delete '%s'\"",
"%",
"path",
")",
"else",
":",
"self",
".",
"log",
"(",
"\"Deleting '%s'\"",
"%",
"path",
")",
"self",
".",
"storage",
".",
"delete",
"(",
"prefixed_path",
")",
"return",
"True"
] |
a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54
|
valid
|
Command.link_file
|
Attempt to link ``path``
|
django_media_fixtures/management/commands/collectmedia.py
|
def link_file(self, path, prefixed_path, source_storage):
"""
Attempt to link ``path``
"""
# Skip this file if it was already copied earlier
if prefixed_path in self.symlinked_files:
return self.log("Skipping '%s' (already linked earlier)" % path)
# Delete the target file if needed or break
if not self.delete_file(path, prefixed_path, source_storage):
return
# The full path of the source file
source_path = source_storage.path(path)
# Finally link the file
if self.dry_run:
self.log("Pretending to link '%s'" % source_path, level=1)
else:
self.log("Linking '%s'" % source_path, level=1)
full_path = self.storage.path(prefixed_path)
try:
os.makedirs(os.path.dirname(full_path))
except OSError:
pass
try:
if os.path.lexists(full_path):
os.unlink(full_path)
os.symlink(source_path, full_path)
except AttributeError:
import platform
raise CommandError("Symlinking is not supported by Python %s." %
platform.python_version())
except NotImplementedError:
import platform
raise CommandError("Symlinking is not supported in this "
"platform (%s)." % platform.platform())
except OSError as e:
raise CommandError(e)
if prefixed_path not in self.symlinked_files:
self.symlinked_files.append(prefixed_path)
|
def link_file(self, path, prefixed_path, source_storage):
"""
Attempt to link ``path``
"""
# Skip this file if it was already copied earlier
if prefixed_path in self.symlinked_files:
return self.log("Skipping '%s' (already linked earlier)" % path)
# Delete the target file if needed or break
if not self.delete_file(path, prefixed_path, source_storage):
return
# The full path of the source file
source_path = source_storage.path(path)
# Finally link the file
if self.dry_run:
self.log("Pretending to link '%s'" % source_path, level=1)
else:
self.log("Linking '%s'" % source_path, level=1)
full_path = self.storage.path(prefixed_path)
try:
os.makedirs(os.path.dirname(full_path))
except OSError:
pass
try:
if os.path.lexists(full_path):
os.unlink(full_path)
os.symlink(source_path, full_path)
except AttributeError:
import platform
raise CommandError("Symlinking is not supported by Python %s." %
platform.python_version())
except NotImplementedError:
import platform
raise CommandError("Symlinking is not supported in this "
"platform (%s)." % platform.platform())
except OSError as e:
raise CommandError(e)
if prefixed_path not in self.symlinked_files:
self.symlinked_files.append(prefixed_path)
|
[
"Attempt",
"to",
"link",
"path"
] |
adrianoveiga/django-media-fixtures
|
python
|
https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/management/commands/collectmedia.py#L266-L303
|
[
"def",
"link_file",
"(",
"self",
",",
"path",
",",
"prefixed_path",
",",
"source_storage",
")",
":",
"# Skip this file if it was already copied earlier",
"if",
"prefixed_path",
"in",
"self",
".",
"symlinked_files",
":",
"return",
"self",
".",
"log",
"(",
"\"Skipping '%s' (already linked earlier)\"",
"%",
"path",
")",
"# Delete the target file if needed or break",
"if",
"not",
"self",
".",
"delete_file",
"(",
"path",
",",
"prefixed_path",
",",
"source_storage",
")",
":",
"return",
"# The full path of the source file",
"source_path",
"=",
"source_storage",
".",
"path",
"(",
"path",
")",
"# Finally link the file",
"if",
"self",
".",
"dry_run",
":",
"self",
".",
"log",
"(",
"\"Pretending to link '%s'\"",
"%",
"source_path",
",",
"level",
"=",
"1",
")",
"else",
":",
"self",
".",
"log",
"(",
"\"Linking '%s'\"",
"%",
"source_path",
",",
"level",
"=",
"1",
")",
"full_path",
"=",
"self",
".",
"storage",
".",
"path",
"(",
"prefixed_path",
")",
"try",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"full_path",
")",
")",
"except",
"OSError",
":",
"pass",
"try",
":",
"if",
"os",
".",
"path",
".",
"lexists",
"(",
"full_path",
")",
":",
"os",
".",
"unlink",
"(",
"full_path",
")",
"os",
".",
"symlink",
"(",
"source_path",
",",
"full_path",
")",
"except",
"AttributeError",
":",
"import",
"platform",
"raise",
"CommandError",
"(",
"\"Symlinking is not supported by Python %s.\"",
"%",
"platform",
".",
"python_version",
"(",
")",
")",
"except",
"NotImplementedError",
":",
"import",
"platform",
"raise",
"CommandError",
"(",
"\"Symlinking is not supported in this \"",
"\"platform (%s).\"",
"%",
"platform",
".",
"platform",
"(",
")",
")",
"except",
"OSError",
"as",
"e",
":",
"raise",
"CommandError",
"(",
"e",
")",
"if",
"prefixed_path",
"not",
"in",
"self",
".",
"symlinked_files",
":",
"self",
".",
"symlinked_files",
".",
"append",
"(",
"prefixed_path",
")"
] |
a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54
|
valid
|
Command.copy_file
|
Attempt to copy ``path`` with storage
|
django_media_fixtures/management/commands/collectmedia.py
|
def copy_file(self, path, prefixed_path, source_storage):
"""
Attempt to copy ``path`` with storage
"""
# Skip this file if it was already copied earlier
if prefixed_path in self.copied_files:
return self.log("Skipping '%s' (already copied earlier)" % path)
# Delete the target file if needed or break
if not self.delete_file(path, prefixed_path, source_storage):
return
# The full path of the source file
source_path = source_storage.path(path)
# Finally start copying
if self.dry_run:
self.log("Pretending to copy '%s'" % source_path, level=1)
else:
self.log("Copying '%s'" % source_path, level=1)
with source_storage.open(path) as source_file:
self.storage.save(prefixed_path, source_file)
self.copied_files.append(prefixed_path)
|
def copy_file(self, path, prefixed_path, source_storage):
"""
Attempt to copy ``path`` with storage
"""
# Skip this file if it was already copied earlier
if prefixed_path in self.copied_files:
return self.log("Skipping '%s' (already copied earlier)" % path)
# Delete the target file if needed or break
if not self.delete_file(path, prefixed_path, source_storage):
return
# The full path of the source file
source_path = source_storage.path(path)
# Finally start copying
if self.dry_run:
self.log("Pretending to copy '%s'" % source_path, level=1)
else:
self.log("Copying '%s'" % source_path, level=1)
with source_storage.open(path) as source_file:
self.storage.save(prefixed_path, source_file)
self.copied_files.append(prefixed_path)
|
[
"Attempt",
"to",
"copy",
"path",
"with",
"storage"
] |
adrianoveiga/django-media-fixtures
|
python
|
https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/management/commands/collectmedia.py#L305-L324
|
[
"def",
"copy_file",
"(",
"self",
",",
"path",
",",
"prefixed_path",
",",
"source_storage",
")",
":",
"# Skip this file if it was already copied earlier",
"if",
"prefixed_path",
"in",
"self",
".",
"copied_files",
":",
"return",
"self",
".",
"log",
"(",
"\"Skipping '%s' (already copied earlier)\"",
"%",
"path",
")",
"# Delete the target file if needed or break",
"if",
"not",
"self",
".",
"delete_file",
"(",
"path",
",",
"prefixed_path",
",",
"source_storage",
")",
":",
"return",
"# The full path of the source file",
"source_path",
"=",
"source_storage",
".",
"path",
"(",
"path",
")",
"# Finally start copying",
"if",
"self",
".",
"dry_run",
":",
"self",
".",
"log",
"(",
"\"Pretending to copy '%s'\"",
"%",
"source_path",
",",
"level",
"=",
"1",
")",
"else",
":",
"self",
".",
"log",
"(",
"\"Copying '%s'\"",
"%",
"source_path",
",",
"level",
"=",
"1",
")",
"with",
"source_storage",
".",
"open",
"(",
"path",
")",
"as",
"source_file",
":",
"self",
".",
"storage",
".",
"save",
"(",
"prefixed_path",
",",
"source_file",
")",
"self",
".",
"copied_files",
".",
"append",
"(",
"prefixed_path",
")"
] |
a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54
|
valid
|
ModelTreeModel.reorderChild
|
Reorder a list to match target by moving a sequence at a time.
Written for QtAbstractItemModel.moveRows.
|
modelx/qtgui/modeltree.py
|
def reorderChild(self, parent, newitem):
"""Reorder a list to match target by moving a sequence at a time.
Written for QtAbstractItemModel.moveRows.
"""
source = self.getItem(parent).childItems
target = newitem.childItems
i = 0
while i < len(source):
if source[i] == target[i]:
i += 1
continue
else:
i0 = i
j0 = source.index(target[i0])
j = j0 + 1
while j < len(source):
if source[j] == target[j - j0 + i0]:
j += 1
continue
else:
break
self.moveRows(parent, i0, j0, j - j0)
i += j - j0
|
def reorderChild(self, parent, newitem):
"""Reorder a list to match target by moving a sequence at a time.
Written for QtAbstractItemModel.moveRows.
"""
source = self.getItem(parent).childItems
target = newitem.childItems
i = 0
while i < len(source):
if source[i] == target[i]:
i += 1
continue
else:
i0 = i
j0 = source.index(target[i0])
j = j0 + 1
while j < len(source):
if source[j] == target[j - j0 + i0]:
j += 1
continue
else:
break
self.moveRows(parent, i0, j0, j - j0)
i += j - j0
|
[
"Reorder",
"a",
"list",
"to",
"match",
"target",
"by",
"moving",
"a",
"sequence",
"at",
"a",
"time",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/qtgui/modeltree.py#L331-L356
|
[
"def",
"reorderChild",
"(",
"self",
",",
"parent",
",",
"newitem",
")",
":",
"source",
"=",
"self",
".",
"getItem",
"(",
"parent",
")",
".",
"childItems",
"target",
"=",
"newitem",
".",
"childItems",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"source",
")",
":",
"if",
"source",
"[",
"i",
"]",
"==",
"target",
"[",
"i",
"]",
":",
"i",
"+=",
"1",
"continue",
"else",
":",
"i0",
"=",
"i",
"j0",
"=",
"source",
".",
"index",
"(",
"target",
"[",
"i0",
"]",
")",
"j",
"=",
"j0",
"+",
"1",
"while",
"j",
"<",
"len",
"(",
"source",
")",
":",
"if",
"source",
"[",
"j",
"]",
"==",
"target",
"[",
"j",
"-",
"j0",
"+",
"i0",
"]",
":",
"j",
"+=",
"1",
"continue",
"else",
":",
"break",
"self",
".",
"moveRows",
"(",
"parent",
",",
"i0",
",",
"j0",
",",
"j",
"-",
"j0",
")",
"i",
"+=",
"j",
"-",
"j0"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
ModelTreeModel.moveRows
|
Move a sub sequence in a list
index_to must be smaller than index_from
|
modelx/qtgui/modeltree.py
|
def moveRows(self, parent, index_to, index_from, length):
"""Move a sub sequence in a list
index_to must be smaller than index_from
"""
source = self.getItem(parent).childItems
self.beginMoveRows(
parent, index_from, index_from + length - 1, parent, index_to
)
sublist = [source.pop(index_from) for _ in range(length)]
for _ in range(length):
source.insert(index_to, sublist.pop())
self.endMoveRows()
|
def moveRows(self, parent, index_to, index_from, length):
"""Move a sub sequence in a list
index_to must be smaller than index_from
"""
source = self.getItem(parent).childItems
self.beginMoveRows(
parent, index_from, index_from + length - 1, parent, index_to
)
sublist = [source.pop(index_from) for _ in range(length)]
for _ in range(length):
source.insert(index_to, sublist.pop())
self.endMoveRows()
|
[
"Move",
"a",
"sub",
"sequence",
"in",
"a",
"list"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/qtgui/modeltree.py#L358-L374
|
[
"def",
"moveRows",
"(",
"self",
",",
"parent",
",",
"index_to",
",",
"index_from",
",",
"length",
")",
":",
"source",
"=",
"self",
".",
"getItem",
"(",
"parent",
")",
".",
"childItems",
"self",
".",
"beginMoveRows",
"(",
"parent",
",",
"index_from",
",",
"index_from",
"+",
"length",
"-",
"1",
",",
"parent",
",",
"index_to",
")",
"sublist",
"=",
"[",
"source",
".",
"pop",
"(",
"index_from",
")",
"for",
"_",
"in",
"range",
"(",
"length",
")",
"]",
"for",
"_",
"in",
"range",
"(",
"length",
")",
":",
"source",
".",
"insert",
"(",
"index_to",
",",
"sublist",
".",
"pop",
"(",
")",
")",
"self",
".",
"endMoveRows",
"(",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
BaseSpaceContainer.cur_space
|
Set the current space to Space ``name`` and return it.
If called without arguments, the current space is returned.
Otherwise, the current space is set to the space named ``name``
and the space is returned.
|
modelx/core/spacecontainer.py
|
def cur_space(self, name=None):
"""Set the current space to Space ``name`` and return it.
If called without arguments, the current space is returned.
Otherwise, the current space is set to the space named ``name``
and the space is returned.
"""
if name is None:
return self._impl.model.currentspace.interface
else:
self._impl.model.currentspace = self._impl.spaces[name]
return self.cur_space()
|
def cur_space(self, name=None):
"""Set the current space to Space ``name`` and return it.
If called without arguments, the current space is returned.
Otherwise, the current space is set to the space named ``name``
and the space is returned.
"""
if name is None:
return self._impl.model.currentspace.interface
else:
self._impl.model.currentspace = self._impl.spaces[name]
return self.cur_space()
|
[
"Set",
"the",
"current",
"space",
"to",
"Space",
"name",
"and",
"return",
"it",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/spacecontainer.py#L41-L52
|
[
"def",
"cur_space",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"return",
"self",
".",
"_impl",
".",
"model",
".",
"currentspace",
".",
"interface",
"else",
":",
"self",
".",
"_impl",
".",
"model",
".",
"currentspace",
"=",
"self",
".",
"_impl",
".",
"spaces",
"[",
"name",
"]",
"return",
"self",
".",
"cur_space",
"(",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
BaseSpaceContainer._baseattrs
|
A dict of members expressed in literals
|
modelx/core/spacecontainer.py
|
def _baseattrs(self):
"""A dict of members expressed in literals"""
result = super()._baseattrs
result["spaces"] = self.spaces._baseattrs
return result
|
def _baseattrs(self):
"""A dict of members expressed in literals"""
result = super()._baseattrs
result["spaces"] = self.spaces._baseattrs
return result
|
[
"A",
"dict",
"of",
"members",
"expressed",
"in",
"literals"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/spacecontainer.py#L58-L63
|
[
"def",
"_baseattrs",
"(",
"self",
")",
":",
"result",
"=",
"super",
"(",
")",
".",
"_baseattrs",
"result",
"[",
"\"spaces\"",
"]",
"=",
"self",
".",
"spaces",
".",
"_baseattrs",
"return",
"result"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
EditableSpaceContainer.new_space
|
Create a child space.
Args:
name (str, optional): Name of the space. Defaults to ``SpaceN``,
where ``N`` is a number determined automatically.
bases (optional): A space or a sequence of spaces to be the base
space(s) of the created space.
formula (optional): Function to specify the parameters of
dynamic child spaces. The signature of this function is used
for setting parameters for dynamic child spaces.
This function should return a mapping of keyword arguments
to be passed to this method when the dynamic child spaces
are created.
Returns:
The new child space.
|
modelx/core/spacecontainer.py
|
def new_space(self, name=None, bases=None, formula=None, refs=None):
"""Create a child space.
Args:
name (str, optional): Name of the space. Defaults to ``SpaceN``,
where ``N`` is a number determined automatically.
bases (optional): A space or a sequence of spaces to be the base
space(s) of the created space.
formula (optional): Function to specify the parameters of
dynamic child spaces. The signature of this function is used
for setting parameters for dynamic child spaces.
This function should return a mapping of keyword arguments
to be passed to this method when the dynamic child spaces
are created.
Returns:
The new child space.
"""
space = self._impl.model.currentspace = self._impl.new_space(
name=name, bases=get_impls(bases), formula=formula, refs=refs
)
return space.interface
|
def new_space(self, name=None, bases=None, formula=None, refs=None):
"""Create a child space.
Args:
name (str, optional): Name of the space. Defaults to ``SpaceN``,
where ``N`` is a number determined automatically.
bases (optional): A space or a sequence of spaces to be the base
space(s) of the created space.
formula (optional): Function to specify the parameters of
dynamic child spaces. The signature of this function is used
for setting parameters for dynamic child spaces.
This function should return a mapping of keyword arguments
to be passed to this method when the dynamic child spaces
are created.
Returns:
The new child space.
"""
space = self._impl.model.currentspace = self._impl.new_space(
name=name, bases=get_impls(bases), formula=formula, refs=refs
)
return space.interface
|
[
"Create",
"a",
"child",
"space",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/spacecontainer.py#L70-L92
|
[
"def",
"new_space",
"(",
"self",
",",
"name",
"=",
"None",
",",
"bases",
"=",
"None",
",",
"formula",
"=",
"None",
",",
"refs",
"=",
"None",
")",
":",
"space",
"=",
"self",
".",
"_impl",
".",
"model",
".",
"currentspace",
"=",
"self",
".",
"_impl",
".",
"new_space",
"(",
"name",
"=",
"name",
",",
"bases",
"=",
"get_impls",
"(",
"bases",
")",
",",
"formula",
"=",
"formula",
",",
"refs",
"=",
"refs",
")",
"return",
"space",
".",
"interface"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
EditableSpaceContainer.import_module
|
Create a child space from an module.
Args:
module: a module object or name of the module object.
recursive: Not yet implemented.
**params: arguments to pass to ``new_space``
Returns:
The new child space created from the module.
|
modelx/core/spacecontainer.py
|
def import_module(self, module=None, recursive=False, **params):
"""Create a child space from an module.
Args:
module: a module object or name of the module object.
recursive: Not yet implemented.
**params: arguments to pass to ``new_space``
Returns:
The new child space created from the module.
"""
if module is None:
if "module_" in params:
warnings.warn(
"Parameter 'module_' is deprecated. Use 'module' instead.")
module = params.pop("module_")
else:
raise ValueError("no module specified")
if "bases" in params:
params["bases"] = get_impls(params["bases"])
space = (
self._impl.model.currentspace
) = self._impl.new_space_from_module(
module, recursive=recursive, **params
)
return get_interfaces(space)
|
def import_module(self, module=None, recursive=False, **params):
"""Create a child space from an module.
Args:
module: a module object or name of the module object.
recursive: Not yet implemented.
**params: arguments to pass to ``new_space``
Returns:
The new child space created from the module.
"""
if module is None:
if "module_" in params:
warnings.warn(
"Parameter 'module_' is deprecated. Use 'module' instead.")
module = params.pop("module_")
else:
raise ValueError("no module specified")
if "bases" in params:
params["bases"] = get_impls(params["bases"])
space = (
self._impl.model.currentspace
) = self._impl.new_space_from_module(
module, recursive=recursive, **params
)
return get_interfaces(space)
|
[
"Create",
"a",
"child",
"space",
"from",
"an",
"module",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/spacecontainer.py#L94-L121
|
[
"def",
"import_module",
"(",
"self",
",",
"module",
"=",
"None",
",",
"recursive",
"=",
"False",
",",
"*",
"*",
"params",
")",
":",
"if",
"module",
"is",
"None",
":",
"if",
"\"module_\"",
"in",
"params",
":",
"warnings",
".",
"warn",
"(",
"\"Parameter 'module_' is deprecated. Use 'module' instead.\"",
")",
"module",
"=",
"params",
".",
"pop",
"(",
"\"module_\"",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"no module specified\"",
")",
"if",
"\"bases\"",
"in",
"params",
":",
"params",
"[",
"\"bases\"",
"]",
"=",
"get_impls",
"(",
"params",
"[",
"\"bases\"",
"]",
")",
"space",
"=",
"(",
"self",
".",
"_impl",
".",
"model",
".",
"currentspace",
")",
"=",
"self",
".",
"_impl",
".",
"new_space_from_module",
"(",
"module",
",",
"recursive",
"=",
"recursive",
",",
"*",
"*",
"params",
")",
"return",
"get_interfaces",
"(",
"space",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
EditableSpaceContainer.new_space_from_module
|
Create a child space from an module.
Alias to :py:meth:`import_module`.
Args:
module: a module object or name of the module object.
recursive: Not yet implemented.
**params: arguments to pass to ``new_space``
Returns:
The new child space created from the module.
|
modelx/core/spacecontainer.py
|
def new_space_from_module(self, module, recursive=False, **params):
"""Create a child space from an module.
Alias to :py:meth:`import_module`.
Args:
module: a module object or name of the module object.
recursive: Not yet implemented.
**params: arguments to pass to ``new_space``
Returns:
The new child space created from the module.
"""
if "bases" in params:
params["bases"] = get_impls(params["bases"])
space = (
self._impl.model.currentspace
) = self._impl.new_space_from_module(
module, recursive=recursive, **params
)
return get_interfaces(space)
|
def new_space_from_module(self, module, recursive=False, **params):
"""Create a child space from an module.
Alias to :py:meth:`import_module`.
Args:
module: a module object or name of the module object.
recursive: Not yet implemented.
**params: arguments to pass to ``new_space``
Returns:
The new child space created from the module.
"""
if "bases" in params:
params["bases"] = get_impls(params["bases"])
space = (
self._impl.model.currentspace
) = self._impl.new_space_from_module(
module, recursive=recursive, **params
)
return get_interfaces(space)
|
[
"Create",
"a",
"child",
"space",
"from",
"an",
"module",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/spacecontainer.py#L123-L144
|
[
"def",
"new_space_from_module",
"(",
"self",
",",
"module",
",",
"recursive",
"=",
"False",
",",
"*",
"*",
"params",
")",
":",
"if",
"\"bases\"",
"in",
"params",
":",
"params",
"[",
"\"bases\"",
"]",
"=",
"get_impls",
"(",
"params",
"[",
"\"bases\"",
"]",
")",
"space",
"=",
"(",
"self",
".",
"_impl",
".",
"model",
".",
"currentspace",
")",
"=",
"self",
".",
"_impl",
".",
"new_space_from_module",
"(",
"module",
",",
"recursive",
"=",
"recursive",
",",
"*",
"*",
"params",
")",
"return",
"get_interfaces",
"(",
"space",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
EditableSpaceContainer.new_space_from_excel
|
Create a child space from an Excel range.
To use this method, ``openpyxl`` package must be installed.
Args:
book (str): Path to an Excel file.
range_ (str): Range expression, such as "A1", "$G4:$K10",
or named range "NamedRange1".
sheet (str): Sheet name (case ignored).
name (str, optional): Name of the space. Defaults to ``SpaceN``,
where ``N`` is a number determined automatically.
names_row (optional): an index number indicating
what row contains the names of cells and parameters.
Defaults to the top row (0).
param_cols (optional): a sequence of index numbers
indicating parameter columns.
Defaults to only the leftmost column ([0]).
names_col (optional): an index number, starting from 0,
indicating what column contains additional parameters.
param_rows (optional): a sequence of index numbers, starting from
0, indicating rows of additional parameters, in case cells are
defined in two dimensions.
transpose (optional): Defaults to ``False``.
If set to ``True``, "row(s)" and "col(s)" in the parameter
names are interpreted inversely, i.e.
all indexes passed to "row(s)" parameters are interpreted
as column indexes,
and all indexes passed to "col(s)" parameters as row indexes.
space_param_order: a sequence to specify space parameters and
their orders. The elements of the sequence denote the indexes
of ``param_cols`` elements, and optionally the index of
``param_rows`` elements shifted by the length of
``param_cols``. The elements of this parameter and
``cell_param_order`` must not overlap.
cell_param_order (optional): a sequence to reorder the parameters.
The elements of the sequence denote the indexes of
``param_cols`` elements, and optionally the index of
``param_rows`` elements shifted by the length of
``param_cols``. The elements of this parameter and
``cell_space_order`` must not overlap.
Returns:
The new child space created from the Excel range.
|
modelx/core/spacecontainer.py
|
def new_space_from_excel(
self,
book,
range_,
sheet=None,
name=None,
names_row=None,
param_cols=None,
space_param_order=None,
cells_param_order=None,
transpose=False,
names_col=None,
param_rows=None,
):
"""Create a child space from an Excel range.
To use this method, ``openpyxl`` package must be installed.
Args:
book (str): Path to an Excel file.
range_ (str): Range expression, such as "A1", "$G4:$K10",
or named range "NamedRange1".
sheet (str): Sheet name (case ignored).
name (str, optional): Name of the space. Defaults to ``SpaceN``,
where ``N`` is a number determined automatically.
names_row (optional): an index number indicating
what row contains the names of cells and parameters.
Defaults to the top row (0).
param_cols (optional): a sequence of index numbers
indicating parameter columns.
Defaults to only the leftmost column ([0]).
names_col (optional): an index number, starting from 0,
indicating what column contains additional parameters.
param_rows (optional): a sequence of index numbers, starting from
0, indicating rows of additional parameters, in case cells are
defined in two dimensions.
transpose (optional): Defaults to ``False``.
If set to ``True``, "row(s)" and "col(s)" in the parameter
names are interpreted inversely, i.e.
all indexes passed to "row(s)" parameters are interpreted
as column indexes,
and all indexes passed to "col(s)" parameters as row indexes.
space_param_order: a sequence to specify space parameters and
their orders. The elements of the sequence denote the indexes
of ``param_cols`` elements, and optionally the index of
``param_rows`` elements shifted by the length of
``param_cols``. The elements of this parameter and
``cell_param_order`` must not overlap.
cell_param_order (optional): a sequence to reorder the parameters.
The elements of the sequence denote the indexes of
``param_cols`` elements, and optionally the index of
``param_rows`` elements shifted by the length of
``param_cols``. The elements of this parameter and
``cell_space_order`` must not overlap.
Returns:
The new child space created from the Excel range.
"""
space = self._impl.new_space_from_excel(
book,
range_,
sheet,
name,
names_row,
param_cols,
space_param_order,
cells_param_order,
transpose,
names_col,
param_rows,
)
return get_interfaces(space)
|
def new_space_from_excel(
self,
book,
range_,
sheet=None,
name=None,
names_row=None,
param_cols=None,
space_param_order=None,
cells_param_order=None,
transpose=False,
names_col=None,
param_rows=None,
):
"""Create a child space from an Excel range.
To use this method, ``openpyxl`` package must be installed.
Args:
book (str): Path to an Excel file.
range_ (str): Range expression, such as "A1", "$G4:$K10",
or named range "NamedRange1".
sheet (str): Sheet name (case ignored).
name (str, optional): Name of the space. Defaults to ``SpaceN``,
where ``N`` is a number determined automatically.
names_row (optional): an index number indicating
what row contains the names of cells and parameters.
Defaults to the top row (0).
param_cols (optional): a sequence of index numbers
indicating parameter columns.
Defaults to only the leftmost column ([0]).
names_col (optional): an index number, starting from 0,
indicating what column contains additional parameters.
param_rows (optional): a sequence of index numbers, starting from
0, indicating rows of additional parameters, in case cells are
defined in two dimensions.
transpose (optional): Defaults to ``False``.
If set to ``True``, "row(s)" and "col(s)" in the parameter
names are interpreted inversely, i.e.
all indexes passed to "row(s)" parameters are interpreted
as column indexes,
and all indexes passed to "col(s)" parameters as row indexes.
space_param_order: a sequence to specify space parameters and
their orders. The elements of the sequence denote the indexes
of ``param_cols`` elements, and optionally the index of
``param_rows`` elements shifted by the length of
``param_cols``. The elements of this parameter and
``cell_param_order`` must not overlap.
cell_param_order (optional): a sequence to reorder the parameters.
The elements of the sequence denote the indexes of
``param_cols`` elements, and optionally the index of
``param_rows`` elements shifted by the length of
``param_cols``. The elements of this parameter and
``cell_space_order`` must not overlap.
Returns:
The new child space created from the Excel range.
"""
space = self._impl.new_space_from_excel(
book,
range_,
sheet,
name,
names_row,
param_cols,
space_param_order,
cells_param_order,
transpose,
names_col,
param_rows,
)
return get_interfaces(space)
|
[
"Create",
"a",
"child",
"space",
"from",
"an",
"Excel",
"range",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/spacecontainer.py#L146-L219
|
[
"def",
"new_space_from_excel",
"(",
"self",
",",
"book",
",",
"range_",
",",
"sheet",
"=",
"None",
",",
"name",
"=",
"None",
",",
"names_row",
"=",
"None",
",",
"param_cols",
"=",
"None",
",",
"space_param_order",
"=",
"None",
",",
"cells_param_order",
"=",
"None",
",",
"transpose",
"=",
"False",
",",
"names_col",
"=",
"None",
",",
"param_rows",
"=",
"None",
",",
")",
":",
"space",
"=",
"self",
".",
"_impl",
".",
"new_space_from_excel",
"(",
"book",
",",
"range_",
",",
"sheet",
",",
"name",
",",
"names_row",
",",
"param_cols",
",",
"space_param_order",
",",
"cells_param_order",
",",
"transpose",
",",
"names_col",
",",
"param_rows",
",",
")",
"return",
"get_interfaces",
"(",
"space",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
BaseSpaceContainerImpl.restore_state
|
Called after unpickling to restore some attributes manually.
|
modelx/core/spacecontainer.py
|
def restore_state(self, system):
"""Called after unpickling to restore some attributes manually."""
for space in self._spaces.values():
space.restore_state(system)
|
def restore_state(self, system):
"""Called after unpickling to restore some attributes manually."""
for space in self._spaces.values():
space.restore_state(system)
|
[
"Called",
"after",
"unpickling",
"to",
"restore",
"some",
"attributes",
"manually",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/spacecontainer.py#L252-L256
|
[
"def",
"restore_state",
"(",
"self",
",",
"system",
")",
":",
"for",
"space",
"in",
"self",
".",
"_spaces",
".",
"values",
"(",
")",
":",
"space",
".",
"restore_state",
"(",
"system",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
EditableSpaceContainerImpl.new_space
|
Create a new child space.
Args:
name (str): Name of the space. If omitted, the space is
created automatically.
bases: If specified, the new space becomes a derived space of
the `base` space.
formula: Function whose parameters used to set space parameters.
refs: a mapping of refs to be added.
arguments: ordered dict of space parameter names to their values.
source: A source module from which cell definitions are read.
prefix: Prefix to the autogenerated name when name is None.
|
modelx/core/spacecontainer.py
|
def new_space(
self,
name=None,
bases=None,
formula=None,
*,
refs=None,
source=None,
is_derived=False,
prefix=""
):
"""Create a new child space.
Args:
name (str): Name of the space. If omitted, the space is
created automatically.
bases: If specified, the new space becomes a derived space of
the `base` space.
formula: Function whose parameters used to set space parameters.
refs: a mapping of refs to be added.
arguments: ordered dict of space parameter names to their values.
source: A source module from which cell definitions are read.
prefix: Prefix to the autogenerated name when name is None.
"""
from modelx.core.space import StaticSpaceImpl
if name is None:
name = self.spacenamer.get_next(self.namespace, prefix)
if name in self.namespace:
raise ValueError("Name '%s' already exists." % name)
if not prefix and not is_valid_name(name):
raise ValueError("Invalid name '%s'." % name)
space = self._new_space(
name=name,
formula=formula,
refs=refs,
source=source,
is_derived=is_derived,
)
self._set_space(space)
self.model.spacegraph.add_space(space)
# Set up direct base spaces and mro
if bases is not None:
if isinstance(bases, StaticSpaceImpl):
bases = [bases]
space.add_bases(bases)
return space
|
def new_space(
self,
name=None,
bases=None,
formula=None,
*,
refs=None,
source=None,
is_derived=False,
prefix=""
):
"""Create a new child space.
Args:
name (str): Name of the space. If omitted, the space is
created automatically.
bases: If specified, the new space becomes a derived space of
the `base` space.
formula: Function whose parameters used to set space parameters.
refs: a mapping of refs to be added.
arguments: ordered dict of space parameter names to their values.
source: A source module from which cell definitions are read.
prefix: Prefix to the autogenerated name when name is None.
"""
from modelx.core.space import StaticSpaceImpl
if name is None:
name = self.spacenamer.get_next(self.namespace, prefix)
if name in self.namespace:
raise ValueError("Name '%s' already exists." % name)
if not prefix and not is_valid_name(name):
raise ValueError("Invalid name '%s'." % name)
space = self._new_space(
name=name,
formula=formula,
refs=refs,
source=source,
is_derived=is_derived,
)
self._set_space(space)
self.model.spacegraph.add_space(space)
# Set up direct base spaces and mro
if bases is not None:
if isinstance(bases, StaticSpaceImpl):
bases = [bases]
space.add_bases(bases)
return space
|
[
"Create",
"a",
"new",
"child",
"space",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/spacecontainer.py#L307-L360
|
[
"def",
"new_space",
"(",
"self",
",",
"name",
"=",
"None",
",",
"bases",
"=",
"None",
",",
"formula",
"=",
"None",
",",
"*",
",",
"refs",
"=",
"None",
",",
"source",
"=",
"None",
",",
"is_derived",
"=",
"False",
",",
"prefix",
"=",
"\"\"",
")",
":",
"from",
"modelx",
".",
"core",
".",
"space",
"import",
"StaticSpaceImpl",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"self",
".",
"spacenamer",
".",
"get_next",
"(",
"self",
".",
"namespace",
",",
"prefix",
")",
"if",
"name",
"in",
"self",
".",
"namespace",
":",
"raise",
"ValueError",
"(",
"\"Name '%s' already exists.\"",
"%",
"name",
")",
"if",
"not",
"prefix",
"and",
"not",
"is_valid_name",
"(",
"name",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid name '%s'.\"",
"%",
"name",
")",
"space",
"=",
"self",
".",
"_new_space",
"(",
"name",
"=",
"name",
",",
"formula",
"=",
"formula",
",",
"refs",
"=",
"refs",
",",
"source",
"=",
"source",
",",
"is_derived",
"=",
"is_derived",
",",
")",
"self",
".",
"_set_space",
"(",
"space",
")",
"self",
".",
"model",
".",
"spacegraph",
".",
"add_space",
"(",
"space",
")",
"# Set up direct base spaces and mro",
"if",
"bases",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"bases",
",",
"StaticSpaceImpl",
")",
":",
"bases",
"=",
"[",
"bases",
"]",
"space",
".",
"add_bases",
"(",
"bases",
")",
"return",
"space"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
get_node
|
Create a node from arguments and return it
|
modelx/core/node.py
|
def get_node(obj, args, kwargs):
"""Create a node from arguments and return it"""
if args is None and kwargs is None:
return (obj,)
if kwargs is None:
kwargs = {}
return obj, _bind_args(obj, args, kwargs)
|
def get_node(obj, args, kwargs):
"""Create a node from arguments and return it"""
if args is None and kwargs is None:
return (obj,)
if kwargs is None:
kwargs = {}
return obj, _bind_args(obj, args, kwargs)
|
[
"Create",
"a",
"node",
"from",
"arguments",
"and",
"return",
"it"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/node.py#L43-L51
|
[
"def",
"get_node",
"(",
"obj",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"args",
"is",
"None",
"and",
"kwargs",
"is",
"None",
":",
"return",
"(",
"obj",
",",
")",
"if",
"kwargs",
"is",
"None",
":",
"kwargs",
"=",
"{",
"}",
"return",
"obj",
",",
"_bind_args",
"(",
"obj",
",",
"args",
",",
"kwargs",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
node_get_args
|
Return an ordered mapping from params to args
|
modelx/core/node.py
|
def node_get_args(node):
"""Return an ordered mapping from params to args"""
obj = node[OBJ]
key = node[KEY]
boundargs = obj.formula.signature.bind(*key)
boundargs.apply_defaults()
return boundargs.arguments
|
def node_get_args(node):
"""Return an ordered mapping from params to args"""
obj = node[OBJ]
key = node[KEY]
boundargs = obj.formula.signature.bind(*key)
boundargs.apply_defaults()
return boundargs.arguments
|
[
"Return",
"an",
"ordered",
"mapping",
"from",
"params",
"to",
"args"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/node.py#L54-L60
|
[
"def",
"node_get_args",
"(",
"node",
")",
":",
"obj",
"=",
"node",
"[",
"OBJ",
"]",
"key",
"=",
"node",
"[",
"KEY",
"]",
"boundargs",
"=",
"obj",
".",
"formula",
".",
"signature",
".",
"bind",
"(",
"*",
"key",
")",
"boundargs",
".",
"apply_defaults",
"(",
")",
"return",
"boundargs",
".",
"arguments"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
tuplize_key
|
Args
|
modelx/core/node.py
|
def tuplize_key(obj, key, remove_extra=False):
"""Args"""
paramlen = len(obj.formula.parameters)
if isinstance(key, str):
key = (key,)
elif not isinstance(key, Sequence):
key = (key,)
if not remove_extra:
return key
else:
arglen = len(key)
if arglen:
return key[: min(arglen, paramlen)]
else:
return key
|
def tuplize_key(obj, key, remove_extra=False):
"""Args"""
paramlen = len(obj.formula.parameters)
if isinstance(key, str):
key = (key,)
elif not isinstance(key, Sequence):
key = (key,)
if not remove_extra:
return key
else:
arglen = len(key)
if arglen:
return key[: min(arglen, paramlen)]
else:
return key
|
[
"Args"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/node.py#L63-L80
|
[
"def",
"tuplize_key",
"(",
"obj",
",",
"key",
",",
"remove_extra",
"=",
"False",
")",
":",
"paramlen",
"=",
"len",
"(",
"obj",
".",
"formula",
".",
"parameters",
")",
"if",
"isinstance",
"(",
"key",
",",
"str",
")",
":",
"key",
"=",
"(",
"key",
",",
")",
"elif",
"not",
"isinstance",
"(",
"key",
",",
"Sequence",
")",
":",
"key",
"=",
"(",
"key",
",",
")",
"if",
"not",
"remove_extra",
":",
"return",
"key",
"else",
":",
"arglen",
"=",
"len",
"(",
"key",
")",
"if",
"arglen",
":",
"return",
"key",
"[",
":",
"min",
"(",
"arglen",
",",
"paramlen",
")",
"]",
"else",
":",
"return",
"key"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
defcells
|
Decorator/function to create cells from Python functions.
Convenience decorator/function to create new cells directly from function
definitions or function objects substituting for calling
:py:meth:`new_cells <modelx.core.space.StaticSpace.new_cells>`
method of the parent space.
There are 3 ways to use ``defcells`` to define cells from functions.
**1. As a decorator without arguments**
To create a cells from a function definition in the current space of the
current model with the same name as the function's::
@defcells
def foo(x):
return x
**2. As a decorator with arguments**
To create a cells from a function definition in a given space and/or with
a given name::
@defcells(space=space, name=name)
def foo(x):
return x
**3. As a function**
To create a multiple cells from a multiple function definitions::
def foo(x):
return x
def bar(y):
return foo(y)
foo, bar = defcells(foo, bar)
Args:
space(optional): For the 2nd usage, a space to create the cells in.
Defaults to the current space of the current model.
name(optional): For the 2nd usage, a name of the created cells.
Defaults to the function name.
*funcs: For the 3rd usage, function objects. (``space`` and ``name``
also take function objects for the 3rd usage.)
Returns:
For the 1st and 2nd usage, the newly created single cells is returned.
For the 3rd usage, a list of newly created cells are returned.
|
modelx/core/api.py
|
def defcells(space=None, name=None, *funcs):
"""Decorator/function to create cells from Python functions.
Convenience decorator/function to create new cells directly from function
definitions or function objects substituting for calling
:py:meth:`new_cells <modelx.core.space.StaticSpace.new_cells>`
method of the parent space.
There are 3 ways to use ``defcells`` to define cells from functions.
**1. As a decorator without arguments**
To create a cells from a function definition in the current space of the
current model with the same name as the function's::
@defcells
def foo(x):
return x
**2. As a decorator with arguments**
To create a cells from a function definition in a given space and/or with
a given name::
@defcells(space=space, name=name)
def foo(x):
return x
**3. As a function**
To create a multiple cells from a multiple function definitions::
def foo(x):
return x
def bar(y):
return foo(y)
foo, bar = defcells(foo, bar)
Args:
space(optional): For the 2nd usage, a space to create the cells in.
Defaults to the current space of the current model.
name(optional): For the 2nd usage, a name of the created cells.
Defaults to the function name.
*funcs: For the 3rd usage, function objects. (``space`` and ``name``
also take function objects for the 3rd usage.)
Returns:
For the 1st and 2nd usage, the newly created single cells is returned.
For the 3rd usage, a list of newly created cells are returned.
"""
if isinstance(space, _FunctionType) and name is None:
# called as a function decorator
func = space
return _system.currentspace.new_cells(formula=func).interface
elif (isinstance(space, _Space) or space is None) and (
isinstance(name, str) or name is None
):
# return decorator itself
if space is None:
space = _system.currentspace.interface
return _CellsMaker(space=space._impl, name=name)
elif all(
isinstance(func, _FunctionType) for func in (space, name) + funcs
):
return [defcells(func) for func in (space, name) + funcs]
else:
raise TypeError("invalid defcells arguments")
|
def defcells(space=None, name=None, *funcs):
"""Decorator/function to create cells from Python functions.
Convenience decorator/function to create new cells directly from function
definitions or function objects substituting for calling
:py:meth:`new_cells <modelx.core.space.StaticSpace.new_cells>`
method of the parent space.
There are 3 ways to use ``defcells`` to define cells from functions.
**1. As a decorator without arguments**
To create a cells from a function definition in the current space of the
current model with the same name as the function's::
@defcells
def foo(x):
return x
**2. As a decorator with arguments**
To create a cells from a function definition in a given space and/or with
a given name::
@defcells(space=space, name=name)
def foo(x):
return x
**3. As a function**
To create a multiple cells from a multiple function definitions::
def foo(x):
return x
def bar(y):
return foo(y)
foo, bar = defcells(foo, bar)
Args:
space(optional): For the 2nd usage, a space to create the cells in.
Defaults to the current space of the current model.
name(optional): For the 2nd usage, a name of the created cells.
Defaults to the function name.
*funcs: For the 3rd usage, function objects. (``space`` and ``name``
also take function objects for the 3rd usage.)
Returns:
For the 1st and 2nd usage, the newly created single cells is returned.
For the 3rd usage, a list of newly created cells are returned.
"""
if isinstance(space, _FunctionType) and name is None:
# called as a function decorator
func = space
return _system.currentspace.new_cells(formula=func).interface
elif (isinstance(space, _Space) or space is None) and (
isinstance(name, str) or name is None
):
# return decorator itself
if space is None:
space = _system.currentspace.interface
return _CellsMaker(space=space._impl, name=name)
elif all(
isinstance(func, _FunctionType) for func in (space, name) + funcs
):
return [defcells(func) for func in (space, name) + funcs]
else:
raise TypeError("invalid defcells arguments")
|
[
"Decorator",
"/",
"function",
"to",
"create",
"cells",
"from",
"Python",
"functions",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/api.py#L112-L186
|
[
"def",
"defcells",
"(",
"space",
"=",
"None",
",",
"name",
"=",
"None",
",",
"*",
"funcs",
")",
":",
"if",
"isinstance",
"(",
"space",
",",
"_FunctionType",
")",
"and",
"name",
"is",
"None",
":",
"# called as a function decorator",
"func",
"=",
"space",
"return",
"_system",
".",
"currentspace",
".",
"new_cells",
"(",
"formula",
"=",
"func",
")",
".",
"interface",
"elif",
"(",
"isinstance",
"(",
"space",
",",
"_Space",
")",
"or",
"space",
"is",
"None",
")",
"and",
"(",
"isinstance",
"(",
"name",
",",
"str",
")",
"or",
"name",
"is",
"None",
")",
":",
"# return decorator itself",
"if",
"space",
"is",
"None",
":",
"space",
"=",
"_system",
".",
"currentspace",
".",
"interface",
"return",
"_CellsMaker",
"(",
"space",
"=",
"space",
".",
"_impl",
",",
"name",
"=",
"name",
")",
"elif",
"all",
"(",
"isinstance",
"(",
"func",
",",
"_FunctionType",
")",
"for",
"func",
"in",
"(",
"space",
",",
"name",
")",
"+",
"funcs",
")",
":",
"return",
"[",
"defcells",
"(",
"func",
")",
"for",
"func",
"in",
"(",
"space",
",",
"name",
")",
"+",
"funcs",
"]",
"else",
":",
"raise",
"TypeError",
"(",
"\"invalid defcells arguments\"",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
get_object
|
Get a modelx object from its full name.
|
modelx/core/api.py
|
def get_object(name: str):
"""Get a modelx object from its full name."""
# TODO: Duplicate of system.get_object
elms = name.split(".")
parent = get_models()[elms.pop(0)]
while len(elms) > 0:
obj = elms.pop(0)
parent = getattr(parent, obj)
return parent
|
def get_object(name: str):
"""Get a modelx object from its full name."""
# TODO: Duplicate of system.get_object
elms = name.split(".")
parent = get_models()[elms.pop(0)]
while len(elms) > 0:
obj = elms.pop(0)
parent = getattr(parent, obj)
return parent
|
[
"Get",
"a",
"modelx",
"object",
"from",
"its",
"full",
"name",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/api.py#L194-L203
|
[
"def",
"get_object",
"(",
"name",
":",
"str",
")",
":",
"# TODO: Duplicate of system.get_object",
"elms",
"=",
"name",
".",
"split",
"(",
"\".\"",
")",
"parent",
"=",
"get_models",
"(",
")",
"[",
"elms",
".",
"pop",
"(",
"0",
")",
"]",
"while",
"len",
"(",
"elms",
")",
">",
"0",
":",
"obj",
"=",
"elms",
".",
"pop",
"(",
"0",
")",
"parent",
"=",
"getattr",
"(",
"parent",
",",
"obj",
")",
"return",
"parent"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
_get_node
|
Get node from object name and arg string
Not Used. Left for future reference purpose.
|
modelx/core/api.py
|
def _get_node(name: str, args: str):
"""Get node from object name and arg string
Not Used. Left for future reference purpose.
"""
obj = get_object(name)
args = ast.literal_eval(args)
if not isinstance(args, tuple):
args = (args,)
return obj.node(*args)
|
def _get_node(name: str, args: str):
"""Get node from object name and arg string
Not Used. Left for future reference purpose.
"""
obj = get_object(name)
args = ast.literal_eval(args)
if not isinstance(args, tuple):
args = (args,)
return obj.node(*args)
|
[
"Get",
"node",
"from",
"object",
"name",
"and",
"arg",
"string"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/api.py#L206-L216
|
[
"def",
"_get_node",
"(",
"name",
":",
"str",
",",
"args",
":",
"str",
")",
":",
"obj",
"=",
"get_object",
"(",
"name",
")",
"args",
"=",
"ast",
".",
"literal_eval",
"(",
"args",
")",
"if",
"not",
"isinstance",
"(",
"args",
",",
"tuple",
")",
":",
"args",
"=",
"(",
"args",
",",
")",
"return",
"obj",
".",
"node",
"(",
"*",
"args",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
cur_model
|
Get and/or set the current model.
If ``model`` is given, set the current model to ``model`` and return it.
``model`` can be the name of a model object, or a model object itself.
If ``model`` is not given, the current model is returned.
|
modelx/core/api.py
|
def cur_model(model=None):
"""Get and/or set the current model.
If ``model`` is given, set the current model to ``model`` and return it.
``model`` can be the name of a model object, or a model object itself.
If ``model`` is not given, the current model is returned.
"""
if model is None:
if _system.currentmodel is not None:
return _system.currentmodel.interface
else:
return None
else:
if isinstance(model, _Model):
_system.currentmodel = model._impl
else:
_system.currentmodel = _system.models[model]
return _system.currentmodel.interface
|
def cur_model(model=None):
"""Get and/or set the current model.
If ``model`` is given, set the current model to ``model`` and return it.
``model`` can be the name of a model object, or a model object itself.
If ``model`` is not given, the current model is returned.
"""
if model is None:
if _system.currentmodel is not None:
return _system.currentmodel.interface
else:
return None
else:
if isinstance(model, _Model):
_system.currentmodel = model._impl
else:
_system.currentmodel = _system.models[model]
return _system.currentmodel.interface
|
[
"Get",
"and",
"/",
"or",
"set",
"the",
"current",
"model",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/api.py#L219-L237
|
[
"def",
"cur_model",
"(",
"model",
"=",
"None",
")",
":",
"if",
"model",
"is",
"None",
":",
"if",
"_system",
".",
"currentmodel",
"is",
"not",
"None",
":",
"return",
"_system",
".",
"currentmodel",
".",
"interface",
"else",
":",
"return",
"None",
"else",
":",
"if",
"isinstance",
"(",
"model",
",",
"_Model",
")",
":",
"_system",
".",
"currentmodel",
"=",
"model",
".",
"_impl",
"else",
":",
"_system",
".",
"currentmodel",
"=",
"_system",
".",
"models",
"[",
"model",
"]",
"return",
"_system",
".",
"currentmodel",
".",
"interface"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
cur_space
|
Get and/or set the current space of the current model.
If ``name`` is given, the current space of the current model is
set to ``name`` and return it.
If ``name`` is not given, the current space of the current model
is returned.
|
modelx/core/api.py
|
def cur_space(space=None):
"""Get and/or set the current space of the current model.
If ``name`` is given, the current space of the current model is
set to ``name`` and return it.
If ``name`` is not given, the current space of the current model
is returned.
"""
if space is None:
if _system.currentmodel is not None:
if _system.currentmodel.currentspace is not None:
return _system.currentmodel.currentspace.interface
else:
return None
else:
return None
else:
if isinstance(space, _Space):
cur_model(space.model)
_system.currentmodel.currentspace = space._impl
else:
_system.currentmodel.currentspace = _system.currentmodel.spaces[
space
]
return cur_space()
|
def cur_space(space=None):
"""Get and/or set the current space of the current model.
If ``name`` is given, the current space of the current model is
set to ``name`` and return it.
If ``name`` is not given, the current space of the current model
is returned.
"""
if space is None:
if _system.currentmodel is not None:
if _system.currentmodel.currentspace is not None:
return _system.currentmodel.currentspace.interface
else:
return None
else:
return None
else:
if isinstance(space, _Space):
cur_model(space.model)
_system.currentmodel.currentspace = space._impl
else:
_system.currentmodel.currentspace = _system.currentmodel.spaces[
space
]
return cur_space()
|
[
"Get",
"and",
"/",
"or",
"set",
"the",
"current",
"space",
"of",
"the",
"current",
"model",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/api.py#L240-L265
|
[
"def",
"cur_space",
"(",
"space",
"=",
"None",
")",
":",
"if",
"space",
"is",
"None",
":",
"if",
"_system",
".",
"currentmodel",
"is",
"not",
"None",
":",
"if",
"_system",
".",
"currentmodel",
".",
"currentspace",
"is",
"not",
"None",
":",
"return",
"_system",
".",
"currentmodel",
".",
"currentspace",
".",
"interface",
"else",
":",
"return",
"None",
"else",
":",
"return",
"None",
"else",
":",
"if",
"isinstance",
"(",
"space",
",",
"_Space",
")",
":",
"cur_model",
"(",
"space",
".",
"model",
")",
"_system",
".",
"currentmodel",
".",
"currentspace",
"=",
"space",
".",
"_impl",
"else",
":",
"_system",
".",
"currentmodel",
".",
"currentspace",
"=",
"_system",
".",
"currentmodel",
".",
"spaces",
"[",
"space",
"]",
"return",
"cur_space",
"(",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
custom_showwarning
|
Hook to override default showwarning.
https://stackoverflow.com/questions/2187269/python-print-only-the-message-on-warnings
|
modelx/core/system.py
|
def custom_showwarning(
message, category, filename="", lineno=-1, file=None, line=None
):
"""Hook to override default showwarning.
https://stackoverflow.com/questions/2187269/python-print-only-the-message-on-warnings
"""
if file is None:
file = sys.stderr
if file is None:
# sys.stderr is None when run with pythonw.exe:
# warnings get lost
return
text = "%s: %s\n" % (category.__name__, message)
try:
file.write(text)
except OSError:
# the file (probably stderr) is invalid - this warning gets lost.
pass
|
def custom_showwarning(
message, category, filename="", lineno=-1, file=None, line=None
):
"""Hook to override default showwarning.
https://stackoverflow.com/questions/2187269/python-print-only-the-message-on-warnings
"""
if file is None:
file = sys.stderr
if file is None:
# sys.stderr is None when run with pythonw.exe:
# warnings get lost
return
text = "%s: %s\n" % (category.__name__, message)
try:
file.write(text)
except OSError:
# the file (probably stderr) is invalid - this warning gets lost.
pass
|
[
"Hook",
"to",
"override",
"default",
"showwarning",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/system.py#L143-L162
|
[
"def",
"custom_showwarning",
"(",
"message",
",",
"category",
",",
"filename",
"=",
"\"\"",
",",
"lineno",
"=",
"-",
"1",
",",
"file",
"=",
"None",
",",
"line",
"=",
"None",
")",
":",
"if",
"file",
"is",
"None",
":",
"file",
"=",
"sys",
".",
"stderr",
"if",
"file",
"is",
"None",
":",
"# sys.stderr is None when run with pythonw.exe:",
"# warnings get lost",
"return",
"text",
"=",
"\"%s: %s\\n\"",
"%",
"(",
"category",
".",
"__name__",
",",
"message",
")",
"try",
":",
"file",
".",
"write",
"(",
"text",
")",
"except",
"OSError",
":",
"# the file (probably stderr) is invalid - this warning gets lost.",
"pass"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
custom_showtraceback
|
Custom showtraceback for monkey-patching IPython's InteractiveShell
https://stackoverflow.com/questions/1261668/cannot-override-sys-excepthook
|
modelx/core/system.py
|
def custom_showtraceback(
self,
exc_tuple=None,
filename=None,
tb_offset=None,
exception_only=False,
running_compiled_code=False,
):
"""Custom showtraceback for monkey-patching IPython's InteractiveShell
https://stackoverflow.com/questions/1261668/cannot-override-sys-excepthook
"""
self.default_showtraceback(
exc_tuple,
filename,
tb_offset,
exception_only=True,
running_compiled_code=running_compiled_code,
)
|
def custom_showtraceback(
self,
exc_tuple=None,
filename=None,
tb_offset=None,
exception_only=False,
running_compiled_code=False,
):
"""Custom showtraceback for monkey-patching IPython's InteractiveShell
https://stackoverflow.com/questions/1261668/cannot-override-sys-excepthook
"""
self.default_showtraceback(
exc_tuple,
filename,
tb_offset,
exception_only=True,
running_compiled_code=running_compiled_code,
)
|
[
"Custom",
"showtraceback",
"for",
"monkey",
"-",
"patching",
"IPython",
"s",
"InteractiveShell"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/system.py#L355-L373
|
[
"def",
"custom_showtraceback",
"(",
"self",
",",
"exc_tuple",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"tb_offset",
"=",
"None",
",",
"exception_only",
"=",
"False",
",",
"running_compiled_code",
"=",
"False",
",",
")",
":",
"self",
".",
"default_showtraceback",
"(",
"exc_tuple",
",",
"filename",
",",
"tb_offset",
",",
"exception_only",
"=",
"True",
",",
"running_compiled_code",
"=",
"running_compiled_code",
",",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
excepthook
|
Not Used: Custom exception hook to replace sys.excepthook
This is for CPython's default shell. IPython does not use sys.exepthook.
https://stackoverflow.com/questions/27674602/hide-traceback-unless-a-debug-flag-is-set
|
modelx/core/system.py
|
def excepthook(self, except_type, exception, traceback):
"""Not Used: Custom exception hook to replace sys.excepthook
This is for CPython's default shell. IPython does not use sys.exepthook.
https://stackoverflow.com/questions/27674602/hide-traceback-unless-a-debug-flag-is-set
"""
if except_type is DeepReferenceError:
print(exception.msg)
else:
self.default_excepthook(except_type, exception, traceback)
|
def excepthook(self, except_type, exception, traceback):
"""Not Used: Custom exception hook to replace sys.excepthook
This is for CPython's default shell. IPython does not use sys.exepthook.
https://stackoverflow.com/questions/27674602/hide-traceback-unless-a-debug-flag-is-set
"""
if except_type is DeepReferenceError:
print(exception.msg)
else:
self.default_excepthook(except_type, exception, traceback)
|
[
"Not",
"Used",
":",
"Custom",
"exception",
"hook",
"to",
"replace",
"sys",
".",
"excepthook"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/system.py#L376-L386
|
[
"def",
"excepthook",
"(",
"self",
",",
"except_type",
",",
"exception",
",",
"traceback",
")",
":",
"if",
"except_type",
"is",
"DeepReferenceError",
":",
"print",
"(",
"exception",
".",
"msg",
")",
"else",
":",
"self",
".",
"default_excepthook",
"(",
"except_type",
",",
"exception",
",",
"traceback",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
CallStack.tracemessage
|
if maxlen > 0, the message is shortened to maxlen traces.
|
modelx/core/system.py
|
def tracemessage(self, maxlen=6):
"""
if maxlen > 0, the message is shortened to maxlen traces.
"""
result = ""
for i, value in enumerate(self):
result += "{0}: {1}\n".format(i, get_node_repr(value))
result = result.strip("\n")
lines = result.split("\n")
if maxlen and len(lines) > maxlen:
i = int(maxlen / 2)
lines = lines[:i] + ["..."] + lines[-(maxlen - i) :]
result = "\n".join(lines)
return result
|
def tracemessage(self, maxlen=6):
"""
if maxlen > 0, the message is shortened to maxlen traces.
"""
result = ""
for i, value in enumerate(self):
result += "{0}: {1}\n".format(i, get_node_repr(value))
result = result.strip("\n")
lines = result.split("\n")
if maxlen and len(lines) > maxlen:
i = int(maxlen / 2)
lines = lines[:i] + ["..."] + lines[-(maxlen - i) :]
result = "\n".join(lines)
return result
|
[
"if",
"maxlen",
">",
"0",
"the",
"message",
"is",
"shortened",
"to",
"maxlen",
"traces",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/system.py#L124-L140
|
[
"def",
"tracemessage",
"(",
"self",
",",
"maxlen",
"=",
"6",
")",
":",
"result",
"=",
"\"\"",
"for",
"i",
",",
"value",
"in",
"enumerate",
"(",
"self",
")",
":",
"result",
"+=",
"\"{0}: {1}\\n\"",
".",
"format",
"(",
"i",
",",
"get_node_repr",
"(",
"value",
")",
")",
"result",
"=",
"result",
".",
"strip",
"(",
"\"\\n\"",
")",
"lines",
"=",
"result",
".",
"split",
"(",
"\"\\n\"",
")",
"if",
"maxlen",
"and",
"len",
"(",
"lines",
")",
">",
"maxlen",
":",
"i",
"=",
"int",
"(",
"maxlen",
"/",
"2",
")",
"lines",
"=",
"lines",
"[",
":",
"i",
"]",
"+",
"[",
"\"...\"",
"]",
"+",
"lines",
"[",
"-",
"(",
"maxlen",
"-",
"i",
")",
":",
"]",
"result",
"=",
"\"\\n\"",
".",
"join",
"(",
"lines",
")",
"return",
"result"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
System.setup_ipython
|
Monkey patch shell's error handler.
This method is to monkey-patch the showtraceback method of
IPython's InteractiveShell to
__IPYTHON__ is not detected when starting an IPython kernel,
so this method is called from start_kernel in spyder-modelx.
|
modelx/core/system.py
|
def setup_ipython(self):
"""Monkey patch shell's error handler.
This method is to monkey-patch the showtraceback method of
IPython's InteractiveShell to
__IPYTHON__ is not detected when starting an IPython kernel,
so this method is called from start_kernel in spyder-modelx.
"""
if self.is_ipysetup:
return
from ipykernel.kernelapp import IPKernelApp
self.shell = IPKernelApp.instance().shell # None in PyCharm console
if not self.shell and is_ipython():
self.shell = get_ipython()
if self.shell:
shell_class = type(self.shell)
shell_class.default_showtraceback = shell_class.showtraceback
shell_class.showtraceback = custom_showtraceback
self.is_ipysetup = True
else:
raise RuntimeError("IPython shell not found.")
|
def setup_ipython(self):
"""Monkey patch shell's error handler.
This method is to monkey-patch the showtraceback method of
IPython's InteractiveShell to
__IPYTHON__ is not detected when starting an IPython kernel,
so this method is called from start_kernel in spyder-modelx.
"""
if self.is_ipysetup:
return
from ipykernel.kernelapp import IPKernelApp
self.shell = IPKernelApp.instance().shell # None in PyCharm console
if not self.shell and is_ipython():
self.shell = get_ipython()
if self.shell:
shell_class = type(self.shell)
shell_class.default_showtraceback = shell_class.showtraceback
shell_class.showtraceback = custom_showtraceback
self.is_ipysetup = True
else:
raise RuntimeError("IPython shell not found.")
|
[
"Monkey",
"patch",
"shell",
"s",
"error",
"handler",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/system.py#L207-L232
|
[
"def",
"setup_ipython",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_ipysetup",
":",
"return",
"from",
"ipykernel",
".",
"kernelapp",
"import",
"IPKernelApp",
"self",
".",
"shell",
"=",
"IPKernelApp",
".",
"instance",
"(",
")",
".",
"shell",
"# None in PyCharm console",
"if",
"not",
"self",
".",
"shell",
"and",
"is_ipython",
"(",
")",
":",
"self",
".",
"shell",
"=",
"get_ipython",
"(",
")",
"if",
"self",
".",
"shell",
":",
"shell_class",
"=",
"type",
"(",
"self",
".",
"shell",
")",
"shell_class",
".",
"default_showtraceback",
"=",
"shell_class",
".",
"showtraceback",
"shell_class",
".",
"showtraceback",
"=",
"custom_showtraceback",
"self",
".",
"is_ipysetup",
"=",
"True",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"IPython shell not found.\"",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
System.restore_ipython
|
Restore default IPython showtraceback
|
modelx/core/system.py
|
def restore_ipython(self):
"""Restore default IPython showtraceback"""
if not self.is_ipysetup:
return
shell_class = type(self.shell)
shell_class.showtraceback = shell_class.default_showtraceback
del shell_class.default_showtraceback
self.is_ipysetup = False
|
def restore_ipython(self):
"""Restore default IPython showtraceback"""
if not self.is_ipysetup:
return
shell_class = type(self.shell)
shell_class.showtraceback = shell_class.default_showtraceback
del shell_class.default_showtraceback
self.is_ipysetup = False
|
[
"Restore",
"default",
"IPython",
"showtraceback"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/system.py#L234-L243
|
[
"def",
"restore_ipython",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_ipysetup",
":",
"return",
"shell_class",
"=",
"type",
"(",
"self",
".",
"shell",
")",
"shell_class",
".",
"showtraceback",
"=",
"shell_class",
".",
"default_showtraceback",
"del",
"shell_class",
".",
"default_showtraceback",
"self",
".",
"is_ipysetup",
"=",
"False"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
System.restore_python
|
Restore Python settings to the original states
|
modelx/core/system.py
|
def restore_python(self):
"""Restore Python settings to the original states"""
orig = self.orig_settings
sys.setrecursionlimit(orig["sys.recursionlimit"])
if "sys.tracebacklimit" in orig:
sys.tracebacklimit = orig["sys.tracebacklimit"]
else:
if hasattr(sys, "tracebacklimit"):
del sys.tracebacklimit
if "showwarning" in orig:
warnings.showwarning = orig["showwarning"]
orig.clear()
threading.stack_size()
|
def restore_python(self):
"""Restore Python settings to the original states"""
orig = self.orig_settings
sys.setrecursionlimit(orig["sys.recursionlimit"])
if "sys.tracebacklimit" in orig:
sys.tracebacklimit = orig["sys.tracebacklimit"]
else:
if hasattr(sys, "tracebacklimit"):
del sys.tracebacklimit
if "showwarning" in orig:
warnings.showwarning = orig["showwarning"]
orig.clear()
threading.stack_size()
|
[
"Restore",
"Python",
"settings",
"to",
"the",
"original",
"states"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/system.py#L254-L269
|
[
"def",
"restore_python",
"(",
"self",
")",
":",
"orig",
"=",
"self",
".",
"orig_settings",
"sys",
".",
"setrecursionlimit",
"(",
"orig",
"[",
"\"sys.recursionlimit\"",
"]",
")",
"if",
"\"sys.tracebacklimit\"",
"in",
"orig",
":",
"sys",
".",
"tracebacklimit",
"=",
"orig",
"[",
"\"sys.tracebacklimit\"",
"]",
"else",
":",
"if",
"hasattr",
"(",
"sys",
",",
"\"tracebacklimit\"",
")",
":",
"del",
"sys",
".",
"tracebacklimit",
"if",
"\"showwarning\"",
"in",
"orig",
":",
"warnings",
".",
"showwarning",
"=",
"orig",
"[",
"\"showwarning\"",
"]",
"orig",
".",
"clear",
"(",
")",
"threading",
".",
"stack_size",
"(",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
System.get_object
|
Retrieve an object by its absolute name.
|
modelx/core/system.py
|
def get_object(self, name):
"""Retrieve an object by its absolute name."""
parts = name.split(".")
model_name = parts.pop(0)
return self.models[model_name].get_object(".".join(parts))
|
def get_object(self, name):
"""Retrieve an object by its absolute name."""
parts = name.split(".")
model_name = parts.pop(0)
return self.models[model_name].get_object(".".join(parts))
|
[
"Retrieve",
"an",
"object",
"by",
"its",
"absolute",
"name",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/system.py#L342-L348
|
[
"def",
"get_object",
"(",
"self",
",",
"name",
")",
":",
"parts",
"=",
"name",
".",
"split",
"(",
"\".\"",
")",
"model_name",
"=",
"parts",
".",
"pop",
"(",
"0",
")",
"return",
"self",
".",
"models",
"[",
"model_name",
"]",
".",
"get_object",
"(",
"\".\"",
".",
"join",
"(",
"parts",
")",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
get_modeltree
|
Alias to :func:`get_tree`.
|
modelx/qtgui/api.py
|
def get_modeltree(model=None):
"""Alias to :func:`get_tree`."""
if model is None:
model = mx.cur_model()
treemodel = ModelTreeModel(model._baseattrs)
view = QTreeView()
view.setModel(treemodel)
view.setWindowTitle("Model %s" % model.name)
view.setAlternatingRowColors(True)
return view
|
def get_modeltree(model=None):
"""Alias to :func:`get_tree`."""
if model is None:
model = mx.cur_model()
treemodel = ModelTreeModel(model._baseattrs)
view = QTreeView()
view.setModel(treemodel)
view.setWindowTitle("Model %s" % model.name)
view.setAlternatingRowColors(True)
return view
|
[
"Alias",
"to",
":",
"func",
":",
"get_tree",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/qtgui/api.py#L41-L50
|
[
"def",
"get_modeltree",
"(",
"model",
"=",
"None",
")",
":",
"if",
"model",
"is",
"None",
":",
"model",
"=",
"mx",
".",
"cur_model",
"(",
")",
"treemodel",
"=",
"ModelTreeModel",
"(",
"model",
".",
"_baseattrs",
")",
"view",
"=",
"QTreeView",
"(",
")",
"view",
".",
"setModel",
"(",
"treemodel",
")",
"view",
".",
"setWindowTitle",
"(",
"\"Model %s\"",
"%",
"model",
".",
"name",
")",
"view",
".",
"setAlternatingRowColors",
"(",
"True",
")",
"return",
"view"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
show_tree
|
Display the model tree window.
Args:
model: :class:`Model <modelx.core.model.Model>` object.
Defaults to the current model.
Warnings:
For this function to work with Spyder, *Graphics backend* option
of Spyder must be set to *inline*.
|
modelx/qtgui/api.py
|
def show_tree(model=None):
"""Display the model tree window.
Args:
model: :class:`Model <modelx.core.model.Model>` object.
Defaults to the current model.
Warnings:
For this function to work with Spyder, *Graphics backend* option
of Spyder must be set to *inline*.
"""
if model is None:
model = mx.cur_model()
view = get_modeltree(model)
app = QApplication.instance()
if not app:
raise RuntimeError("QApplication does not exist.")
view.show()
app.exec_()
|
def show_tree(model=None):
"""Display the model tree window.
Args:
model: :class:`Model <modelx.core.model.Model>` object.
Defaults to the current model.
Warnings:
For this function to work with Spyder, *Graphics backend* option
of Spyder must be set to *inline*.
"""
if model is None:
model = mx.cur_model()
view = get_modeltree(model)
app = QApplication.instance()
if not app:
raise RuntimeError("QApplication does not exist.")
view.show()
app.exec_()
|
[
"Display",
"the",
"model",
"tree",
"window",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/qtgui/api.py#L70-L88
|
[
"def",
"show_tree",
"(",
"model",
"=",
"None",
")",
":",
"if",
"model",
"is",
"None",
":",
"model",
"=",
"mx",
".",
"cur_model",
"(",
")",
"view",
"=",
"get_modeltree",
"(",
"model",
")",
"app",
"=",
"QApplication",
".",
"instance",
"(",
")",
"if",
"not",
"app",
":",
"raise",
"RuntimeError",
"(",
"\"QApplication does not exist.\"",
")",
"view",
".",
"show",
"(",
")",
"app",
".",
"exec_",
"(",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
get_interfaces
|
Get interfaces from their implementations.
|
modelx/core/base.py
|
def get_interfaces(impls):
"""Get interfaces from their implementations."""
if impls is None:
return None
elif isinstance(impls, OrderMixin):
result = OrderedDict()
for name in impls.order:
result[name] = impls[name].interface
return result
elif isinstance(impls, Mapping):
return {name: impls[name].interface for name in impls}
elif isinstance(impls, Sequence):
return [impl.interface for impl in impls]
else:
return impls.interface
|
def get_interfaces(impls):
"""Get interfaces from their implementations."""
if impls is None:
return None
elif isinstance(impls, OrderMixin):
result = OrderedDict()
for name in impls.order:
result[name] = impls[name].interface
return result
elif isinstance(impls, Mapping):
return {name: impls[name].interface for name in impls}
elif isinstance(impls, Sequence):
return [impl.interface for impl in impls]
else:
return impls.interface
|
[
"Get",
"interfaces",
"from",
"their",
"implementations",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/base.py#L60-L78
|
[
"def",
"get_interfaces",
"(",
"impls",
")",
":",
"if",
"impls",
"is",
"None",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"impls",
",",
"OrderMixin",
")",
":",
"result",
"=",
"OrderedDict",
"(",
")",
"for",
"name",
"in",
"impls",
".",
"order",
":",
"result",
"[",
"name",
"]",
"=",
"impls",
"[",
"name",
"]",
".",
"interface",
"return",
"result",
"elif",
"isinstance",
"(",
"impls",
",",
"Mapping",
")",
":",
"return",
"{",
"name",
":",
"impls",
"[",
"name",
"]",
".",
"interface",
"for",
"name",
"in",
"impls",
"}",
"elif",
"isinstance",
"(",
"impls",
",",
"Sequence",
")",
":",
"return",
"[",
"impl",
".",
"interface",
"for",
"impl",
"in",
"impls",
"]",
"else",
":",
"return",
"impls",
".",
"interface"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
get_impls
|
Get impls from their interfaces.
|
modelx/core/base.py
|
def get_impls(interfaces):
"""Get impls from their interfaces."""
if interfaces is None:
return None
elif isinstance(interfaces, Mapping):
return {name: interfaces[name]._impl for name in interfaces}
elif isinstance(interfaces, Sequence):
return [interfaces._impl for interfaces in interfaces]
else:
return interfaces._impl
|
def get_impls(interfaces):
"""Get impls from their interfaces."""
if interfaces is None:
return None
elif isinstance(interfaces, Mapping):
return {name: interfaces[name]._impl for name in interfaces}
elif isinstance(interfaces, Sequence):
return [interfaces._impl for interfaces in interfaces]
else:
return interfaces._impl
|
[
"Get",
"impls",
"from",
"their",
"interfaces",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/base.py#L81-L93
|
[
"def",
"get_impls",
"(",
"interfaces",
")",
":",
"if",
"interfaces",
"is",
"None",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"interfaces",
",",
"Mapping",
")",
":",
"return",
"{",
"name",
":",
"interfaces",
"[",
"name",
"]",
".",
"_impl",
"for",
"name",
"in",
"interfaces",
"}",
"elif",
"isinstance",
"(",
"interfaces",
",",
"Sequence",
")",
":",
"return",
"[",
"interfaces",
".",
"_impl",
"for",
"interfaces",
"in",
"interfaces",
"]",
"else",
":",
"return",
"interfaces",
".",
"_impl"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
Impl.update_lazyevals
|
Update all LazyEvals in self
self.lzy_evals must be set to LazyEval object(s) enough to
update all owned LazyEval objects.
|
modelx/core/base.py
|
def update_lazyevals(self):
"""Update all LazyEvals in self
self.lzy_evals must be set to LazyEval object(s) enough to
update all owned LazyEval objects.
"""
if self.lazy_evals is None:
return
elif isinstance(self.lazy_evals, LazyEval):
self.lazy_evals.get_updated()
else:
for lz in self.lazy_evals:
lz.get_updated()
|
def update_lazyevals(self):
"""Update all LazyEvals in self
self.lzy_evals must be set to LazyEval object(s) enough to
update all owned LazyEval objects.
"""
if self.lazy_evals is None:
return
elif isinstance(self.lazy_evals, LazyEval):
self.lazy_evals.get_updated()
else:
for lz in self.lazy_evals:
lz.get_updated()
|
[
"Update",
"all",
"LazyEvals",
"in",
"self"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/base.py#L129-L141
|
[
"def",
"update_lazyevals",
"(",
"self",
")",
":",
"if",
"self",
".",
"lazy_evals",
"is",
"None",
":",
"return",
"elif",
"isinstance",
"(",
"self",
".",
"lazy_evals",
",",
"LazyEval",
")",
":",
"self",
".",
"lazy_evals",
".",
"get_updated",
"(",
")",
"else",
":",
"for",
"lz",
"in",
"self",
".",
"lazy_evals",
":",
"lz",
".",
"get_updated",
"(",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
Impl.evalrepr
|
Evaluable repr
|
modelx/core/base.py
|
def evalrepr(self):
"""Evaluable repr"""
if self.is_model():
return self.get_fullname()
else:
return self.parent.evalrepr + "." + self.name
|
def evalrepr(self):
"""Evaluable repr"""
if self.is_model():
return self.get_fullname()
else:
return self.parent.evalrepr + "." + self.name
|
[
"Evaluable",
"repr"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/base.py#L160-L165
|
[
"def",
"evalrepr",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_model",
"(",
")",
":",
"return",
"self",
".",
"get_fullname",
"(",
")",
"else",
":",
"return",
"self",
".",
"parent",
".",
"evalrepr",
"+",
"\".\"",
"+",
"self",
".",
"name"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
Interface._baseattrs
|
A dict of members expressed in literals
|
modelx/core/base.py
|
def _baseattrs(self):
"""A dict of members expressed in literals"""
result = {
"type": type(self).__name__,
"id": id(self),
"name": self.name,
"fullname": self.fullname,
"repr": self._get_repr(),
}
return result
|
def _baseattrs(self):
"""A dict of members expressed in literals"""
result = {
"type": type(self).__name__,
"id": id(self),
"name": self.name,
"fullname": self.fullname,
"repr": self._get_repr(),
}
return result
|
[
"A",
"dict",
"of",
"members",
"expressed",
"in",
"literals"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/base.py#L442-L453
|
[
"def",
"_baseattrs",
"(",
"self",
")",
":",
"result",
"=",
"{",
"\"type\"",
":",
"type",
"(",
"self",
")",
".",
"__name__",
",",
"\"id\"",
":",
"id",
"(",
"self",
")",
",",
"\"name\"",
":",
"self",
".",
"name",
",",
"\"fullname\"",
":",
"self",
".",
"fullname",
",",
"\"repr\"",
":",
"self",
".",
"_get_repr",
"(",
")",
",",
"}",
"return",
"result"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
Interface._to_attrdict
|
Get extra attributes
|
modelx/core/base.py
|
def _to_attrdict(self, attrs=None):
"""Get extra attributes"""
result = self._baseattrs
for attr in attrs:
if hasattr(self, attr):
result[attr] = getattr(self, attr)._to_attrdict(attrs)
return result
|
def _to_attrdict(self, attrs=None):
"""Get extra attributes"""
result = self._baseattrs
for attr in attrs:
if hasattr(self, attr):
result[attr] = getattr(self, attr)._to_attrdict(attrs)
return result
|
[
"Get",
"extra",
"attributes"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/base.py#L455-L463
|
[
"def",
"_to_attrdict",
"(",
"self",
",",
"attrs",
"=",
"None",
")",
":",
"result",
"=",
"self",
".",
"_baseattrs",
"for",
"attr",
"in",
"attrs",
":",
"if",
"hasattr",
"(",
"self",
",",
"attr",
")",
":",
"result",
"[",
"attr",
"]",
"=",
"getattr",
"(",
"self",
",",
"attr",
")",
".",
"_to_attrdict",
"(",
"attrs",
")",
"return",
"result"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
BaseView._baseattrs
|
A dict of members expressed in literals
|
modelx/core/base.py
|
def _baseattrs(self):
"""A dict of members expressed in literals"""
result = {"type": type(self).__name__}
try:
result["items"] = {
name: item._baseattrs
for name, item in self.items()
if name[0] != "_"
}
except:
raise RuntimeError("%s literadict raised an error" % self)
return result
|
def _baseattrs(self):
"""A dict of members expressed in literals"""
result = {"type": type(self).__name__}
try:
result["items"] = {
name: item._baseattrs
for name, item in self.items()
if name[0] != "_"
}
except:
raise RuntimeError("%s literadict raised an error" % self)
return result
|
[
"A",
"dict",
"of",
"members",
"expressed",
"in",
"literals"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/base.py#L753-L766
|
[
"def",
"_baseattrs",
"(",
"self",
")",
":",
"result",
"=",
"{",
"\"type\"",
":",
"type",
"(",
"self",
")",
".",
"__name__",
"}",
"try",
":",
"result",
"[",
"\"items\"",
"]",
"=",
"{",
"name",
":",
"item",
".",
"_baseattrs",
"for",
"name",
",",
"item",
"in",
"self",
".",
"items",
"(",
")",
"if",
"name",
"[",
"0",
"]",
"!=",
"\"_\"",
"}",
"except",
":",
"raise",
"RuntimeError",
"(",
"\"%s literadict raised an error\"",
"%",
"self",
")",
"return",
"result"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
BoundFunction._update_data
|
Update altfunc
|
modelx/core/base.py
|
def _update_data(self):
"""Update altfunc"""
func = self.owner.formula.func
codeobj = func.__code__
name = func.__name__ # self.cells.name # func.__name__
namespace_impl = self.owner._namespace_impl.get_updated()
namespace = namespace_impl.interfaces
selfnode = get_node(self.owner, None, None)
for name in self.owner.formula.srcnames:
if name in namespace_impl and isinstance(
namespace_impl[name], ReferenceImpl
):
refnode = get_node(namespace_impl[name], None, None)
self.owner.model.lexdep.add_path([selfnode, refnode])
closure = func.__closure__ # None normally.
if closure is not None: # pytest fails without this.
closure = create_closure(self.owner.interface)
self.altfunc = FunctionType(
codeobj, namespace, name=name, closure=closure
)
|
def _update_data(self):
"""Update altfunc"""
func = self.owner.formula.func
codeobj = func.__code__
name = func.__name__ # self.cells.name # func.__name__
namespace_impl = self.owner._namespace_impl.get_updated()
namespace = namespace_impl.interfaces
selfnode = get_node(self.owner, None, None)
for name in self.owner.formula.srcnames:
if name in namespace_impl and isinstance(
namespace_impl[name], ReferenceImpl
):
refnode = get_node(namespace_impl[name], None, None)
self.owner.model.lexdep.add_path([selfnode, refnode])
closure = func.__closure__ # None normally.
if closure is not None: # pytest fails without this.
closure = create_closure(self.owner.interface)
self.altfunc = FunctionType(
codeobj, namespace, name=name, closure=closure
)
|
[
"Update",
"altfunc"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/base.py#L854-L877
|
[
"def",
"_update_data",
"(",
"self",
")",
":",
"func",
"=",
"self",
".",
"owner",
".",
"formula",
".",
"func",
"codeobj",
"=",
"func",
".",
"__code__",
"name",
"=",
"func",
".",
"__name__",
"# self.cells.name # func.__name__",
"namespace_impl",
"=",
"self",
".",
"owner",
".",
"_namespace_impl",
".",
"get_updated",
"(",
")",
"namespace",
"=",
"namespace_impl",
".",
"interfaces",
"selfnode",
"=",
"get_node",
"(",
"self",
".",
"owner",
",",
"None",
",",
"None",
")",
"for",
"name",
"in",
"self",
".",
"owner",
".",
"formula",
".",
"srcnames",
":",
"if",
"name",
"in",
"namespace_impl",
"and",
"isinstance",
"(",
"namespace_impl",
"[",
"name",
"]",
",",
"ReferenceImpl",
")",
":",
"refnode",
"=",
"get_node",
"(",
"namespace_impl",
"[",
"name",
"]",
",",
"None",
",",
"None",
")",
"self",
".",
"owner",
".",
"model",
".",
"lexdep",
".",
"add_path",
"(",
"[",
"selfnode",
",",
"refnode",
"]",
")",
"closure",
"=",
"func",
".",
"__closure__",
"# None normally.",
"if",
"closure",
"is",
"not",
"None",
":",
"# pytest fails without this.",
"closure",
"=",
"create_closure",
"(",
"self",
".",
"owner",
".",
"interface",
")",
"self",
".",
"altfunc",
"=",
"FunctionType",
"(",
"codeobj",
",",
"namespace",
",",
"name",
"=",
"name",
",",
"closure",
"=",
"closure",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
convert_args
|
If args and kwargs contains Cells, Convert them to their values.
|
modelx/core/cells.py
|
def convert_args(args, kwargs):
"""If args and kwargs contains Cells, Convert them to their values."""
found = False
for arg in args:
if isinstance(arg, Cells):
found = True
break
if found:
args = tuple(
arg.value if isinstance(arg, Cells) else arg for arg in args
)
if kwargs is not None:
for key, arg in kwargs.items():
if isinstance(arg, Cells):
kwargs[key] = arg.value
return args, kwargs
|
def convert_args(args, kwargs):
"""If args and kwargs contains Cells, Convert them to their values."""
found = False
for arg in args:
if isinstance(arg, Cells):
found = True
break
if found:
args = tuple(
arg.value if isinstance(arg, Cells) else arg for arg in args
)
if kwargs is not None:
for key, arg in kwargs.items():
if isinstance(arg, Cells):
kwargs[key] = arg.value
return args, kwargs
|
[
"If",
"args",
"and",
"kwargs",
"contains",
"Cells",
"Convert",
"them",
"to",
"their",
"values",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/cells.py#L28-L47
|
[
"def",
"convert_args",
"(",
"args",
",",
"kwargs",
")",
":",
"found",
"=",
"False",
"for",
"arg",
"in",
"args",
":",
"if",
"isinstance",
"(",
"arg",
",",
"Cells",
")",
":",
"found",
"=",
"True",
"break",
"if",
"found",
":",
"args",
"=",
"tuple",
"(",
"arg",
".",
"value",
"if",
"isinstance",
"(",
"arg",
",",
"Cells",
")",
"else",
"arg",
"for",
"arg",
"in",
"args",
")",
"if",
"kwargs",
"is",
"not",
"None",
":",
"for",
"key",
",",
"arg",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"arg",
",",
"Cells",
")",
":",
"kwargs",
"[",
"key",
"]",
"=",
"arg",
".",
"value",
"return",
"args",
",",
"kwargs"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
shareable_parameters
|
Return parameter names if the parameters are shareable among cells.
Parameters are shareable among multiple cells when all the cells
have the parameters in the same order if they ever have any.
For example, if cells are foo(), bar(x), baz(x, y), then
('x', 'y') are shareable parameters amounts them, as 'x' and 'y'
appear in the same order in the parameter list if they ever appear.
Args:
cells: An iterator yielding cells.
Returns:
None if parameters are not share,
tuple of shareable parameter names,
() if cells are all scalars.
|
modelx/core/cells.py
|
def shareable_parameters(cells):
"""Return parameter names if the parameters are shareable among cells.
Parameters are shareable among multiple cells when all the cells
have the parameters in the same order if they ever have any.
For example, if cells are foo(), bar(x), baz(x, y), then
('x', 'y') are shareable parameters amounts them, as 'x' and 'y'
appear in the same order in the parameter list if they ever appear.
Args:
cells: An iterator yielding cells.
Returns:
None if parameters are not share,
tuple of shareable parameter names,
() if cells are all scalars.
"""
result = []
for c in cells.values():
params = c.formula.parameters
for i in range(min(len(result), len(params))):
if params[i] != result[i]:
return None
for i in range(len(result), len(params)):
result.append(params[i])
return result
|
def shareable_parameters(cells):
"""Return parameter names if the parameters are shareable among cells.
Parameters are shareable among multiple cells when all the cells
have the parameters in the same order if they ever have any.
For example, if cells are foo(), bar(x), baz(x, y), then
('x', 'y') are shareable parameters amounts them, as 'x' and 'y'
appear in the same order in the parameter list if they ever appear.
Args:
cells: An iterator yielding cells.
Returns:
None if parameters are not share,
tuple of shareable parameter names,
() if cells are all scalars.
"""
result = []
for c in cells.values():
params = c.formula.parameters
for i in range(min(len(result), len(params))):
if params[i] != result[i]:
return None
for i in range(len(result), len(params)):
result.append(params[i])
return result
|
[
"Return",
"parameter",
"names",
"if",
"the",
"parameters",
"are",
"shareable",
"among",
"cells",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/cells.py#L752-L781
|
[
"def",
"shareable_parameters",
"(",
"cells",
")",
":",
"result",
"=",
"[",
"]",
"for",
"c",
"in",
"cells",
".",
"values",
"(",
")",
":",
"params",
"=",
"c",
".",
"formula",
".",
"parameters",
"for",
"i",
"in",
"range",
"(",
"min",
"(",
"len",
"(",
"result",
")",
",",
"len",
"(",
"params",
")",
")",
")",
":",
"if",
"params",
"[",
"i",
"]",
"!=",
"result",
"[",
"i",
"]",
":",
"return",
"None",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"result",
")",
",",
"len",
"(",
"params",
")",
")",
":",
"result",
".",
"append",
"(",
"params",
"[",
"i",
"]",
")",
"return",
"result"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
Cells.copy
|
Make a copy of itself and return it.
|
modelx/core/cells.py
|
def copy(self, space=None, name=None):
"""Make a copy of itself and return it."""
return Cells(space=space, name=name, formula=self.formula)
|
def copy(self, space=None, name=None):
"""Make a copy of itself and return it."""
return Cells(space=space, name=name, formula=self.formula)
|
[
"Make",
"a",
"copy",
"of",
"itself",
"and",
"return",
"it",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/cells.py#L111-L113
|
[
"def",
"copy",
"(",
"self",
",",
"space",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"return",
"Cells",
"(",
"space",
"=",
"space",
",",
"name",
"=",
"name",
",",
"formula",
"=",
"self",
".",
"formula",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
Cells.node
|
Return a :class:`CellNode` object for the given arguments.
|
modelx/core/cells.py
|
def node(self, *args, **kwargs):
"""Return a :class:`CellNode` object for the given arguments."""
return CellNode(get_node(self._impl, *convert_args(args, kwargs)))
|
def node(self, *args, **kwargs):
"""Return a :class:`CellNode` object for the given arguments."""
return CellNode(get_node(self._impl, *convert_args(args, kwargs)))
|
[
"Return",
"a",
":",
"class",
":",
"CellNode",
"object",
"for",
"the",
"given",
"arguments",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/cells.py#L297-L299
|
[
"def",
"node",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"CellNode",
"(",
"get_node",
"(",
"self",
".",
"_impl",
",",
"*",
"convert_args",
"(",
"args",
",",
"kwargs",
")",
")",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
Cells._baseattrs
|
A dict of members expressed in literals
|
modelx/core/cells.py
|
def _baseattrs(self):
"""A dict of members expressed in literals"""
result = super()._baseattrs
result["params"] = ", ".join(self.parameters)
return result
|
def _baseattrs(self):
"""A dict of members expressed in literals"""
result = super()._baseattrs
result["params"] = ", ".join(self.parameters)
return result
|
[
"A",
"dict",
"of",
"members",
"expressed",
"in",
"literals"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/cells.py#L323-L328
|
[
"def",
"_baseattrs",
"(",
"self",
")",
":",
"result",
"=",
"super",
"(",
")",
".",
"_baseattrs",
"result",
"[",
"\"params\"",
"]",
"=",
"\", \"",
".",
"join",
"(",
"self",
".",
"parameters",
")",
"return",
"result"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
CellNode.value
|
Return the value of the cells.
|
modelx/core/cells.py
|
def value(self):
"""Return the value of the cells."""
if self.has_value:
return self._impl[OBJ].get_value(self._impl[KEY])
else:
raise ValueError("Value not found")
|
def value(self):
"""Return the value of the cells."""
if self.has_value:
return self._impl[OBJ].get_value(self._impl[KEY])
else:
raise ValueError("Value not found")
|
[
"Return",
"the",
"value",
"of",
"the",
"cells",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/cells.py#L703-L708
|
[
"def",
"value",
"(",
"self",
")",
":",
"if",
"self",
".",
"has_value",
":",
"return",
"self",
".",
"_impl",
"[",
"OBJ",
"]",
".",
"get_value",
"(",
"self",
".",
"_impl",
"[",
"KEY",
"]",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Value not found\"",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
CellNode._baseattrs
|
A dict of members expressed in literals
|
modelx/core/cells.py
|
def _baseattrs(self):
"""A dict of members expressed in literals"""
result = {
"type": type(self).__name__,
"obj": self.cells._baseattrs,
"args": self.args,
"value": self.value if self.has_value else None,
"predslen": len(self.preds),
"succslen": len(self.succs),
"repr_parent": self.cells._impl.repr_parent(),
"repr": self.cells._get_repr(),
}
return result
|
def _baseattrs(self):
"""A dict of members expressed in literals"""
result = {
"type": type(self).__name__,
"obj": self.cells._baseattrs,
"args": self.args,
"value": self.value if self.has_value else None,
"predslen": len(self.preds),
"succslen": len(self.succs),
"repr_parent": self.cells._impl.repr_parent(),
"repr": self.cells._get_repr(),
}
return result
|
[
"A",
"dict",
"of",
"members",
"expressed",
"in",
"literals"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/cells.py#L721-L735
|
[
"def",
"_baseattrs",
"(",
"self",
")",
":",
"result",
"=",
"{",
"\"type\"",
":",
"type",
"(",
"self",
")",
".",
"__name__",
",",
"\"obj\"",
":",
"self",
".",
"cells",
".",
"_baseattrs",
",",
"\"args\"",
":",
"self",
".",
"args",
",",
"\"value\"",
":",
"self",
".",
"value",
"if",
"self",
".",
"has_value",
"else",
"None",
",",
"\"predslen\"",
":",
"len",
"(",
"self",
".",
"preds",
")",
",",
"\"succslen\"",
":",
"len",
"(",
"self",
".",
"succs",
")",
",",
"\"repr_parent\"",
":",
"self",
".",
"cells",
".",
"_impl",
".",
"repr_parent",
"(",
")",
",",
"\"repr\"",
":",
"self",
".",
"cells",
".",
"_get_repr",
"(",
")",
",",
"}",
"return",
"result"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
reorder_list
|
Reorder a list to match target by moving a sequence at a time.
Written for QtAbstractItemModel.moveRows.
|
devnotes/reorder_list.py
|
def reorder_list(source, targetorder):
"""Reorder a list to match target by moving a sequence at a time.
Written for QtAbstractItemModel.moveRows.
"""
i = 0
while i < len(source):
if source[i] == targetorder[i]:
i += 1
continue
else:
i0 = i
j0 = source.index(targetorder[i0])
j = j0 + 1
while j < len(source):
if source[j] == targetorder[j - j0 + i0]:
j += 1
continue
else:
break
move_elements(source, i0, j0, j - j0)
i += j - j0
|
def reorder_list(source, targetorder):
"""Reorder a list to match target by moving a sequence at a time.
Written for QtAbstractItemModel.moveRows.
"""
i = 0
while i < len(source):
if source[i] == targetorder[i]:
i += 1
continue
else:
i0 = i
j0 = source.index(targetorder[i0])
j = j0 + 1
while j < len(source):
if source[j] == targetorder[j - j0 + i0]:
j += 1
continue
else:
break
move_elements(source, i0, j0, j - j0)
i += j - j0
|
[
"Reorder",
"a",
"list",
"to",
"match",
"target",
"by",
"moving",
"a",
"sequence",
"at",
"a",
"time",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/devnotes/reorder_list.py#L5-L27
|
[
"def",
"reorder_list",
"(",
"source",
",",
"targetorder",
")",
":",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"source",
")",
":",
"if",
"source",
"[",
"i",
"]",
"==",
"targetorder",
"[",
"i",
"]",
":",
"i",
"+=",
"1",
"continue",
"else",
":",
"i0",
"=",
"i",
"j0",
"=",
"source",
".",
"index",
"(",
"targetorder",
"[",
"i0",
"]",
")",
"j",
"=",
"j0",
"+",
"1",
"while",
"j",
"<",
"len",
"(",
"source",
")",
":",
"if",
"source",
"[",
"j",
"]",
"==",
"targetorder",
"[",
"j",
"-",
"j0",
"+",
"i0",
"]",
":",
"j",
"+=",
"1",
"continue",
"else",
":",
"break",
"move_elements",
"(",
"source",
",",
"i0",
",",
"j0",
",",
"j",
"-",
"j0",
")",
"i",
"+=",
"j",
"-",
"j0"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
move_elements
|
Move a sub sequence in a list
|
devnotes/reorder_list.py
|
def move_elements(source, index_to, index_from, length):
"""Move a sub sequence in a list"""
sublist = [source.pop(index_from) for _ in range(length)]
for _ in range(length):
source.insert(index_to, sublist.pop())
|
def move_elements(source, index_to, index_from, length):
"""Move a sub sequence in a list"""
sublist = [source.pop(index_from) for _ in range(length)]
for _ in range(length):
source.insert(index_to, sublist.pop())
|
[
"Move",
"a",
"sub",
"sequence",
"in",
"a",
"list"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/devnotes/reorder_list.py#L30-L36
|
[
"def",
"move_elements",
"(",
"source",
",",
"index_to",
",",
"index_from",
",",
"length",
")",
":",
"sublist",
"=",
"[",
"source",
".",
"pop",
"(",
"index_from",
")",
"for",
"_",
"in",
"range",
"(",
"length",
")",
"]",
"for",
"_",
"in",
"range",
"(",
"length",
")",
":",
"source",
".",
"insert",
"(",
"index_to",
",",
"sublist",
".",
"pop",
"(",
")",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
_get_col_index
|
Convert column name to index.
|
modelx/io/excel.py
|
def _get_col_index(name):
"""Convert column name to index."""
index = string.ascii_uppercase.index
col = 0
for c in name.upper():
col = col * 26 + index(c) + 1
return col
|
def _get_col_index(name):
"""Convert column name to index."""
index = string.ascii_uppercase.index
col = 0
for c in name.upper():
col = col * 26 + index(c) + 1
return col
|
[
"Convert",
"column",
"name",
"to",
"index",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/io/excel.py#L23-L30
|
[
"def",
"_get_col_index",
"(",
"name",
")",
":",
"index",
"=",
"string",
".",
"ascii_uppercase",
".",
"index",
"col",
"=",
"0",
"for",
"c",
"in",
"name",
".",
"upper",
"(",
")",
":",
"col",
"=",
"col",
"*",
"26",
"+",
"index",
"(",
"c",
")",
"+",
"1",
"return",
"col"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
_get_range
|
Return a range as nested dict of openpyxl cells.
|
modelx/io/excel.py
|
def _get_range(book, range_, sheet):
"""Return a range as nested dict of openpyxl cells."""
filename = None
if isinstance(book, str):
filename = book
book = opxl.load_workbook(book, data_only=True)
elif isinstance(book, opxl.Workbook):
pass
else:
raise TypeError
if _is_range_address(range_):
sheet_names = [name.upper() for name in book.sheetnames]
index = sheet_names.index(sheet.upper())
data = book.worksheets[index][range_]
else:
data = _get_namedrange(book, range_, sheet)
if data is None:
raise ValueError(
"Named range '%s' not found in %s" % (range_, filename or book)
)
return data
|
def _get_range(book, range_, sheet):
"""Return a range as nested dict of openpyxl cells."""
filename = None
if isinstance(book, str):
filename = book
book = opxl.load_workbook(book, data_only=True)
elif isinstance(book, opxl.Workbook):
pass
else:
raise TypeError
if _is_range_address(range_):
sheet_names = [name.upper() for name in book.sheetnames]
index = sheet_names.index(sheet.upper())
data = book.worksheets[index][range_]
else:
data = _get_namedrange(book, range_, sheet)
if data is None:
raise ValueError(
"Named range '%s' not found in %s" % (range_, filename or book)
)
return data
|
[
"Return",
"a",
"range",
"as",
"nested",
"dict",
"of",
"openpyxl",
"cells",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/io/excel.py#L80-L103
|
[
"def",
"_get_range",
"(",
"book",
",",
"range_",
",",
"sheet",
")",
":",
"filename",
"=",
"None",
"if",
"isinstance",
"(",
"book",
",",
"str",
")",
":",
"filename",
"=",
"book",
"book",
"=",
"opxl",
".",
"load_workbook",
"(",
"book",
",",
"data_only",
"=",
"True",
")",
"elif",
"isinstance",
"(",
"book",
",",
"opxl",
".",
"Workbook",
")",
":",
"pass",
"else",
":",
"raise",
"TypeError",
"if",
"_is_range_address",
"(",
"range_",
")",
":",
"sheet_names",
"=",
"[",
"name",
".",
"upper",
"(",
")",
"for",
"name",
"in",
"book",
".",
"sheetnames",
"]",
"index",
"=",
"sheet_names",
".",
"index",
"(",
"sheet",
".",
"upper",
"(",
")",
")",
"data",
"=",
"book",
".",
"worksheets",
"[",
"index",
"]",
"[",
"range_",
"]",
"else",
":",
"data",
"=",
"_get_namedrange",
"(",
"book",
",",
"range_",
",",
"sheet",
")",
"if",
"data",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Named range '%s' not found in %s\"",
"%",
"(",
"range_",
",",
"filename",
"or",
"book",
")",
")",
"return",
"data"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
read_range
|
Read values from an Excel range into a dictionary.
`range_expr` ie either a range address string, such as "A1", "$C$3:$E$5",
or a defined name string for a range, such as "NamedRange1".
If a range address is provided, `sheet` argument must also be provided.
If a named range is provided and `sheet` is not, book level defined name
is searched. If `sheet` is also provided, sheet level defined name for the
specified `sheet` is searched.
If range_expr points to a single cell, its value is returned.
`dictgenerator` is a generator function that yields keys and values of
the returned dictionary. the excel range, as a nested tuple of openpyxl's
Cell objects, is passed to the generator function as its single argument.
If not specified, default generator is used, which maps tuples of row and
column indexes, both starting with 0, to their values.
Args:
filepath (str): Path to an Excel file.
range_epxr (str): Range expression, such as "A1", "$G4:$K10",
or named range "NamedRange1"
sheet (str): Sheet name (case ignored).
None if book level defined range name is passed as `range_epxr`.
dict_generator: A generator function taking a nested tuple of cells
as a single parameter.
Returns:
Nested list containing range values.
|
modelx/io/excel.py
|
def read_range(filepath, range_expr, sheet=None, dict_generator=None):
"""Read values from an Excel range into a dictionary.
`range_expr` ie either a range address string, such as "A1", "$C$3:$E$5",
or a defined name string for a range, such as "NamedRange1".
If a range address is provided, `sheet` argument must also be provided.
If a named range is provided and `sheet` is not, book level defined name
is searched. If `sheet` is also provided, sheet level defined name for the
specified `sheet` is searched.
If range_expr points to a single cell, its value is returned.
`dictgenerator` is a generator function that yields keys and values of
the returned dictionary. the excel range, as a nested tuple of openpyxl's
Cell objects, is passed to the generator function as its single argument.
If not specified, default generator is used, which maps tuples of row and
column indexes, both starting with 0, to their values.
Args:
filepath (str): Path to an Excel file.
range_epxr (str): Range expression, such as "A1", "$G4:$K10",
or named range "NamedRange1"
sheet (str): Sheet name (case ignored).
None if book level defined range name is passed as `range_epxr`.
dict_generator: A generator function taking a nested tuple of cells
as a single parameter.
Returns:
Nested list containing range values.
"""
def default_generator(cells):
for row_ind, row in enumerate(cells):
for col_ind, cell in enumerate(row):
yield (row_ind, col_ind), cell.value
book = opxl.load_workbook(filepath, data_only=True)
if _is_range_address(range_expr):
sheet_names = [name.upper() for name in book.sheetnames]
index = sheet_names.index(sheet.upper())
cells = book.worksheets[index][range_expr]
else:
cells = _get_namedrange(book, range_expr, sheet)
# In case of a single cell, return its value.
if isinstance(cells, opxl.cell.Cell):
return cells.value
if dict_generator is None:
dict_generator = default_generator
gen = dict_generator(cells)
return {keyval[0]: keyval[1] for keyval in gen}
|
def read_range(filepath, range_expr, sheet=None, dict_generator=None):
"""Read values from an Excel range into a dictionary.
`range_expr` ie either a range address string, such as "A1", "$C$3:$E$5",
or a defined name string for a range, such as "NamedRange1".
If a range address is provided, `sheet` argument must also be provided.
If a named range is provided and `sheet` is not, book level defined name
is searched. If `sheet` is also provided, sheet level defined name for the
specified `sheet` is searched.
If range_expr points to a single cell, its value is returned.
`dictgenerator` is a generator function that yields keys and values of
the returned dictionary. the excel range, as a nested tuple of openpyxl's
Cell objects, is passed to the generator function as its single argument.
If not specified, default generator is used, which maps tuples of row and
column indexes, both starting with 0, to their values.
Args:
filepath (str): Path to an Excel file.
range_epxr (str): Range expression, such as "A1", "$G4:$K10",
or named range "NamedRange1"
sheet (str): Sheet name (case ignored).
None if book level defined range name is passed as `range_epxr`.
dict_generator: A generator function taking a nested tuple of cells
as a single parameter.
Returns:
Nested list containing range values.
"""
def default_generator(cells):
for row_ind, row in enumerate(cells):
for col_ind, cell in enumerate(row):
yield (row_ind, col_ind), cell.value
book = opxl.load_workbook(filepath, data_only=True)
if _is_range_address(range_expr):
sheet_names = [name.upper() for name in book.sheetnames]
index = sheet_names.index(sheet.upper())
cells = book.worksheets[index][range_expr]
else:
cells = _get_namedrange(book, range_expr, sheet)
# In case of a single cell, return its value.
if isinstance(cells, opxl.cell.Cell):
return cells.value
if dict_generator is None:
dict_generator = default_generator
gen = dict_generator(cells)
return {keyval[0]: keyval[1] for keyval in gen}
|
[
"Read",
"values",
"from",
"an",
"Excel",
"range",
"into",
"a",
"dictionary",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/io/excel.py#L106-L158
|
[
"def",
"read_range",
"(",
"filepath",
",",
"range_expr",
",",
"sheet",
"=",
"None",
",",
"dict_generator",
"=",
"None",
")",
":",
"def",
"default_generator",
"(",
"cells",
")",
":",
"for",
"row_ind",
",",
"row",
"in",
"enumerate",
"(",
"cells",
")",
":",
"for",
"col_ind",
",",
"cell",
"in",
"enumerate",
"(",
"row",
")",
":",
"yield",
"(",
"row_ind",
",",
"col_ind",
")",
",",
"cell",
".",
"value",
"book",
"=",
"opxl",
".",
"load_workbook",
"(",
"filepath",
",",
"data_only",
"=",
"True",
")",
"if",
"_is_range_address",
"(",
"range_expr",
")",
":",
"sheet_names",
"=",
"[",
"name",
".",
"upper",
"(",
")",
"for",
"name",
"in",
"book",
".",
"sheetnames",
"]",
"index",
"=",
"sheet_names",
".",
"index",
"(",
"sheet",
".",
"upper",
"(",
")",
")",
"cells",
"=",
"book",
".",
"worksheets",
"[",
"index",
"]",
"[",
"range_expr",
"]",
"else",
":",
"cells",
"=",
"_get_namedrange",
"(",
"book",
",",
"range_expr",
",",
"sheet",
")",
"# In case of a single cell, return its value.",
"if",
"isinstance",
"(",
"cells",
",",
"opxl",
".",
"cell",
".",
"Cell",
")",
":",
"return",
"cells",
".",
"value",
"if",
"dict_generator",
"is",
"None",
":",
"dict_generator",
"=",
"default_generator",
"gen",
"=",
"dict_generator",
"(",
"cells",
")",
"return",
"{",
"keyval",
"[",
"0",
"]",
":",
"keyval",
"[",
"1",
"]",
"for",
"keyval",
"in",
"gen",
"}"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
_get_namedrange
|
Get range from a workbook.
A workbook can contain multiple definitions for a single name,
as a name can be defined for the entire book or for
a particular sheet.
If sheet is None, the book-wide def is searched,
otherwise sheet-local def is looked up.
Args:
book: An openpyxl workbook object.
rangename (str): Range expression, such as "A1", "$G4:$K10",
named range "NamedRange1".
sheetname (str, optional): None for book-wide name def,
sheet name for sheet-local named range.
Returns:
Range object specified by the name.
|
modelx/io/excel.py
|
def _get_namedrange(book, rangename, sheetname=None):
"""Get range from a workbook.
A workbook can contain multiple definitions for a single name,
as a name can be defined for the entire book or for
a particular sheet.
If sheet is None, the book-wide def is searched,
otherwise sheet-local def is looked up.
Args:
book: An openpyxl workbook object.
rangename (str): Range expression, such as "A1", "$G4:$K10",
named range "NamedRange1".
sheetname (str, optional): None for book-wide name def,
sheet name for sheet-local named range.
Returns:
Range object specified by the name.
"""
def cond(namedef):
if namedef.type.upper() == "RANGE":
if namedef.name.upper() == rangename.upper():
if sheetname is None:
if not namedef.localSheetId:
return True
else: # sheet local name
sheet_id = [sht.upper() for sht in book.sheetnames].index(
sheetname.upper()
)
if namedef.localSheetId == sheet_id:
return True
return False
def get_destinations(name_def):
"""Workaround for the bug in DefinedName.destinations"""
from openpyxl.formula import Tokenizer
from openpyxl.utils.cell import SHEETRANGE_RE
if name_def.type == "RANGE":
tok = Tokenizer("=" + name_def.value)
for part in tok.items:
if part.subtype == "RANGE":
m = SHEETRANGE_RE.match(part.value)
if m.group("quoted"):
sheet_name = m.group("quoted")
else:
sheet_name = m.group("notquoted")
yield sheet_name, m.group("cells")
namedef = next(
(item for item in book.defined_names.definedName if cond(item)), None
)
if namedef is None:
return None
dests = get_destinations(namedef)
xlranges = []
sheetnames_upper = [name.upper() for name in book.sheetnames]
for sht, addr in dests:
if sheetname:
sht = sheetname
index = sheetnames_upper.index(sht.upper())
xlranges.append(book.worksheets[index][addr])
if len(xlranges) == 1:
return xlranges[0]
else:
return xlranges
|
def _get_namedrange(book, rangename, sheetname=None):
"""Get range from a workbook.
A workbook can contain multiple definitions for a single name,
as a name can be defined for the entire book or for
a particular sheet.
If sheet is None, the book-wide def is searched,
otherwise sheet-local def is looked up.
Args:
book: An openpyxl workbook object.
rangename (str): Range expression, such as "A1", "$G4:$K10",
named range "NamedRange1".
sheetname (str, optional): None for book-wide name def,
sheet name for sheet-local named range.
Returns:
Range object specified by the name.
"""
def cond(namedef):
if namedef.type.upper() == "RANGE":
if namedef.name.upper() == rangename.upper():
if sheetname is None:
if not namedef.localSheetId:
return True
else: # sheet local name
sheet_id = [sht.upper() for sht in book.sheetnames].index(
sheetname.upper()
)
if namedef.localSheetId == sheet_id:
return True
return False
def get_destinations(name_def):
"""Workaround for the bug in DefinedName.destinations"""
from openpyxl.formula import Tokenizer
from openpyxl.utils.cell import SHEETRANGE_RE
if name_def.type == "RANGE":
tok = Tokenizer("=" + name_def.value)
for part in tok.items:
if part.subtype == "RANGE":
m = SHEETRANGE_RE.match(part.value)
if m.group("quoted"):
sheet_name = m.group("quoted")
else:
sheet_name = m.group("notquoted")
yield sheet_name, m.group("cells")
namedef = next(
(item for item in book.defined_names.definedName if cond(item)), None
)
if namedef is None:
return None
dests = get_destinations(namedef)
xlranges = []
sheetnames_upper = [name.upper() for name in book.sheetnames]
for sht, addr in dests:
if sheetname:
sht = sheetname
index = sheetnames_upper.index(sht.upper())
xlranges.append(book.worksheets[index][addr])
if len(xlranges) == 1:
return xlranges[0]
else:
return xlranges
|
[
"Get",
"range",
"from",
"a",
"workbook",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/io/excel.py#L161-L241
|
[
"def",
"_get_namedrange",
"(",
"book",
",",
"rangename",
",",
"sheetname",
"=",
"None",
")",
":",
"def",
"cond",
"(",
"namedef",
")",
":",
"if",
"namedef",
".",
"type",
".",
"upper",
"(",
")",
"==",
"\"RANGE\"",
":",
"if",
"namedef",
".",
"name",
".",
"upper",
"(",
")",
"==",
"rangename",
".",
"upper",
"(",
")",
":",
"if",
"sheetname",
"is",
"None",
":",
"if",
"not",
"namedef",
".",
"localSheetId",
":",
"return",
"True",
"else",
":",
"# sheet local name",
"sheet_id",
"=",
"[",
"sht",
".",
"upper",
"(",
")",
"for",
"sht",
"in",
"book",
".",
"sheetnames",
"]",
".",
"index",
"(",
"sheetname",
".",
"upper",
"(",
")",
")",
"if",
"namedef",
".",
"localSheetId",
"==",
"sheet_id",
":",
"return",
"True",
"return",
"False",
"def",
"get_destinations",
"(",
"name_def",
")",
":",
"\"\"\"Workaround for the bug in DefinedName.destinations\"\"\"",
"from",
"openpyxl",
".",
"formula",
"import",
"Tokenizer",
"from",
"openpyxl",
".",
"utils",
".",
"cell",
"import",
"SHEETRANGE_RE",
"if",
"name_def",
".",
"type",
"==",
"\"RANGE\"",
":",
"tok",
"=",
"Tokenizer",
"(",
"\"=\"",
"+",
"name_def",
".",
"value",
")",
"for",
"part",
"in",
"tok",
".",
"items",
":",
"if",
"part",
".",
"subtype",
"==",
"\"RANGE\"",
":",
"m",
"=",
"SHEETRANGE_RE",
".",
"match",
"(",
"part",
".",
"value",
")",
"if",
"m",
".",
"group",
"(",
"\"quoted\"",
")",
":",
"sheet_name",
"=",
"m",
".",
"group",
"(",
"\"quoted\"",
")",
"else",
":",
"sheet_name",
"=",
"m",
".",
"group",
"(",
"\"notquoted\"",
")",
"yield",
"sheet_name",
",",
"m",
".",
"group",
"(",
"\"cells\"",
")",
"namedef",
"=",
"next",
"(",
"(",
"item",
"for",
"item",
"in",
"book",
".",
"defined_names",
".",
"definedName",
"if",
"cond",
"(",
"item",
")",
")",
",",
"None",
")",
"if",
"namedef",
"is",
"None",
":",
"return",
"None",
"dests",
"=",
"get_destinations",
"(",
"namedef",
")",
"xlranges",
"=",
"[",
"]",
"sheetnames_upper",
"=",
"[",
"name",
".",
"upper",
"(",
")",
"for",
"name",
"in",
"book",
".",
"sheetnames",
"]",
"for",
"sht",
",",
"addr",
"in",
"dests",
":",
"if",
"sheetname",
":",
"sht",
"=",
"sheetname",
"index",
"=",
"sheetnames_upper",
".",
"index",
"(",
"sht",
".",
"upper",
"(",
")",
")",
"xlranges",
".",
"append",
"(",
"book",
".",
"worksheets",
"[",
"index",
"]",
"[",
"addr",
"]",
")",
"if",
"len",
"(",
"xlranges",
")",
"==",
"1",
":",
"return",
"xlranges",
"[",
"0",
"]",
"else",
":",
"return",
"xlranges"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
SpaceGraph.get_mro
|
Calculate the Method Resolution Order of bases using the C3 algorithm.
Code modified from
http://code.activestate.com/recipes/577748-calculate-the-mro-of-a-class/
Args:
bases: sequence of direct base spaces.
Returns:
mro as a list of bases including node itself
|
devnotes/prototype.py
|
def get_mro(self, space):
"""Calculate the Method Resolution Order of bases using the C3 algorithm.
Code modified from
http://code.activestate.com/recipes/577748-calculate-the-mro-of-a-class/
Args:
bases: sequence of direct base spaces.
Returns:
mro as a list of bases including node itself
"""
seqs = [self.get_mro(base) for base
in self.get_bases(space)] + [list(self.get_bases(space))]
res = []
while True:
non_empty = list(filter(None, seqs))
if not non_empty:
# Nothing left to process, we're done.
res.insert(0, space)
return res
for seq in non_empty: # Find merge candidates among seq heads.
candidate = seq[0]
not_head = [s for s in non_empty if candidate in s[1:]]
if not_head:
# Reject the candidate.
candidate = None
else:
break
if not candidate:
raise TypeError(
"inconsistent hierarchy, no C3 MRO is possible")
res.append(candidate)
for seq in non_empty:
# Remove candidate.
if seq[0] == candidate:
del seq[0]
|
def get_mro(self, space):
"""Calculate the Method Resolution Order of bases using the C3 algorithm.
Code modified from
http://code.activestate.com/recipes/577748-calculate-the-mro-of-a-class/
Args:
bases: sequence of direct base spaces.
Returns:
mro as a list of bases including node itself
"""
seqs = [self.get_mro(base) for base
in self.get_bases(space)] + [list(self.get_bases(space))]
res = []
while True:
non_empty = list(filter(None, seqs))
if not non_empty:
# Nothing left to process, we're done.
res.insert(0, space)
return res
for seq in non_empty: # Find merge candidates among seq heads.
candidate = seq[0]
not_head = [s for s in non_empty if candidate in s[1:]]
if not_head:
# Reject the candidate.
candidate = None
else:
break
if not candidate:
raise TypeError(
"inconsistent hierarchy, no C3 MRO is possible")
res.append(candidate)
for seq in non_empty:
# Remove candidate.
if seq[0] == candidate:
del seq[0]
|
[
"Calculate",
"the",
"Method",
"Resolution",
"Order",
"of",
"bases",
"using",
"the",
"C3",
"algorithm",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/devnotes/prototype.py#L31-L72
|
[
"def",
"get_mro",
"(",
"self",
",",
"space",
")",
":",
"seqs",
"=",
"[",
"self",
".",
"get_mro",
"(",
"base",
")",
"for",
"base",
"in",
"self",
".",
"get_bases",
"(",
"space",
")",
"]",
"+",
"[",
"list",
"(",
"self",
".",
"get_bases",
"(",
"space",
")",
")",
"]",
"res",
"=",
"[",
"]",
"while",
"True",
":",
"non_empty",
"=",
"list",
"(",
"filter",
"(",
"None",
",",
"seqs",
")",
")",
"if",
"not",
"non_empty",
":",
"# Nothing left to process, we're done.",
"res",
".",
"insert",
"(",
"0",
",",
"space",
")",
"return",
"res",
"for",
"seq",
"in",
"non_empty",
":",
"# Find merge candidates among seq heads.",
"candidate",
"=",
"seq",
"[",
"0",
"]",
"not_head",
"=",
"[",
"s",
"for",
"s",
"in",
"non_empty",
"if",
"candidate",
"in",
"s",
"[",
"1",
":",
"]",
"]",
"if",
"not_head",
":",
"# Reject the candidate.",
"candidate",
"=",
"None",
"else",
":",
"break",
"if",
"not",
"candidate",
":",
"raise",
"TypeError",
"(",
"\"inconsistent hierarchy, no C3 MRO is possible\"",
")",
"res",
".",
"append",
"(",
"candidate",
")",
"for",
"seq",
"in",
"non_empty",
":",
"# Remove candidate.",
"if",
"seq",
"[",
"0",
"]",
"==",
"candidate",
":",
"del",
"seq",
"[",
"0",
"]"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
_alter_code
|
Create a new code object by altering some of ``code`` attributes
Args:
code: code objcect
attrs: a mapping of names of code object attrs to their values
|
devnotes/cpydep.py
|
def _alter_code(code, **attrs):
"""Create a new code object by altering some of ``code`` attributes
Args:
code: code objcect
attrs: a mapping of names of code object attrs to their values
"""
PyCode_New = ctypes.pythonapi.PyCode_New
PyCode_New.argtypes = (
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.py_object,
ctypes.py_object,
ctypes.py_object,
ctypes.py_object,
ctypes.py_object,
ctypes.py_object,
ctypes.py_object,
ctypes.py_object,
ctypes.c_int,
ctypes.py_object)
PyCode_New.restype = ctypes.py_object
args = [
[code.co_argcount, 'co_argcount'],
[code.co_kwonlyargcount, 'co_kwonlyargcount'],
[code.co_nlocals, 'co_nlocals'],
[code.co_stacksize, 'co_stacksize'],
[code.co_flags, 'co_flags'],
[code.co_code, 'co_code'],
[code.co_consts, 'co_consts'],
[code.co_names, 'co_names'],
[code.co_varnames, 'co_varnames'],
[code.co_freevars, 'co_freevars'],
[code.co_cellvars, 'co_cellvars'],
[code.co_filename, 'co_filename'],
[code.co_name, 'co_name'],
[code.co_firstlineno, 'co_firstlineno'],
[code.co_lnotab, 'co_lnotab']]
for arg in args:
if arg[1] in attrs:
arg[0] = attrs[arg[1]]
return PyCode_New(
args[0][0], # code.co_argcount,
args[1][0], # code.co_kwonlyargcount,
args[2][0], # code.co_nlocals,
args[3][0], # code.co_stacksize,
args[4][0], # code.co_flags,
args[5][0], # code.co_code,
args[6][0], # code.co_consts,
args[7][0], # code.co_names,
args[8][0], # code.co_varnames,
args[9][0], # code.co_freevars,
args[10][0], # code.co_cellvars,
args[11][0], # code.co_filename,
args[12][0], # code.co_name,
args[13][0], # code.co_firstlineno,
args[14][0])
|
def _alter_code(code, **attrs):
"""Create a new code object by altering some of ``code`` attributes
Args:
code: code objcect
attrs: a mapping of names of code object attrs to their values
"""
PyCode_New = ctypes.pythonapi.PyCode_New
PyCode_New.argtypes = (
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.py_object,
ctypes.py_object,
ctypes.py_object,
ctypes.py_object,
ctypes.py_object,
ctypes.py_object,
ctypes.py_object,
ctypes.py_object,
ctypes.c_int,
ctypes.py_object)
PyCode_New.restype = ctypes.py_object
args = [
[code.co_argcount, 'co_argcount'],
[code.co_kwonlyargcount, 'co_kwonlyargcount'],
[code.co_nlocals, 'co_nlocals'],
[code.co_stacksize, 'co_stacksize'],
[code.co_flags, 'co_flags'],
[code.co_code, 'co_code'],
[code.co_consts, 'co_consts'],
[code.co_names, 'co_names'],
[code.co_varnames, 'co_varnames'],
[code.co_freevars, 'co_freevars'],
[code.co_cellvars, 'co_cellvars'],
[code.co_filename, 'co_filename'],
[code.co_name, 'co_name'],
[code.co_firstlineno, 'co_firstlineno'],
[code.co_lnotab, 'co_lnotab']]
for arg in args:
if arg[1] in attrs:
arg[0] = attrs[arg[1]]
return PyCode_New(
args[0][0], # code.co_argcount,
args[1][0], # code.co_kwonlyargcount,
args[2][0], # code.co_nlocals,
args[3][0], # code.co_stacksize,
args[4][0], # code.co_flags,
args[5][0], # code.co_code,
args[6][0], # code.co_consts,
args[7][0], # code.co_names,
args[8][0], # code.co_varnames,
args[9][0], # code.co_freevars,
args[10][0], # code.co_cellvars,
args[11][0], # code.co_filename,
args[12][0], # code.co_name,
args[13][0], # code.co_firstlineno,
args[14][0])
|
[
"Create",
"a",
"new",
"code",
"object",
"by",
"altering",
"some",
"of",
"code",
"attributes"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/devnotes/cpydep.py#L39-L104
|
[
"def",
"_alter_code",
"(",
"code",
",",
"*",
"*",
"attrs",
")",
":",
"PyCode_New",
"=",
"ctypes",
".",
"pythonapi",
".",
"PyCode_New",
"PyCode_New",
".",
"argtypes",
"=",
"(",
"ctypes",
".",
"c_int",
",",
"ctypes",
".",
"c_int",
",",
"ctypes",
".",
"c_int",
",",
"ctypes",
".",
"c_int",
",",
"ctypes",
".",
"c_int",
",",
"ctypes",
".",
"py_object",
",",
"ctypes",
".",
"py_object",
",",
"ctypes",
".",
"py_object",
",",
"ctypes",
".",
"py_object",
",",
"ctypes",
".",
"py_object",
",",
"ctypes",
".",
"py_object",
",",
"ctypes",
".",
"py_object",
",",
"ctypes",
".",
"py_object",
",",
"ctypes",
".",
"c_int",
",",
"ctypes",
".",
"py_object",
")",
"PyCode_New",
".",
"restype",
"=",
"ctypes",
".",
"py_object",
"args",
"=",
"[",
"[",
"code",
".",
"co_argcount",
",",
"'co_argcount'",
"]",
",",
"[",
"code",
".",
"co_kwonlyargcount",
",",
"'co_kwonlyargcount'",
"]",
",",
"[",
"code",
".",
"co_nlocals",
",",
"'co_nlocals'",
"]",
",",
"[",
"code",
".",
"co_stacksize",
",",
"'co_stacksize'",
"]",
",",
"[",
"code",
".",
"co_flags",
",",
"'co_flags'",
"]",
",",
"[",
"code",
".",
"co_code",
",",
"'co_code'",
"]",
",",
"[",
"code",
".",
"co_consts",
",",
"'co_consts'",
"]",
",",
"[",
"code",
".",
"co_names",
",",
"'co_names'",
"]",
",",
"[",
"code",
".",
"co_varnames",
",",
"'co_varnames'",
"]",
",",
"[",
"code",
".",
"co_freevars",
",",
"'co_freevars'",
"]",
",",
"[",
"code",
".",
"co_cellvars",
",",
"'co_cellvars'",
"]",
",",
"[",
"code",
".",
"co_filename",
",",
"'co_filename'",
"]",
",",
"[",
"code",
".",
"co_name",
",",
"'co_name'",
"]",
",",
"[",
"code",
".",
"co_firstlineno",
",",
"'co_firstlineno'",
"]",
",",
"[",
"code",
".",
"co_lnotab",
",",
"'co_lnotab'",
"]",
"]",
"for",
"arg",
"in",
"args",
":",
"if",
"arg",
"[",
"1",
"]",
"in",
"attrs",
":",
"arg",
"[",
"0",
"]",
"=",
"attrs",
"[",
"arg",
"[",
"1",
"]",
"]",
"return",
"PyCode_New",
"(",
"args",
"[",
"0",
"]",
"[",
"0",
"]",
",",
"# code.co_argcount,",
"args",
"[",
"1",
"]",
"[",
"0",
"]",
",",
"# code.co_kwonlyargcount,",
"args",
"[",
"2",
"]",
"[",
"0",
"]",
",",
"# code.co_nlocals,",
"args",
"[",
"3",
"]",
"[",
"0",
"]",
",",
"# code.co_stacksize,",
"args",
"[",
"4",
"]",
"[",
"0",
"]",
",",
"# code.co_flags,",
"args",
"[",
"5",
"]",
"[",
"0",
"]",
",",
"# code.co_code,",
"args",
"[",
"6",
"]",
"[",
"0",
"]",
",",
"# code.co_consts,",
"args",
"[",
"7",
"]",
"[",
"0",
"]",
",",
"# code.co_names,",
"args",
"[",
"8",
"]",
"[",
"0",
"]",
",",
"# code.co_varnames,",
"args",
"[",
"9",
"]",
"[",
"0",
"]",
",",
"# code.co_freevars,",
"args",
"[",
"10",
"]",
"[",
"0",
"]",
",",
"# code.co_cellvars,",
"args",
"[",
"11",
"]",
"[",
"0",
"]",
",",
"# code.co_filename,",
"args",
"[",
"12",
"]",
"[",
"0",
"]",
",",
"# code.co_name,",
"args",
"[",
"13",
"]",
"[",
"0",
"]",
",",
"# code.co_firstlineno,",
"args",
"[",
"14",
"]",
"[",
"0",
"]",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
alter_freevars
|
Replace local variables with free variables
Warnings:
This function does not work.
|
devnotes/cpydep.py
|
def alter_freevars(func, globals_=None, **vars):
"""Replace local variables with free variables
Warnings:
This function does not work.
"""
if globals_ is None:
globals_ = func.__globals__
frees = tuple(vars.keys())
oldlocs = func.__code__.co_names
newlocs = tuple(name for name in oldlocs if name not in frees)
code = _alter_code(func.__code__,
co_freevars=frees,
co_names=newlocs,
co_flags=func.__code__.co_flags | inspect.CO_NESTED)
closure = _create_closure(*vars.values())
return FunctionType(code, globals_, closure=closure)
|
def alter_freevars(func, globals_=None, **vars):
"""Replace local variables with free variables
Warnings:
This function does not work.
"""
if globals_ is None:
globals_ = func.__globals__
frees = tuple(vars.keys())
oldlocs = func.__code__.co_names
newlocs = tuple(name for name in oldlocs if name not in frees)
code = _alter_code(func.__code__,
co_freevars=frees,
co_names=newlocs,
co_flags=func.__code__.co_flags | inspect.CO_NESTED)
closure = _create_closure(*vars.values())
return FunctionType(code, globals_, closure=closure)
|
[
"Replace",
"local",
"variables",
"with",
"free",
"variables"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/devnotes/cpydep.py#L120-L140
|
[
"def",
"alter_freevars",
"(",
"func",
",",
"globals_",
"=",
"None",
",",
"*",
"*",
"vars",
")",
":",
"if",
"globals_",
"is",
"None",
":",
"globals_",
"=",
"func",
".",
"__globals__",
"frees",
"=",
"tuple",
"(",
"vars",
".",
"keys",
"(",
")",
")",
"oldlocs",
"=",
"func",
".",
"__code__",
".",
"co_names",
"newlocs",
"=",
"tuple",
"(",
"name",
"for",
"name",
"in",
"oldlocs",
"if",
"name",
"not",
"in",
"frees",
")",
"code",
"=",
"_alter_code",
"(",
"func",
".",
"__code__",
",",
"co_freevars",
"=",
"frees",
",",
"co_names",
"=",
"newlocs",
",",
"co_flags",
"=",
"func",
".",
"__code__",
".",
"co_flags",
"|",
"inspect",
".",
"CO_NESTED",
")",
"closure",
"=",
"_create_closure",
"(",
"*",
"vars",
".",
"values",
"(",
")",
")",
"return",
"FunctionType",
"(",
"code",
",",
"globals_",
",",
"closure",
"=",
"closure",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
fix_lamdaline
|
Remove the last redundant token from lambda expression
lambda x: return x)
^
Return string without irrelevant tokens
returned from inspect.getsource on lamda expr returns
|
modelx/core/formula.py
|
def fix_lamdaline(source):
"""Remove the last redundant token from lambda expression
lambda x: return x)
^
Return string without irrelevant tokens
returned from inspect.getsource on lamda expr returns
"""
# Using undocumented generate_tokens due to a tokenize.tokenize bug
# See https://bugs.python.org/issue23297
strio = io.StringIO(source)
gen = tokenize.generate_tokens(strio.readline)
tkns = []
try:
for t in gen:
tkns.append(t)
except tokenize.TokenError:
pass
# Find the position of 'lambda'
lambda_pos = [(t.type, t.string) for t in tkns].index(
(tokenize.NAME, "lambda")
)
# Ignore tokes before 'lambda'
tkns = tkns[lambda_pos:]
# Find the position of th las OP
lastop_pos = (
len(tkns) - 1 - [t.type for t in tkns[::-1]].index(tokenize.OP)
)
lastop = tkns[lastop_pos]
# Remove OP from the line
fiedlineno = lastop.start[0]
fixedline = lastop.line[: lastop.start[1]] + lastop.line[lastop.end[1] :]
tkns = tkns[:lastop_pos]
fixedlines = ""
last_lineno = 0
for t in tkns:
if last_lineno == t.start[0]:
continue
elif t.start[0] == fiedlineno:
fixedlines += fixedline
last_lineno = t.start[0]
else:
fixedlines += t.line
last_lineno = t.start[0]
return fixedlines
|
def fix_lamdaline(source):
"""Remove the last redundant token from lambda expression
lambda x: return x)
^
Return string without irrelevant tokens
returned from inspect.getsource on lamda expr returns
"""
# Using undocumented generate_tokens due to a tokenize.tokenize bug
# See https://bugs.python.org/issue23297
strio = io.StringIO(source)
gen = tokenize.generate_tokens(strio.readline)
tkns = []
try:
for t in gen:
tkns.append(t)
except tokenize.TokenError:
pass
# Find the position of 'lambda'
lambda_pos = [(t.type, t.string) for t in tkns].index(
(tokenize.NAME, "lambda")
)
# Ignore tokes before 'lambda'
tkns = tkns[lambda_pos:]
# Find the position of th las OP
lastop_pos = (
len(tkns) - 1 - [t.type for t in tkns[::-1]].index(tokenize.OP)
)
lastop = tkns[lastop_pos]
# Remove OP from the line
fiedlineno = lastop.start[0]
fixedline = lastop.line[: lastop.start[1]] + lastop.line[lastop.end[1] :]
tkns = tkns[:lastop_pos]
fixedlines = ""
last_lineno = 0
for t in tkns:
if last_lineno == t.start[0]:
continue
elif t.start[0] == fiedlineno:
fixedlines += fixedline
last_lineno = t.start[0]
else:
fixedlines += t.line
last_lineno = t.start[0]
return fixedlines
|
[
"Remove",
"the",
"last",
"redundant",
"token",
"from",
"lambda",
"expression"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/formula.py#L27-L80
|
[
"def",
"fix_lamdaline",
"(",
"source",
")",
":",
"# Using undocumented generate_tokens due to a tokenize.tokenize bug",
"# See https://bugs.python.org/issue23297",
"strio",
"=",
"io",
".",
"StringIO",
"(",
"source",
")",
"gen",
"=",
"tokenize",
".",
"generate_tokens",
"(",
"strio",
".",
"readline",
")",
"tkns",
"=",
"[",
"]",
"try",
":",
"for",
"t",
"in",
"gen",
":",
"tkns",
".",
"append",
"(",
"t",
")",
"except",
"tokenize",
".",
"TokenError",
":",
"pass",
"# Find the position of 'lambda'",
"lambda_pos",
"=",
"[",
"(",
"t",
".",
"type",
",",
"t",
".",
"string",
")",
"for",
"t",
"in",
"tkns",
"]",
".",
"index",
"(",
"(",
"tokenize",
".",
"NAME",
",",
"\"lambda\"",
")",
")",
"# Ignore tokes before 'lambda'",
"tkns",
"=",
"tkns",
"[",
"lambda_pos",
":",
"]",
"# Find the position of th las OP",
"lastop_pos",
"=",
"(",
"len",
"(",
"tkns",
")",
"-",
"1",
"-",
"[",
"t",
".",
"type",
"for",
"t",
"in",
"tkns",
"[",
":",
":",
"-",
"1",
"]",
"]",
".",
"index",
"(",
"tokenize",
".",
"OP",
")",
")",
"lastop",
"=",
"tkns",
"[",
"lastop_pos",
"]",
"# Remove OP from the line",
"fiedlineno",
"=",
"lastop",
".",
"start",
"[",
"0",
"]",
"fixedline",
"=",
"lastop",
".",
"line",
"[",
":",
"lastop",
".",
"start",
"[",
"1",
"]",
"]",
"+",
"lastop",
".",
"line",
"[",
"lastop",
".",
"end",
"[",
"1",
"]",
":",
"]",
"tkns",
"=",
"tkns",
"[",
":",
"lastop_pos",
"]",
"fixedlines",
"=",
"\"\"",
"last_lineno",
"=",
"0",
"for",
"t",
"in",
"tkns",
":",
"if",
"last_lineno",
"==",
"t",
".",
"start",
"[",
"0",
"]",
":",
"continue",
"elif",
"t",
".",
"start",
"[",
"0",
"]",
"==",
"fiedlineno",
":",
"fixedlines",
"+=",
"fixedline",
"last_lineno",
"=",
"t",
".",
"start",
"[",
"0",
"]",
"else",
":",
"fixedlines",
"+=",
"t",
".",
"line",
"last_lineno",
"=",
"t",
".",
"start",
"[",
"0",
"]",
"return",
"fixedlines"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
find_funcdef
|
Find the first FuncDef ast object in source
|
modelx/core/formula.py
|
def find_funcdef(source):
"""Find the first FuncDef ast object in source"""
try:
module_node = compile(
source, "<string>", mode="exec", flags=ast.PyCF_ONLY_AST
)
except SyntaxError:
return find_funcdef(fix_lamdaline(source))
for node in ast.walk(module_node):
if isinstance(node, ast.FunctionDef) or isinstance(node, ast.Lambda):
return node
raise ValueError("function definition not found")
|
def find_funcdef(source):
"""Find the first FuncDef ast object in source"""
try:
module_node = compile(
source, "<string>", mode="exec", flags=ast.PyCF_ONLY_AST
)
except SyntaxError:
return find_funcdef(fix_lamdaline(source))
for node in ast.walk(module_node):
if isinstance(node, ast.FunctionDef) or isinstance(node, ast.Lambda):
return node
raise ValueError("function definition not found")
|
[
"Find",
"the",
"first",
"FuncDef",
"ast",
"object",
"in",
"source"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/formula.py#L83-L97
|
[
"def",
"find_funcdef",
"(",
"source",
")",
":",
"try",
":",
"module_node",
"=",
"compile",
"(",
"source",
",",
"\"<string>\"",
",",
"mode",
"=",
"\"exec\"",
",",
"flags",
"=",
"ast",
".",
"PyCF_ONLY_AST",
")",
"except",
"SyntaxError",
":",
"return",
"find_funcdef",
"(",
"fix_lamdaline",
"(",
"source",
")",
")",
"for",
"node",
"in",
"ast",
".",
"walk",
"(",
"module_node",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"ast",
".",
"FunctionDef",
")",
"or",
"isinstance",
"(",
"node",
",",
"ast",
".",
"Lambda",
")",
":",
"return",
"node",
"raise",
"ValueError",
"(",
"\"function definition not found\"",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
extract_params
|
Extract parameters from a function definition
|
modelx/core/formula.py
|
def extract_params(source):
"""Extract parameters from a function definition"""
funcdef = find_funcdef(source)
params = []
for node in ast.walk(funcdef.args):
if isinstance(node, ast.arg):
if node.arg not in params:
params.append(node.arg)
return params
|
def extract_params(source):
"""Extract parameters from a function definition"""
funcdef = find_funcdef(source)
params = []
for node in ast.walk(funcdef.args):
if isinstance(node, ast.arg):
if node.arg not in params:
params.append(node.arg)
return params
|
[
"Extract",
"parameters",
"from",
"a",
"function",
"definition"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/formula.py#L100-L110
|
[
"def",
"extract_params",
"(",
"source",
")",
":",
"funcdef",
"=",
"find_funcdef",
"(",
"source",
")",
"params",
"=",
"[",
"]",
"for",
"node",
"in",
"ast",
".",
"walk",
"(",
"funcdef",
".",
"args",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"ast",
".",
"arg",
")",
":",
"if",
"node",
".",
"arg",
"not",
"in",
"params",
":",
"params",
".",
"append",
"(",
"node",
".",
"arg",
")",
"return",
"params"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
extract_names
|
Extract names from a function definition
Looks for a function definition in the source.
Only the first function definition is examined.
Returns:
a list names(identifiers) used in the body of the function
excluding function parameters.
|
modelx/core/formula.py
|
def extract_names(source):
"""Extract names from a function definition
Looks for a function definition in the source.
Only the first function definition is examined.
Returns:
a list names(identifiers) used in the body of the function
excluding function parameters.
"""
if source is None:
return None
source = dedent(source)
funcdef = find_funcdef(source)
params = extract_params(source)
names = []
if isinstance(funcdef, ast.FunctionDef):
stmts = funcdef.body
elif isinstance(funcdef, ast.Lambda):
stmts = [funcdef.body]
else:
raise ValueError("must not happen")
for stmt in stmts:
for node in ast.walk(stmt):
if isinstance(node, ast.Name):
if node.id not in names and node.id not in params:
names.append(node.id)
return names
|
def extract_names(source):
"""Extract names from a function definition
Looks for a function definition in the source.
Only the first function definition is examined.
Returns:
a list names(identifiers) used in the body of the function
excluding function parameters.
"""
if source is None:
return None
source = dedent(source)
funcdef = find_funcdef(source)
params = extract_params(source)
names = []
if isinstance(funcdef, ast.FunctionDef):
stmts = funcdef.body
elif isinstance(funcdef, ast.Lambda):
stmts = [funcdef.body]
else:
raise ValueError("must not happen")
for stmt in stmts:
for node in ast.walk(stmt):
if isinstance(node, ast.Name):
if node.id not in names and node.id not in params:
names.append(node.id)
return names
|
[
"Extract",
"names",
"from",
"a",
"function",
"definition"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/formula.py#L113-L144
|
[
"def",
"extract_names",
"(",
"source",
")",
":",
"if",
"source",
"is",
"None",
":",
"return",
"None",
"source",
"=",
"dedent",
"(",
"source",
")",
"funcdef",
"=",
"find_funcdef",
"(",
"source",
")",
"params",
"=",
"extract_params",
"(",
"source",
")",
"names",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"funcdef",
",",
"ast",
".",
"FunctionDef",
")",
":",
"stmts",
"=",
"funcdef",
".",
"body",
"elif",
"isinstance",
"(",
"funcdef",
",",
"ast",
".",
"Lambda",
")",
":",
"stmts",
"=",
"[",
"funcdef",
".",
"body",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"\"must not happen\"",
")",
"for",
"stmt",
"in",
"stmts",
":",
"for",
"node",
"in",
"ast",
".",
"walk",
"(",
"stmt",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"ast",
".",
"Name",
")",
":",
"if",
"node",
".",
"id",
"not",
"in",
"names",
"and",
"node",
".",
"id",
"not",
"in",
"params",
":",
"names",
".",
"append",
"(",
"node",
".",
"id",
")",
"return",
"names"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
is_funcdef
|
True if src is a function definition
|
modelx/core/formula.py
|
def is_funcdef(src):
"""True if src is a function definition"""
module_node = ast.parse(dedent(src))
if len(module_node.body) == 1 and isinstance(
module_node.body[0], ast.FunctionDef
):
return True
else:
return False
|
def is_funcdef(src):
"""True if src is a function definition"""
module_node = ast.parse(dedent(src))
if len(module_node.body) == 1 and isinstance(
module_node.body[0], ast.FunctionDef
):
return True
else:
return False
|
[
"True",
"if",
"src",
"is",
"a",
"function",
"definition"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/formula.py#L219-L229
|
[
"def",
"is_funcdef",
"(",
"src",
")",
":",
"module_node",
"=",
"ast",
".",
"parse",
"(",
"dedent",
"(",
"src",
")",
")",
"if",
"len",
"(",
"module_node",
".",
"body",
")",
"==",
"1",
"and",
"isinstance",
"(",
"module_node",
".",
"body",
"[",
"0",
"]",
",",
"ast",
".",
"FunctionDef",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
remove_decorator
|
Remove decorators from function definition
|
modelx/core/formula.py
|
def remove_decorator(source: str):
"""Remove decorators from function definition"""
lines = source.splitlines()
atok = asttokens.ASTTokens(source, parse=True)
for node in ast.walk(atok.tree):
if isinstance(node, ast.FunctionDef):
break
if node.decorator_list:
deco_first = node.decorator_list[0]
deco_last = node.decorator_list[-1]
line_first = atok.tokens[deco_first.first_token.index - 1].start[0]
line_last = atok.tokens[deco_last.last_token.index + 1].start[0]
lines = lines[:line_first - 1] + lines[line_last:]
return "\n".join(lines) + "\n"
|
def remove_decorator(source: str):
"""Remove decorators from function definition"""
lines = source.splitlines()
atok = asttokens.ASTTokens(source, parse=True)
for node in ast.walk(atok.tree):
if isinstance(node, ast.FunctionDef):
break
if node.decorator_list:
deco_first = node.decorator_list[0]
deco_last = node.decorator_list[-1]
line_first = atok.tokens[deco_first.first_token.index - 1].start[0]
line_last = atok.tokens[deco_last.last_token.index + 1].start[0]
lines = lines[:line_first - 1] + lines[line_last:]
return "\n".join(lines) + "\n"
|
[
"Remove",
"decorators",
"from",
"function",
"definition"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/formula.py#L232-L249
|
[
"def",
"remove_decorator",
"(",
"source",
":",
"str",
")",
":",
"lines",
"=",
"source",
".",
"splitlines",
"(",
")",
"atok",
"=",
"asttokens",
".",
"ASTTokens",
"(",
"source",
",",
"parse",
"=",
"True",
")",
"for",
"node",
"in",
"ast",
".",
"walk",
"(",
"atok",
".",
"tree",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"ast",
".",
"FunctionDef",
")",
":",
"break",
"if",
"node",
".",
"decorator_list",
":",
"deco_first",
"=",
"node",
".",
"decorator_list",
"[",
"0",
"]",
"deco_last",
"=",
"node",
".",
"decorator_list",
"[",
"-",
"1",
"]",
"line_first",
"=",
"atok",
".",
"tokens",
"[",
"deco_first",
".",
"first_token",
".",
"index",
"-",
"1",
"]",
".",
"start",
"[",
"0",
"]",
"line_last",
"=",
"atok",
".",
"tokens",
"[",
"deco_last",
".",
"last_token",
".",
"index",
"+",
"1",
"]",
".",
"start",
"[",
"0",
"]",
"lines",
"=",
"lines",
"[",
":",
"line_first",
"-",
"1",
"]",
"+",
"lines",
"[",
"line_last",
":",
"]",
"return",
"\"\\n\"",
".",
"join",
"(",
"lines",
")",
"+",
"\"\\n\""
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
replace_funcname
|
Replace function name
|
modelx/core/formula.py
|
def replace_funcname(source: str, name: str):
"""Replace function name"""
lines = source.splitlines()
atok = asttokens.ASTTokens(source, parse=True)
for node in ast.walk(atok.tree):
if isinstance(node, ast.FunctionDef):
break
i = node.first_token.index
for i in range(node.first_token.index, node.last_token.index):
if (atok.tokens[i].type == token.NAME
and atok.tokens[i].string == "def"):
break
lineno, col_begin = atok.tokens[i + 1].start
lineno_end, col_end = atok.tokens[i + 1].end
assert lineno == lineno_end
lines[lineno-1] = (
lines[lineno-1][:col_begin] + name + lines[lineno-1][col_end:]
)
return "\n".join(lines) + "\n"
|
def replace_funcname(source: str, name: str):
"""Replace function name"""
lines = source.splitlines()
atok = asttokens.ASTTokens(source, parse=True)
for node in ast.walk(atok.tree):
if isinstance(node, ast.FunctionDef):
break
i = node.first_token.index
for i in range(node.first_token.index, node.last_token.index):
if (atok.tokens[i].type == token.NAME
and atok.tokens[i].string == "def"):
break
lineno, col_begin = atok.tokens[i + 1].start
lineno_end, col_end = atok.tokens[i + 1].end
assert lineno == lineno_end
lines[lineno-1] = (
lines[lineno-1][:col_begin] + name + lines[lineno-1][col_end:]
)
return "\n".join(lines) + "\n"
|
[
"Replace",
"function",
"name"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/formula.py#L252-L277
|
[
"def",
"replace_funcname",
"(",
"source",
":",
"str",
",",
"name",
":",
"str",
")",
":",
"lines",
"=",
"source",
".",
"splitlines",
"(",
")",
"atok",
"=",
"asttokens",
".",
"ASTTokens",
"(",
"source",
",",
"parse",
"=",
"True",
")",
"for",
"node",
"in",
"ast",
".",
"walk",
"(",
"atok",
".",
"tree",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"ast",
".",
"FunctionDef",
")",
":",
"break",
"i",
"=",
"node",
".",
"first_token",
".",
"index",
"for",
"i",
"in",
"range",
"(",
"node",
".",
"first_token",
".",
"index",
",",
"node",
".",
"last_token",
".",
"index",
")",
":",
"if",
"(",
"atok",
".",
"tokens",
"[",
"i",
"]",
".",
"type",
"==",
"token",
".",
"NAME",
"and",
"atok",
".",
"tokens",
"[",
"i",
"]",
".",
"string",
"==",
"\"def\"",
")",
":",
"break",
"lineno",
",",
"col_begin",
"=",
"atok",
".",
"tokens",
"[",
"i",
"+",
"1",
"]",
".",
"start",
"lineno_end",
",",
"col_end",
"=",
"atok",
".",
"tokens",
"[",
"i",
"+",
"1",
"]",
".",
"end",
"assert",
"lineno",
"==",
"lineno_end",
"lines",
"[",
"lineno",
"-",
"1",
"]",
"=",
"(",
"lines",
"[",
"lineno",
"-",
"1",
"]",
"[",
":",
"col_begin",
"]",
"+",
"name",
"+",
"lines",
"[",
"lineno",
"-",
"1",
"]",
"[",
"col_end",
":",
"]",
")",
"return",
"\"\\n\"",
".",
"join",
"(",
"lines",
")",
"+",
"\"\\n\""
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
has_lambda
|
True if only one lambda expression is included
|
modelx/core/formula.py
|
def has_lambda(src):
"""True if only one lambda expression is included"""
module_node = ast.parse(dedent(src))
lambdaexp = [node for node in ast.walk(module_node)
if isinstance(node, ast.Lambda)]
return bool(lambdaexp)
|
def has_lambda(src):
"""True if only one lambda expression is included"""
module_node = ast.parse(dedent(src))
lambdaexp = [node for node in ast.walk(module_node)
if isinstance(node, ast.Lambda)]
return bool(lambdaexp)
|
[
"True",
"if",
"only",
"one",
"lambda",
"expression",
"is",
"included"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/formula.py#L280-L287
|
[
"def",
"has_lambda",
"(",
"src",
")",
":",
"module_node",
"=",
"ast",
".",
"parse",
"(",
"dedent",
"(",
"src",
")",
")",
"lambdaexp",
"=",
"[",
"node",
"for",
"node",
"in",
"ast",
".",
"walk",
"(",
"module_node",
")",
"if",
"isinstance",
"(",
"node",
",",
"ast",
".",
"Lambda",
")",
"]",
"return",
"bool",
"(",
"lambdaexp",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
Formula._reload
|
Reload the source function from the source module.
**Internal use only**
Update the source function of the formula.
This method is used to updated the underlying formula
when the source code of the module in which the source function
is read from is modified.
If the formula was not created from a module, an error is raised.
If ``module_`` is not given, the source module of the formula is
reloaded. If ``module_`` is given and matches the source module,
then the module_ is used without being reloaded.
If ``module_`` is given and does not match the source module of
the formula, an error is raised.
Args:
module_: A ``ModuleSource`` object
Returns:
self
|
modelx/core/formula.py
|
def _reload(self, module=None):
"""Reload the source function from the source module.
**Internal use only**
Update the source function of the formula.
This method is used to updated the underlying formula
when the source code of the module in which the source function
is read from is modified.
If the formula was not created from a module, an error is raised.
If ``module_`` is not given, the source module of the formula is
reloaded. If ``module_`` is given and matches the source module,
then the module_ is used without being reloaded.
If ``module_`` is given and does not match the source module of
the formula, an error is raised.
Args:
module_: A ``ModuleSource`` object
Returns:
self
"""
if self.module is None:
raise RuntimeError
elif module is None:
import importlib
module = ModuleSource(importlib.reload(module))
elif module.name != self.module:
raise RuntimeError
if self.name in module.funcs:
func = module.funcs[self.name]
self.__init__(func=func)
else:
self.__init__(func=NULL_FORMULA)
return self
|
def _reload(self, module=None):
"""Reload the source function from the source module.
**Internal use only**
Update the source function of the formula.
This method is used to updated the underlying formula
when the source code of the module in which the source function
is read from is modified.
If the formula was not created from a module, an error is raised.
If ``module_`` is not given, the source module of the formula is
reloaded. If ``module_`` is given and matches the source module,
then the module_ is used without being reloaded.
If ``module_`` is given and does not match the source module of
the formula, an error is raised.
Args:
module_: A ``ModuleSource`` object
Returns:
self
"""
if self.module is None:
raise RuntimeError
elif module is None:
import importlib
module = ModuleSource(importlib.reload(module))
elif module.name != self.module:
raise RuntimeError
if self.name in module.funcs:
func = module.funcs[self.name]
self.__init__(func=func)
else:
self.__init__(func=NULL_FORMULA)
return self
|
[
"Reload",
"the",
"source",
"function",
"from",
"the",
"source",
"module",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/formula.py#L406-L443
|
[
"def",
"_reload",
"(",
"self",
",",
"module",
"=",
"None",
")",
":",
"if",
"self",
".",
"module",
"is",
"None",
":",
"raise",
"RuntimeError",
"elif",
"module",
"is",
"None",
":",
"import",
"importlib",
"module",
"=",
"ModuleSource",
"(",
"importlib",
".",
"reload",
"(",
"module",
")",
")",
"elif",
"module",
".",
"name",
"!=",
"self",
".",
"module",
":",
"raise",
"RuntimeError",
"if",
"self",
".",
"name",
"in",
"module",
".",
"funcs",
":",
"func",
"=",
"module",
".",
"funcs",
"[",
"self",
".",
"name",
"]",
"self",
".",
"__init__",
"(",
"func",
"=",
"func",
")",
"else",
":",
"self",
".",
"__init__",
"(",
"func",
"=",
"NULL_FORMULA",
")",
"return",
"self"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
get_description
|
Get long description from README.
|
setup.py
|
def get_description():
"""Get long description from README."""
with open(path.join(here, 'README.rst'), 'r') as f:
data = f.read()
return data
|
def get_description():
"""Get long description from README."""
with open(path.join(here, 'README.rst'), 'r') as f:
data = f.read()
return data
|
[
"Get",
"long",
"description",
"from",
"README",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/setup.py#L25-L29
|
[
"def",
"get_description",
"(",
")",
":",
"with",
"open",
"(",
"path",
".",
"join",
"(",
"here",
",",
"'README.rst'",
")",
",",
"'r'",
")",
"as",
"f",
":",
"data",
"=",
"f",
".",
"read",
"(",
")",
"return",
"data"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
CellsView.to_frame
|
Convert the cells in the view into a DataFrame object.
If ``args`` is not given, this method returns a DataFrame that
has an Index or a MultiIndex depending of the number of
cells parameters and columns each of which corresponds to each
cells included in the view.
``args`` can be given to calculate cells values and limit the
DataFrame indexes to the given arguments.
The cells in this view may have different number of parameters,
but parameters shared among multiple cells
must appear in the same position in all the parameter lists.
For example,
Having ``foo()``, ``bar(x)`` and ``baz(x, y=1)`` is okay
because the shared parameter ``x`` is always the first parameter,
but this method does not work if the view has ``quz(x, z=2, y=1)``
cells in addition to the first three cells, because ``y`` appears
in different positions.
Args:
args(optional): multiple arguments,
or an iterator of arguments to the cells.
|
modelx/core/space.py
|
def to_frame(self, *args):
"""Convert the cells in the view into a DataFrame object.
If ``args`` is not given, this method returns a DataFrame that
has an Index or a MultiIndex depending of the number of
cells parameters and columns each of which corresponds to each
cells included in the view.
``args`` can be given to calculate cells values and limit the
DataFrame indexes to the given arguments.
The cells in this view may have different number of parameters,
but parameters shared among multiple cells
must appear in the same position in all the parameter lists.
For example,
Having ``foo()``, ``bar(x)`` and ``baz(x, y=1)`` is okay
because the shared parameter ``x`` is always the first parameter,
but this method does not work if the view has ``quz(x, z=2, y=1)``
cells in addition to the first three cells, because ``y`` appears
in different positions.
Args:
args(optional): multiple arguments,
or an iterator of arguments to the cells.
"""
if sys.version_info < (3, 6, 0):
from collections import OrderedDict
impls = OrderedDict()
for name, obj in self.items():
impls[name] = obj._impl
else:
impls = get_impls(self)
return _to_frame_inner(impls, args)
|
def to_frame(self, *args):
"""Convert the cells in the view into a DataFrame object.
If ``args`` is not given, this method returns a DataFrame that
has an Index or a MultiIndex depending of the number of
cells parameters and columns each of which corresponds to each
cells included in the view.
``args`` can be given to calculate cells values and limit the
DataFrame indexes to the given arguments.
The cells in this view may have different number of parameters,
but parameters shared among multiple cells
must appear in the same position in all the parameter lists.
For example,
Having ``foo()``, ``bar(x)`` and ``baz(x, y=1)`` is okay
because the shared parameter ``x`` is always the first parameter,
but this method does not work if the view has ``quz(x, z=2, y=1)``
cells in addition to the first three cells, because ``y`` appears
in different positions.
Args:
args(optional): multiple arguments,
or an iterator of arguments to the cells.
"""
if sys.version_info < (3, 6, 0):
from collections import OrderedDict
impls = OrderedDict()
for name, obj in self.items():
impls[name] = obj._impl
else:
impls = get_impls(self)
return _to_frame_inner(impls, args)
|
[
"Convert",
"the",
"cells",
"in",
"the",
"view",
"into",
"a",
"DataFrame",
"object",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L149-L183
|
[
"def",
"to_frame",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"6",
",",
"0",
")",
":",
"from",
"collections",
"import",
"OrderedDict",
"impls",
"=",
"OrderedDict",
"(",
")",
"for",
"name",
",",
"obj",
"in",
"self",
".",
"items",
"(",
")",
":",
"impls",
"[",
"name",
"]",
"=",
"obj",
".",
"_impl",
"else",
":",
"impls",
"=",
"get_impls",
"(",
"self",
")",
"return",
"_to_frame_inner",
"(",
"impls",
",",
"args",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
BaseSpace._baseattrs
|
A dict of members expressed in literals
|
modelx/core/space.py
|
def _baseattrs(self):
"""A dict of members expressed in literals"""
result = super()._baseattrs
result["static_spaces"] = self.static_spaces._baseattrs
result["dynamic_spaces"] = self.dynamic_spaces._baseattrs
result["cells"] = self.cells._baseattrs
result["refs"] = self.refs._baseattrs
if self.has_params():
result["params"] = ", ".join(self.parameters)
else:
result["params"] = ""
return result
|
def _baseattrs(self):
"""A dict of members expressed in literals"""
result = super()._baseattrs
result["static_spaces"] = self.static_spaces._baseattrs
result["dynamic_spaces"] = self.dynamic_spaces._baseattrs
result["cells"] = self.cells._baseattrs
result["refs"] = self.refs._baseattrs
if self.has_params():
result["params"] = ", ".join(self.parameters)
else:
result["params"] = ""
return result
|
[
"A",
"dict",
"of",
"members",
"expressed",
"in",
"literals"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L370-L384
|
[
"def",
"_baseattrs",
"(",
"self",
")",
":",
"result",
"=",
"super",
"(",
")",
".",
"_baseattrs",
"result",
"[",
"\"static_spaces\"",
"]",
"=",
"self",
".",
"static_spaces",
".",
"_baseattrs",
"result",
"[",
"\"dynamic_spaces\"",
"]",
"=",
"self",
".",
"dynamic_spaces",
".",
"_baseattrs",
"result",
"[",
"\"cells\"",
"]",
"=",
"self",
".",
"cells",
".",
"_baseattrs",
"result",
"[",
"\"refs\"",
"]",
"=",
"self",
".",
"refs",
".",
"_baseattrs",
"if",
"self",
".",
"has_params",
"(",
")",
":",
"result",
"[",
"\"params\"",
"]",
"=",
"\", \"",
".",
"join",
"(",
"self",
".",
"parameters",
")",
"else",
":",
"result",
"[",
"\"params\"",
"]",
"=",
"\"\"",
"return",
"result"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
StaticSpace.new_cells
|
Create a cells in the space.
Args:
name: If omitted, the model is named automatically ``CellsN``,
where ``N`` is an available number.
func: The function to define the formula of the cells.
Returns:
The new cells.
|
modelx/core/space.py
|
def new_cells(self, name=None, formula=None):
"""Create a cells in the space.
Args:
name: If omitted, the model is named automatically ``CellsN``,
where ``N`` is an available number.
func: The function to define the formula of the cells.
Returns:
The new cells.
"""
# Outside formulas only
return self._impl.new_cells(name, formula).interface
|
def new_cells(self, name=None, formula=None):
"""Create a cells in the space.
Args:
name: If omitted, the model is named automatically ``CellsN``,
where ``N`` is an available number.
func: The function to define the formula of the cells.
Returns:
The new cells.
"""
# Outside formulas only
return self._impl.new_cells(name, formula).interface
|
[
"Create",
"a",
"cells",
"in",
"the",
"space",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L399-L411
|
[
"def",
"new_cells",
"(",
"self",
",",
"name",
"=",
"None",
",",
"formula",
"=",
"None",
")",
":",
"# Outside formulas only",
"return",
"self",
".",
"_impl",
".",
"new_cells",
"(",
"name",
",",
"formula",
")",
".",
"interface"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
StaticSpace.import_funcs
|
Create a cells from a module.
|
modelx/core/space.py
|
def import_funcs(self, module):
"""Create a cells from a module."""
# Outside formulas only
newcells = self._impl.new_cells_from_module(module)
return get_interfaces(newcells)
|
def import_funcs(self, module):
"""Create a cells from a module."""
# Outside formulas only
newcells = self._impl.new_cells_from_module(module)
return get_interfaces(newcells)
|
[
"Create",
"a",
"cells",
"from",
"a",
"module",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L421-L425
|
[
"def",
"import_funcs",
"(",
"self",
",",
"module",
")",
":",
"# Outside formulas only",
"newcells",
"=",
"self",
".",
"_impl",
".",
"new_cells_from_module",
"(",
"module",
")",
"return",
"get_interfaces",
"(",
"newcells",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
StaticSpace.new_cells_from_excel
|
Create multiple cells from an Excel range.
This method reads values from a range in an Excel file,
create cells and populate them with the values in the range.
To use this method, ``openpyxl`` package must be installed.
The Excel file to read data from is specified by ``book``
parameters. The ``range_`` can be a range address, such as "$G4:$K10",
or a named range. In case a range address is given,
``sheet`` must also be given.
By default, cells data are interpreted as being laid out side-by-side.
``names_row`` is a row index (starting from 0) to specify the
row that contains the names of cells and parameters.
Cells and parameter names must be contained in a single row.
``param_cols`` accepts a sequence (such as list or tuple) of
column indexes (starting from 0) that indicate columns that
contain cells arguments.
**2-dimensional cells definitions**
The optional ``names_col`` and ``param_rows`` parameters are used,
when data for one cells spans more than one column.
In such cases, the cells data is 2-dimensional, and
there must be parameter row(s) across the columns
that contain arguments of the parameters.
A sequence of row indexes that indicate parameter rows
is passed to ``param_rows``.
The names of those parameters must be contained in the
same rows as parameter values (arguments), and
``names_col`` is to indicate the column position at which
the parameter names are defined.
**Horizontal arrangement**
By default, cells data are interpreted as being placed
side-by-side, regardless of whether one cells corresponds
to a single column or multiple columns.
``transpose`` parameter is used to alter this orientation,
and if it is set to ``True``, cells values are
interpreted as being placed one above the other.
"row(s)" and "col(s)" in the parameter
names are interpreted inversely, i.e.
all indexes passed to "row(s)" parameters are interpreted
as column indexes,
and all indexes passed to "col(s)" parameters as row indexes.
Args:
book (str): Path to an Excel file.
range_ (str): Range expression, such as "A1", "$G4:$K10",
or named range "NamedRange1".
sheet (str): Sheet name (case ignored).
names_row (optional): an index number indicating
what row contains the names of cells and parameters.
Defaults to the top row (0).
param_cols (optional): a sequence of index numbers
indicating parameter columns.
Defaults to only the leftmost column ([0]).
names_col (optional): an index number, starting from 0,
indicating what column contains additional parameters.
param_rows (optional): a sequence of index numbers, starting from
0, indicating rows of additional parameters, in case cells are
defined in two dimensions.
transpose (optional): Defaults to ``False``.
If set to ``True``, "row(s)" and "col(s)" in the parameter
names are interpreted inversely, i.e.
all indexes passed to "row(s)" parameters are interpreted
as column indexes,
and all indexes passed to "col(s)" parameters as row indexes.
param_order (optional): a sequence to reorder the parameters.
The elements of the sequence are the indexes of ``param_cols``
elements, and optionally the index of ``param_rows`` elements
shifted by the length of ``param_cols``.
|
modelx/core/space.py
|
def new_cells_from_excel(
self,
book,
range_,
sheet=None,
names_row=None,
param_cols=None,
param_order=None,
transpose=False,
names_col=None,
param_rows=None,
):
"""Create multiple cells from an Excel range.
This method reads values from a range in an Excel file,
create cells and populate them with the values in the range.
To use this method, ``openpyxl`` package must be installed.
The Excel file to read data from is specified by ``book``
parameters. The ``range_`` can be a range address, such as "$G4:$K10",
or a named range. In case a range address is given,
``sheet`` must also be given.
By default, cells data are interpreted as being laid out side-by-side.
``names_row`` is a row index (starting from 0) to specify the
row that contains the names of cells and parameters.
Cells and parameter names must be contained in a single row.
``param_cols`` accepts a sequence (such as list or tuple) of
column indexes (starting from 0) that indicate columns that
contain cells arguments.
**2-dimensional cells definitions**
The optional ``names_col`` and ``param_rows`` parameters are used,
when data for one cells spans more than one column.
In such cases, the cells data is 2-dimensional, and
there must be parameter row(s) across the columns
that contain arguments of the parameters.
A sequence of row indexes that indicate parameter rows
is passed to ``param_rows``.
The names of those parameters must be contained in the
same rows as parameter values (arguments), and
``names_col`` is to indicate the column position at which
the parameter names are defined.
**Horizontal arrangement**
By default, cells data are interpreted as being placed
side-by-side, regardless of whether one cells corresponds
to a single column or multiple columns.
``transpose`` parameter is used to alter this orientation,
and if it is set to ``True``, cells values are
interpreted as being placed one above the other.
"row(s)" and "col(s)" in the parameter
names are interpreted inversely, i.e.
all indexes passed to "row(s)" parameters are interpreted
as column indexes,
and all indexes passed to "col(s)" parameters as row indexes.
Args:
book (str): Path to an Excel file.
range_ (str): Range expression, such as "A1", "$G4:$K10",
or named range "NamedRange1".
sheet (str): Sheet name (case ignored).
names_row (optional): an index number indicating
what row contains the names of cells and parameters.
Defaults to the top row (0).
param_cols (optional): a sequence of index numbers
indicating parameter columns.
Defaults to only the leftmost column ([0]).
names_col (optional): an index number, starting from 0,
indicating what column contains additional parameters.
param_rows (optional): a sequence of index numbers, starting from
0, indicating rows of additional parameters, in case cells are
defined in two dimensions.
transpose (optional): Defaults to ``False``.
If set to ``True``, "row(s)" and "col(s)" in the parameter
names are interpreted inversely, i.e.
all indexes passed to "row(s)" parameters are interpreted
as column indexes,
and all indexes passed to "col(s)" parameters as row indexes.
param_order (optional): a sequence to reorder the parameters.
The elements of the sequence are the indexes of ``param_cols``
elements, and optionally the index of ``param_rows`` elements
shifted by the length of ``param_cols``.
"""
return self._impl.new_cells_from_excel(
book,
range_,
sheet,
names_row,
param_cols,
param_order,
transpose,
names_col,
param_rows,
)
|
def new_cells_from_excel(
self,
book,
range_,
sheet=None,
names_row=None,
param_cols=None,
param_order=None,
transpose=False,
names_col=None,
param_rows=None,
):
"""Create multiple cells from an Excel range.
This method reads values from a range in an Excel file,
create cells and populate them with the values in the range.
To use this method, ``openpyxl`` package must be installed.
The Excel file to read data from is specified by ``book``
parameters. The ``range_`` can be a range address, such as "$G4:$K10",
or a named range. In case a range address is given,
``sheet`` must also be given.
By default, cells data are interpreted as being laid out side-by-side.
``names_row`` is a row index (starting from 0) to specify the
row that contains the names of cells and parameters.
Cells and parameter names must be contained in a single row.
``param_cols`` accepts a sequence (such as list or tuple) of
column indexes (starting from 0) that indicate columns that
contain cells arguments.
**2-dimensional cells definitions**
The optional ``names_col`` and ``param_rows`` parameters are used,
when data for one cells spans more than one column.
In such cases, the cells data is 2-dimensional, and
there must be parameter row(s) across the columns
that contain arguments of the parameters.
A sequence of row indexes that indicate parameter rows
is passed to ``param_rows``.
The names of those parameters must be contained in the
same rows as parameter values (arguments), and
``names_col`` is to indicate the column position at which
the parameter names are defined.
**Horizontal arrangement**
By default, cells data are interpreted as being placed
side-by-side, regardless of whether one cells corresponds
to a single column or multiple columns.
``transpose`` parameter is used to alter this orientation,
and if it is set to ``True``, cells values are
interpreted as being placed one above the other.
"row(s)" and "col(s)" in the parameter
names are interpreted inversely, i.e.
all indexes passed to "row(s)" parameters are interpreted
as column indexes,
and all indexes passed to "col(s)" parameters as row indexes.
Args:
book (str): Path to an Excel file.
range_ (str): Range expression, such as "A1", "$G4:$K10",
or named range "NamedRange1".
sheet (str): Sheet name (case ignored).
names_row (optional): an index number indicating
what row contains the names of cells and parameters.
Defaults to the top row (0).
param_cols (optional): a sequence of index numbers
indicating parameter columns.
Defaults to only the leftmost column ([0]).
names_col (optional): an index number, starting from 0,
indicating what column contains additional parameters.
param_rows (optional): a sequence of index numbers, starting from
0, indicating rows of additional parameters, in case cells are
defined in two dimensions.
transpose (optional): Defaults to ``False``.
If set to ``True``, "row(s)" and "col(s)" in the parameter
names are interpreted inversely, i.e.
all indexes passed to "row(s)" parameters are interpreted
as column indexes,
and all indexes passed to "col(s)" parameters as row indexes.
param_order (optional): a sequence to reorder the parameters.
The elements of the sequence are the indexes of ``param_cols``
elements, and optionally the index of ``param_rows`` elements
shifted by the length of ``param_cols``.
"""
return self._impl.new_cells_from_excel(
book,
range_,
sheet,
names_row,
param_cols,
param_order,
transpose,
names_col,
param_rows,
)
|
[
"Create",
"multiple",
"cells",
"from",
"an",
"Excel",
"range",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L461-L558
|
[
"def",
"new_cells_from_excel",
"(",
"self",
",",
"book",
",",
"range_",
",",
"sheet",
"=",
"None",
",",
"names_row",
"=",
"None",
",",
"param_cols",
"=",
"None",
",",
"param_order",
"=",
"None",
",",
"transpose",
"=",
"False",
",",
"names_col",
"=",
"None",
",",
"param_rows",
"=",
"None",
",",
")",
":",
"return",
"self",
".",
"_impl",
".",
"new_cells_from_excel",
"(",
"book",
",",
"range_",
",",
"sheet",
",",
"names_row",
",",
"param_cols",
",",
"param_order",
",",
"transpose",
",",
"names_col",
",",
"param_rows",
",",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
BaseSpaceImpl.get_object
|
Retrieve an object by a dotted name relative to the space.
|
modelx/core/space.py
|
def get_object(self, name):
"""Retrieve an object by a dotted name relative to the space."""
parts = name.split(".")
child = parts.pop(0)
if parts:
return self.spaces[child].get_object(".".join(parts))
else:
return self._namespace_impl[child]
|
def get_object(self, name):
"""Retrieve an object by a dotted name relative to the space."""
parts = name.split(".")
child = parts.pop(0)
if parts:
return self.spaces[child].get_object(".".join(parts))
else:
return self._namespace_impl[child]
|
[
"Retrieve",
"an",
"object",
"by",
"a",
"dotted",
"name",
"relative",
"to",
"the",
"space",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L920-L929
|
[
"def",
"get_object",
"(",
"self",
",",
"name",
")",
":",
"parts",
"=",
"name",
".",
"split",
"(",
"\".\"",
")",
"child",
"=",
"parts",
".",
"pop",
"(",
"0",
")",
"if",
"parts",
":",
"return",
"self",
".",
"spaces",
"[",
"child",
"]",
".",
"get_object",
"(",
"\".\"",
".",
"join",
"(",
"parts",
")",
")",
"else",
":",
"return",
"self",
".",
"_namespace_impl",
"[",
"child",
"]"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
BaseSpaceImpl._get_dynamic_base
|
Create or get the base space from a list of spaces
if a direct base space in `bases` is dynamic, replace it with
its base.
|
modelx/core/space.py
|
def _get_dynamic_base(self, bases_):
"""Create or get the base space from a list of spaces
if a direct base space in `bases` is dynamic, replace it with
its base.
"""
bases = tuple(
base.bases[0] if base.is_dynamic() else base for base in bases_
)
if len(bases) == 1:
return bases[0]
elif len(bases) > 1:
return self.model.get_dynamic_base(bases)
else:
RuntimeError("must not happen")
|
def _get_dynamic_base(self, bases_):
"""Create or get the base space from a list of spaces
if a direct base space in `bases` is dynamic, replace it with
its base.
"""
bases = tuple(
base.bases[0] if base.is_dynamic() else base for base in bases_
)
if len(bases) == 1:
return bases[0]
elif len(bases) > 1:
return self.model.get_dynamic_base(bases)
else:
RuntimeError("must not happen")
|
[
"Create",
"or",
"get",
"the",
"base",
"space",
"from",
"a",
"list",
"of",
"spaces"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L947-L964
|
[
"def",
"_get_dynamic_base",
"(",
"self",
",",
"bases_",
")",
":",
"bases",
"=",
"tuple",
"(",
"base",
".",
"bases",
"[",
"0",
"]",
"if",
"base",
".",
"is_dynamic",
"(",
")",
"else",
"base",
"for",
"base",
"in",
"bases_",
")",
"if",
"len",
"(",
"bases",
")",
"==",
"1",
":",
"return",
"bases",
"[",
"0",
"]",
"elif",
"len",
"(",
"bases",
")",
">",
"1",
":",
"return",
"self",
".",
"model",
".",
"get_dynamic_base",
"(",
"bases",
")",
"else",
":",
"RuntimeError",
"(",
"\"must not happen\"",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
BaseSpaceImpl._new_dynspace
|
Create a new dynamic root space.
|
modelx/core/space.py
|
def _new_dynspace(
self,
name=None,
bases=None,
formula=None,
refs=None,
arguments=None,
source=None,
):
"""Create a new dynamic root space."""
if name is None:
name = self.spacenamer.get_next(self.namespace)
if name in self.namespace:
raise ValueError("Name '%s' already exists." % name)
if not is_valid_name(name):
raise ValueError("Invalid name '%s'." % name)
space = RootDynamicSpaceImpl(
parent=self,
name=name,
formula=formula,
refs=refs,
source=source,
arguments=arguments,
)
space.is_derived = False
self._set_space(space)
if bases: # i.e. not []
dynbase = self._get_dynamic_base(bases)
space._dynbase = dynbase
dynbase._dynamic_subs.append(space)
return space
|
def _new_dynspace(
self,
name=None,
bases=None,
formula=None,
refs=None,
arguments=None,
source=None,
):
"""Create a new dynamic root space."""
if name is None:
name = self.spacenamer.get_next(self.namespace)
if name in self.namespace:
raise ValueError("Name '%s' already exists." % name)
if not is_valid_name(name):
raise ValueError("Invalid name '%s'." % name)
space = RootDynamicSpaceImpl(
parent=self,
name=name,
formula=formula,
refs=refs,
source=source,
arguments=arguments,
)
space.is_derived = False
self._set_space(space)
if bases: # i.e. not []
dynbase = self._get_dynamic_base(bases)
space._dynbase = dynbase
dynbase._dynamic_subs.append(space)
return space
|
[
"Create",
"a",
"new",
"dynamic",
"root",
"space",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L966-L1002
|
[
"def",
"_new_dynspace",
"(",
"self",
",",
"name",
"=",
"None",
",",
"bases",
"=",
"None",
",",
"formula",
"=",
"None",
",",
"refs",
"=",
"None",
",",
"arguments",
"=",
"None",
",",
"source",
"=",
"None",
",",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"self",
".",
"spacenamer",
".",
"get_next",
"(",
"self",
".",
"namespace",
")",
"if",
"name",
"in",
"self",
".",
"namespace",
":",
"raise",
"ValueError",
"(",
"\"Name '%s' already exists.\"",
"%",
"name",
")",
"if",
"not",
"is_valid_name",
"(",
"name",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid name '%s'.\"",
"%",
"name",
")",
"space",
"=",
"RootDynamicSpaceImpl",
"(",
"parent",
"=",
"self",
",",
"name",
"=",
"name",
",",
"formula",
"=",
"formula",
",",
"refs",
"=",
"refs",
",",
"source",
"=",
"source",
",",
"arguments",
"=",
"arguments",
",",
")",
"space",
".",
"is_derived",
"=",
"False",
"self",
".",
"_set_space",
"(",
"space",
")",
"if",
"bases",
":",
"# i.e. not []",
"dynbase",
"=",
"self",
".",
"_get_dynamic_base",
"(",
"bases",
")",
"space",
".",
"_dynbase",
"=",
"dynbase",
"dynbase",
".",
"_dynamic_subs",
".",
"append",
"(",
"space",
")",
"return",
"space"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
BaseSpaceImpl.get_dynspace
|
Create a dynamic root space
Called from interface methods
|
modelx/core/space.py
|
def get_dynspace(self, args, kwargs=None):
"""Create a dynamic root space
Called from interface methods
"""
node = get_node(self, *convert_args(args, kwargs))
key = node[KEY]
if key in self.param_spaces:
return self.param_spaces[key]
else:
last_self = self.system.self
self.system.self = self
try:
space_args = self.eval_formula(node)
finally:
self.system.self = last_self
if space_args is None:
space_args = {"bases": [self]} # Default
else:
if "bases" in space_args:
bases = get_impls(space_args["bases"])
if isinstance(bases, StaticSpaceImpl):
space_args["bases"] = [bases]
elif bases is None:
space_args["bases"] = [self] # Default
else:
space_args["bases"] = bases
else:
space_args["bases"] = [self]
space_args["arguments"] = node_get_args(node)
space = self._new_dynspace(**space_args)
self.param_spaces[key] = space
space.inherit(clear_value=False)
return space
|
def get_dynspace(self, args, kwargs=None):
"""Create a dynamic root space
Called from interface methods
"""
node = get_node(self, *convert_args(args, kwargs))
key = node[KEY]
if key in self.param_spaces:
return self.param_spaces[key]
else:
last_self = self.system.self
self.system.self = self
try:
space_args = self.eval_formula(node)
finally:
self.system.self = last_self
if space_args is None:
space_args = {"bases": [self]} # Default
else:
if "bases" in space_args:
bases = get_impls(space_args["bases"])
if isinstance(bases, StaticSpaceImpl):
space_args["bases"] = [bases]
elif bases is None:
space_args["bases"] = [self] # Default
else:
space_args["bases"] = bases
else:
space_args["bases"] = [self]
space_args["arguments"] = node_get_args(node)
space = self._new_dynspace(**space_args)
self.param_spaces[key] = space
space.inherit(clear_value=False)
return space
|
[
"Create",
"a",
"dynamic",
"root",
"space"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L1004-L1044
|
[
"def",
"get_dynspace",
"(",
"self",
",",
"args",
",",
"kwargs",
"=",
"None",
")",
":",
"node",
"=",
"get_node",
"(",
"self",
",",
"*",
"convert_args",
"(",
"args",
",",
"kwargs",
")",
")",
"key",
"=",
"node",
"[",
"KEY",
"]",
"if",
"key",
"in",
"self",
".",
"param_spaces",
":",
"return",
"self",
".",
"param_spaces",
"[",
"key",
"]",
"else",
":",
"last_self",
"=",
"self",
".",
"system",
".",
"self",
"self",
".",
"system",
".",
"self",
"=",
"self",
"try",
":",
"space_args",
"=",
"self",
".",
"eval_formula",
"(",
"node",
")",
"finally",
":",
"self",
".",
"system",
".",
"self",
"=",
"last_self",
"if",
"space_args",
"is",
"None",
":",
"space_args",
"=",
"{",
"\"bases\"",
":",
"[",
"self",
"]",
"}",
"# Default",
"else",
":",
"if",
"\"bases\"",
"in",
"space_args",
":",
"bases",
"=",
"get_impls",
"(",
"space_args",
"[",
"\"bases\"",
"]",
")",
"if",
"isinstance",
"(",
"bases",
",",
"StaticSpaceImpl",
")",
":",
"space_args",
"[",
"\"bases\"",
"]",
"=",
"[",
"bases",
"]",
"elif",
"bases",
"is",
"None",
":",
"space_args",
"[",
"\"bases\"",
"]",
"=",
"[",
"self",
"]",
"# Default",
"else",
":",
"space_args",
"[",
"\"bases\"",
"]",
"=",
"bases",
"else",
":",
"space_args",
"[",
"\"bases\"",
"]",
"=",
"[",
"self",
"]",
"space_args",
"[",
"\"arguments\"",
"]",
"=",
"node_get_args",
"(",
"node",
")",
"space",
"=",
"self",
".",
"_new_dynspace",
"(",
"*",
"*",
"space_args",
")",
"self",
".",
"param_spaces",
"[",
"key",
"]",
"=",
"space",
"space",
".",
"inherit",
"(",
"clear_value",
"=",
"False",
")",
"return",
"space"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
BaseSpaceImpl.restore_state
|
Called after unpickling to restore some attributes manually.
|
modelx/core/space.py
|
def restore_state(self, system):
"""Called after unpickling to restore some attributes manually."""
super().restore_state(system)
BaseSpaceContainerImpl.restore_state(self, system)
for cells in self._cells.values():
cells.restore_state(system)
|
def restore_state(self, system):
"""Called after unpickling to restore some attributes manually."""
super().restore_state(system)
BaseSpaceContainerImpl.restore_state(self, system)
for cells in self._cells.values():
cells.restore_state(system)
|
[
"Called",
"after",
"unpickling",
"to",
"restore",
"some",
"attributes",
"manually",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L1075-L1081
|
[
"def",
"restore_state",
"(",
"self",
",",
"system",
")",
":",
"super",
"(",
")",
".",
"restore_state",
"(",
"system",
")",
"BaseSpaceContainerImpl",
".",
"restore_state",
"(",
"self",
",",
"system",
")",
"for",
"cells",
"in",
"self",
".",
"_cells",
".",
"values",
"(",
")",
":",
"cells",
".",
"restore_state",
"(",
"system",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
StaticSpaceImpl.new_cells_from_excel
|
Create multiple cells from an Excel range.
Args:
book (str): Path to an Excel file.
range_ (str): Range expression, such as "A1", "$G4:$K10",
or named range "NamedRange1".
sheet (str): Sheet name (case ignored).
names_row: Cells names in a sequence, or an integer number, or
a string expression indicating row (or column depending on
```orientation```) to read cells names from.
param_cols: a sequence of them
indicating parameter columns (or rows depending on ```
orientation```)
param_order: a sequence of integers representing
the order of params and extra_params.
transpose: in which direction 'vertical' or 'horizontal'
names_col: a string or a list of names of the extra params.
param_rows: integer or string expression, or a sequence of them
indicating row (or column) to be interpreted as parameters.
|
modelx/core/space.py
|
def new_cells_from_excel(
self,
book,
range_,
sheet=None,
names_row=None,
param_cols=None,
param_order=None,
transpose=False,
names_col=None,
param_rows=None,
):
"""Create multiple cells from an Excel range.
Args:
book (str): Path to an Excel file.
range_ (str): Range expression, such as "A1", "$G4:$K10",
or named range "NamedRange1".
sheet (str): Sheet name (case ignored).
names_row: Cells names in a sequence, or an integer number, or
a string expression indicating row (or column depending on
```orientation```) to read cells names from.
param_cols: a sequence of them
indicating parameter columns (or rows depending on ```
orientation```)
param_order: a sequence of integers representing
the order of params and extra_params.
transpose: in which direction 'vertical' or 'horizontal'
names_col: a string or a list of names of the extra params.
param_rows: integer or string expression, or a sequence of them
indicating row (or column) to be interpreted as parameters.
"""
import modelx.io.excel as xl
cellstable = xl.CellsTable(
book,
range_,
sheet,
names_row,
param_cols,
param_order,
transpose,
names_col,
param_rows,
)
if cellstable.param_names:
sig = "=None, ".join(cellstable.param_names) + "=None"
else:
sig = ""
blank_func = "def _blank_func(" + sig + "): pass"
for cellsdata in cellstable.items():
cells = self.new_cells(name=cellsdata.name, formula=blank_func)
for args, value in cellsdata.items():
cells.set_value(args, value)
|
def new_cells_from_excel(
self,
book,
range_,
sheet=None,
names_row=None,
param_cols=None,
param_order=None,
transpose=False,
names_col=None,
param_rows=None,
):
"""Create multiple cells from an Excel range.
Args:
book (str): Path to an Excel file.
range_ (str): Range expression, such as "A1", "$G4:$K10",
or named range "NamedRange1".
sheet (str): Sheet name (case ignored).
names_row: Cells names in a sequence, or an integer number, or
a string expression indicating row (or column depending on
```orientation```) to read cells names from.
param_cols: a sequence of them
indicating parameter columns (or rows depending on ```
orientation```)
param_order: a sequence of integers representing
the order of params and extra_params.
transpose: in which direction 'vertical' or 'horizontal'
names_col: a string or a list of names of the extra params.
param_rows: integer or string expression, or a sequence of them
indicating row (or column) to be interpreted as parameters.
"""
import modelx.io.excel as xl
cellstable = xl.CellsTable(
book,
range_,
sheet,
names_row,
param_cols,
param_order,
transpose,
names_col,
param_rows,
)
if cellstable.param_names:
sig = "=None, ".join(cellstable.param_names) + "=None"
else:
sig = ""
blank_func = "def _blank_func(" + sig + "): pass"
for cellsdata in cellstable.items():
cells = self.new_cells(name=cellsdata.name, formula=blank_func)
for args, value in cellsdata.items():
cells.set_value(args, value)
|
[
"Create",
"multiple",
"cells",
"from",
"an",
"Excel",
"range",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L1172-L1228
|
[
"def",
"new_cells_from_excel",
"(",
"self",
",",
"book",
",",
"range_",
",",
"sheet",
"=",
"None",
",",
"names_row",
"=",
"None",
",",
"param_cols",
"=",
"None",
",",
"param_order",
"=",
"None",
",",
"transpose",
"=",
"False",
",",
"names_col",
"=",
"None",
",",
"param_rows",
"=",
"None",
",",
")",
":",
"import",
"modelx",
".",
"io",
".",
"excel",
"as",
"xl",
"cellstable",
"=",
"xl",
".",
"CellsTable",
"(",
"book",
",",
"range_",
",",
"sheet",
",",
"names_row",
",",
"param_cols",
",",
"param_order",
",",
"transpose",
",",
"names_col",
",",
"param_rows",
",",
")",
"if",
"cellstable",
".",
"param_names",
":",
"sig",
"=",
"\"=None, \"",
".",
"join",
"(",
"cellstable",
".",
"param_names",
")",
"+",
"\"=None\"",
"else",
":",
"sig",
"=",
"\"\"",
"blank_func",
"=",
"\"def _blank_func(\"",
"+",
"sig",
"+",
"\"): pass\"",
"for",
"cellsdata",
"in",
"cellstable",
".",
"items",
"(",
")",
":",
"cells",
"=",
"self",
".",
"new_cells",
"(",
"name",
"=",
"cellsdata",
".",
"name",
",",
"formula",
"=",
"blank_func",
")",
"for",
"args",
",",
"value",
"in",
"cellsdata",
".",
"items",
"(",
")",
":",
"cells",
".",
"set_value",
"(",
"args",
",",
"value",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
StaticSpaceImpl.set_attr
|
Implementation of attribute setting
``space.name = value`` by user script
Called from ``Space.__setattr__``
|
modelx/core/space.py
|
def set_attr(self, name, value):
"""Implementation of attribute setting
``space.name = value`` by user script
Called from ``Space.__setattr__``
"""
if not is_valid_name(name):
raise ValueError("Invalid name '%s'" % name)
if name in self.namespace:
if name in self.refs:
if name in self.self_refs:
self.new_ref(name, value)
else:
raise KeyError("Ref '%s' cannot be changed" % name)
elif name in self.cells:
if self.cells[name].is_scalar():
self.cells[name].set_value((), value)
else:
raise AttributeError("Cells '%s' is not a scalar." % name)
else:
raise ValueError
else:
self.new_ref(name, value)
|
def set_attr(self, name, value):
"""Implementation of attribute setting
``space.name = value`` by user script
Called from ``Space.__setattr__``
"""
if not is_valid_name(name):
raise ValueError("Invalid name '%s'" % name)
if name in self.namespace:
if name in self.refs:
if name in self.self_refs:
self.new_ref(name, value)
else:
raise KeyError("Ref '%s' cannot be changed" % name)
elif name in self.cells:
if self.cells[name].is_scalar():
self.cells[name].set_value((), value)
else:
raise AttributeError("Cells '%s' is not a scalar." % name)
else:
raise ValueError
else:
self.new_ref(name, value)
|
[
"Implementation",
"of",
"attribute",
"setting"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L1241-L1265
|
[
"def",
"set_attr",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"not",
"is_valid_name",
"(",
"name",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid name '%s'\"",
"%",
"name",
")",
"if",
"name",
"in",
"self",
".",
"namespace",
":",
"if",
"name",
"in",
"self",
".",
"refs",
":",
"if",
"name",
"in",
"self",
".",
"self_refs",
":",
"self",
".",
"new_ref",
"(",
"name",
",",
"value",
")",
"else",
":",
"raise",
"KeyError",
"(",
"\"Ref '%s' cannot be changed\"",
"%",
"name",
")",
"elif",
"name",
"in",
"self",
".",
"cells",
":",
"if",
"self",
".",
"cells",
"[",
"name",
"]",
".",
"is_scalar",
"(",
")",
":",
"self",
".",
"cells",
"[",
"name",
"]",
".",
"set_value",
"(",
"(",
")",
",",
"value",
")",
"else",
":",
"raise",
"AttributeError",
"(",
"\"Cells '%s' is not a scalar.\"",
"%",
"name",
")",
"else",
":",
"raise",
"ValueError",
"else",
":",
"self",
".",
"new_ref",
"(",
"name",
",",
"value",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
StaticSpaceImpl.del_attr
|
Implementation of attribute deletion
``del space.name`` by user script
Called from ``StaticSpace.__delattr__``
|
modelx/core/space.py
|
def del_attr(self, name):
"""Implementation of attribute deletion
``del space.name`` by user script
Called from ``StaticSpace.__delattr__``
"""
if name in self.namespace:
if name in self.cells:
self.del_cells(name)
elif name in self.spaces:
self.del_space(name)
elif name in self.refs:
self.del_ref(name)
else:
raise RuntimeError("Must not happen")
else:
raise KeyError("'%s' not found in Space '%s'" % (name, self.name))
|
def del_attr(self, name):
"""Implementation of attribute deletion
``del space.name`` by user script
Called from ``StaticSpace.__delattr__``
"""
if name in self.namespace:
if name in self.cells:
self.del_cells(name)
elif name in self.spaces:
self.del_space(name)
elif name in self.refs:
self.del_ref(name)
else:
raise RuntimeError("Must not happen")
else:
raise KeyError("'%s' not found in Space '%s'" % (name, self.name))
|
[
"Implementation",
"of",
"attribute",
"deletion"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L1267-L1283
|
[
"def",
"del_attr",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"namespace",
":",
"if",
"name",
"in",
"self",
".",
"cells",
":",
"self",
".",
"del_cells",
"(",
"name",
")",
"elif",
"name",
"in",
"self",
".",
"spaces",
":",
"self",
".",
"del_space",
"(",
"name",
")",
"elif",
"name",
"in",
"self",
".",
"refs",
":",
"self",
".",
"del_ref",
"(",
"name",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"Must not happen\"",
")",
"else",
":",
"raise",
"KeyError",
"(",
"\"'%s' not found in Space '%s'\"",
"%",
"(",
"name",
",",
"self",
".",
"name",
")",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
StaticSpaceImpl.del_space
|
Delete a space.
|
modelx/core/space.py
|
def del_space(self, name):
"""Delete a space."""
if name not in self.spaces:
raise ValueError("Space '%s' does not exist" % name)
if name in self.static_spaces:
space = self.static_spaces[name]
if space.is_derived:
raise ValueError(
"%s has derived spaces" % repr(space.interface)
)
else:
self.static_spaces.del_item(name)
self.model.spacegraph.remove_node(space)
self.inherit()
self.model.spacegraph.update_subspaces(self)
# TODO: Destroy space
elif name in self.dynamic_spaces:
# TODO: Destroy space
self.dynamic_spaces.del_item(name)
else:
raise ValueError("Derived cells cannot be deleted")
|
def del_space(self, name):
"""Delete a space."""
if name not in self.spaces:
raise ValueError("Space '%s' does not exist" % name)
if name in self.static_spaces:
space = self.static_spaces[name]
if space.is_derived:
raise ValueError(
"%s has derived spaces" % repr(space.interface)
)
else:
self.static_spaces.del_item(name)
self.model.spacegraph.remove_node(space)
self.inherit()
self.model.spacegraph.update_subspaces(self)
# TODO: Destroy space
elif name in self.dynamic_spaces:
# TODO: Destroy space
self.dynamic_spaces.del_item(name)
else:
raise ValueError("Derived cells cannot be deleted")
|
[
"Delete",
"a",
"space",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L1316-L1339
|
[
"def",
"del_space",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"spaces",
":",
"raise",
"ValueError",
"(",
"\"Space '%s' does not exist\"",
"%",
"name",
")",
"if",
"name",
"in",
"self",
".",
"static_spaces",
":",
"space",
"=",
"self",
".",
"static_spaces",
"[",
"name",
"]",
"if",
"space",
".",
"is_derived",
":",
"raise",
"ValueError",
"(",
"\"%s has derived spaces\"",
"%",
"repr",
"(",
"space",
".",
"interface",
")",
")",
"else",
":",
"self",
".",
"static_spaces",
".",
"del_item",
"(",
"name",
")",
"self",
".",
"model",
".",
"spacegraph",
".",
"remove_node",
"(",
"space",
")",
"self",
".",
"inherit",
"(",
")",
"self",
".",
"model",
".",
"spacegraph",
".",
"update_subspaces",
"(",
"self",
")",
"# TODO: Destroy space",
"elif",
"name",
"in",
"self",
".",
"dynamic_spaces",
":",
"# TODO: Destroy space",
"self",
".",
"dynamic_spaces",
".",
"del_item",
"(",
"name",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Derived cells cannot be deleted\"",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
StaticSpaceImpl.del_cells
|
Implementation of cells deletion
``del space.name`` where name is a cells, or
``del space.cells['name']``
|
modelx/core/space.py
|
def del_cells(self, name):
"""Implementation of cells deletion
``del space.name`` where name is a cells, or
``del space.cells['name']``
"""
if name in self.cells:
cells = self.cells[name]
self.cells.del_item(name)
self.inherit()
self.model.spacegraph.update_subspaces(self)
elif name in self.dynamic_spaces:
cells = self.dynamic_spaces.pop(name)
self.dynamic_spaces.set_update()
else:
raise KeyError("Cells '%s' does not exist" % name)
NullImpl(cells)
|
def del_cells(self, name):
"""Implementation of cells deletion
``del space.name`` where name is a cells, or
``del space.cells['name']``
"""
if name in self.cells:
cells = self.cells[name]
self.cells.del_item(name)
self.inherit()
self.model.spacegraph.update_subspaces(self)
elif name in self.dynamic_spaces:
cells = self.dynamic_spaces.pop(name)
self.dynamic_spaces.set_update()
else:
raise KeyError("Cells '%s' does not exist" % name)
NullImpl(cells)
|
[
"Implementation",
"of",
"cells",
"deletion"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L1341-L1360
|
[
"def",
"del_cells",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"cells",
":",
"cells",
"=",
"self",
".",
"cells",
"[",
"name",
"]",
"self",
".",
"cells",
".",
"del_item",
"(",
"name",
")",
"self",
".",
"inherit",
"(",
")",
"self",
".",
"model",
".",
"spacegraph",
".",
"update_subspaces",
"(",
"self",
")",
"elif",
"name",
"in",
"self",
".",
"dynamic_spaces",
":",
"cells",
"=",
"self",
".",
"dynamic_spaces",
".",
"pop",
"(",
"name",
")",
"self",
".",
"dynamic_spaces",
".",
"set_update",
"(",
")",
"else",
":",
"raise",
"KeyError",
"(",
"\"Cells '%s' does not exist\"",
"%",
"name",
")",
"NullImpl",
"(",
"cells",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
RootDynamicSpaceImpl.evalrepr
|
Evaluable repr
|
modelx/core/space.py
|
def evalrepr(self):
"""Evaluable repr"""
args = [repr(arg) for arg in get_interfaces(self.argvalues)]
param = ", ".join(args)
return "%s(%s)" % (self.parent.evalrepr, param)
|
def evalrepr(self):
"""Evaluable repr"""
args = [repr(arg) for arg in get_interfaces(self.argvalues)]
param = ", ".join(args)
return "%s(%s)" % (self.parent.evalrepr, param)
|
[
"Evaluable",
"repr"
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/space.py#L1576-L1580
|
[
"def",
"evalrepr",
"(",
"self",
")",
":",
"args",
"=",
"[",
"repr",
"(",
"arg",
")",
"for",
"arg",
"in",
"get_interfaces",
"(",
"self",
".",
"argvalues",
")",
"]",
"param",
"=",
"\", \"",
".",
"join",
"(",
"args",
")",
"return",
"\"%s(%s)\"",
"%",
"(",
"self",
".",
"parent",
".",
"evalrepr",
",",
"param",
")"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
valid
|
cellsiter_to_dataframe
|
Convert multiple cells to a frame.
If args is an empty sequence, all values are included.
If args is specified, cellsiter must have shareable parameters.
Args:
cellsiter: A mapping from cells names to CellsImpl objects.
args: A sequence of arguments
|
modelx/io/pandas.py
|
def cellsiter_to_dataframe(cellsiter, args, drop_allna=True):
"""Convert multiple cells to a frame.
If args is an empty sequence, all values are included.
If args is specified, cellsiter must have shareable parameters.
Args:
cellsiter: A mapping from cells names to CellsImpl objects.
args: A sequence of arguments
"""
from modelx.core.cells import shareable_parameters
if len(args):
indexes = shareable_parameters(cellsiter)
else:
indexes = get_all_params(cellsiter.values())
result = None
for cells in cellsiter.values():
df = cells_to_dataframe(cells, args)
if drop_allna and df.isnull().all().all():
continue # Ignore all NA or empty
if df.index.names != [None]:
if isinstance(df.index, pd.MultiIndex):
if _pd_ver < (0, 20):
df = _reset_naindex(df)
df = df.reset_index()
missing_params = set(indexes) - set(df)
for params in missing_params:
df[params] = np.nan
if result is None:
result = df
else:
try:
result = pd.merge(result, df, how="outer")
except MergeError:
# When no common column exists, i.e. all cells are scalars.
result = pd.concat([result, df], axis=1)
except ValueError:
# When common columns are not coercible (numeric vs object),
# Make the numeric column object type
cols = set(result.columns) & set(df.columns)
for col in cols:
# When only either of them has object dtype
if (
len(
[
str(frame[col].dtype)
for frame in (result, df)
if str(frame[col].dtype) == "object"
]
)
== 1
):
if str(result[col].dtype) == "object":
frame = df
else:
frame = result
frame[[col]] = frame[col].astype("object")
# Try again
result = pd.merge(result, df, how="outer")
if result is None:
return pd.DataFrame()
else:
return result.set_index(indexes) if indexes else result
|
def cellsiter_to_dataframe(cellsiter, args, drop_allna=True):
"""Convert multiple cells to a frame.
If args is an empty sequence, all values are included.
If args is specified, cellsiter must have shareable parameters.
Args:
cellsiter: A mapping from cells names to CellsImpl objects.
args: A sequence of arguments
"""
from modelx.core.cells import shareable_parameters
if len(args):
indexes = shareable_parameters(cellsiter)
else:
indexes = get_all_params(cellsiter.values())
result = None
for cells in cellsiter.values():
df = cells_to_dataframe(cells, args)
if drop_allna and df.isnull().all().all():
continue # Ignore all NA or empty
if df.index.names != [None]:
if isinstance(df.index, pd.MultiIndex):
if _pd_ver < (0, 20):
df = _reset_naindex(df)
df = df.reset_index()
missing_params = set(indexes) - set(df)
for params in missing_params:
df[params] = np.nan
if result is None:
result = df
else:
try:
result = pd.merge(result, df, how="outer")
except MergeError:
# When no common column exists, i.e. all cells are scalars.
result = pd.concat([result, df], axis=1)
except ValueError:
# When common columns are not coercible (numeric vs object),
# Make the numeric column object type
cols = set(result.columns) & set(df.columns)
for col in cols:
# When only either of them has object dtype
if (
len(
[
str(frame[col].dtype)
for frame in (result, df)
if str(frame[col].dtype) == "object"
]
)
== 1
):
if str(result[col].dtype) == "object":
frame = df
else:
frame = result
frame[[col]] = frame[col].astype("object")
# Try again
result = pd.merge(result, df, how="outer")
if result is None:
return pd.DataFrame()
else:
return result.set_index(indexes) if indexes else result
|
[
"Convert",
"multiple",
"cells",
"to",
"a",
"frame",
"."
] |
fumitoh/modelx
|
python
|
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/io/pandas.py#L44-L119
|
[
"def",
"cellsiter_to_dataframe",
"(",
"cellsiter",
",",
"args",
",",
"drop_allna",
"=",
"True",
")",
":",
"from",
"modelx",
".",
"core",
".",
"cells",
"import",
"shareable_parameters",
"if",
"len",
"(",
"args",
")",
":",
"indexes",
"=",
"shareable_parameters",
"(",
"cellsiter",
")",
"else",
":",
"indexes",
"=",
"get_all_params",
"(",
"cellsiter",
".",
"values",
"(",
")",
")",
"result",
"=",
"None",
"for",
"cells",
"in",
"cellsiter",
".",
"values",
"(",
")",
":",
"df",
"=",
"cells_to_dataframe",
"(",
"cells",
",",
"args",
")",
"if",
"drop_allna",
"and",
"df",
".",
"isnull",
"(",
")",
".",
"all",
"(",
")",
".",
"all",
"(",
")",
":",
"continue",
"# Ignore all NA or empty",
"if",
"df",
".",
"index",
".",
"names",
"!=",
"[",
"None",
"]",
":",
"if",
"isinstance",
"(",
"df",
".",
"index",
",",
"pd",
".",
"MultiIndex",
")",
":",
"if",
"_pd_ver",
"<",
"(",
"0",
",",
"20",
")",
":",
"df",
"=",
"_reset_naindex",
"(",
"df",
")",
"df",
"=",
"df",
".",
"reset_index",
"(",
")",
"missing_params",
"=",
"set",
"(",
"indexes",
")",
"-",
"set",
"(",
"df",
")",
"for",
"params",
"in",
"missing_params",
":",
"df",
"[",
"params",
"]",
"=",
"np",
".",
"nan",
"if",
"result",
"is",
"None",
":",
"result",
"=",
"df",
"else",
":",
"try",
":",
"result",
"=",
"pd",
".",
"merge",
"(",
"result",
",",
"df",
",",
"how",
"=",
"\"outer\"",
")",
"except",
"MergeError",
":",
"# When no common column exists, i.e. all cells are scalars.",
"result",
"=",
"pd",
".",
"concat",
"(",
"[",
"result",
",",
"df",
"]",
",",
"axis",
"=",
"1",
")",
"except",
"ValueError",
":",
"# When common columns are not coercible (numeric vs object),",
"# Make the numeric column object type",
"cols",
"=",
"set",
"(",
"result",
".",
"columns",
")",
"&",
"set",
"(",
"df",
".",
"columns",
")",
"for",
"col",
"in",
"cols",
":",
"# When only either of them has object dtype",
"if",
"(",
"len",
"(",
"[",
"str",
"(",
"frame",
"[",
"col",
"]",
".",
"dtype",
")",
"for",
"frame",
"in",
"(",
"result",
",",
"df",
")",
"if",
"str",
"(",
"frame",
"[",
"col",
"]",
".",
"dtype",
")",
"==",
"\"object\"",
"]",
")",
"==",
"1",
")",
":",
"if",
"str",
"(",
"result",
"[",
"col",
"]",
".",
"dtype",
")",
"==",
"\"object\"",
":",
"frame",
"=",
"df",
"else",
":",
"frame",
"=",
"result",
"frame",
"[",
"[",
"col",
"]",
"]",
"=",
"frame",
"[",
"col",
"]",
".",
"astype",
"(",
"\"object\"",
")",
"# Try again",
"result",
"=",
"pd",
".",
"merge",
"(",
"result",
",",
"df",
",",
"how",
"=",
"\"outer\"",
")",
"if",
"result",
"is",
"None",
":",
"return",
"pd",
".",
"DataFrame",
"(",
")",
"else",
":",
"return",
"result",
".",
"set_index",
"(",
"indexes",
")",
"if",
"indexes",
"else",
"result"
] |
0180da34d052c44fb94dab9e115e218bbebfc9c3
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.