repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
pioneers/python-grizzly | grizzly/__init__.py | GrizzlyUSB.get_device_address | def get_device_address(usb_device):
""" Returns the grizzly's internal address value. Returns a negative error value in case of error. """
try:
usb_device.ctrl_transfer(0x21, 0x09, 0x0300, 0, GrizzlyUSB.COMMAND_GET_ADDR)
internal_addr = usb_device.ctrl_transfer(0xa1, 0x01, 0x0301... | python | def get_device_address(usb_device):
""" Returns the grizzly's internal address value. Returns a negative error value in case of error. """
try:
usb_device.ctrl_transfer(0x21, 0x09, 0x0300, 0, GrizzlyUSB.COMMAND_GET_ADDR)
internal_addr = usb_device.ctrl_transfer(0xa1, 0x01, 0x0301... | [
"def",
"get_device_address",
"(",
"usb_device",
")",
":",
"try",
":",
"usb_device",
".",
"ctrl_transfer",
"(",
"0x21",
",",
"0x09",
",",
"0x0300",
",",
"0",
",",
"GrizzlyUSB",
".",
"COMMAND_GET_ADDR",
")",
"internal_addr",
"=",
"usb_device",
".",
"ctrl_transfe... | Returns the grizzly's internal address value. Returns a negative error value in case of error. | [
"Returns",
"the",
"grizzly",
"s",
"internal",
"address",
"value",
".",
"Returns",
"a",
"negative",
"error",
"value",
"in",
"case",
"of",
"error",
"."
] | train | https://github.com/pioneers/python-grizzly/blob/a6482c722d5712d6ebe12d48921815276c826c7f/grizzly/__init__.py#L52-L59 |
pioneers/python-grizzly | grizzly/__init__.py | GrizzlyUSB.exchange_bytes | def exchange_bytes(self, cmd):
"""Sends a packet to the grizzly, requesting information. Reads back
the data requested.
Packet format looks like:
Byte 0: Register
Byte 1 (bit 6:0): Length of data to read/write
Byte 1 (bit 7): R/W flag (1 = write)
... | python | def exchange_bytes(self, cmd):
"""Sends a packet to the grizzly, requesting information. Reads back
the data requested.
Packet format looks like:
Byte 0: Register
Byte 1 (bit 6:0): Length of data to read/write
Byte 1 (bit 7): R/W flag (1 = write)
... | [
"def",
"exchange_bytes",
"(",
"self",
",",
"cmd",
")",
":",
"assert",
"len",
"(",
"cmd",
")",
"==",
"16",
",",
"\"Must send 16 bytes\"",
"self",
".",
"_dev",
".",
"ctrl_transfer",
"(",
"0x21",
",",
"0x09",
",",
"0x0300",
",",
"0",
",",
"cmd",
")",
"n... | Sends a packet to the grizzly, requesting information. Reads back
the data requested.
Packet format looks like:
Byte 0: Register
Byte 1 (bit 6:0): Length of data to read/write
Byte 1 (bit 7): R/W flag (1 = write)
Byte 2-15: Data
... | [
"Sends",
"a",
"packet",
"to",
"the",
"grizzly",
"requesting",
"information",
".",
"Reads",
"back",
"the",
"data",
"requested",
".",
"Packet",
"format",
"looks",
"like",
":",
"Byte",
"0",
":",
"Register",
"Byte",
"1",
"(",
"bit",
"6",
":",
"0",
")",
":"... | train | https://github.com/pioneers/python-grizzly/blob/a6482c722d5712d6ebe12d48921815276c826c7f/grizzly/__init__.py#L76-L91 |
pioneers/python-grizzly | grizzly/__init__.py | Grizzly.get_all_ids | def get_all_ids(idVendor = GrizzlyUSB.ID_VENDOR, idProduct=GrizzlyUSB.ID_PRODUCT):
""" Scans for grizzlies that have not been bound, or constructed, and returns a list
of their id's, or motor number."""
all_dev = GrizzlyUSB.get_all_usb_devices(idVendor, idProduct)
if len(all... | python | def get_all_ids(idVendor = GrizzlyUSB.ID_VENDOR, idProduct=GrizzlyUSB.ID_PRODUCT):
""" Scans for grizzlies that have not been bound, or constructed, and returns a list
of their id's, or motor number."""
all_dev = GrizzlyUSB.get_all_usb_devices(idVendor, idProduct)
if len(all... | [
"def",
"get_all_ids",
"(",
"idVendor",
"=",
"GrizzlyUSB",
".",
"ID_VENDOR",
",",
"idProduct",
"=",
"GrizzlyUSB",
".",
"ID_PRODUCT",
")",
":",
"all_dev",
"=",
"GrizzlyUSB",
".",
"get_all_usb_devices",
"(",
"idVendor",
",",
"idProduct",
")",
"if",
"len",
"(",
... | Scans for grizzlies that have not been bound, or constructed, and returns a list
of their id's, or motor number. | [
"Scans",
"for",
"grizzlies",
"that",
"have",
"not",
"been",
"bound",
"or",
"constructed",
"and",
"returns",
"a",
"list",
"of",
"their",
"id",
"s",
"or",
"motor",
"number",
"."
] | train | https://github.com/pioneers/python-grizzly/blob/a6482c722d5712d6ebe12d48921815276c826c7f/grizzly/__init__.py#L100-L124 |
pioneers/python-grizzly | grizzly/__init__.py | Grizzly.set_register | def set_register(self, addr, data):
"""Sets an arbitrary register at @addr and subsequent registers depending
on how much data you decide to write. It will automatically fill extra
bytes with zeros. You cannot write more than 14 bytes at a time.
@addr should be a static constant from the... | python | def set_register(self, addr, data):
"""Sets an arbitrary register at @addr and subsequent registers depending
on how much data you decide to write. It will automatically fill extra
bytes with zeros. You cannot write more than 14 bytes at a time.
@addr should be a static constant from the... | [
"def",
"set_register",
"(",
"self",
",",
"addr",
",",
"data",
")",
":",
"assert",
"len",
"(",
"data",
")",
"<=",
"14",
",",
"\"Cannot write more than 14 bytes at a time\"",
"cmd",
"=",
"chr",
"(",
"addr",
")",
"+",
"chr",
"(",
"len",
"(",
"data",
")",
... | Sets an arbitrary register at @addr and subsequent registers depending
on how much data you decide to write. It will automatically fill extra
bytes with zeros. You cannot write more than 14 bytes at a time.
@addr should be a static constant from the Addr class, e.g. Addr.Speed | [
"Sets",
"an",
"arbitrary",
"register",
"at"
] | train | https://github.com/pioneers/python-grizzly/blob/a6482c722d5712d6ebe12d48921815276c826c7f/grizzly/__init__.py#L136-L146 |
pioneers/python-grizzly | grizzly/__init__.py | Grizzly.read_register | def read_register(self, addr, numBytes):
"""Reads @numBytes bytes from the grizzly starting at @addr. Due
to packet format, cannot read more than 127 packets at a time.
Returns a byte array of the requested data in little endian.
@addr should be from the Addr class e.g. Addr.Speed"""
... | python | def read_register(self, addr, numBytes):
"""Reads @numBytes bytes from the grizzly starting at @addr. Due
to packet format, cannot read more than 127 packets at a time.
Returns a byte array of the requested data in little endian.
@addr should be from the Addr class e.g. Addr.Speed"""
... | [
"def",
"read_register",
"(",
"self",
",",
"addr",
",",
"numBytes",
")",
":",
"assert",
"numBytes",
"<=",
"0x7f",
",",
"\"Cannot read more than 127 bytes at a time\"",
"cmd",
"=",
"chr",
"(",
"addr",
")",
"+",
"chr",
"(",
"numBytes",
")",
"cmd",
"+=",
"(",
... | Reads @numBytes bytes from the grizzly starting at @addr. Due
to packet format, cannot read more than 127 packets at a time.
Returns a byte array of the requested data in little endian.
@addr should be from the Addr class e.g. Addr.Speed | [
"Reads"
] | train | https://github.com/pioneers/python-grizzly/blob/a6482c722d5712d6ebe12d48921815276c826c7f/grizzly/__init__.py#L148-L156 |
pioneers/python-grizzly | grizzly/__init__.py | Grizzly.set_mode | def set_mode(self, controlmode, drivemode):
"""Higher level abstraction for setting the mode register. This will
set the mode according the the @controlmode and @drivemode you specify.
@controlmode and @drivemode should come from the ControlMode and DriveMode
class respectively."""
... | python | def set_mode(self, controlmode, drivemode):
"""Higher level abstraction for setting the mode register. This will
set the mode according the the @controlmode and @drivemode you specify.
@controlmode and @drivemode should come from the ControlMode and DriveMode
class respectively."""
... | [
"def",
"set_mode",
"(",
"self",
",",
"controlmode",
",",
"drivemode",
")",
":",
"self",
".",
"set_register",
"(",
"Addr",
".",
"Mode",
",",
"[",
"0x01",
"|",
"controlmode",
"|",
"drivemode",
"]",
")"
] | Higher level abstraction for setting the mode register. This will
set the mode according the the @controlmode and @drivemode you specify.
@controlmode and @drivemode should come from the ControlMode and DriveMode
class respectively. | [
"Higher",
"level",
"abstraction",
"for",
"setting",
"the",
"mode",
"register",
".",
"This",
"will",
"set",
"the",
"mode",
"according",
"the",
"the"
] | train | https://github.com/pioneers/python-grizzly/blob/a6482c722d5712d6ebe12d48921815276c826c7f/grizzly/__init__.py#L158-L163 |
pioneers/python-grizzly | grizzly/__init__.py | Grizzly.set_target | def set_target(self, setpoint):
"""Higher level abstraction for setting the speed register. This
register is responsible for telling the grizzly at what speed or
position to drive at. The different control modes and type it expects is
documented in the table below:
Mode ... | python | def set_target(self, setpoint):
"""Higher level abstraction for setting the speed register. This
register is responsible for telling the grizzly at what speed or
position to drive at. The different control modes and type it expects is
documented in the table below:
Mode ... | [
"def",
"set_target",
"(",
"self",
",",
"setpoint",
")",
":",
"fixed_set",
"=",
"int",
"(",
"setpoint",
"*",
"(",
"2",
"**",
"16",
")",
")",
"buf",
"=",
"[",
"cast_to_byte",
"(",
"fixed_set",
">>",
"8",
"*",
"i",
")",
"for",
"i",
"in",
"range",
"(... | Higher level abstraction for setting the speed register. This
register is responsible for telling the grizzly at what speed or
position to drive at. The different control modes and type it expects is
documented in the table below:
Mode Type Range
... | [
"Higher",
"level",
"abstraction",
"for",
"setting",
"the",
"speed",
"register",
".",
"This",
"register",
"is",
"responsible",
"for",
"telling",
"the",
"grizzly",
"at",
"what",
"speed",
"or",
"position",
"to",
"drive",
"at",
".",
"The",
"different",
"control",
... | train | https://github.com/pioneers/python-grizzly/blob/a6482c722d5712d6ebe12d48921815276c826c7f/grizzly/__init__.py#L165-L189 |
pioneers/python-grizzly | grizzly/__init__.py | Grizzly._read_as_int | def _read_as_int(self, addr, numBytes):
"""Convenience method. Oftentimes we need to read a range of
registers to represent an int. This method will automatically read
@numBytes registers starting at @addr and convert the array into an int."""
buf = self.read_register(addr, numBytes)
... | python | def _read_as_int(self, addr, numBytes):
"""Convenience method. Oftentimes we need to read a range of
registers to represent an int. This method will automatically read
@numBytes registers starting at @addr and convert the array into an int."""
buf = self.read_register(addr, numBytes)
... | [
"def",
"_read_as_int",
"(",
"self",
",",
"addr",
",",
"numBytes",
")",
":",
"buf",
"=",
"self",
".",
"read_register",
"(",
"addr",
",",
"numBytes",
")",
"if",
"len",
"(",
"buf",
")",
">=",
"4",
":",
"return",
"struct",
".",
"unpack_from",
"(",
"\"<i\... | Convenience method. Oftentimes we need to read a range of
registers to represent an int. This method will automatically read
@numBytes registers starting at @addr and convert the array into an int. | [
"Convenience",
"method",
".",
"Oftentimes",
"we",
"need",
"to",
"read",
"a",
"range",
"of",
"registers",
"to",
"represent",
"an",
"int",
".",
"This",
"method",
"will",
"automatically",
"read"
] | train | https://github.com/pioneers/python-grizzly/blob/a6482c722d5712d6ebe12d48921815276c826c7f/grizzly/__init__.py#L191-L202 |
pioneers/python-grizzly | grizzly/__init__.py | Grizzly._set_as_int | def _set_as_int(self, addr, val, numBytes = 1):
"""Convenience method. Oftentimes we need to set a range of registers
to represent an int. This method will automatically set @numBytes registers
starting at @addr. It will convert the int @val into an array of bytes."""
if not isinstance(v... | python | def _set_as_int(self, addr, val, numBytes = 1):
"""Convenience method. Oftentimes we need to set a range of registers
to represent an int. This method will automatically set @numBytes registers
starting at @addr. It will convert the int @val into an array of bytes."""
if not isinstance(v... | [
"def",
"_set_as_int",
"(",
"self",
",",
"addr",
",",
"val",
",",
"numBytes",
"=",
"1",
")",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"int",
")",
":",
"raise",
"ValueError",
"(",
"\"val must be an int. You provided: %s\"",
"%",
"str",
"(",
"val",
... | Convenience method. Oftentimes we need to set a range of registers
to represent an int. This method will automatically set @numBytes registers
starting at @addr. It will convert the int @val into an array of bytes. | [
"Convenience",
"method",
".",
"Oftentimes",
"we",
"need",
"to",
"set",
"a",
"range",
"of",
"registers",
"to",
"represent",
"an",
"int",
".",
"This",
"method",
"will",
"automatically",
"set"
] | train | https://github.com/pioneers/python-grizzly/blob/a6482c722d5712d6ebe12d48921815276c826c7f/grizzly/__init__.py#L204-L213 |
pioneers/python-grizzly | grizzly/__init__.py | Grizzly.has_reset | def has_reset(self):
"""Checks the grizzly to see if it reset itself because of
voltage sag or other reasons. Useful to reinitialize acceleration or
current limiting."""
currentTime = self._read_as_int(Addr.Uptime, 4)
if currentTime <= self._ticks:
self._ticks = curre... | python | def has_reset(self):
"""Checks the grizzly to see if it reset itself because of
voltage sag or other reasons. Useful to reinitialize acceleration or
current limiting."""
currentTime = self._read_as_int(Addr.Uptime, 4)
if currentTime <= self._ticks:
self._ticks = curre... | [
"def",
"has_reset",
"(",
"self",
")",
":",
"currentTime",
"=",
"self",
".",
"_read_as_int",
"(",
"Addr",
".",
"Uptime",
",",
"4",
")",
"if",
"currentTime",
"<=",
"self",
".",
"_ticks",
":",
"self",
".",
"_ticks",
"=",
"currentTime",
"return",
"True",
"... | Checks the grizzly to see if it reset itself because of
voltage sag or other reasons. Useful to reinitialize acceleration or
current limiting. | [
"Checks",
"the",
"grizzly",
"to",
"see",
"if",
"it",
"reset",
"itself",
"because",
"of",
"voltage",
"sag",
"or",
"other",
"reasons",
".",
"Useful",
"to",
"reinitialize",
"acceleration",
"or",
"current",
"limiting",
"."
] | train | https://github.com/pioneers/python-grizzly/blob/a6482c722d5712d6ebe12d48921815276c826c7f/grizzly/__init__.py#L231-L240 |
pioneers/python-grizzly | grizzly/__init__.py | Grizzly.limit_acceleration | def limit_acceleration(self, accel):
"""Sets the acceleration limit on the Grizzly. The max value is
143. Units are change in pwm per millisecond. Internally, the pwm is in
the range [-0x7f, 0x7f] or [-127, 127]. So in one millisecond the maximum
acceleration limit possible is 127 - -127... | python | def limit_acceleration(self, accel):
"""Sets the acceleration limit on the Grizzly. The max value is
143. Units are change in pwm per millisecond. Internally, the pwm is in
the range [-0x7f, 0x7f] or [-127, 127]. So in one millisecond the maximum
acceleration limit possible is 127 - -127... | [
"def",
"limit_acceleration",
"(",
"self",
",",
"accel",
")",
":",
"if",
"accel",
">=",
"143",
":",
"raise",
"ValueError",
"(",
"\"Acceleration limit cannot exceed 143. You provided: %s\"",
"%",
"str",
"(",
"accel",
")",
")",
"if",
"accel",
"<=",
"0",
":",
"rai... | Sets the acceleration limit on the Grizzly. The max value is
143. Units are change in pwm per millisecond. Internally, the pwm is in
the range [-0x7f, 0x7f] or [-127, 127]. So in one millisecond the maximum
acceleration limit possible is 127 - -127 = 142. The internal default
value is 4*... | [
"Sets",
"the",
"acceleration",
"limit",
"on",
"the",
"Grizzly",
".",
"The",
"max",
"value",
"is",
"143",
".",
"Units",
"are",
"change",
"in",
"pwm",
"per",
"millisecond",
".",
"Internally",
"the",
"pwm",
"is",
"in",
"the",
"range",
"[",
"-",
"0x7f",
"0... | train | https://github.com/pioneers/python-grizzly/blob/a6482c722d5712d6ebe12d48921815276c826c7f/grizzly/__init__.py#L242-L253 |
pioneers/python-grizzly | grizzly/__init__.py | Grizzly.limit_current | def limit_current(self, curr):
"""Sets the current limit on the Grizzly. The units are in amps. The
internal default value is 5 amps."""
if curr <= 0:
raise ValueError("Current limit must be a positive number. You provided: %s" % str(curr))
current = int(curr * (1024.0 / 5.0)... | python | def limit_current(self, curr):
"""Sets the current limit on the Grizzly. The units are in amps. The
internal default value is 5 amps."""
if curr <= 0:
raise ValueError("Current limit must be a positive number. You provided: %s" % str(curr))
current = int(curr * (1024.0 / 5.0)... | [
"def",
"limit_current",
"(",
"self",
",",
"curr",
")",
":",
"if",
"curr",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"Current limit must be a positive number. You provided: %s\"",
"%",
"str",
"(",
"curr",
")",
")",
"current",
"=",
"int",
"(",
"curr",
"*",
... | Sets the current limit on the Grizzly. The units are in amps. The
internal default value is 5 amps. | [
"Sets",
"the",
"current",
"limit",
"on",
"the",
"Grizzly",
".",
"The",
"units",
"are",
"in",
"amps",
".",
"The",
"internal",
"default",
"value",
"is",
"5",
"amps",
"."
] | train | https://github.com/pioneers/python-grizzly/blob/a6482c722d5712d6ebe12d48921815276c826c7f/grizzly/__init__.py#L255-L261 |
pioneers/python-grizzly | grizzly/__init__.py | Grizzly.init_pid | def init_pid(self, kp, ki, kd):
"""Sets the PID constants for the PID modes. Arguments are all
floating point numbers."""
p, i, d = map(lambda x: int(x * (2 ** 16)), (kp, ki, kd))
self._set_as_int(Addr.PConstant, p, 4)
self._set_as_int(Addr.IConstant, i, 4)
self._set_as_i... | python | def init_pid(self, kp, ki, kd):
"""Sets the PID constants for the PID modes. Arguments are all
floating point numbers."""
p, i, d = map(lambda x: int(x * (2 ** 16)), (kp, ki, kd))
self._set_as_int(Addr.PConstant, p, 4)
self._set_as_int(Addr.IConstant, i, 4)
self._set_as_i... | [
"def",
"init_pid",
"(",
"self",
",",
"kp",
",",
"ki",
",",
"kd",
")",
":",
"p",
",",
"i",
",",
"d",
"=",
"map",
"(",
"lambda",
"x",
":",
"int",
"(",
"x",
"*",
"(",
"2",
"**",
"16",
")",
")",
",",
"(",
"kp",
",",
"ki",
",",
"kd",
")",
... | Sets the PID constants for the PID modes. Arguments are all
floating point numbers. | [
"Sets",
"the",
"PID",
"constants",
"for",
"the",
"PID",
"modes",
".",
"Arguments",
"are",
"all",
"floating",
"point",
"numbers",
"."
] | train | https://github.com/pioneers/python-grizzly/blob/a6482c722d5712d6ebe12d48921815276c826c7f/grizzly/__init__.py#L263-L269 |
pioneers/python-grizzly | grizzly/__init__.py | Grizzly.read_pid_constants | def read_pid_constants(self):
"""Reads back the PID constants stored on the Grizzly."""
p = self._read_as_int(Addr.PConstant, 4)
i = self._read_as_int(Addr.IConstant, 4)
d = self._read_as_int(Addr.DConstant, 4)
return map(lambda x: x / (2 ** 16), (p, i, d)) | python | def read_pid_constants(self):
"""Reads back the PID constants stored on the Grizzly."""
p = self._read_as_int(Addr.PConstant, 4)
i = self._read_as_int(Addr.IConstant, 4)
d = self._read_as_int(Addr.DConstant, 4)
return map(lambda x: x / (2 ** 16), (p, i, d)) | [
"def",
"read_pid_constants",
"(",
"self",
")",
":",
"p",
"=",
"self",
".",
"_read_as_int",
"(",
"Addr",
".",
"PConstant",
",",
"4",
")",
"i",
"=",
"self",
".",
"_read_as_int",
"(",
"Addr",
".",
"IConstant",
",",
"4",
")",
"d",
"=",
"self",
".",
"_r... | Reads back the PID constants stored on the Grizzly. | [
"Reads",
"back",
"the",
"PID",
"constants",
"stored",
"on",
"the",
"Grizzly",
"."
] | train | https://github.com/pioneers/python-grizzly/blob/a6482c722d5712d6ebe12d48921815276c826c7f/grizzly/__init__.py#L271-L277 |
TC01/calcpkg | calcrepo/util.py | getReposPackageFolder | def getReposPackageFolder():
"""Returns the folder the package is located in."""
libdir = sysconfig.get_python_lib()
repodir = os.path.join(libdir, "calcrepo", "repos")
return repodir | python | def getReposPackageFolder():
"""Returns the folder the package is located in."""
libdir = sysconfig.get_python_lib()
repodir = os.path.join(libdir, "calcrepo", "repos")
return repodir | [
"def",
"getReposPackageFolder",
"(",
")",
":",
"libdir",
"=",
"sysconfig",
".",
"get_python_lib",
"(",
")",
"repodir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"libdir",
",",
"\"calcrepo\"",
",",
"\"repos\"",
")",
"return",
"repodir"
] | Returns the folder the package is located in. | [
"Returns",
"the",
"folder",
"the",
"package",
"is",
"located",
"in",
"."
] | train | https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/util.py#L7-L11 |
TC01/calcpkg | calcrepo/util.py | replaceNewlines | def replaceNewlines(string, newlineChar):
"""There's probably a way to do this with string functions but I was lazy.
Replace all instances of \r or \n in a string with something else."""
if newlineChar in string:
segments = string.split(newlineChar)
string = ""
for segment in segments:
string += segment
r... | python | def replaceNewlines(string, newlineChar):
"""There's probably a way to do this with string functions but I was lazy.
Replace all instances of \r or \n in a string with something else."""
if newlineChar in string:
segments = string.split(newlineChar)
string = ""
for segment in segments:
string += segment
r... | [
"def",
"replaceNewlines",
"(",
"string",
",",
"newlineChar",
")",
":",
"if",
"newlineChar",
"in",
"string",
":",
"segments",
"=",
"string",
".",
"split",
"(",
"newlineChar",
")",
"string",
"=",
"\"\"",
"for",
"segment",
"in",
"segments",
":",
"string",
"+=... | There's probably a way to do this with string functions but I was lazy.
Replace all instances of \r or \n in a string with something else. | [
"There",
"s",
"probably",
"a",
"way",
"to",
"do",
"this",
"with",
"string",
"functions",
"but",
"I",
"was",
"lazy",
".",
"Replace",
"all",
"instances",
"of",
"\\",
"r",
"or",
"\\",
"n",
"in",
"a",
"string",
"with",
"something",
"else",
"."
] | train | https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/util.py#L13-L21 |
TC01/calcpkg | calcrepo/util.py | removeRootFromName | def removeRootFromName(string):
"""Helper function to remove /pub, /files from string."""
global garbageRoots
for root in garbageRoots:
if root in string:
string = string[string.find(root) + len(root):]
return string | python | def removeRootFromName(string):
"""Helper function to remove /pub, /files from string."""
global garbageRoots
for root in garbageRoots:
if root in string:
string = string[string.find(root) + len(root):]
return string | [
"def",
"removeRootFromName",
"(",
"string",
")",
":",
"global",
"garbageRoots",
"for",
"root",
"in",
"garbageRoots",
":",
"if",
"root",
"in",
"string",
":",
"string",
"=",
"string",
"[",
"string",
".",
"find",
"(",
"root",
")",
"+",
"len",
"(",
"root",
... | Helper function to remove /pub, /files from string. | [
"Helper",
"function",
"to",
"remove",
"/",
"pub",
"/",
"files",
"from",
"string",
"."
] | train | https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/util.py#L23-L29 |
TC01/calcpkg | calcrepo/util.py | getScriptLocation | def getScriptLocation():
"""Helper function to get the location of a Python file."""
location = os.path.abspath("./")
if __file__.rfind("/") != -1:
location = __file__[:__file__.rfind("/")]
return location | python | def getScriptLocation():
"""Helper function to get the location of a Python file."""
location = os.path.abspath("./")
if __file__.rfind("/") != -1:
location = __file__[:__file__.rfind("/")]
return location | [
"def",
"getScriptLocation",
"(",
")",
":",
"location",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"\"./\"",
")",
"if",
"__file__",
".",
"rfind",
"(",
"\"/\"",
")",
"!=",
"-",
"1",
":",
"location",
"=",
"__file__",
"[",
":",
"__file__",
".",
"rfind"... | Helper function to get the location of a Python file. | [
"Helper",
"function",
"to",
"get",
"the",
"location",
"of",
"a",
"Python",
"file",
"."
] | train | https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/util.py#L31-L36 |
sassoo/goldman | goldman/queryparams/fields.py | _parse_param | def _parse_param(key, val):
""" Parse the query param looking for sparse fields params
Ensure the `val` or what will become the sparse fields
is always an array. If the query param is not a sparse
fields query param then return None.
:param key:
the query parameter key in the request (left... | python | def _parse_param(key, val):
""" Parse the query param looking for sparse fields params
Ensure the `val` or what will become the sparse fields
is always an array. If the query param is not a sparse
fields query param then return None.
:param key:
the query parameter key in the request (left... | [
"def",
"_parse_param",
"(",
"key",
",",
"val",
")",
":",
"regex",
"=",
"re",
".",
"compile",
"(",
"r'fields\\[([A-Za-z]+)\\]'",
")",
"match",
"=",
"regex",
".",
"match",
"(",
"key",
")",
"if",
"match",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
... | Parse the query param looking for sparse fields params
Ensure the `val` or what will become the sparse fields
is always an array. If the query param is not a sparse
fields query param then return None.
:param key:
the query parameter key in the request (left of =)
:param val:
the q... | [
"Parse",
"the",
"query",
"param",
"looking",
"for",
"sparse",
"fields",
"params"
] | train | https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/queryparams/fields.py#L24-L50 |
sassoo/goldman | goldman/queryparams/fields.py | _validate_param | def _validate_param(rtype, fields):
""" Ensure the sparse fields exists on the models """
try:
# raises ValueError if not found
model = rtype_to_model(rtype)
model_fields = model.all_fields
except ValueError:
raise InvalidQueryParams(**{
'detail': 'The fields que... | python | def _validate_param(rtype, fields):
""" Ensure the sparse fields exists on the models """
try:
# raises ValueError if not found
model = rtype_to_model(rtype)
model_fields = model.all_fields
except ValueError:
raise InvalidQueryParams(**{
'detail': 'The fields que... | [
"def",
"_validate_param",
"(",
"rtype",
",",
"fields",
")",
":",
"try",
":",
"# raises ValueError if not found",
"model",
"=",
"rtype_to_model",
"(",
"rtype",
")",
"model_fields",
"=",
"model",
".",
"all_fields",
"except",
"ValueError",
":",
"raise",
"InvalidQuery... | Ensure the sparse fields exists on the models | [
"Ensure",
"the",
"sparse",
"fields",
"exists",
"on",
"the",
"models"
] | train | https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/queryparams/fields.py#L53-L76 |
sassoo/goldman | goldman/queryparams/fields.py | init | def init(req, model): # pylint: disable=unused-argument
""" Determine the sparse fields to limit the response to
Return a dict where the key is the resource type (rtype) &
the value is an array of string fields names to whitelist
against.
:return:
dict
"""
params = {}
for ke... | python | def init(req, model): # pylint: disable=unused-argument
""" Determine the sparse fields to limit the response to
Return a dict where the key is the resource type (rtype) &
the value is an array of string fields names to whitelist
against.
:return:
dict
"""
params = {}
for ke... | [
"def",
"init",
"(",
"req",
",",
"model",
")",
":",
"# pylint: disable=unused-argument",
"params",
"=",
"{",
"}",
"for",
"key",
",",
"val",
"in",
"req",
".",
"params",
".",
"items",
"(",
")",
":",
"try",
":",
"rtype",
",",
"fields",
"=",
"_parse_param",... | Determine the sparse fields to limit the response to
Return a dict where the key is the resource type (rtype) &
the value is an array of string fields names to whitelist
against.
:return:
dict | [
"Determine",
"the",
"sparse",
"fields",
"to",
"limit",
"the",
"response",
"to"
] | train | https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/queryparams/fields.py#L99-L123 |
jmoiron/gaspar | gaspar/client.py | request | def request(url, message):
"""Given a url (host:port) and a message, sends that message synchronously
and returns the response."""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host, port = url.split(':')
port = int(port)
s.connect((host, port))
s.send(pack(message))
data = s.mak... | python | def request(url, message):
"""Given a url (host:port) and a message, sends that message synchronously
and returns the response."""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host, port = url.split(':')
port = int(port)
s.connect((host, port))
s.send(pack(message))
data = s.mak... | [
"def",
"request",
"(",
"url",
",",
"message",
")",
":",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"host",
",",
"port",
"=",
"url",
".",
"split",
"(",
"':'",
")",
"port",
"=",
"int",
... | Given a url (host:port) and a message, sends that message synchronously
and returns the response. | [
"Given",
"a",
"url",
"(",
"host",
":",
"port",
")",
"and",
"a",
"message",
"sends",
"that",
"message",
"synchronously",
"and",
"returns",
"the",
"response",
"."
] | train | https://github.com/jmoiron/gaspar/blob/cc9d7403a4d86382b10a7e96c6d0a020cc5e1b12/gaspar/client.py#L13-L23 |
jorgebg/lumpy | lumpy/mail.py | Mail.query_mxrecords | def query_mxrecords(self):
"""
Looks up for the MX DNS records of the recipient SMTP server
"""
import dns.resolver
logging.info('Resolving DNS query...')
answers = dns.resolver.query(self.domain, 'MX')
addresses = [answer.exchange.to_text() for answer in answers]... | python | def query_mxrecords(self):
"""
Looks up for the MX DNS records of the recipient SMTP server
"""
import dns.resolver
logging.info('Resolving DNS query...')
answers = dns.resolver.query(self.domain, 'MX')
addresses = [answer.exchange.to_text() for answer in answers]... | [
"def",
"query_mxrecords",
"(",
"self",
")",
":",
"import",
"dns",
".",
"resolver",
"logging",
".",
"info",
"(",
"'Resolving DNS query...'",
")",
"answers",
"=",
"dns",
".",
"resolver",
".",
"query",
"(",
"self",
".",
"domain",
",",
"'MX'",
")",
"addresses"... | Looks up for the MX DNS records of the recipient SMTP server | [
"Looks",
"up",
"for",
"the",
"MX",
"DNS",
"records",
"of",
"the",
"recipient",
"SMTP",
"server"
] | train | https://github.com/jorgebg/lumpy/blob/1555151a5c36a327591ff9ba7ca88d6812eb9949/lumpy/mail.py#L48-L59 |
jorgebg/lumpy | lumpy/mail.py | Mail.send | def send(self):
"""
Attempts the delivery through recipient's domain MX records.
"""
try:
for mx in self.mxrecords:
logging.info('Connecting to {} {}...'.format(mx, self.port))
server = smtplib.SMTP(mx, self.port)
server.set_deb... | python | def send(self):
"""
Attempts the delivery through recipient's domain MX records.
"""
try:
for mx in self.mxrecords:
logging.info('Connecting to {} {}...'.format(mx, self.port))
server = smtplib.SMTP(mx, self.port)
server.set_deb... | [
"def",
"send",
"(",
"self",
")",
":",
"try",
":",
"for",
"mx",
"in",
"self",
".",
"mxrecords",
":",
"logging",
".",
"info",
"(",
"'Connecting to {} {}...'",
".",
"format",
"(",
"mx",
",",
"self",
".",
"port",
")",
")",
"server",
"=",
"smtplib",
".",
... | Attempts the delivery through recipient's domain MX records. | [
"Attempts",
"the",
"delivery",
"through",
"recipient",
"s",
"domain",
"MX",
"records",
"."
] | train | https://github.com/jorgebg/lumpy/blob/1555151a5c36a327591ff9ba7ca88d6812eb9949/lumpy/mail.py#L61-L82 |
Nixiware/viper | nx/viper/dispatcher.py | Dispatcher.dispatch | def dispatch(self, requestProtocol, requestPayload):
"""
Dispatch the request to the appropriate handler.
:param requestProtocol: <AbstractApplicationInterfaceProtocol> request protocol
:param requestPayload: <dict> request
:param version: <float> version
:param ... | python | def dispatch(self, requestProtocol, requestPayload):
"""
Dispatch the request to the appropriate handler.
:param requestProtocol: <AbstractApplicationInterfaceProtocol> request protocol
:param requestPayload: <dict> request
:param version: <float> version
:param ... | [
"def",
"dispatch",
"(",
"self",
",",
"requestProtocol",
",",
"requestPayload",
")",
":",
"# method decoding",
"method",
"=",
"requestPayload",
"[",
"\"method\"",
"]",
".",
"split",
"(",
"\".\"",
")",
"if",
"len",
"(",
"method",
")",
"!=",
"3",
":",
"reques... | Dispatch the request to the appropriate handler.
:param requestProtocol: <AbstractApplicationInterfaceProtocol> request protocol
:param requestPayload: <dict> request
:param version: <float> version
:param method: <str> method name
:param parameters: <dict> data para... | [
"Dispatch",
"the",
"request",
"to",
"the",
"appropriate",
"handler",
"."
] | train | https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/dispatcher.py#L16-L89 |
delfick/aws_syncr | aws_syncr/collector.py | Collector.prepare | def prepare(self, configuration_folder, args_dict, environment):
"""Make a temporary configuration file from the files in our folder"""
self.configuration_folder = configuration_folder
if not os.path.isdir(configuration_folder):
raise BadOption("Specified configuration folder is not ... | python | def prepare(self, configuration_folder, args_dict, environment):
"""Make a temporary configuration file from the files in our folder"""
self.configuration_folder = configuration_folder
if not os.path.isdir(configuration_folder):
raise BadOption("Specified configuration folder is not ... | [
"def",
"prepare",
"(",
"self",
",",
"configuration_folder",
",",
"args_dict",
",",
"environment",
")",
":",
"self",
".",
"configuration_folder",
"=",
"configuration_folder",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"configuration_folder",
")",
":",
"... | Make a temporary configuration file from the files in our folder | [
"Make",
"a",
"temporary",
"configuration",
"file",
"from",
"the",
"files",
"in",
"our",
"folder"
] | train | https://github.com/delfick/aws_syncr/blob/8cd214b27c1eee98dfba4632cbb8bc0ae36356bd/aws_syncr/collector.py#L38-L61 |
delfick/aws_syncr | aws_syncr/collector.py | Collector.extra_prepare | def extra_prepare(self, configuration, args_dict):
"""Called before the configuration.converters are activated"""
aws_syncr = args_dict.pop("aws_syncr")
self.configuration.update(
{ "$@": aws_syncr.get("extra", "")
, "aws_syncr": aws_syncr
, "templates": {}
... | python | def extra_prepare(self, configuration, args_dict):
"""Called before the configuration.converters are activated"""
aws_syncr = args_dict.pop("aws_syncr")
self.configuration.update(
{ "$@": aws_syncr.get("extra", "")
, "aws_syncr": aws_syncr
, "templates": {}
... | [
"def",
"extra_prepare",
"(",
"self",
",",
"configuration",
",",
"args_dict",
")",
":",
"aws_syncr",
"=",
"args_dict",
".",
"pop",
"(",
"\"aws_syncr\"",
")",
"self",
".",
"configuration",
".",
"update",
"(",
"{",
"\"$@\"",
":",
"aws_syncr",
".",
"get",
"(",... | Called before the configuration.converters are activated | [
"Called",
"before",
"the",
"configuration",
".",
"converters",
"are",
"activated"
] | train | https://github.com/delfick/aws_syncr/blob/8cd214b27c1eee98dfba4632cbb8bc0ae36356bd/aws_syncr/collector.py#L68-L79 |
delfick/aws_syncr | aws_syncr/collector.py | Collector.extra_prepare_after_activation | def extra_prepare_after_activation(self, configuration, args_dict):
"""Setup our connection to amazon"""
aws_syncr = configuration['aws_syncr']
configuration["amazon"] = Amazon(configuration['aws_syncr'].environment, configuration['accounts'], debug=aws_syncr.debug, dry_run=aws_syncr.dry_run) | python | def extra_prepare_after_activation(self, configuration, args_dict):
"""Setup our connection to amazon"""
aws_syncr = configuration['aws_syncr']
configuration["amazon"] = Amazon(configuration['aws_syncr'].environment, configuration['accounts'], debug=aws_syncr.debug, dry_run=aws_syncr.dry_run) | [
"def",
"extra_prepare_after_activation",
"(",
"self",
",",
"configuration",
",",
"args_dict",
")",
":",
"aws_syncr",
"=",
"configuration",
"[",
"'aws_syncr'",
"]",
"configuration",
"[",
"\"amazon\"",
"]",
"=",
"Amazon",
"(",
"configuration",
"[",
"'aws_syncr'",
"]... | Setup our connection to amazon | [
"Setup",
"our",
"connection",
"to",
"amazon"
] | train | https://github.com/delfick/aws_syncr/blob/8cd214b27c1eee98dfba4632cbb8bc0ae36356bd/aws_syncr/collector.py#L81-L84 |
delfick/aws_syncr | aws_syncr/collector.py | Collector.add_configuration | def add_configuration(self, configuration, collect_another_source, done, result, src):
"""Used to add a file to the configuration, result here is the yaml.load of the src"""
if "includes" in result:
for include in result["includes"]:
collect_another_source(include)
co... | python | def add_configuration(self, configuration, collect_another_source, done, result, src):
"""Used to add a file to the configuration, result here is the yaml.load of the src"""
if "includes" in result:
for include in result["includes"]:
collect_another_source(include)
co... | [
"def",
"add_configuration",
"(",
"self",
",",
"configuration",
",",
"collect_another_source",
",",
"done",
",",
"result",
",",
"src",
")",
":",
"if",
"\"includes\"",
"in",
"result",
":",
"for",
"include",
"in",
"result",
"[",
"\"includes\"",
"]",
":",
"colle... | Used to add a file to the configuration, result here is the yaml.load of the src | [
"Used",
"to",
"add",
"a",
"file",
"to",
"the",
"configuration",
"result",
"here",
"is",
"the",
"yaml",
".",
"load",
"of",
"the",
"src"
] | train | https://github.com/delfick/aws_syncr/blob/8cd214b27c1eee98dfba4632cbb8bc0ae36356bd/aws_syncr/collector.py#L100-L105 |
delfick/aws_syncr | aws_syncr/collector.py | Collector.extra_configuration_collection | def extra_configuration_collection(self, configuration):
"""Hook to do any extra configuration collection or converter registration"""
aws_syncr_spec = AwsSyncrSpec()
registered = {}
directory = pkg_resources.resource_filename("aws_syncr", "option_spec")
for location in sorted(o... | python | def extra_configuration_collection(self, configuration):
"""Hook to do any extra configuration collection or converter registration"""
aws_syncr_spec = AwsSyncrSpec()
registered = {}
directory = pkg_resources.resource_filename("aws_syncr", "option_spec")
for location in sorted(o... | [
"def",
"extra_configuration_collection",
"(",
"self",
",",
"configuration",
")",
":",
"aws_syncr_spec",
"=",
"AwsSyncrSpec",
"(",
")",
"registered",
"=",
"{",
"}",
"directory",
"=",
"pkg_resources",
".",
"resource_filename",
"(",
"\"aws_syncr\"",
",",
"\"option_spec... | Hook to do any extra configuration collection or converter registration | [
"Hook",
"to",
"do",
"any",
"extra",
"configuration",
"collection",
"or",
"converter",
"registration"
] | train | https://github.com/delfick/aws_syncr/blob/8cd214b27c1eee98dfba4632cbb8bc0ae36356bd/aws_syncr/collector.py#L107-L142 |
stephanepechard/projy | projy/cmdline.py | docopt_arguments | def docopt_arguments():
""" Creates beautiful command-line interfaces.
See https://github.com/docopt/docopt """
doc = """Projy: Create templated project.
Usage: projy <template> <project> [<substitution>...]
projy -i | --info <template>
projy -l | --list
projy -h | ... | python | def docopt_arguments():
""" Creates beautiful command-line interfaces.
See https://github.com/docopt/docopt """
doc = """Projy: Create templated project.
Usage: projy <template> <project> [<substitution>...]
projy -i | --info <template>
projy -l | --list
projy -h | ... | [
"def",
"docopt_arguments",
"(",
")",
":",
"doc",
"=",
"\"\"\"Projy: Create templated project.\n\n Usage: projy <template> <project> [<substitution>...]\n projy -i | --info <template>\n projy -l | --list\n projy -h | --help\n projy -v | --version\n\n Option... | Creates beautiful command-line interfaces.
See https://github.com/docopt/docopt | [
"Creates",
"beautiful",
"command",
"-",
"line",
"interfaces",
".",
"See",
"https",
":",
"//",
"github",
".",
"com",
"/",
"docopt",
"/",
"docopt"
] | train | https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/cmdline.py#L11-L29 |
stephanepechard/projy | projy/cmdline.py | template_name_from_class_name | def template_name_from_class_name(class_name):
""" Remove the last 'Template' in the name. """
suffix = 'Template'
output = class_name
if (class_name.endswith(suffix)):
output = class_name[:-len(suffix)]
return output | python | def template_name_from_class_name(class_name):
""" Remove the last 'Template' in the name. """
suffix = 'Template'
output = class_name
if (class_name.endswith(suffix)):
output = class_name[:-len(suffix)]
return output | [
"def",
"template_name_from_class_name",
"(",
"class_name",
")",
":",
"suffix",
"=",
"'Template'",
"output",
"=",
"class_name",
"if",
"(",
"class_name",
".",
"endswith",
"(",
"suffix",
")",
")",
":",
"output",
"=",
"class_name",
"[",
":",
"-",
"len",
"(",
"... | Remove the last 'Template' in the name. | [
"Remove",
"the",
"last",
"Template",
"in",
"the",
"name",
"."
] | train | https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/cmdline.py#L32-L38 |
stephanepechard/projy | projy/cmdline.py | run_list | def run_list():
""" Print the list of all available templates. """
term = TerminalView()
term.print_info("These are the available templates:")
import pkgutil, projy.templates
pkgpath = os.path.dirname(projy.templates.__file__)
templates = [name for _, name, _ in pkgutil.iter_modules([pkgpath])]
... | python | def run_list():
""" Print the list of all available templates. """
term = TerminalView()
term.print_info("These are the available templates:")
import pkgutil, projy.templates
pkgpath = os.path.dirname(projy.templates.__file__)
templates = [name for _, name, _ in pkgutil.iter_modules([pkgpath])]
... | [
"def",
"run_list",
"(",
")",
":",
"term",
"=",
"TerminalView",
"(",
")",
"term",
".",
"print_info",
"(",
"\"These are the available templates:\"",
")",
"import",
"pkgutil",
",",
"projy",
".",
"templates",
"pkgpath",
"=",
"os",
".",
"path",
".",
"dirname",
"(... | Print the list of all available templates. | [
"Print",
"the",
"list",
"of",
"all",
"available",
"templates",
"."
] | train | https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/cmdline.py#L41-L51 |
stephanepechard/projy | projy/cmdline.py | run_info | def run_info(template):
""" Print information about a specific template. """
template.project_name = 'TowelStuff' # fake project name, always the same
name = template_name_from_class_name(template.__class__.__name__)
term = TerminalView()
term.print_info("Content of template {} with an example proje... | python | def run_info(template):
""" Print information about a specific template. """
template.project_name = 'TowelStuff' # fake project name, always the same
name = template_name_from_class_name(template.__class__.__name__)
term = TerminalView()
term.print_info("Content of template {} with an example proje... | [
"def",
"run_info",
"(",
"template",
")",
":",
"template",
".",
"project_name",
"=",
"'TowelStuff'",
"# fake project name, always the same",
"name",
"=",
"template_name_from_class_name",
"(",
"template",
".",
"__class__",
".",
"__name__",
")",
"term",
"=",
"TerminalVie... | Print information about a specific template. | [
"Print",
"information",
"about",
"a",
"specific",
"template",
"."
] | train | https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/cmdline.py#L54-L91 |
stephanepechard/projy | projy/cmdline.py | template_class_from_name | def template_class_from_name(name):
""" Return the template class object from agiven name. """
# import the right template module
term = TerminalView()
template_name = name + 'Template'
try:
__import__('projy.templates.' + template_name)
template_mod = sys.modules['projy.templates.' ... | python | def template_class_from_name(name):
""" Return the template class object from agiven name. """
# import the right template module
term = TerminalView()
template_name = name + 'Template'
try:
__import__('projy.templates.' + template_name)
template_mod = sys.modules['projy.templates.' ... | [
"def",
"template_class_from_name",
"(",
"name",
")",
":",
"# import the right template module",
"term",
"=",
"TerminalView",
"(",
")",
"template_name",
"=",
"name",
"+",
"'Template'",
"try",
":",
"__import__",
"(",
"'projy.templates.'",
"+",
"template_name",
")",
"t... | Return the template class object from agiven name. | [
"Return",
"the",
"template",
"class",
"object",
"from",
"agiven",
"name",
"."
] | train | https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/cmdline.py#L94-L110 |
stephanepechard/projy | projy/cmdline.py | execute | def execute():
""" Main function. """
args = docopt_arguments()
term = TerminalView()
# print list of installed templates
if args['--list']:
run_list()
return
# instanciate the class
if args['<template>']:
template = template_class_from_name(args['<template>'])
... | python | def execute():
""" Main function. """
args = docopt_arguments()
term = TerminalView()
# print list of installed templates
if args['--list']:
run_list()
return
# instanciate the class
if args['<template>']:
template = template_class_from_name(args['<template>'])
... | [
"def",
"execute",
"(",
")",
":",
"args",
"=",
"docopt_arguments",
"(",
")",
"term",
"=",
"TerminalView",
"(",
")",
"# print list of installed templates",
"if",
"args",
"[",
"'--list'",
"]",
":",
"run_list",
"(",
")",
"return",
"# instanciate the class",
"if",
... | Main function. | [
"Main",
"function",
"."
] | train | https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/cmdline.py#L113-L139 |
wsmith323/namedspace | namedspace/__init__.py | namedspace | def namedspace(typename, required_fields=(), optional_fields=(), mutable_fields=(),
default_values=frozendict(), default_value_factories=frozendict(),
return_none=False):
"""Builds a new class that encapsulates a namespace and provides
various ways to access it.
The typename argument is re... | python | def namedspace(typename, required_fields=(), optional_fields=(), mutable_fields=(),
default_values=frozendict(), default_value_factories=frozendict(),
return_none=False):
"""Builds a new class that encapsulates a namespace and provides
various ways to access it.
The typename argument is re... | [
"def",
"namedspace",
"(",
"typename",
",",
"required_fields",
"=",
"(",
")",
",",
"optional_fields",
"=",
"(",
")",
",",
"mutable_fields",
"=",
"(",
")",
",",
"default_values",
"=",
"frozendict",
"(",
")",
",",
"default_value_factories",
"=",
"frozendict",
"... | Builds a new class that encapsulates a namespace and provides
various ways to access it.
The typename argument is required and is the name of the
namedspace class that will be generated.
The required_fields and optional_fields arguments can be a string
or sequence of strings and together specify ... | [
"Builds",
"a",
"new",
"class",
"that",
"encapsulates",
"a",
"namespace",
"and",
"provides",
"various",
"ways",
"to",
"access",
"it",
"."
] | train | https://github.com/wsmith323/namedspace/blob/b9c5b22eee1e845eeca7b7e803fc4e79a61c2491/namedspace/__init__.py#L13-L396 |
pip-services3-python/pip-services3-components-python | pip_services3_components/Component.py | Component.configure | def configure(self, config):
"""
Configures component by passing configuration parameters.
:param config: configuration parameters to be set.
"""
self._dependency_resolver.configure(config)
self._logger.configure(config) | python | def configure(self, config):
"""
Configures component by passing configuration parameters.
:param config: configuration parameters to be set.
"""
self._dependency_resolver.configure(config)
self._logger.configure(config) | [
"def",
"configure",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"_dependency_resolver",
".",
"configure",
"(",
"config",
")",
"self",
".",
"_logger",
".",
"configure",
"(",
"config",
")"
] | Configures component by passing configuration parameters.
:param config: configuration parameters to be set. | [
"Configures",
"component",
"by",
"passing",
"configuration",
"parameters",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/Component.py#L45-L52 |
mbodenhamer/syn | syn/base_utils/iter.py | consume | def consume(iter, N=None):
'''Consumes N items from iter. If N is None (or not given), consumes all.
'''
i = iter
if N is not None:
i = islice(iter, N)
for x in i:
pass | python | def consume(iter, N=None):
'''Consumes N items from iter. If N is None (or not given), consumes all.
'''
i = iter
if N is not None:
i = islice(iter, N)
for x in i:
pass | [
"def",
"consume",
"(",
"iter",
",",
"N",
"=",
"None",
")",
":",
"i",
"=",
"iter",
"if",
"N",
"is",
"not",
"None",
":",
"i",
"=",
"islice",
"(",
"iter",
",",
"N",
")",
"for",
"x",
"in",
"i",
":",
"pass"
] | Consumes N items from iter. If N is None (or not given), consumes all. | [
"Consumes",
"N",
"items",
"from",
"iter",
".",
"If",
"N",
"is",
"None",
"(",
"or",
"not",
"given",
")",
"consumes",
"all",
"."
] | train | https://github.com/mbodenhamer/syn/blob/aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258/syn/base_utils/iter.py#L36-L44 |
mbodenhamer/syn | syn/base_utils/iter.py | iteration_length | def iteration_length(N, start=0, step=1):
'''Return the number of iteration steps over a list of length N,
starting at index start, proceeding step elements at a time.
'''
if N < 0:
raise ValueError('N cannot be negative')
if start < 0:
start += N
if start < 0:
raise... | python | def iteration_length(N, start=0, step=1):
'''Return the number of iteration steps over a list of length N,
starting at index start, proceeding step elements at a time.
'''
if N < 0:
raise ValueError('N cannot be negative')
if start < 0:
start += N
if start < 0:
raise... | [
"def",
"iteration_length",
"(",
"N",
",",
"start",
"=",
"0",
",",
"step",
"=",
"1",
")",
":",
"if",
"N",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'N cannot be negative'",
")",
"if",
"start",
"<",
"0",
":",
"start",
"+=",
"N",
"if",
"start",
"<",... | Return the number of iteration steps over a list of length N,
starting at index start, proceeding step elements at a time. | [
"Return",
"the",
"number",
"of",
"iteration",
"steps",
"over",
"a",
"list",
"of",
"length",
"N",
"starting",
"at",
"index",
"start",
"proceeding",
"step",
"elements",
"at",
"a",
"time",
"."
] | train | https://github.com/mbodenhamer/syn/blob/aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258/syn/base_utils/iter.py#L59-L80 |
noirbizarre/minibench | minibench/runner.py | BenchmarkRunner.run | def run(self, **kwargs):
'''
Run all benchmarks.
Extras kwargs are passed to benchmarks construtors.
'''
self.report_start()
for bench in self.benchmarks:
bench = bench(before=self.report_before_method,
after=self.report_after_method,
... | python | def run(self, **kwargs):
'''
Run all benchmarks.
Extras kwargs are passed to benchmarks construtors.
'''
self.report_start()
for bench in self.benchmarks:
bench = bench(before=self.report_before_method,
after=self.report_after_method,
... | [
"def",
"run",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"report_start",
"(",
")",
"for",
"bench",
"in",
"self",
".",
"benchmarks",
":",
"bench",
"=",
"bench",
"(",
"before",
"=",
"self",
".",
"report_before_method",
",",
"after",
"... | Run all benchmarks.
Extras kwargs are passed to benchmarks construtors. | [
"Run",
"all",
"benchmarks",
"."
] | train | https://github.com/noirbizarre/minibench/blob/a1ac66dc075181c62bb3c0d3a26beb5c46d5f4ab/minibench/runner.py#L46-L63 |
noirbizarre/minibench | minibench/runner.py | BenchmarkRunner.load_module | def load_module(self, filename):
'''Load a benchmark module from file'''
if not isinstance(filename, string_types):
return filename
basename = os.path.splitext(os.path.basename(filename))[0]
basename = basename.replace('.bench', '')
modulename = 'benchmarks.{0}'.forma... | python | def load_module(self, filename):
'''Load a benchmark module from file'''
if not isinstance(filename, string_types):
return filename
basename = os.path.splitext(os.path.basename(filename))[0]
basename = basename.replace('.bench', '')
modulename = 'benchmarks.{0}'.forma... | [
"def",
"load_module",
"(",
"self",
",",
"filename",
")",
":",
"if",
"not",
"isinstance",
"(",
"filename",
",",
"string_types",
")",
":",
"return",
"filename",
"basename",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
... | Load a benchmark module from file | [
"Load",
"a",
"benchmark",
"module",
"from",
"file"
] | train | https://github.com/noirbizarre/minibench/blob/a1ac66dc075181c62bb3c0d3a26beb5c46d5f4ab/minibench/runner.py#L65-L72 |
noirbizarre/minibench | minibench/runner.py | BenchmarkRunner.load_from_module | def load_from_module(self, module):
'''Load all benchmarks from a given module'''
benchmarks = []
for name in dir(module):
obj = getattr(module, name)
if (inspect.isclass(obj) and issubclass(obj, Benchmark)
and obj != Benchmark):
benchm... | python | def load_from_module(self, module):
'''Load all benchmarks from a given module'''
benchmarks = []
for name in dir(module):
obj = getattr(module, name)
if (inspect.isclass(obj) and issubclass(obj, Benchmark)
and obj != Benchmark):
benchm... | [
"def",
"load_from_module",
"(",
"self",
",",
"module",
")",
":",
"benchmarks",
"=",
"[",
"]",
"for",
"name",
"in",
"dir",
"(",
"module",
")",
":",
"obj",
"=",
"getattr",
"(",
"module",
",",
"name",
")",
"if",
"(",
"inspect",
".",
"isclass",
"(",
"o... | Load all benchmarks from a given module | [
"Load",
"all",
"benchmarks",
"from",
"a",
"given",
"module"
] | train | https://github.com/noirbizarre/minibench/blob/a1ac66dc075181c62bb3c0d3a26beb5c46d5f4ab/minibench/runner.py#L74-L82 |
radjkarl/fancyTools | fancytools/math/boundingBox.py | boundingBox | def boundingBox(booleanArray):
"""
return indices of the smallest bounding box enclosing all
non-zero values within an array
>>> a = np.array([ [0,0,0,0],
... [0,1,0,1],
... [0,0,1,0],
... [1,0,0,0],
... [0,0,0,0] ])
>>> pr... | python | def boundingBox(booleanArray):
"""
return indices of the smallest bounding box enclosing all
non-zero values within an array
>>> a = np.array([ [0,0,0,0],
... [0,1,0,1],
... [0,0,1,0],
... [1,0,0,0],
... [0,0,0,0] ])
>>> pr... | [
"def",
"boundingBox",
"(",
"booleanArray",
")",
":",
"w",
"=",
"np",
".",
"where",
"(",
"booleanArray",
")",
"p",
"=",
"[",
"]",
"for",
"i",
"in",
"w",
":",
"if",
"len",
"(",
"i",
")",
":",
"p",
".",
"append",
"(",
"slice",
"(",
"i",
".",
"mi... | return indices of the smallest bounding box enclosing all
non-zero values within an array
>>> a = np.array([ [0,0,0,0],
... [0,1,0,1],
... [0,0,1,0],
... [1,0,0,0],
... [0,0,0,0] ])
>>> print ( boundingBox(a) )
(slice(1, 3, No... | [
"return",
"indices",
"of",
"the",
"smallest",
"bounding",
"box",
"enclosing",
"all",
"non",
"-",
"zero",
"values",
"within",
"an",
"array"
] | train | https://github.com/radjkarl/fancyTools/blob/4c4d961003dc4ed6e46429a0c24f7e2bb52caa8b/fancytools/math/boundingBox.py#L5-L27 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/generate/containers.py | IsRPC | def IsRPC(item):
"""item -- OperationBinding instance.
"""
if not isinstance(item, WSDLTools.OperationBinding):
raise TypeError, 'IsRPC takes 1 argument of type WSDLTools.OperationBinding'
soapbinding = item.getBinding().findBinding(WSDLTools.SoapBinding)
sob = item.findBinding(WSDLTools.Soa... | python | def IsRPC(item):
"""item -- OperationBinding instance.
"""
if not isinstance(item, WSDLTools.OperationBinding):
raise TypeError, 'IsRPC takes 1 argument of type WSDLTools.OperationBinding'
soapbinding = item.getBinding().findBinding(WSDLTools.SoapBinding)
sob = item.findBinding(WSDLTools.Soa... | [
"def",
"IsRPC",
"(",
"item",
")",
":",
"if",
"not",
"isinstance",
"(",
"item",
",",
"WSDLTools",
".",
"OperationBinding",
")",
":",
"raise",
"TypeError",
",",
"'IsRPC takes 1 argument of type WSDLTools.OperationBinding'",
"soapbinding",
"=",
"item",
".",
"getBinding... | item -- OperationBinding instance. | [
"item",
"--",
"OperationBinding",
"instance",
"."
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/containers.py#L43-L53 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/generate/containers.py | IsLiteral | def IsLiteral(item):
"""item -- MessageRoleBinding instance.
"""
if not isinstance(item, WSDLTools.MessageRoleBinding):
raise TypeError, 'IsLiteral takes 1 argument of type WSDLTools.MessageRoleBinding'
sbb = None
if item.type == 'input' or item.type == 'output':
sbb = item.findBindi... | python | def IsLiteral(item):
"""item -- MessageRoleBinding instance.
"""
if not isinstance(item, WSDLTools.MessageRoleBinding):
raise TypeError, 'IsLiteral takes 1 argument of type WSDLTools.MessageRoleBinding'
sbb = None
if item.type == 'input' or item.type == 'output':
sbb = item.findBindi... | [
"def",
"IsLiteral",
"(",
"item",
")",
":",
"if",
"not",
"isinstance",
"(",
"item",
",",
"WSDLTools",
".",
"MessageRoleBinding",
")",
":",
"raise",
"TypeError",
",",
"'IsLiteral takes 1 argument of type WSDLTools.MessageRoleBinding'",
"sbb",
"=",
"None",
"if",
"item"... | item -- MessageRoleBinding instance. | [
"item",
"--",
"MessageRoleBinding",
"instance",
"."
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/containers.py#L56-L66 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/generate/containers.py | FromMessageGetSimpleElementDeclaration | def FromMessageGetSimpleElementDeclaration(message):
'''If message consists of one part with an element attribute,
and this element is a simpleType return a string representing
the python type, else return None.
'''
assert isinstance(message, WSDLTools.Message), 'expecting WSDLTools.Message'
... | python | def FromMessageGetSimpleElementDeclaration(message):
'''If message consists of one part with an element attribute,
and this element is a simpleType return a string representing
the python type, else return None.
'''
assert isinstance(message, WSDLTools.Message), 'expecting WSDLTools.Message'
... | [
"def",
"FromMessageGetSimpleElementDeclaration",
"(",
"message",
")",
":",
"assert",
"isinstance",
"(",
"message",
",",
"WSDLTools",
".",
"Message",
")",
",",
"'expecting WSDLTools.Message'",
"if",
"len",
"(",
"message",
".",
"parts",
")",
"==",
"1",
"and",
"mes... | If message consists of one part with an element attribute,
and this element is a simpleType return a string representing
the python type, else return None. | [
"If",
"message",
"consists",
"of",
"one",
"part",
"with",
"an",
"element",
"attribute",
"and",
"this",
"element",
"is",
"a",
"simpleType",
"return",
"a",
"string",
"representing",
"the",
"python",
"type",
"else",
"return",
"None",
"."
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/containers.py#L86-L107 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/generate/containers.py | AttributeMixIn._setAttributes | def _setAttributes(self, attributes):
'''parameters
attributes -- a flat list of all attributes,
from this list all items in attribute_typecode_dict will
be generated into attrComponents.
returns a list of strings representing the attribute_typecode_dict.
'''
... | python | def _setAttributes(self, attributes):
'''parameters
attributes -- a flat list of all attributes,
from this list all items in attribute_typecode_dict will
be generated into attrComponents.
returns a list of strings representing the attribute_typecode_dict.
'''
... | [
"def",
"_setAttributes",
"(",
"self",
",",
"attributes",
")",
":",
"atd",
"=",
"self",
".",
"attribute_typecode",
"atd_list",
"=",
"formatted_attribute_list",
"=",
"[",
"]",
"if",
"not",
"attributes",
":",
"return",
"formatted_attribute_list",
"atd_list",
".",
"... | parameters
attributes -- a flat list of all attributes,
from this list all items in attribute_typecode_dict will
be generated into attrComponents.
returns a list of strings representing the attribute_typecode_dict. | [
"parameters",
"attributes",
"--",
"a",
"flat",
"list",
"of",
"all",
"attributes",
"from",
"this",
"list",
"all",
"items",
"in",
"attribute_typecode_dict",
"will",
"be",
"generated",
"into",
"attrComponents",
".",
"returns",
"a",
"list",
"of",
"strings",
"represe... | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/containers.py#L120-L231 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/generate/containers.py | ContainerBase.getAttributeName | def getAttributeName(self, name):
'''represents the aname
'''
if self.func_aname is None:
return name
assert callable(self.func_aname), \
'expecting callable method for attribute func_aname, not %s' %type(self.func_aname)
f = self.func_aname
return... | python | def getAttributeName(self, name):
'''represents the aname
'''
if self.func_aname is None:
return name
assert callable(self.func_aname), \
'expecting callable method for attribute func_aname, not %s' %type(self.func_aname)
f = self.func_aname
return... | [
"def",
"getAttributeName",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"func_aname",
"is",
"None",
":",
"return",
"name",
"assert",
"callable",
"(",
"self",
".",
"func_aname",
")",
",",
"'expecting callable method for attribute func_aname, not %s'",
"%"... | represents the aname | [
"represents",
"the",
"aname"
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/containers.py#L288-L296 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/generate/containers.py | ServiceHeaderContainer.appendImport | def appendImport(self, statement):
'''append additional import statement(s).
import_stament -- tuple or list or str
'''
if type(statement) in (list,tuple):
self.extras += statement
else:
self.extras.append(statement) | python | def appendImport(self, statement):
'''append additional import statement(s).
import_stament -- tuple or list or str
'''
if type(statement) in (list,tuple):
self.extras += statement
else:
self.extras.append(statement) | [
"def",
"appendImport",
"(",
"self",
",",
"statement",
")",
":",
"if",
"type",
"(",
"statement",
")",
"in",
"(",
"list",
",",
"tuple",
")",
":",
"self",
".",
"extras",
"+=",
"statement",
"else",
":",
"self",
".",
"extras",
".",
"append",
"(",
"stateme... | append additional import statement(s).
import_stament -- tuple or list or str | [
"append",
"additional",
"import",
"statement",
"(",
"s",
")",
".",
"import_stament",
"--",
"tuple",
"or",
"list",
"or",
"str"
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/containers.py#L330-L337 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/generate/containers.py | ServiceOperationContainer.setUp | def setUp(self, item):
'''
Parameters:
item -- WSDLTools BindingOperation instance.
'''
if not isinstance(item, WSDLTools.OperationBinding):
raise TypeError, 'Expecting WSDLTools Operation instance'
if not item.input:
raise WSDLFormatError('No... | python | def setUp(self, item):
'''
Parameters:
item -- WSDLTools BindingOperation instance.
'''
if not isinstance(item, WSDLTools.OperationBinding):
raise TypeError, 'Expecting WSDLTools Operation instance'
if not item.input:
raise WSDLFormatError('No... | [
"def",
"setUp",
"(",
"self",
",",
"item",
")",
":",
"if",
"not",
"isinstance",
"(",
"item",
",",
"WSDLTools",
".",
"OperationBinding",
")",
":",
"raise",
"TypeError",
",",
"'Expecting WSDLTools Operation instance'",
"if",
"not",
"item",
".",
"input",
":",
"r... | Parameters:
item -- WSDLTools BindingOperation instance. | [
"Parameters",
":",
"item",
"--",
"WSDLTools",
"BindingOperation",
"instance",
"."
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/containers.py#L460-L526 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/generate/containers.py | ServiceOperationContainer._setContent | def _setContent(self):
'''create string representation of operation.
'''
kwstring = 'kw = {}'
tCheck = 'if isinstance(request, %s) is False:' % self.inputName
bindArgs = ''
if self.encodingStyle is not None:
bindArgs = 'encodingStyle="%s", ' %self.encodingStyl... | python | def _setContent(self):
'''create string representation of operation.
'''
kwstring = 'kw = {}'
tCheck = 'if isinstance(request, %s) is False:' % self.inputName
bindArgs = ''
if self.encodingStyle is not None:
bindArgs = 'encodingStyle="%s", ' %self.encodingStyl... | [
"def",
"_setContent",
"(",
"self",
")",
":",
"kwstring",
"=",
"'kw = {}'",
"tCheck",
"=",
"'if isinstance(request, %s) is False:'",
"%",
"self",
".",
"inputName",
"bindArgs",
"=",
"''",
"if",
"self",
".",
"encodingStyle",
"is",
"not",
"None",
":",
"bindArgs",
... | create string representation of operation. | [
"create",
"string",
"representation",
"of",
"operation",
"."
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/containers.py#L528-L691 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/generate/containers.py | BindingDescription.setUp | def setUp(self, item):
'''This method finds all SOAP Binding Operations, it will skip
all bindings that are not SOAP.
item -- WSDL.Binding instance
'''
assert isinstance(item, WSDLTools.Binding), \
'expecting WSDLTools Binding instance'
portType = item.g... | python | def setUp(self, item):
'''This method finds all SOAP Binding Operations, it will skip
all bindings that are not SOAP.
item -- WSDL.Binding instance
'''
assert isinstance(item, WSDLTools.Binding), \
'expecting WSDLTools Binding instance'
portType = item.g... | [
"def",
"setUp",
"(",
"self",
",",
"item",
")",
":",
"assert",
"isinstance",
"(",
"item",
",",
"WSDLTools",
".",
"Binding",
")",
",",
"'expecting WSDLTools Binding instance'",
"portType",
"=",
"item",
".",
"getPortType",
"(",
")",
"self",
".",
"_kwargs",
"=",... | This method finds all SOAP Binding Operations, it will skip
all bindings that are not SOAP.
item -- WSDL.Binding instance | [
"This",
"method",
"finds",
"all",
"SOAP",
"Binding",
"Operations",
"it",
"will",
"skip",
"all",
"bindings",
"that",
"are",
"not",
"SOAP",
".",
"item",
"--",
"WSDL",
".",
"Binding",
"instance"
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/containers.py#L742-L787 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/generate/containers.py | ServiceDocumentLiteralMessageContainer._setContent | def _setContent(self):
'''create string representation of doc/lit message container. If
message element is simple(primitive), use python type as base class.
'''
try:
simple = self._simple
except AttributeError:
raise RuntimeError, 'call setUp first'
... | python | def _setContent(self):
'''create string representation of doc/lit message container. If
message element is simple(primitive), use python type as base class.
'''
try:
simple = self._simple
except AttributeError:
raise RuntimeError, 'call setUp first'
... | [
"def",
"_setContent",
"(",
"self",
")",
":",
"try",
":",
"simple",
"=",
"self",
".",
"_simple",
"except",
"AttributeError",
":",
"raise",
"RuntimeError",
",",
"'call setUp first'",
"# TODO: Hidden contract. Must set self.ns before getNSAlias...",
"# File \"/usr/local/pyth... | create string representation of doc/lit message container. If
message element is simple(primitive), use python type as base class. | [
"create",
"string",
"representation",
"of",
"doc",
"/",
"lit",
"message",
"container",
".",
"If",
"message",
"element",
"is",
"simple",
"(",
"primitive",
")",
"use",
"python",
"type",
"as",
"base",
"class",
"."
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/containers.py#L896-L924 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/generate/containers.py | ServiceRPCEncodedMessageContainer.setUp | def setUp(self, port, soc, input):
'''
Instance Data:
op -- WSDLTools Operation instance
bop -- WSDLTools BindingOperation instance
input -- boolean input/output
'''
name = soc.getOperationName()
bop = port.getBinding().operations.get(name)
... | python | def setUp(self, port, soc, input):
'''
Instance Data:
op -- WSDLTools Operation instance
bop -- WSDLTools BindingOperation instance
input -- boolean input/output
'''
name = soc.getOperationName()
bop = port.getBinding().operations.get(name)
... | [
"def",
"setUp",
"(",
"self",
",",
"port",
",",
"soc",
",",
"input",
")",
":",
"name",
"=",
"soc",
".",
"getOperationName",
"(",
")",
"bop",
"=",
"port",
".",
"getBinding",
"(",
")",
".",
"operations",
".",
"get",
"(",
"name",
")",
"op",
"=",
"por... | Instance Data:
op -- WSDLTools Operation instance
bop -- WSDLTools BindingOperation instance
input -- boolean input/output | [
"Instance",
"Data",
":",
"op",
"--",
"WSDLTools",
"Operation",
"instance",
"bop",
"--",
"WSDLTools",
"BindingOperation",
"instance",
"input",
"--",
"boolean",
"input",
"/",
"output"
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/containers.py#L929-L945 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/generate/containers.py | TypecodeContainerBase.getPyClass | def getPyClass(self):
'''Name of generated inner class that will be specified as pyclass.
'''
# --> EXTENDED
if self.hasExtPyClass():
classInfo = self.extPyClasses[self.name]
return ".".join(classInfo)
# <--
return 'Holder' | python | def getPyClass(self):
'''Name of generated inner class that will be specified as pyclass.
'''
# --> EXTENDED
if self.hasExtPyClass():
classInfo = self.extPyClasses[self.name]
return ".".join(classInfo)
# <--
return 'Holder' | [
"def",
"getPyClass",
"(",
"self",
")",
":",
"# --> EXTENDED",
"if",
"self",
".",
"hasExtPyClass",
"(",
")",
":",
"classInfo",
"=",
"self",
".",
"extPyClasses",
"[",
"self",
".",
"name",
"]",
"return",
"\".\"",
".",
"join",
"(",
"classInfo",
")",
"# <-- "... | Name of generated inner class that will be specified as pyclass. | [
"Name",
"of",
"generated",
"inner",
"class",
"that",
"will",
"be",
"specified",
"as",
"pyclass",
"."
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/containers.py#L1293-L1302 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/generate/containers.py | TypecodeContainerBase.getPyClassDefinition | def getPyClassDefinition(self):
'''Return a list containing pyclass definition.
'''
kw = KW.copy()
# --> EXTENDED
if self.hasExtPyClass():
classInfo = self.extPyClasses[self.name]
kw['classInfo'] = classInfo[0]
return ["%(ID3)simport %... | python | def getPyClassDefinition(self):
'''Return a list containing pyclass definition.
'''
kw = KW.copy()
# --> EXTENDED
if self.hasExtPyClass():
classInfo = self.extPyClasses[self.name]
kw['classInfo'] = classInfo[0]
return ["%(ID3)simport %... | [
"def",
"getPyClassDefinition",
"(",
"self",
")",
":",
"kw",
"=",
"KW",
".",
"copy",
"(",
")",
"# --> EXTENDED",
"if",
"self",
".",
"hasExtPyClass",
"(",
")",
":",
"classInfo",
"=",
"self",
".",
"extPyClasses",
"[",
"self",
".",
"name",
"]",
"kw",
"[",
... | Return a list containing pyclass definition. | [
"Return",
"a",
"list",
"containing",
"pyclass",
"definition",
"."
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/containers.py#L1304-L1345 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/generate/containers.py | TypecodeContainerBase.nsuriLogic | def nsuriLogic(self):
'''set a variable "ns" that represents the targetNamespace in
which this item is defined. Used for namespacing local elements.
'''
if self.parentClass:
return 'ns = %s.%s.schema' %(self.parentClass, self.getClassName())
return 'ns = %s.%s.schema... | python | def nsuriLogic(self):
'''set a variable "ns" that represents the targetNamespace in
which this item is defined. Used for namespacing local elements.
'''
if self.parentClass:
return 'ns = %s.%s.schema' %(self.parentClass, self.getClassName())
return 'ns = %s.%s.schema... | [
"def",
"nsuriLogic",
"(",
"self",
")",
":",
"if",
"self",
".",
"parentClass",
":",
"return",
"'ns = %s.%s.schema'",
"%",
"(",
"self",
".",
"parentClass",
",",
"self",
".",
"getClassName",
"(",
")",
")",
"return",
"'ns = %s.%s.schema'",
"%",
"(",
"self",
".... | set a variable "ns" that represents the targetNamespace in
which this item is defined. Used for namespacing local elements. | [
"set",
"a",
"variable",
"ns",
"that",
"represents",
"the",
"targetNamespace",
"in",
"which",
"this",
"item",
"is",
"defined",
".",
"Used",
"for",
"namespacing",
"local",
"elements",
"."
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/containers.py#L1347-L1353 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/generate/containers.py | TypecodeContainerBase._setUpElements | def _setUpElements(self):
"""TODO: Remove this method
This method ONLY sets up the instance attributes.
Dependency instance attribute:
mgContent -- expected to be either a complex definition
with model group content, a model group, or model group
... | python | def _setUpElements(self):
"""TODO: Remove this method
This method ONLY sets up the instance attributes.
Dependency instance attribute:
mgContent -- expected to be either a complex definition
with model group content, a model group, or model group
... | [
"def",
"_setUpElements",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"_setUpElements: %s\"",
"%",
"self",
".",
"_item",
".",
"getItemTrace",
"(",
")",
")",
"if",
"hasattr",
"(",
"self",
",",
"'_done'",
")",
":",
"#return '\\n'.join(s... | TODO: Remove this method
This method ONLY sets up the instance attributes.
Dependency instance attribute:
mgContent -- expected to be either a complex definition
with model group content, a model group, or model group
content. TODO: should only supp... | [
"TODO",
":",
"Remove",
"this",
"method",
"This",
"method",
"ONLY",
"sets",
"up",
"the",
"instance",
"attributes",
".",
"Dependency",
"instance",
"attribute",
":",
"mgContent",
"--",
"expected",
"to",
"be",
"either",
"a",
"complex",
"definition",
"with",
"model... | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/containers.py#L1391-L1489 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/generate/containers.py | TypecodeContainerBase._setTypecodeList | def _setTypecodeList(self):
"""generates ofwhat content, minOccurs/maxOccurs facet generation.
Dependency instance attribute:
mgContent -- expected to be either a complex definition
with model group content, a model group, or model group
content. TODO: shoul... | python | def _setTypecodeList(self):
"""generates ofwhat content, minOccurs/maxOccurs facet generation.
Dependency instance attribute:
mgContent -- expected to be either a complex definition
with model group content, a model group, or model group
content. TODO: shoul... | [
"def",
"_setTypecodeList",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"_setTypecodeList(%r): %s\"",
"%",
"(",
"self",
".",
"mgContent",
",",
"self",
".",
"_item",
".",
"getItemTrace",
"(",
")",
")",
")",
"flat",
"=",
"[",
"]",
"... | generates ofwhat content, minOccurs/maxOccurs facet generation.
Dependency instance attribute:
mgContent -- expected to be either a complex definition
with model group content, a model group, or model group
content. TODO: should only support the first two.
... | [
"generates",
"ofwhat",
"content",
"minOccurs",
"/",
"maxOccurs",
"facet",
"generation",
".",
"Dependency",
"instance",
"attribute",
":",
"mgContent",
"--",
"expected",
"to",
"be",
"either",
"a",
"complex",
"definition",
"with",
"model",
"group",
"content",
"a",
... | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/containers.py#L1491-L1668 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/generate/containers.py | MessageTypecodeContainer._getOccurs | def _getOccurs(self, e):
'''return a 3 item tuple
'''
minOccurs = maxOccurs = '1'
nillable = True
return minOccurs,maxOccurs,nillable | python | def _getOccurs(self, e):
'''return a 3 item tuple
'''
minOccurs = maxOccurs = '1'
nillable = True
return minOccurs,maxOccurs,nillable | [
"def",
"_getOccurs",
"(",
"self",
",",
"e",
")",
":",
"minOccurs",
"=",
"maxOccurs",
"=",
"'1'",
"nillable",
"=",
"True",
"return",
"minOccurs",
",",
"maxOccurs",
",",
"nillable"
] | return a 3 item tuple | [
"return",
"a",
"3",
"item",
"tuple"
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/containers.py#L1752-L1757 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/generate/containers.py | MessageTypecodeContainer.getAttributeNames | def getAttributeNames(self):
'''returns a list of anames representing the parts
of the message.
'''
return map(lambda e: self.getAttributeName(e.name), self.tcListElements) | python | def getAttributeNames(self):
'''returns a list of anames representing the parts
of the message.
'''
return map(lambda e: self.getAttributeName(e.name), self.tcListElements) | [
"def",
"getAttributeNames",
"(",
"self",
")",
":",
"return",
"map",
"(",
"lambda",
"e",
":",
"self",
".",
"getAttributeName",
"(",
"e",
".",
"name",
")",
",",
"self",
".",
"tcListElements",
")"
] | returns a list of anames representing the parts
of the message. | [
"returns",
"a",
"list",
"of",
"anames",
"representing",
"the",
"parts",
"of",
"the",
"message",
"."
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/containers.py#L1798-L1802 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/generate/containers.py | ElementLocalComplexTypeContainer.setUp | def setUp(self, tp):
'''
{'xsd':['annotation', 'simpleContent', 'complexContent',\
'group', 'all', 'choice', 'sequence', 'attribute', 'attributeGroup',\
'anyAttribute', 'any']}
'''
#
# TODO: Need a Recursive solution, this is incomplete will ignore many
#... | python | def setUp(self, tp):
'''
{'xsd':['annotation', 'simpleContent', 'complexContent',\
'group', 'all', 'choice', 'sequence', 'attribute', 'attributeGroup',\
'anyAttribute', 'any']}
'''
#
# TODO: Need a Recursive solution, this is incomplete will ignore many
#... | [
"def",
"setUp",
"(",
"self",
",",
"tp",
")",
":",
"# ",
"# TODO: Need a Recursive solution, this is incomplete will ignore many",
"# extensions, restrictions, etc.",
"# ",
"self",
".",
"_item",
"=",
"tp",
"# JRB HACK SUPPORTING element/no content.",
"assert",
"tp",
".",
"i... | {'xsd':['annotation', 'simpleContent', 'complexContent',\
'group', 'all', 'choice', 'sequence', 'attribute', 'attributeGroup',\
'anyAttribute', 'any']} | [
"{",
"xsd",
":",
"[",
"annotation",
"simpleContent",
"complexContent",
"\\",
"group",
"all",
"choice",
"sequence",
"attribute",
"attributeGroup",
"\\",
"anyAttribute",
"any",
"]",
"}"
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/containers.py#L2190-L2279 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/generate/containers.py | ElementGlobalDefContainer._setContent | def _setContent(self):
'''GED defines element name, so also define typecode aname
'''
kw = KW.copy()
try:
kw.update(dict(klass=self.getClassName(),
element='ElementDeclaration',
literal=self.literalTag(),
su... | python | def _setContent(self):
'''GED defines element name, so also define typecode aname
'''
kw = KW.copy()
try:
kw.update(dict(klass=self.getClassName(),
element='ElementDeclaration',
literal=self.literalTag(),
su... | [
"def",
"_setContent",
"(",
"self",
")",
":",
"kw",
"=",
"KW",
".",
"copy",
"(",
")",
"try",
":",
"kw",
".",
"update",
"(",
"dict",
"(",
"klass",
"=",
"self",
".",
"getClassName",
"(",
")",
",",
"element",
"=",
"'ElementDeclaration'",
",",
"literal",
... | GED defines element name, so also define typecode aname | [
"GED",
"defines",
"element",
"name",
"so",
"also",
"define",
"typecode",
"aname"
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/containers.py#L2294-L2337 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/generate/containers.py | ComplexTypeComplexContentContainer.setUp | def setUp(self, tp):
'''complexContent/[extension,restriction]
restriction
extension
extType -- used in figuring attrs for extensions
'''
self._item = tp
assert tp.content.isComplex() is True and \
(tp.content.content.isRestriction() or tp.... | python | def setUp(self, tp):
'''complexContent/[extension,restriction]
restriction
extension
extType -- used in figuring attrs for extensions
'''
self._item = tp
assert tp.content.isComplex() is True and \
(tp.content.content.isRestriction() or tp.... | [
"def",
"setUp",
"(",
"self",
",",
"tp",
")",
":",
"self",
".",
"_item",
"=",
"tp",
"assert",
"tp",
".",
"content",
".",
"isComplex",
"(",
")",
"is",
"True",
"and",
"(",
"tp",
".",
"content",
".",
"content",
".",
"isRestriction",
"(",
")",
"or",
"... | complexContent/[extension,restriction]
restriction
extension
extType -- used in figuring attrs for extensions | [
"complexContent",
"/",
"[",
"extension",
"restriction",
"]",
"restriction",
"extension",
"extType",
"--",
"used",
"in",
"figuring",
"attrs",
"for",
"extensions"
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/containers.py#L2360-L2493 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/generate/containers.py | ComplexTypeComplexContentContainer._setContent | def _setContent(self):
'''JRB What is the difference between instance data
ns, name, -- type definition?
sKlass, sKlassNS? -- element declaration?
'''
kw = KW.copy()
definition = []
if self._is_array:
# SOAP-ENC:Array
if _is_xsd_or_soap_ns(... | python | def _setContent(self):
'''JRB What is the difference between instance data
ns, name, -- type definition?
sKlass, sKlassNS? -- element declaration?
'''
kw = KW.copy()
definition = []
if self._is_array:
# SOAP-ENC:Array
if _is_xsd_or_soap_ns(... | [
"def",
"_setContent",
"(",
"self",
")",
":",
"kw",
"=",
"KW",
".",
"copy",
"(",
")",
"definition",
"=",
"[",
"]",
"if",
"self",
".",
"_is_array",
":",
"# SOAP-ENC:Array",
"if",
"_is_xsd_or_soap_ns",
"(",
"self",
".",
"sKlassNS",
")",
"is",
"False",
"an... | JRB What is the difference between instance data
ns, name, -- type definition?
sKlass, sKlassNS? -- element declaration? | [
"JRB",
"What",
"is",
"the",
"difference",
"between",
"instance",
"data",
"ns",
"name",
"--",
"type",
"definition?",
"sKlass",
"sKlassNS?",
"--",
"element",
"declaration?"
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/containers.py#L2495-L2600 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/generate/containers.py | ComplexTypeContainer.setUp | def setUp(self, tp, empty=False):
'''Problematic, loose all model group information.
<all>, <choice>, <sequence> ..
tp -- type definition
empty -- no model group, just use as a dummy holder.
'''
self._item = tp
self.name = tp.getAttribute('name')
... | python | def setUp(self, tp, empty=False):
'''Problematic, loose all model group information.
<all>, <choice>, <sequence> ..
tp -- type definition
empty -- no model group, just use as a dummy holder.
'''
self._item = tp
self.name = tp.getAttribute('name')
... | [
"def",
"setUp",
"(",
"self",
",",
"tp",
",",
"empty",
"=",
"False",
")",
":",
"self",
".",
"_item",
"=",
"tp",
"self",
".",
"name",
"=",
"tp",
".",
"getAttribute",
"(",
"'name'",
")",
"self",
".",
"ns",
"=",
"tp",
".",
"getTargetNamespace",
"(",
... | Problematic, loose all model group information.
<all>, <choice>, <sequence> ..
tp -- type definition
empty -- no model group, just use as a dummy holder. | [
"Problematic",
"loose",
"all",
"model",
"group",
"information",
".",
"<all",
">",
"<choice",
">",
"<sequence",
">",
".."
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/containers.py#L2615-L2648 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/generate/containers.py | ComplexTypeSimpleContentContainer.setUp | def setUp(self, tp):
'''tp -- complexType/simpleContent/[Exention,Restriction]
'''
self._item = tp
assert tp.isComplex() is True and tp.content.isSimple() is True,\
'expecting complexType/simpleContent not: %s' %tp.content.getItemTrace()
simple = tp.content
... | python | def setUp(self, tp):
'''tp -- complexType/simpleContent/[Exention,Restriction]
'''
self._item = tp
assert tp.isComplex() is True and tp.content.isSimple() is True,\
'expecting complexType/simpleContent not: %s' %tp.content.getItemTrace()
simple = tp.content
... | [
"def",
"setUp",
"(",
"self",
",",
"tp",
")",
":",
"self",
".",
"_item",
"=",
"tp",
"assert",
"tp",
".",
"isComplex",
"(",
")",
"is",
"True",
"and",
"tp",
".",
"content",
".",
"isSimple",
"(",
")",
"is",
"True",
",",
"'expecting complexType/simpleConten... | tp -- complexType/simpleContent/[Exention,Restriction] | [
"tp",
"--",
"complexType",
"/",
"simpleContent",
"/",
"[",
"Exention",
"Restriction",
"]"
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/containers.py#L2850-L2881 |
ronaldguillen/wave | wave/utils/model_meta.py | _resolve_model | def _resolve_model(obj):
"""
Resolve supplied `obj` to a Django model class.
`obj` must be a Django model class itself, or a string
representation of one. Useful in situations like GH #1225 where
Django may not have resolved a string-based reference to a model in
another model's foreign key de... | python | def _resolve_model(obj):
"""
Resolve supplied `obj` to a Django model class.
`obj` must be a Django model class itself, or a string
representation of one. Useful in situations like GH #1225 where
Django may not have resolved a string-based reference to a model in
another model's foreign key de... | [
"def",
"_resolve_model",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"six",
".",
"string_types",
")",
"and",
"len",
"(",
"obj",
".",
"split",
"(",
"'.'",
")",
")",
"==",
"2",
":",
"app_name",
",",
"model_name",
"=",
"obj",
".",
"spli... | Resolve supplied `obj` to a Django model class.
`obj` must be a Django model class itself, or a string
representation of one. Useful in situations like GH #1225 where
Django may not have resolved a string-based reference to a model in
another model's foreign key definition.
String representations... | [
"Resolve",
"supplied",
"obj",
"to",
"a",
"Django",
"model",
"class",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/utils/model_meta.py#L38-L59 |
ronaldguillen/wave | wave/utils/model_meta.py | get_field_info | def get_field_info(model):
"""
Given a model class, returns a `FieldInfo` instance, which is a
`namedtuple`, containing metadata about the various field types on the model
including information about their relationships.
"""
opts = model._meta.concrete_model._meta
pk = _get_pk(opts)
fie... | python | def get_field_info(model):
"""
Given a model class, returns a `FieldInfo` instance, which is a
`namedtuple`, containing metadata about the various field types on the model
including information about their relationships.
"""
opts = model._meta.concrete_model._meta
pk = _get_pk(opts)
fie... | [
"def",
"get_field_info",
"(",
"model",
")",
":",
"opts",
"=",
"model",
".",
"_meta",
".",
"concrete_model",
".",
"_meta",
"pk",
"=",
"_get_pk",
"(",
"opts",
")",
"fields",
"=",
"_get_fields",
"(",
"opts",
")",
"forward_relations",
"=",
"_get_forward_relation... | Given a model class, returns a `FieldInfo` instance, which is a
`namedtuple`, containing metadata about the various field types on the model
including information about their relationships. | [
"Given",
"a",
"model",
"class",
"returns",
"a",
"FieldInfo",
"instance",
"which",
"is",
"a",
"namedtuple",
"containing",
"metadata",
"about",
"the",
"various",
"field",
"types",
"on",
"the",
"model",
"including",
"information",
"about",
"their",
"relationships",
... | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/utils/model_meta.py#L62-L78 |
ronaldguillen/wave | wave/utils/model_meta.py | _get_forward_relationships | def _get_forward_relationships(opts):
"""
Returns an `OrderedDict` of field names to `RelationInfo`.
"""
forward_relations = OrderedDict()
for field in [field for field in opts.fields if field.serialize and field.rel]:
forward_relations[field.name] = RelationInfo(
model_field=fie... | python | def _get_forward_relationships(opts):
"""
Returns an `OrderedDict` of field names to `RelationInfo`.
"""
forward_relations = OrderedDict()
for field in [field for field in opts.fields if field.serialize and field.rel]:
forward_relations[field.name] = RelationInfo(
model_field=fie... | [
"def",
"_get_forward_relationships",
"(",
"opts",
")",
":",
"forward_relations",
"=",
"OrderedDict",
"(",
")",
"for",
"field",
"in",
"[",
"field",
"for",
"field",
"in",
"opts",
".",
"fields",
"if",
"field",
".",
"serialize",
"and",
"field",
".",
"rel",
"]"... | Returns an `OrderedDict` of field names to `RelationInfo`. | [
"Returns",
"an",
"OrderedDict",
"of",
"field",
"names",
"to",
"RelationInfo",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/utils/model_meta.py#L102-L129 |
ronaldguillen/wave | wave/utils/model_meta.py | _get_reverse_relationships | def _get_reverse_relationships(opts):
"""
Returns an `OrderedDict` of field names to `RelationInfo`.
"""
# Note that we have a hack here to handle internal API differences for
# this internal API across Django 1.7 -> Django 1.8.
# See: https://code.djangoproject.com/ticket/24208
reverse_rel... | python | def _get_reverse_relationships(opts):
"""
Returns an `OrderedDict` of field names to `RelationInfo`.
"""
# Note that we have a hack here to handle internal API differences for
# this internal API across Django 1.7 -> Django 1.8.
# See: https://code.djangoproject.com/ticket/24208
reverse_rel... | [
"def",
"_get_reverse_relationships",
"(",
"opts",
")",
":",
"# Note that we have a hack here to handle internal API differences for",
"# this internal API across Django 1.7 -> Django 1.8.",
"# See: https://code.djangoproject.com/ticket/24208",
"reverse_relations",
"=",
"OrderedDict",
"(",
... | Returns an `OrderedDict` of field names to `RelationInfo`. | [
"Returns",
"an",
"OrderedDict",
"of",
"field",
"names",
"to",
"RelationInfo",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/utils/model_meta.py#L132-L168 |
ronaldguillen/wave | wave/utils/model_meta.py | is_abstract_model | def is_abstract_model(model):
"""
Given a model class, returns a boolean True if it is abstract and False if it is not.
"""
return hasattr(model, '_meta') and hasattr(model._meta, 'abstract') and model._meta.abstract | python | def is_abstract_model(model):
"""
Given a model class, returns a boolean True if it is abstract and False if it is not.
"""
return hasattr(model, '_meta') and hasattr(model._meta, 'abstract') and model._meta.abstract | [
"def",
"is_abstract_model",
"(",
"model",
")",
":",
"return",
"hasattr",
"(",
"model",
",",
"'_meta'",
")",
"and",
"hasattr",
"(",
"model",
".",
"_meta",
",",
"'abstract'",
")",
"and",
"model",
".",
"_meta",
".",
"abstract"
] | Given a model class, returns a boolean True if it is abstract and False if it is not. | [
"Given",
"a",
"model",
"class",
"returns",
"a",
"boolean",
"True",
"if",
"it",
"is",
"abstract",
"and",
"False",
"if",
"it",
"is",
"not",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/utils/model_meta.py#L187-L191 |
radjkarl/fancyTools | fancytools/math/linRegressUsingMasked2dArrays.py | linRegressUsingMasked2dArrays | def linRegressUsingMasked2dArrays(xVals, arrays, badMask=None,
zeroOffset=False,
calcError=False):
"""
if you have multiple 2d arrays each with position given by
xVals[array-index]
and you want to do a linear regression on all cells
... | python | def linRegressUsingMasked2dArrays(xVals, arrays, badMask=None,
zeroOffset=False,
calcError=False):
"""
if you have multiple 2d arrays each with position given by
xVals[array-index]
and you want to do a linear regression on all cells
... | [
"def",
"linRegressUsingMasked2dArrays",
"(",
"xVals",
",",
"arrays",
",",
"badMask",
"=",
"None",
",",
"zeroOffset",
"=",
"False",
",",
"calcError",
"=",
"False",
")",
":",
"assert",
"arrays",
".",
"ndim",
"==",
"3",
",",
"'need multiple 2d arrays'",
"if",
"... | if you have multiple 2d arrays each with position given by
xVals[array-index]
and you want to do a linear regression on all cells
but you also might mask different areas in each 2darray
zeroOffset - whether plot goest through origin
returns ascent, offset, RMS-error | [
"if",
"you",
"have",
"multiple",
"2d",
"arrays",
"each",
"with",
"position",
"given",
"by",
"xVals",
"[",
"array",
"-",
"index",
"]",
"and",
"you",
"want",
"to",
"do",
"a",
"linear",
"regression",
"on",
"all",
"cells",
"but",
"you",
"also",
"might",
"m... | train | https://github.com/radjkarl/fancyTools/blob/4c4d961003dc4ed6e46429a0c24f7e2bb52caa8b/fancytools/math/linRegressUsingMasked2dArrays.py#L6-L67 |
ravenac95/lxc4u | lxc4u/utils.py | LXCService.create | def create(cls, *args, **kwargs):
"""Creates an LXC"""
container = LXC.create(*args, **kwargs)
return container | python | def create(cls, *args, **kwargs):
"""Creates an LXC"""
container = LXC.create(*args, **kwargs)
return container | [
"def",
"create",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"container",
"=",
"LXC",
".",
"create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"container"
] | Creates an LXC | [
"Creates",
"an",
"LXC"
] | train | https://github.com/ravenac95/lxc4u/blob/4b5a9c8e25af97e5637db2f4c0c67d319ab0ed32/lxc4u/utils.py#L12-L15 |
collectiveacuity/labPack | labpack/email/mailgun.py | mailgunClient.validate_email | def validate_email(self, email_address):
'''
a method to validate an email address
:param email_address: string with email address to validate
:return: dictionary with validation fields in response_details['json']
'''
title = '%s.validate_email... | python | def validate_email(self, email_address):
'''
a method to validate an email address
:param email_address: string with email address to validate
:return: dictionary with validation fields in response_details['json']
'''
title = '%s.validate_email... | [
"def",
"validate_email",
"(",
"self",
",",
"email_address",
")",
":",
"title",
"=",
"'%s.validate_email'",
"%",
"__class__",
".",
"__name__",
"# validate inputs\r",
"object_title",
"=",
"'%s(email_address=\"\")'",
"%",
"title",
"email_address",
"=",
"self",
".",
"fi... | a method to validate an email address
:param email_address: string with email address to validate
:return: dictionary with validation fields in response_details['json'] | [
"a",
"method",
"to",
"validate",
"an",
"email",
"address",
":",
"param",
"email_address",
":",
"string",
"with",
"email",
"address",
"to",
"validate",
":",
"return",
":",
"dictionary",
"with",
"validation",
"fields",
"in",
"response_details",
"[",
"json",
"]"
... | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/email/mailgun.py#L264-L288 |
infant-cognition-tampere/fixationmodel-py | fixationmodel/__init__.py | fit | def fit(pointlist):
'''
Parameters
pointlist
[[x0,y0], [x1,y1], [x2,y2], ...]
Points [None, None] are allowed but ignored.
'''
# Separate x and y and clear Nones
is_num = lambda x: isinstance(x, Number)
pick_x = lambda x: x[0]
pick_y = lambda x: x[1]
xs =... | python | def fit(pointlist):
'''
Parameters
pointlist
[[x0,y0], [x1,y1], [x2,y2], ...]
Points [None, None] are allowed but ignored.
'''
# Separate x and y and clear Nones
is_num = lambda x: isinstance(x, Number)
pick_x = lambda x: x[0]
pick_y = lambda x: x[1]
xs =... | [
"def",
"fit",
"(",
"pointlist",
")",
":",
"# Separate x and y and clear Nones",
"is_num",
"=",
"lambda",
"x",
":",
"isinstance",
"(",
"x",
",",
"Number",
")",
"pick_x",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
"pick_y",
"=",
"lambda",
"x",
":",
"x"... | Parameters
pointlist
[[x0,y0], [x1,y1], [x2,y2], ...]
Points [None, None] are allowed but ignored. | [
"Parameters",
"pointlist",
"[[",
"x0",
"y0",
"]",
"[",
"x1",
"y1",
"]",
"[",
"x2",
"y2",
"]",
"...",
"]",
"Points",
"[",
"None",
"None",
"]",
"are",
"allowed",
"but",
"ignored",
"."
] | train | https://github.com/infant-cognition-tampere/fixationmodel-py/blob/fe44356140c9790c55df9b47072d7b96f9cd8b37/fixationmodel/__init__.py#L14-L45 |
radjkarl/fancyTools | fancytools/math/angleDiff.py | angleDiff | def angleDiff(angle1, angle2, take_smaller=True):
"""
smallest difference between 2 angles
code from http://stackoverflow.com/questions/1878907/the-smallest-difference-between-2-angles
"""
a = np.arctan2(np.sin(angle1 - angle2), np.cos(angle1 - angle2))
if isinstance(a, np.ndarray) and take_smal... | python | def angleDiff(angle1, angle2, take_smaller=True):
"""
smallest difference between 2 angles
code from http://stackoverflow.com/questions/1878907/the-smallest-difference-between-2-angles
"""
a = np.arctan2(np.sin(angle1 - angle2), np.cos(angle1 - angle2))
if isinstance(a, np.ndarray) and take_smal... | [
"def",
"angleDiff",
"(",
"angle1",
",",
"angle2",
",",
"take_smaller",
"=",
"True",
")",
":",
"a",
"=",
"np",
".",
"arctan2",
"(",
"np",
".",
"sin",
"(",
"angle1",
"-",
"angle2",
")",
",",
"np",
".",
"cos",
"(",
"angle1",
"-",
"angle2",
")",
")",... | smallest difference between 2 angles
code from http://stackoverflow.com/questions/1878907/the-smallest-difference-between-2-angles | [
"smallest",
"difference",
"between",
"2",
"angles",
"code",
"from",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"1878907",
"/",
"the",
"-",
"smallest",
"-",
"difference",
"-",
"between",
"-",
"2",
"-",
"angles"
] | train | https://github.com/radjkarl/fancyTools/blob/4c4d961003dc4ed6e46429a0c24f7e2bb52caa8b/fancytools/math/angleDiff.py#L5-L18 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/twisted/wsgi.py | SOAPCallbackHandler.processRequest | def processRequest(cls, ps, **kw):
"""invokes callback that should return a (request,response) tuple.
representing the SOAP request and response respectively.
ps -- ParsedSoap instance representing HTTP Body.
request -- twisted.web.server.Request
"""
resource = kw['resour... | python | def processRequest(cls, ps, **kw):
"""invokes callback that should return a (request,response) tuple.
representing the SOAP request and response respectively.
ps -- ParsedSoap instance representing HTTP Body.
request -- twisted.web.server.Request
"""
resource = kw['resour... | [
"def",
"processRequest",
"(",
"cls",
",",
"ps",
",",
"*",
"*",
"kw",
")",
":",
"resource",
"=",
"kw",
"[",
"'resource'",
"]",
"request",
"=",
"kw",
"[",
"'request'",
"]",
"root",
"=",
"_get_element_nsuri_name",
"(",
"ps",
".",
"body_root",
")",
"for",
... | invokes callback that should return a (request,response) tuple.
representing the SOAP request and response respectively.
ps -- ParsedSoap instance representing HTTP Body.
request -- twisted.web.server.Request | [
"invokes",
"callback",
"that",
"should",
"return",
"a",
"(",
"request",
"response",
")",
"tuple",
".",
"representing",
"the",
"SOAP",
"request",
"and",
"response",
"respectively",
".",
"ps",
"--",
"ParsedSoap",
"instance",
"representing",
"HTTP",
"Body",
".",
... | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/twisted/wsgi.py#L52-L82 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/twisted/wsgi.py | SOAPApplication._request_cb | def _request_cb(self, env, start_response):
"""process request,
"""
if env['REQUEST_METHOD'] == 'GET':
return self._handle_GET(env, start_response)
if env['REQUEST_METHOD'] == 'POST':
return self._handle_POST(env, start_response)
start_respo... | python | def _request_cb(self, env, start_response):
"""process request,
"""
if env['REQUEST_METHOD'] == 'GET':
return self._handle_GET(env, start_response)
if env['REQUEST_METHOD'] == 'POST':
return self._handle_POST(env, start_response)
start_respo... | [
"def",
"_request_cb",
"(",
"self",
",",
"env",
",",
"start_response",
")",
":",
"if",
"env",
"[",
"'REQUEST_METHOD'",
"]",
"==",
"'GET'",
":",
"return",
"self",
".",
"_handle_GET",
"(",
"env",
",",
"start_response",
")",
"if",
"env",
"[",
"'REQUEST_METHOD'... | process request, | [
"process",
"request"
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/twisted/wsgi.py#L158-L172 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/twisted/wsgi.py | SOAPApplication._handle_POST | def _handle_POST(self, env, start_response):
"""Dispatch Method called by twisted render, creates a
request/response handler chain.
request -- twisted.web.server.Request
"""
input = env['wsgi.input']
data = input.read( int(env['CONTENT_LENGTH']) )
mimeType = "text... | python | def _handle_POST(self, env, start_response):
"""Dispatch Method called by twisted render, creates a
request/response handler chain.
request -- twisted.web.server.Request
"""
input = env['wsgi.input']
data = input.read( int(env['CONTENT_LENGTH']) )
mimeType = "text... | [
"def",
"_handle_POST",
"(",
"self",
",",
"env",
",",
"start_response",
")",
":",
"input",
"=",
"env",
"[",
"'wsgi.input'",
"]",
"data",
"=",
"input",
".",
"read",
"(",
"int",
"(",
"env",
"[",
"'CONTENT_LENGTH'",
"]",
")",
")",
"mimeType",
"=",
"\"text/... | Dispatch Method called by twisted render, creates a
request/response handler chain.
request -- twisted.web.server.Request | [
"Dispatch",
"Method",
"called",
"by",
"twisted",
"render",
"creates",
"a",
"request",
"/",
"response",
"handler",
"chain",
".",
"request",
"--",
"twisted",
".",
"web",
".",
"server",
".",
"Request"
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/twisted/wsgi.py#L183-L210 |
praekeltfoundation/seed-control-interface-service | services/tasks.py | DeliverHook.run | def run(self, target, payload, instance_id=None, hook_id=None, **kwargs):
"""
target: the url to receive the payload.
payload: a python primitive data structure
instance_id: a possibly None "trigger" instance ID
hook_id: the ID of defining Hook object
"""
... | python | def run(self, target, payload, instance_id=None, hook_id=None, **kwargs):
"""
target: the url to receive the payload.
payload: a python primitive data structure
instance_id: a possibly None "trigger" instance ID
hook_id: the ID of defining Hook object
"""
... | [
"def",
"run",
"(",
"self",
",",
"target",
",",
"payload",
",",
"instance_id",
"=",
"None",
",",
"hook_id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"requests",
".",
"post",
"(",
"url",
"=",
"target",
",",
"data",
"=",
"json",
".",
"dumps",
... | target: the url to receive the payload.
payload: a python primitive data structure
instance_id: a possibly None "trigger" instance ID
hook_id: the ID of defining Hook object | [
"target",
":",
"the",
"url",
"to",
"receive",
"the",
"payload",
".",
"payload",
":",
"a",
"python",
"primitive",
"data",
"structure",
"instance_id",
":",
"a",
"possibly",
"None",
"trigger",
"instance",
"ID",
"hook_id",
":",
"the",
"ID",
"of",
"defining",
"... | train | https://github.com/praekeltfoundation/seed-control-interface-service/blob/0c8ec58ae61e72d4443e6c9a4d8b7dd12dd8a86e/services/tasks.py#L23-L37 |
praekeltfoundation/seed-control-interface-service | services/tasks.py | QueuePollService.run | def run(self):
"""
Queues all services to be polled. Should be run via beat.
"""
services = Service.objects.all()
for service in services:
poll_service.apply_async(kwargs={"service_id": str(service.id)})
return "Queued <%s> Service(s) for Polling" % services.c... | python | def run(self):
"""
Queues all services to be polled. Should be run via beat.
"""
services = Service.objects.all()
for service in services:
poll_service.apply_async(kwargs={"service_id": str(service.id)})
return "Queued <%s> Service(s) for Polling" % services.c... | [
"def",
"run",
"(",
"self",
")",
":",
"services",
"=",
"Service",
".",
"objects",
".",
"all",
"(",
")",
"for",
"service",
"in",
"services",
":",
"poll_service",
".",
"apply_async",
"(",
"kwargs",
"=",
"{",
"\"service_id\"",
":",
"str",
"(",
"service",
"... | Queues all services to be polled. Should be run via beat. | [
"Queues",
"all",
"services",
"to",
"be",
"polled",
".",
"Should",
"be",
"run",
"via",
"beat",
"."
] | train | https://github.com/praekeltfoundation/seed-control-interface-service/blob/0c8ec58ae61e72d4443e6c9a4d8b7dd12dd8a86e/services/tasks.py#L81-L88 |
praekeltfoundation/seed-control-interface-service | services/tasks.py | PollService.run | def run(self, service_id, **kwargs):
"""
Retrieve a status from remote service. Set the up/down state and log.
"""
log = self.get_logger(**kwargs)
log.info("Loading Service for healthcheck")
try:
service = Service.objects.get(id=service_id)
log.in... | python | def run(self, service_id, **kwargs):
"""
Retrieve a status from remote service. Set the up/down state and log.
"""
log = self.get_logger(**kwargs)
log.info("Loading Service for healthcheck")
try:
service = Service.objects.get(id=service_id)
log.in... | [
"def",
"run",
"(",
"self",
",",
"service_id",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
"=",
"self",
".",
"get_logger",
"(",
"*",
"*",
"kwargs",
")",
"log",
".",
"info",
"(",
"\"Loading Service for healthcheck\"",
")",
"try",
":",
"service",
"=",
"Serv... | Retrieve a status from remote service. Set the up/down state and log. | [
"Retrieve",
"a",
"status",
"from",
"remote",
"service",
".",
"Set",
"the",
"up",
"/",
"down",
"state",
"and",
"log",
"."
] | train | https://github.com/praekeltfoundation/seed-control-interface-service/blob/0c8ec58ae61e72d4443e6c9a4d8b7dd12dd8a86e/services/tasks.py#L116-L166 |
praekeltfoundation/seed-control-interface-service | services/tasks.py | GetUserToken.run | def run(self, service_id, user_id, email, **kwargs):
"""
Create and Retrieve a token from remote service. Save to DB.
"""
log = self.get_logger(**kwargs)
log.info("Loading Service for token creation")
try:
service = Service.objects.get(id=service_id)
... | python | def run(self, service_id, user_id, email, **kwargs):
"""
Create and Retrieve a token from remote service. Save to DB.
"""
log = self.get_logger(**kwargs)
log.info("Loading Service for token creation")
try:
service = Service.objects.get(id=service_id)
... | [
"def",
"run",
"(",
"self",
",",
"service_id",
",",
"user_id",
",",
"email",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
"=",
"self",
".",
"get_logger",
"(",
"*",
"*",
"kwargs",
")",
"log",
".",
"info",
"(",
"\"Loading Service for token creation\"",
")",
... | Create and Retrieve a token from remote service. Save to DB. | [
"Create",
"and",
"Retrieve",
"a",
"token",
"from",
"remote",
"service",
".",
"Save",
"to",
"DB",
"."
] | train | https://github.com/praekeltfoundation/seed-control-interface-service/blob/0c8ec58ae61e72d4443e6c9a4d8b7dd12dd8a86e/services/tasks.py#L195-L225 |
praekeltfoundation/seed-control-interface-service | services/tasks.py | QueueServiceMetricSync.run | def run(self):
"""
Queues all services to be polled for metrics. Should be run via beat.
"""
services = Service.objects.all()
for service in services:
service_metric_sync.apply_async(
kwargs={"service_id": str(service.id)})
key = "service... | python | def run(self):
"""
Queues all services to be polled for metrics. Should be run via beat.
"""
services = Service.objects.all()
for service in services:
service_metric_sync.apply_async(
kwargs={"service_id": str(service.id)})
key = "service... | [
"def",
"run",
"(",
"self",
")",
":",
"services",
"=",
"Service",
".",
"objects",
".",
"all",
"(",
")",
"for",
"service",
"in",
"services",
":",
"service_metric_sync",
".",
"apply_async",
"(",
"kwargs",
"=",
"{",
"\"service_id\"",
":",
"str",
"(",
"servic... | Queues all services to be polled for metrics. Should be run via beat. | [
"Queues",
"all",
"services",
"to",
"be",
"polled",
"for",
"metrics",
".",
"Should",
"be",
"run",
"via",
"beat",
"."
] | train | https://github.com/praekeltfoundation/seed-control-interface-service/blob/0c8ec58ae61e72d4443e6c9a4d8b7dd12dd8a86e/services/tasks.py#L232-L251 |
praekeltfoundation/seed-control-interface-service | services/tasks.py | ServiceMetricSync.run | def run(self, service_id, **kwargs):
"""
Retrieve a list of metrics. Ensure they are set as metric data sources.
"""
log = self.get_logger(**kwargs)
log.info("Loading Service for metric sync")
try:
service = Service.objects.get(id=service_id)
log.... | python | def run(self, service_id, **kwargs):
"""
Retrieve a list of metrics. Ensure they are set as metric data sources.
"""
log = self.get_logger(**kwargs)
log.info("Loading Service for metric sync")
try:
service = Service.objects.get(id=service_id)
log.... | [
"def",
"run",
"(",
"self",
",",
"service_id",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
"=",
"self",
".",
"get_logger",
"(",
"*",
"*",
"kwargs",
")",
"log",
".",
"info",
"(",
"\"Loading Service for metric sync\"",
")",
"try",
":",
"service",
"=",
"Serv... | Retrieve a list of metrics. Ensure they are set as metric data sources. | [
"Retrieve",
"a",
"list",
"of",
"metrics",
".",
"Ensure",
"they",
"are",
"set",
"as",
"metric",
"data",
"sources",
"."
] | train | https://github.com/praekeltfoundation/seed-control-interface-service/blob/0c8ec58ae61e72d4443e6c9a4d8b7dd12dd8a86e/services/tasks.py#L279-L309 |
telminov/sw-django-rest-auth | sw_rest_auth/views.py | check_token | def check_token(request):
"""
Resource check is token valid.
---
request_serializer: serializers.CheckToken
type:
username:
required: true
type: string
description: token related user
responseMessages:
- code: 200
message: Token is v... | python | def check_token(request):
"""
Resource check is token valid.
---
request_serializer: serializers.CheckToken
type:
username:
required: true
type: string
description: token related user
responseMessages:
- code: 200
message: Token is v... | [
"def",
"check_token",
"(",
"request",
")",
":",
"serializer",
"=",
"serializers",
".",
"CheckToken",
"(",
"data",
"=",
"request",
".",
"data",
")",
"serializer",
".",
"is_valid",
"(",
"raise_exception",
"=",
"True",
")",
"token",
"=",
"serializer",
".",
"v... | Resource check is token valid.
---
request_serializer: serializers.CheckToken
type:
username:
required: true
type: string
description: token related user
responseMessages:
- code: 200
message: Token is valid
- code: 400
me... | [
"Resource",
"check",
"is",
"token",
"valid",
".",
"---",
"request_serializer",
":",
"serializers",
".",
"CheckToken",
"type",
":",
"username",
":",
"required",
":",
"true",
"type",
":",
"string",
"description",
":",
"token",
"related",
"user"
] | train | https://github.com/telminov/sw-django-rest-auth/blob/ba63b6d6c86e4325cac38ae8e2fde1501b47ce0a/sw_rest_auth/views.py#L14-L39 |
telminov/sw-django-rest-auth | sw_rest_auth/views.py | check_login_password | def check_login_password(request):
"""
Resource check login and password combination is valid.
---
request_serializer: serializers.CheckLoginPassword
response_serializer: serializers.User
responseMessages:
- code: 200
message: Login and password is valid
- code: 400
... | python | def check_login_password(request):
"""
Resource check login and password combination is valid.
---
request_serializer: serializers.CheckLoginPassword
response_serializer: serializers.User
responseMessages:
- code: 200
message: Login and password is valid
- code: 400
... | [
"def",
"check_login_password",
"(",
"request",
")",
":",
"serializer",
"=",
"serializers",
".",
"CheckLoginPassword",
"(",
"request",
"=",
"request",
",",
"data",
"=",
"request",
".",
"data",
")",
"serializer",
".",
"is_valid",
"(",
"raise_exception",
"=",
"Tr... | Resource check login and password combination is valid.
---
request_serializer: serializers.CheckLoginPassword
response_serializer: serializers.User
responseMessages:
- code: 200
message: Login and password is valid
- code: 400
message: Login and password is not val... | [
"Resource",
"check",
"login",
"and",
"password",
"combination",
"is",
"valid",
".",
"---",
"request_serializer",
":",
"serializers",
".",
"CheckLoginPassword",
"response_serializer",
":",
"serializers",
".",
"User"
] | train | https://github.com/telminov/sw-django-rest-auth/blob/ba63b6d6c86e4325cac38ae8e2fde1501b47ce0a/sw_rest_auth/views.py#L44-L66 |
telminov/sw-django-rest-auth | sw_rest_auth/views.py | check_perm | def check_perm(request):
"""
Check user permission.
---
request_serializer: serializers.CheckPerm
parameters:
- name: user
type: string
required: true
description: username
paramType: query
- name: perm
type: string
requir... | python | def check_perm(request):
"""
Check user permission.
---
request_serializer: serializers.CheckPerm
parameters:
- name: user
type: string
required: true
description: username
paramType: query
- name: perm
type: string
requir... | [
"def",
"check_perm",
"(",
"request",
")",
":",
"serializer",
"=",
"serializers",
".",
"CheckPerm",
"(",
"data",
"=",
"request",
".",
"query_params",
")",
"serializer",
".",
"is_valid",
"(",
"raise_exception",
"=",
"True",
")",
"logger",
".",
"debug",
"(",
... | Check user permission.
---
request_serializer: serializers.CheckPerm
parameters:
- name: user
type: string
required: true
description: username
paramType: query
- name: perm
type: string
required: true
description: permi... | [
"Check",
"user",
"permission",
".",
"---",
"request_serializer",
":",
"serializers",
".",
"CheckPerm"
] | train | https://github.com/telminov/sw-django-rest-auth/blob/ba63b6d6c86e4325cac38ae8e2fde1501b47ce0a/sw_rest_auth/views.py#L72-L110 |
pip-services3-python/pip-services3-components-python | pip_services3_components/count/Timing.py | Timing.end_timing | def end_timing(self):
"""
Ends timing of an execution block, calculates elapsed time and updates the associated counter.
"""
if self._callback != None:
elapsed = time.perf_counter() * 1000 - self._start
self._callback.end_timing(self._counter, elapsed) | python | def end_timing(self):
"""
Ends timing of an execution block, calculates elapsed time and updates the associated counter.
"""
if self._callback != None:
elapsed = time.perf_counter() * 1000 - self._start
self._callback.end_timing(self._counter, elapsed) | [
"def",
"end_timing",
"(",
"self",
")",
":",
"if",
"self",
".",
"_callback",
"!=",
"None",
":",
"elapsed",
"=",
"time",
".",
"perf_counter",
"(",
")",
"*",
"1000",
"-",
"self",
".",
"_start",
"self",
".",
"_callback",
".",
"end_timing",
"(",
"self",
"... | Ends timing of an execution block, calculates elapsed time and updates the associated counter. | [
"Ends",
"timing",
"of",
"an",
"execution",
"block",
"calculates",
"elapsed",
"time",
"and",
"updates",
"the",
"associated",
"counter",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/count/Timing.py#L42-L49 |
RazerM/bucketcache | bucketcache/buckets.py | deferred_write | def deferred_write(bucket):
"""Context manager for deferring writes of a :py:class:`Bucket` within a
block.
Parameters:
bucket (:py:class:`Bucket`): Bucket to defer writes for within context.
Returns:
Bucket to use within context.
:rtype: :py:class:`DeferredWriteBucket`
When ... | python | def deferred_write(bucket):
"""Context manager for deferring writes of a :py:class:`Bucket` within a
block.
Parameters:
bucket (:py:class:`Bucket`): Bucket to defer writes for within context.
Returns:
Bucket to use within context.
:rtype: :py:class:`DeferredWriteBucket`
When ... | [
"def",
"deferred_write",
"(",
"bucket",
")",
":",
"deferred_write_bucket",
"=",
"DeferredWriteBucket",
".",
"from_bucket",
"(",
"bucket",
")",
"yield",
"deferred_write_bucket",
"deferred_write_bucket",
".",
"sync",
"(",
")",
"bucket",
".",
"_cache",
".",
"update",
... | Context manager for deferring writes of a :py:class:`Bucket` within a
block.
Parameters:
bucket (:py:class:`Bucket`): Bucket to defer writes for within context.
Returns:
Bucket to use within context.
:rtype: :py:class:`DeferredWriteBucket`
When the context is closed, the stored o... | [
"Context",
"manager",
"for",
"deferring",
"writes",
"of",
"a",
":",
"py",
":",
"class",
":",
"Bucket",
"within",
"a",
"block",
"."
] | train | https://github.com/RazerM/bucketcache/blob/8d9b163b73da8c498793cce2f22f6a7cbe524d94/bucketcache/buckets.py#L483-L509 |
RazerM/bucketcache | bucketcache/buckets.py | Bucket.prune_directory | def prune_directory(self):
"""Delete any objects that can be loaded and are expired according to
the current lifetime setting.
A file will be deleted if the following conditions are met:
- The file extension matches :py:meth:`bucketcache.backends.Backend.file_extension`
- The o... | python | def prune_directory(self):
"""Delete any objects that can be loaded and are expired according to
the current lifetime setting.
A file will be deleted if the following conditions are met:
- The file extension matches :py:meth:`bucketcache.backends.Backend.file_extension`
- The o... | [
"def",
"prune_directory",
"(",
"self",
")",
":",
"glob",
"=",
"'*.{ext}'",
".",
"format",
"(",
"ext",
"=",
"self",
".",
"backend",
".",
"file_extension",
")",
"totalsize",
"=",
"0",
"totalnum",
"=",
"0",
"for",
"f",
"in",
"self",
".",
"_path",
".",
"... | Delete any objects that can be loaded and are expired according to
the current lifetime setting.
A file will be deleted if the following conditions are met:
- The file extension matches :py:meth:`bucketcache.backends.Backend.file_extension`
- The object can be loaded by the configured ... | [
"Delete",
"any",
"objects",
"that",
"can",
"be",
"loaded",
"and",
"are",
"expired",
"according",
"to",
"the",
"current",
"lifetime",
"setting",
"."
] | train | https://github.com/RazerM/bucketcache/blob/8d9b163b73da8c498793cce2f22f6a7cbe524d94/bucketcache/buckets.py#L237-L280 |
RazerM/bucketcache | bucketcache/buckets.py | Bucket.unload_key | def unload_key(self, key):
"""Remove key from memory, leaving file in place."""
key_hash = self._hash_for_key(key)
if key in self:
del self._cache[key_hash] | python | def unload_key(self, key):
"""Remove key from memory, leaving file in place."""
key_hash = self._hash_for_key(key)
if key in self:
del self._cache[key_hash] | [
"def",
"unload_key",
"(",
"self",
",",
"key",
")",
":",
"key_hash",
"=",
"self",
".",
"_hash_for_key",
"(",
"key",
")",
"if",
"key",
"in",
"self",
":",
"del",
"self",
".",
"_cache",
"[",
"key_hash",
"]"
] | Remove key from memory, leaving file in place. | [
"Remove",
"key",
"from",
"memory",
"leaving",
"file",
"in",
"place",
"."
] | train | https://github.com/RazerM/bucketcache/blob/8d9b163b73da8c498793cce2f22f6a7cbe524d94/bucketcache/buckets.py#L282-L286 |
RazerM/bucketcache | bucketcache/buckets.py | DeferredWriteBucket.unload_key | def unload_key(self, key):
"""Remove key from memory, leaving file in place.
This forces :py:meth:`~bucketcache.buckets.DeferredWriteBucket.sync`.
"""
self.sync()
return super(DeferredWriteBucket, self).unload_key(key) | python | def unload_key(self, key):
"""Remove key from memory, leaving file in place.
This forces :py:meth:`~bucketcache.buckets.DeferredWriteBucket.sync`.
"""
self.sync()
return super(DeferredWriteBucket, self).unload_key(key) | [
"def",
"unload_key",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"sync",
"(",
")",
"return",
"super",
"(",
"DeferredWriteBucket",
",",
"self",
")",
".",
"unload_key",
"(",
"key",
")"
] | Remove key from memory, leaving file in place.
This forces :py:meth:`~bucketcache.buckets.DeferredWriteBucket.sync`. | [
"Remove",
"key",
"from",
"memory",
"leaving",
"file",
"in",
"place",
"."
] | train | https://github.com/RazerM/bucketcache/blob/8d9b163b73da8c498793cce2f22f6a7cbe524d94/bucketcache/buckets.py#L463-L469 |
RazerM/bucketcache | bucketcache/buckets.py | DeferredWriteBucket.sync | def sync(self):
"""Commit deferred writes to file."""
for key_hash, obj in six.iteritems(self._cache):
# Objects are checked for expiration in __getitem__,
# but we can check here to avoid unnecessary writes.
if not obj.has_expired():
file_path = self.... | python | def sync(self):
"""Commit deferred writes to file."""
for key_hash, obj in six.iteritems(self._cache):
# Objects are checked for expiration in __getitem__,
# but we can check here to avoid unnecessary writes.
if not obj.has_expired():
file_path = self.... | [
"def",
"sync",
"(",
"self",
")",
":",
"for",
"key_hash",
",",
"obj",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_cache",
")",
":",
"# Objects are checked for expiration in __getitem__,",
"# but we can check here to avoid unnecessary writes.",
"if",
"not",
"obj"... | Commit deferred writes to file. | [
"Commit",
"deferred",
"writes",
"to",
"file",
"."
] | train | https://github.com/RazerM/bucketcache/blob/8d9b163b73da8c498793cce2f22f6a7cbe524d94/bucketcache/buckets.py#L471-L479 |
tomi77/python-t77-date | t77_date/time.py | diff_time | def diff_time(t1, t2):
"""
Calculates datetime.timedelta between two datetime.time values.
:param t1: First time
:type t1: datetime.time
:param t2: Second time
:type t2: datetime.time
:return: Differences between t1 and t2 or None when t1 or t2 is None
:rtype: datetime.timedelta/None
... | python | def diff_time(t1, t2):
"""
Calculates datetime.timedelta between two datetime.time values.
:param t1: First time
:type t1: datetime.time
:param t2: Second time
:type t2: datetime.time
:return: Differences between t1 and t2 or None when t1 or t2 is None
:rtype: datetime.timedelta/None
... | [
"def",
"diff_time",
"(",
"t1",
",",
"t2",
")",
":",
"if",
"t1",
"is",
"None",
"or",
"t2",
"is",
"None",
":",
"return",
"None",
"if",
"not",
"isinstance",
"(",
"t1",
",",
"time",
")",
":",
"raise",
"ValueError",
"(",
"'\"t1\" must be a datetime.time'",
... | Calculates datetime.timedelta between two datetime.time values.
:param t1: First time
:type t1: datetime.time
:param t2: Second time
:type t2: datetime.time
:return: Differences between t1 and t2 or None when t1 or t2 is None
:rtype: datetime.timedelta/None
:raise: ValueError when t1 or t2 i... | [
"Calculates",
"datetime",
".",
"timedelta",
"between",
"two",
"datetime",
".",
"time",
"values",
".",
":",
"param",
"t1",
":",
"First",
"time",
":",
"type",
"t1",
":",
"datetime",
".",
"time",
":",
"param",
"t2",
":",
"Second",
"time",
":",
"type",
"t2... | train | https://github.com/tomi77/python-t77-date/blob/b4b12ce6a02884fb62460f6b9068e7fa28979fce/t77_date/time.py#L7-L31 |
radjkarl/fancyTools | fancytools/math/MovingAverage.py | staticMovingAverage | def staticMovingAverage(arr, fineness=10):
"""
smooth [arr] using moving average
"""
s0 = arr.shape[0]
window_len = int(round(s0 / fineness))
start = arr[0] + arr[0] - arr[window_len - 1:0:-1]
end = arr[-1] + arr[-1] - arr[-1:-window_len:-1]
s = np.r_[start, arr, end]
w = np.ones(wi... | python | def staticMovingAverage(arr, fineness=10):
"""
smooth [arr] using moving average
"""
s0 = arr.shape[0]
window_len = int(round(s0 / fineness))
start = arr[0] + arr[0] - arr[window_len - 1:0:-1]
end = arr[-1] + arr[-1] - arr[-1:-window_len:-1]
s = np.r_[start, arr, end]
w = np.ones(wi... | [
"def",
"staticMovingAverage",
"(",
"arr",
",",
"fineness",
"=",
"10",
")",
":",
"s0",
"=",
"arr",
".",
"shape",
"[",
"0",
"]",
"window_len",
"=",
"int",
"(",
"round",
"(",
"s0",
"/",
"fineness",
")",
")",
"start",
"=",
"arr",
"[",
"0",
"]",
"+",
... | smooth [arr] using moving average | [
"smooth",
"[",
"arr",
"]",
"using",
"moving",
"average"
] | train | https://github.com/radjkarl/fancyTools/blob/4c4d961003dc4ed6e46429a0c24f7e2bb52caa8b/fancytools/math/MovingAverage.py#L33-L47 |
radjkarl/fancyTools | fancytools/math/MovingAverage.py | staticMovingAverage2 | def staticMovingAverage2(x, N=3, mode='reflect'):
"""
moving average filter for 1d arrays
supported modes for boundary handling: 'reflect' , 'constant'
"""
assert N > 1
x2 = np.empty(shape=x.shape[0] + N, dtype=x.dtype)
start = N - 2
if N == 2:
start = 1
end = N - start
... | python | def staticMovingAverage2(x, N=3, mode='reflect'):
"""
moving average filter for 1d arrays
supported modes for boundary handling: 'reflect' , 'constant'
"""
assert N > 1
x2 = np.empty(shape=x.shape[0] + N, dtype=x.dtype)
start = N - 2
if N == 2:
start = 1
end = N - start
... | [
"def",
"staticMovingAverage2",
"(",
"x",
",",
"N",
"=",
"3",
",",
"mode",
"=",
"'reflect'",
")",
":",
"assert",
"N",
">",
"1",
"x2",
"=",
"np",
".",
"empty",
"(",
"shape",
"=",
"x",
".",
"shape",
"[",
"0",
"]",
"+",
"N",
",",
"dtype",
"=",
"x... | moving average filter for 1d arrays
supported modes for boundary handling: 'reflect' , 'constant' | [
"moving",
"average",
"filter",
"for",
"1d",
"arrays",
"supported",
"modes",
"for",
"boundary",
"handling",
":",
"reflect",
"constant"
] | train | https://github.com/radjkarl/fancyTools/blob/4c4d961003dc4ed6e46429a0c24f7e2bb52caa8b/fancytools/math/MovingAverage.py#L51-L84 |
akolpakov/paynova-api-python-client | paynova_api_python_client/paynova.py | Paynova.get_url | def get_url(self, resource, params=None):
"""
Generate url for request
"""
# replace placeholders
pattern = r'\{(.+?)\}'
resource = re.sub(pattern, lambda t: str(params.get(t.group(1), '')), resource)
# build url
parts = (self.endpoint, '/api/', r... | python | def get_url(self, resource, params=None):
"""
Generate url for request
"""
# replace placeholders
pattern = r'\{(.+?)\}'
resource = re.sub(pattern, lambda t: str(params.get(t.group(1), '')), resource)
# build url
parts = (self.endpoint, '/api/', r... | [
"def",
"get_url",
"(",
"self",
",",
"resource",
",",
"params",
"=",
"None",
")",
":",
"# replace placeholders",
"pattern",
"=",
"r'\\{(.+?)\\}'",
"resource",
"=",
"re",
".",
"sub",
"(",
"pattern",
",",
"lambda",
"t",
":",
"str",
"(",
"params",
".",
"get"... | Generate url for request | [
"Generate",
"url",
"for",
"request"
] | train | https://github.com/akolpakov/paynova-api-python-client/blob/930277623fc7b142ae9365a44f15a3a7b79bd974/paynova_api_python_client/paynova.py#L37-L51 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.