repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
JukeboxPipeline/jukeboxmaya
src/jukeboxmaya/reftrack/asset.py
AssetReftypeInterface.delete
def delete(self, refobj): """Delete the content of the given refobj :param refobj: the refobj that represents the content that should be deleted :type refobj: refobj :returns: None :rtype: None :raises: None """ refobjinter = self.get_refobjinter() reference = refobjinter.get_reference(refobj) if reference: fullns = cmds.referenceQuery(reference, namespace=True) cmds.file(removeReference=True, referenceNode=reference) else: parentns = common.get_namespace(refobj) ns = cmds.getAttr("%s.namespace" % refobj) fullns = ":".join((parentns.rstrip(":"), ns.lstrip(":"))) cmds.namespace(removeNamespace=fullns, deleteNamespaceContent=True)
python
def delete(self, refobj): """Delete the content of the given refobj :param refobj: the refobj that represents the content that should be deleted :type refobj: refobj :returns: None :rtype: None :raises: None """ refobjinter = self.get_refobjinter() reference = refobjinter.get_reference(refobj) if reference: fullns = cmds.referenceQuery(reference, namespace=True) cmds.file(removeReference=True, referenceNode=reference) else: parentns = common.get_namespace(refobj) ns = cmds.getAttr("%s.namespace" % refobj) fullns = ":".join((parentns.rstrip(":"), ns.lstrip(":"))) cmds.namespace(removeNamespace=fullns, deleteNamespaceContent=True)
[ "def", "delete", "(", "self", ",", "refobj", ")", ":", "refobjinter", "=", "self", ".", "get_refobjinter", "(", ")", "reference", "=", "refobjinter", ".", "get_reference", "(", "refobj", ")", "if", "reference", ":", "fullns", "=", "cmds", ".", "referenceQuery", "(", "reference", ",", "namespace", "=", "True", ")", "cmds", ".", "file", "(", "removeReference", "=", "True", ",", "referenceNode", "=", "reference", ")", "else", ":", "parentns", "=", "common", ".", "get_namespace", "(", "refobj", ")", "ns", "=", "cmds", ".", "getAttr", "(", "\"%s.namespace\"", "%", "refobj", ")", "fullns", "=", "\":\"", ".", "join", "(", "(", "parentns", ".", "rstrip", "(", "\":\"", ")", ",", "ns", ".", "lstrip", "(", "\":\"", ")", ")", ")", "cmds", ".", "namespace", "(", "removeNamespace", "=", "fullns", ",", "deleteNamespaceContent", "=", "True", ")" ]
Delete the content of the given refobj :param refobj: the refobj that represents the content that should be deleted :type refobj: refobj :returns: None :rtype: None :raises: None
[ "Delete", "the", "content", "of", "the", "given", "refobj" ]
c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c
https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/reftrack/asset.py#L195-L213
train
JukeboxPipeline/jukeboxmaya
src/jukeboxmaya/reftrack/asset.py
AssetReftypeInterface.import_reference
def import_reference(self, refobj, reference): """Import the given reference The reference of the refobj will be set to None automatically afterwards with :meth:`RefobjInterface.set_reference` :param refobj: the refobj that is linked to the reference :param reference: the reference object. E.g. in Maya a reference node :returns: None :rtype: None :raises: None """ cmds.file(importReference=True, referenceNode=reference)
python
def import_reference(self, refobj, reference): """Import the given reference The reference of the refobj will be set to None automatically afterwards with :meth:`RefobjInterface.set_reference` :param refobj: the refobj that is linked to the reference :param reference: the reference object. E.g. in Maya a reference node :returns: None :rtype: None :raises: None """ cmds.file(importReference=True, referenceNode=reference)
[ "def", "import_reference", "(", "self", ",", "refobj", ",", "reference", ")", ":", "cmds", ".", "file", "(", "importReference", "=", "True", ",", "referenceNode", "=", "reference", ")" ]
Import the given reference The reference of the refobj will be set to None automatically afterwards with :meth:`RefobjInterface.set_reference` :param refobj: the refobj that is linked to the reference :param reference: the reference object. E.g. in Maya a reference node :returns: None :rtype: None :raises: None
[ "Import", "the", "given", "reference" ]
c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c
https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/reftrack/asset.py#L215-L227
train
JukeboxPipeline/jukeboxmaya
src/jukeboxmaya/reftrack/asset.py
AssetReftypeInterface.create_options_model
def create_options_model(self, taskfileinfos): """Create a new treemodel that has the taskfileinfos as internal_data of the leaves. I recommend using :class:`jukeboxcore.gui.filesysitemdata.TaskFileInfoItemData` for the leaves. So a valid root item would be something like:: rootdata = jukeboxcore.gui.treemodel.ListItemData(["Asset/Shot", "Task", "Descriptor", "Version", "Releasetype"]) rootitem = jukeboxcore.gui.treemodel.TreeItem(rootdata) :returns: the option model with :class:`TaskFileInfo` as internal_data of the leaves. :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel` :raises: None """ rootdata = ListItemData(["Asset/Shot", "Task", "Descriptor", "Version", "Releasetype"]) rootitem = TreeItem(rootdata) tasks = defaultdict(list) for tfi in taskfileinfos: tasks[tfi.task].append(tfi) for task in reversed(sorted(tasks.keys(), key=lambda t: t.department.ordervalue)): tfis = tasks[task] taskdata = djitemdata.TaskItemData(task) taskitem = TreeItem(taskdata, rootitem) for tfi in reversed(tfis): tfidata = TaskFileInfoItemData(tfi) TreeItem(tfidata, taskitem) return TreeModel(rootitem)
python
def create_options_model(self, taskfileinfos): """Create a new treemodel that has the taskfileinfos as internal_data of the leaves. I recommend using :class:`jukeboxcore.gui.filesysitemdata.TaskFileInfoItemData` for the leaves. So a valid root item would be something like:: rootdata = jukeboxcore.gui.treemodel.ListItemData(["Asset/Shot", "Task", "Descriptor", "Version", "Releasetype"]) rootitem = jukeboxcore.gui.treemodel.TreeItem(rootdata) :returns: the option model with :class:`TaskFileInfo` as internal_data of the leaves. :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel` :raises: None """ rootdata = ListItemData(["Asset/Shot", "Task", "Descriptor", "Version", "Releasetype"]) rootitem = TreeItem(rootdata) tasks = defaultdict(list) for tfi in taskfileinfos: tasks[tfi.task].append(tfi) for task in reversed(sorted(tasks.keys(), key=lambda t: t.department.ordervalue)): tfis = tasks[task] taskdata = djitemdata.TaskItemData(task) taskitem = TreeItem(taskdata, rootitem) for tfi in reversed(tfis): tfidata = TaskFileInfoItemData(tfi) TreeItem(tfidata, taskitem) return TreeModel(rootitem)
[ "def", "create_options_model", "(", "self", ",", "taskfileinfos", ")", ":", "rootdata", "=", "ListItemData", "(", "[", "\"Asset/Shot\"", ",", "\"Task\"", ",", "\"Descriptor\"", ",", "\"Version\"", ",", "\"Releasetype\"", "]", ")", "rootitem", "=", "TreeItem", "(", "rootdata", ")", "tasks", "=", "defaultdict", "(", "list", ")", "for", "tfi", "in", "taskfileinfos", ":", "tasks", "[", "tfi", ".", "task", "]", ".", "append", "(", "tfi", ")", "for", "task", "in", "reversed", "(", "sorted", "(", "tasks", ".", "keys", "(", ")", ",", "key", "=", "lambda", "t", ":", "t", ".", "department", ".", "ordervalue", ")", ")", ":", "tfis", "=", "tasks", "[", "task", "]", "taskdata", "=", "djitemdata", ".", "TaskItemData", "(", "task", ")", "taskitem", "=", "TreeItem", "(", "taskdata", ",", "rootitem", ")", "for", "tfi", "in", "reversed", "(", "tfis", ")", ":", "tfidata", "=", "TaskFileInfoItemData", "(", "tfi", ")", "TreeItem", "(", "tfidata", ",", "taskitem", ")", "return", "TreeModel", "(", "rootitem", ")" ]
Create a new treemodel that has the taskfileinfos as internal_data of the leaves. I recommend using :class:`jukeboxcore.gui.filesysitemdata.TaskFileInfoItemData` for the leaves. So a valid root item would be something like:: rootdata = jukeboxcore.gui.treemodel.ListItemData(["Asset/Shot", "Task", "Descriptor", "Version", "Releasetype"]) rootitem = jukeboxcore.gui.treemodel.TreeItem(rootdata) :returns: the option model with :class:`TaskFileInfo` as internal_data of the leaves. :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel` :raises: None
[ "Create", "a", "new", "treemodel", "that", "has", "the", "taskfileinfos", "as", "internal_data", "of", "the", "leaves", "." ]
c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c
https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/reftrack/asset.py#L279-L304
train
JukeboxPipeline/jukeboxmaya
src/jukeboxmaya/reftrack/asset.py
AssetReftypeInterface.get_scene_suggestions
def get_scene_suggestions(self, current): """Return a list with elements for reftracks for the current scene with this type. For every element returned, the reftrack system will create a :class:`Reftrack` with the type of this interface, if it is not already in the scene. E.g. if you have a type that references whole scenes, you might suggest all linked assets for shots, and all liked assets plus the current element itself for assets. If you have a type like shader, that usually need a parent, you would return an empty list. Cameras might only make sense for shots and not for assets etc. Do not confuse this with :meth:`ReftypeInterface.get_suggestions`. It will gather suggestions for children of a :class:`Reftrack`. The standard implementation only returns an empty list! :param reftrack: the reftrack which needs suggestions :type reftrack: :class:`Reftrack` :returns: list of suggestions, tuples of type and element. :rtype: list :raises: None """ l = [] if isinstance(current, djadapter.models.Asset): l.append(current) l.extend(list(current.assets.all())) return l
python
def get_scene_suggestions(self, current): """Return a list with elements for reftracks for the current scene with this type. For every element returned, the reftrack system will create a :class:`Reftrack` with the type of this interface, if it is not already in the scene. E.g. if you have a type that references whole scenes, you might suggest all linked assets for shots, and all liked assets plus the current element itself for assets. If you have a type like shader, that usually need a parent, you would return an empty list. Cameras might only make sense for shots and not for assets etc. Do not confuse this with :meth:`ReftypeInterface.get_suggestions`. It will gather suggestions for children of a :class:`Reftrack`. The standard implementation only returns an empty list! :param reftrack: the reftrack which needs suggestions :type reftrack: :class:`Reftrack` :returns: list of suggestions, tuples of type and element. :rtype: list :raises: None """ l = [] if isinstance(current, djadapter.models.Asset): l.append(current) l.extend(list(current.assets.all())) return l
[ "def", "get_scene_suggestions", "(", "self", ",", "current", ")", ":", "l", "=", "[", "]", "if", "isinstance", "(", "current", ",", "djadapter", ".", "models", ".", "Asset", ")", ":", "l", ".", "append", "(", "current", ")", "l", ".", "extend", "(", "list", "(", "current", ".", "assets", ".", "all", "(", ")", ")", ")", "return", "l" ]
Return a list with elements for reftracks for the current scene with this type. For every element returned, the reftrack system will create a :class:`Reftrack` with the type of this interface, if it is not already in the scene. E.g. if you have a type that references whole scenes, you might suggest all linked assets for shots, and all liked assets plus the current element itself for assets. If you have a type like shader, that usually need a parent, you would return an empty list. Cameras might only make sense for shots and not for assets etc. Do not confuse this with :meth:`ReftypeInterface.get_suggestions`. It will gather suggestions for children of a :class:`Reftrack`. The standard implementation only returns an empty list! :param reftrack: the reftrack which needs suggestions :type reftrack: :class:`Reftrack` :returns: list of suggestions, tuples of type and element. :rtype: list :raises: None
[ "Return", "a", "list", "with", "elements", "for", "reftracks", "for", "the", "current", "scene", "with", "this", "type", "." ]
c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c
https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/reftrack/asset.py#L360-L386
train
JukeboxPipeline/jukeboxmaya
src/jukeboxmaya/addons/mayaconfiger/mayaconfiger.py
MayaConfiger.init_ui
def init_ui(self, ): """Create the menu \"Preferences\" under \"Jukebox\" to start the plugin :returns: None :rtype: None :raises: None """ self.mm = MenuManager.get() p = self.mm.menus['Jukebox'] self.menu = self.mm.create_menu("Preferences", p, command=self.run)
python
def init_ui(self, ): """Create the menu \"Preferences\" under \"Jukebox\" to start the plugin :returns: None :rtype: None :raises: None """ self.mm = MenuManager.get() p = self.mm.menus['Jukebox'] self.menu = self.mm.create_menu("Preferences", p, command=self.run)
[ "def", "init_ui", "(", "self", ",", ")", ":", "self", ".", "mm", "=", "MenuManager", ".", "get", "(", ")", "p", "=", "self", ".", "mm", ".", "menus", "[", "'Jukebox'", "]", "self", ".", "menu", "=", "self", ".", "mm", ".", "create_menu", "(", "\"Preferences\"", ",", "p", ",", "command", "=", "self", ".", "run", ")" ]
Create the menu \"Preferences\" under \"Jukebox\" to start the plugin :returns: None :rtype: None :raises: None
[ "Create", "the", "menu", "\\", "Preferences", "\\", "under", "\\", "Jukebox", "\\", "to", "start", "the", "plugin" ]
c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c
https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/addons/mayaconfiger/mayaconfiger.py#L42-L51
train
FaradayRF/faradayio-cli
faradayio_cli/faradayio_cli.py
setupArgparse
def setupArgparse(): """Sets up argparse module to create command line options and parse them. Uses the argparse module to add arguments to the command line for faradayio-cli. Once the arguments are added and parsed the arguments are returned Returns: argparse.Namespace: Populated namespace of arguments """ parser = argparse.ArgumentParser() # Required arguments parser.add_argument("callsign", help="Callsign of radio") parser.add_argument("id", type=int, help="ID number radio") # Optional arguments parser.add_argument("-l", "--loopback", action="store_true", help="Use software loopback serial port") parser.add_argument("-p", "--port", default="/dev/ttyUSB0", help="Physical serial port of radio") # Parse and return arguments return parser.parse_args()
python
def setupArgparse(): """Sets up argparse module to create command line options and parse them. Uses the argparse module to add arguments to the command line for faradayio-cli. Once the arguments are added and parsed the arguments are returned Returns: argparse.Namespace: Populated namespace of arguments """ parser = argparse.ArgumentParser() # Required arguments parser.add_argument("callsign", help="Callsign of radio") parser.add_argument("id", type=int, help="ID number radio") # Optional arguments parser.add_argument("-l", "--loopback", action="store_true", help="Use software loopback serial port") parser.add_argument("-p", "--port", default="/dev/ttyUSB0", help="Physical serial port of radio") # Parse and return arguments return parser.parse_args()
[ "def", "setupArgparse", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "# Required arguments", "parser", ".", "add_argument", "(", "\"callsign\"", ",", "help", "=", "\"Callsign of radio\"", ")", "parser", ".", "add_argument", "(", "\"id\"", ",", "type", "=", "int", ",", "help", "=", "\"ID number radio\"", ")", "# Optional arguments", "parser", ".", "add_argument", "(", "\"-l\"", ",", "\"--loopback\"", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Use software loopback serial port\"", ")", "parser", ".", "add_argument", "(", "\"-p\"", ",", "\"--port\"", ",", "default", "=", "\"/dev/ttyUSB0\"", ",", "help", "=", "\"Physical serial port of radio\"", ")", "# Parse and return arguments", "return", "parser", ".", "parse_args", "(", ")" ]
Sets up argparse module to create command line options and parse them. Uses the argparse module to add arguments to the command line for faradayio-cli. Once the arguments are added and parsed the arguments are returned Returns: argparse.Namespace: Populated namespace of arguments
[ "Sets", "up", "argparse", "module", "to", "create", "command", "line", "options", "and", "parse", "them", "." ]
5acac033f3e44da7e89d97725eed9d336cf16f74
https://github.com/FaradayRF/faradayio-cli/blob/5acac033f3e44da7e89d97725eed9d336cf16f74/faradayio_cli/faradayio_cli.py#L15-L38
train
FaradayRF/faradayio-cli
faradayio_cli/faradayio_cli.py
setupSerialPort
def setupSerialPort(loopback, port): """Sets up serial port by connecting to phsyical or software port. Depending on command line options, this function will either connect to a SerialTestClass() port for loopback testing or to the specified port from the command line option. If loopback is True it overrides the physical port specification. Args: loopback: argparse option port: argparse option Returns: serialPort: Pyserial serial port instance """ if loopback: # Implement loopback software serial port testSerial = SerialTestClass() serialPort = testSerial.serialPort else: # TODO enable serial port command line options (keep simple for user!) serialPort = serial.Serial(port, 115200, timeout=0) return serialPort
python
def setupSerialPort(loopback, port): """Sets up serial port by connecting to phsyical or software port. Depending on command line options, this function will either connect to a SerialTestClass() port for loopback testing or to the specified port from the command line option. If loopback is True it overrides the physical port specification. Args: loopback: argparse option port: argparse option Returns: serialPort: Pyserial serial port instance """ if loopback: # Implement loopback software serial port testSerial = SerialTestClass() serialPort = testSerial.serialPort else: # TODO enable serial port command line options (keep simple for user!) serialPort = serial.Serial(port, 115200, timeout=0) return serialPort
[ "def", "setupSerialPort", "(", "loopback", ",", "port", ")", ":", "if", "loopback", ":", "# Implement loopback software serial port", "testSerial", "=", "SerialTestClass", "(", ")", "serialPort", "=", "testSerial", ".", "serialPort", "else", ":", "# TODO enable serial port command line options (keep simple for user!)", "serialPort", "=", "serial", ".", "Serial", "(", "port", ",", "115200", ",", "timeout", "=", "0", ")", "return", "serialPort" ]
Sets up serial port by connecting to phsyical or software port. Depending on command line options, this function will either connect to a SerialTestClass() port for loopback testing or to the specified port from the command line option. If loopback is True it overrides the physical port specification. Args: loopback: argparse option port: argparse option Returns: serialPort: Pyserial serial port instance
[ "Sets", "up", "serial", "port", "by", "connecting", "to", "phsyical", "or", "software", "port", "." ]
5acac033f3e44da7e89d97725eed9d336cf16f74
https://github.com/FaradayRF/faradayio-cli/blob/5acac033f3e44da7e89d97725eed9d336cf16f74/faradayio_cli/faradayio_cli.py#L41-L64
train
FaradayRF/faradayio-cli
faradayio_cli/faradayio_cli.py
main
def main(): """Main function of faradayio-cli client. Informs user of version being run and then sets up the program followed by starting up the TUN/TAP device threads. """ print("Executing faradayio-cli version {0}".format(__version__)) # Setup command line arguments try: args = setupArgparse() except argparse.ArgumentError as error: raise SystemExit(error) # Setup serial port try: serialPort = setupSerialPort(args.loopback, args.port) except serial.SerialException as error: raise SystemExit(error) # Create TUN adapter name tunName = "{0}-{1}".format(args.callsign.upper(), args.id) # Create threading event for TUN thread control # set() causes while loop to continuously run until clear() is run isRunning = threading.Event() isRunning.set() # Setup TUN adapter and start try: tun = Monitor(serialPort=serialPort, name=tunName, isRunning=isRunning) tun.start() except pytun.Error as error: print("Warning! faradayio-cli must be run with sudo privileges!") raise SystemExit(error) # loop infinitely until KeyboardInterrupt, then clear() event, exit thread try: while True: # Check for KeyboardInterrupt every 100ms time.sleep(0.1) except KeyboardInterrupt: tun.isRunning.clear() tun.join()
python
def main(): """Main function of faradayio-cli client. Informs user of version being run and then sets up the program followed by starting up the TUN/TAP device threads. """ print("Executing faradayio-cli version {0}".format(__version__)) # Setup command line arguments try: args = setupArgparse() except argparse.ArgumentError as error: raise SystemExit(error) # Setup serial port try: serialPort = setupSerialPort(args.loopback, args.port) except serial.SerialException as error: raise SystemExit(error) # Create TUN adapter name tunName = "{0}-{1}".format(args.callsign.upper(), args.id) # Create threading event for TUN thread control # set() causes while loop to continuously run until clear() is run isRunning = threading.Event() isRunning.set() # Setup TUN adapter and start try: tun = Monitor(serialPort=serialPort, name=tunName, isRunning=isRunning) tun.start() except pytun.Error as error: print("Warning! faradayio-cli must be run with sudo privileges!") raise SystemExit(error) # loop infinitely until KeyboardInterrupt, then clear() event, exit thread try: while True: # Check for KeyboardInterrupt every 100ms time.sleep(0.1) except KeyboardInterrupt: tun.isRunning.clear() tun.join()
[ "def", "main", "(", ")", ":", "print", "(", "\"Executing faradayio-cli version {0}\"", ".", "format", "(", "__version__", ")", ")", "# Setup command line arguments", "try", ":", "args", "=", "setupArgparse", "(", ")", "except", "argparse", ".", "ArgumentError", "as", "error", ":", "raise", "SystemExit", "(", "error", ")", "# Setup serial port", "try", ":", "serialPort", "=", "setupSerialPort", "(", "args", ".", "loopback", ",", "args", ".", "port", ")", "except", "serial", ".", "SerialException", "as", "error", ":", "raise", "SystemExit", "(", "error", ")", "# Create TUN adapter name", "tunName", "=", "\"{0}-{1}\"", ".", "format", "(", "args", ".", "callsign", ".", "upper", "(", ")", ",", "args", ".", "id", ")", "# Create threading event for TUN thread control", "# set() causes while loop to continuously run until clear() is run", "isRunning", "=", "threading", ".", "Event", "(", ")", "isRunning", ".", "set", "(", ")", "# Setup TUN adapter and start", "try", ":", "tun", "=", "Monitor", "(", "serialPort", "=", "serialPort", ",", "name", "=", "tunName", ",", "isRunning", "=", "isRunning", ")", "tun", ".", "start", "(", ")", "except", "pytun", ".", "Error", "as", "error", ":", "print", "(", "\"Warning! faradayio-cli must be run with sudo privileges!\"", ")", "raise", "SystemExit", "(", "error", ")", "# loop infinitely until KeyboardInterrupt, then clear() event, exit thread", "try", ":", "while", "True", ":", "# Check for KeyboardInterrupt every 100ms", "time", ".", "sleep", "(", "0.1", ")", "except", "KeyboardInterrupt", ":", "tun", ".", "isRunning", ".", "clear", "(", ")", "tun", ".", "join", "(", ")" ]
Main function of faradayio-cli client. Informs user of version being run and then sets up the program followed by starting up the TUN/TAP device threads.
[ "Main", "function", "of", "faradayio", "-", "cli", "client", "." ]
5acac033f3e44da7e89d97725eed9d336cf16f74
https://github.com/FaradayRF/faradayio-cli/blob/5acac033f3e44da7e89d97725eed9d336cf16f74/faradayio_cli/faradayio_cli.py#L67-L114
train
lsst-sqre/sqre-codekit
codekit/codetools.py
lookup_email
def lookup_email(args): """Return the email address to use when creating git objects or exit program. Parameters ---------- args: parser.parse_args() Returns ------- email : `string` git user email address """ email = args.email if email is None: email = gituseremail() if email is None: raise RuntimeError(textwrap.dedent("""\ unable to determine a git email Specify --email option\ """)) debug("email is {email}".format(email=email)) return email
python
def lookup_email(args): """Return the email address to use when creating git objects or exit program. Parameters ---------- args: parser.parse_args() Returns ------- email : `string` git user email address """ email = args.email if email is None: email = gituseremail() if email is None: raise RuntimeError(textwrap.dedent("""\ unable to determine a git email Specify --email option\ """)) debug("email is {email}".format(email=email)) return email
[ "def", "lookup_email", "(", "args", ")", ":", "email", "=", "args", ".", "email", "if", "email", "is", "None", ":", "email", "=", "gituseremail", "(", ")", "if", "email", "is", "None", ":", "raise", "RuntimeError", "(", "textwrap", ".", "dedent", "(", "\"\"\"\\\n unable to determine a git email\n Specify --email option\\\n \"\"\"", ")", ")", "debug", "(", "\"email is {email}\"", ".", "format", "(", "email", "=", "email", ")", ")", "return", "email" ]
Return the email address to use when creating git objects or exit program. Parameters ---------- args: parser.parse_args() Returns ------- email : `string` git user email address
[ "Return", "the", "email", "address", "to", "use", "when", "creating", "git", "objects", "or", "exit", "program", "." ]
98122404cd9065d4d1d570867fe518042669126c
https://github.com/lsst-sqre/sqre-codekit/blob/98122404cd9065d4d1d570867fe518042669126c/codekit/codetools.py#L132-L157
train
lsst-sqre/sqre-codekit
codekit/codetools.py
lookup_user
def lookup_user(args): """Return the user name to use when creating git objects or exit program. Parameters ---------- args: parser.parse_args() Returns ------- user: `string` git user name """ user = args.user if user is None: user = gitusername() if user is None: raise RuntimeError(textwrap.dedent("""\ unable to determine a git user name Specify --user option\ """)) debug("user name is {user}".format(user=user)) return user
python
def lookup_user(args): """Return the user name to use when creating git objects or exit program. Parameters ---------- args: parser.parse_args() Returns ------- user: `string` git user name """ user = args.user if user is None: user = gitusername() if user is None: raise RuntimeError(textwrap.dedent("""\ unable to determine a git user name Specify --user option\ """)) debug("user name is {user}".format(user=user)) return user
[ "def", "lookup_user", "(", "args", ")", ":", "user", "=", "args", ".", "user", "if", "user", "is", "None", ":", "user", "=", "gitusername", "(", ")", "if", "user", "is", "None", ":", "raise", "RuntimeError", "(", "textwrap", ".", "dedent", "(", "\"\"\"\\\n unable to determine a git user name\n Specify --user option\\\n \"\"\"", ")", ")", "debug", "(", "\"user name is {user}\"", ".", "format", "(", "user", "=", "user", ")", ")", "return", "user" ]
Return the user name to use when creating git objects or exit program. Parameters ---------- args: parser.parse_args() Returns ------- user: `string` git user name
[ "Return", "the", "user", "name", "to", "use", "when", "creating", "git", "objects", "or", "exit", "program", "." ]
98122404cd9065d4d1d570867fe518042669126c
https://github.com/lsst-sqre/sqre-codekit/blob/98122404cd9065d4d1d570867fe518042669126c/codekit/codetools.py#L161-L186
train
lsst-sqre/sqre-codekit
codekit/codetools.py
current_timestamp
def current_timestamp(): """Returns current time as ISO8601 formatted string in the Zulu TZ""" now = datetime.utcnow() timestamp = now.isoformat()[0:19] + 'Z' debug("generated timestamp: {now}".format(now=timestamp)) return timestamp
python
def current_timestamp(): """Returns current time as ISO8601 formatted string in the Zulu TZ""" now = datetime.utcnow() timestamp = now.isoformat()[0:19] + 'Z' debug("generated timestamp: {now}".format(now=timestamp)) return timestamp
[ "def", "current_timestamp", "(", ")", ":", "now", "=", "datetime", ".", "utcnow", "(", ")", "timestamp", "=", "now", ".", "isoformat", "(", ")", "[", "0", ":", "19", "]", "+", "'Z'", "debug", "(", "\"generated timestamp: {now}\"", ".", "format", "(", "now", "=", "timestamp", ")", ")", "return", "timestamp" ]
Returns current time as ISO8601 formatted string in the Zulu TZ
[ "Returns", "current", "time", "as", "ISO8601", "formatted", "string", "in", "the", "Zulu", "TZ" ]
98122404cd9065d4d1d570867fe518042669126c
https://github.com/lsst-sqre/sqre-codekit/blob/98122404cd9065d4d1d570867fe518042669126c/codekit/codetools.py#L313-L320
train
portfors-lab/sparkle
sparkle/tools/audiotools.py
calc_spectrum
def calc_spectrum(signal, rate): """Return the spectrum and frequency indexes for real-valued input signal""" npts = len(signal) padto = 1 << (npts - 1).bit_length() # print 'length of signal {}, pad to {}'.format(npts, padto) npts = padto sp = np.fft.rfft(signal, n=padto) / npts # print('sp len ', len(sp)) freq = np.arange((npts / 2) + 1) / (npts / rate) # print('freq len ', len(freq)) return freq, abs(sp)
python
def calc_spectrum(signal, rate): """Return the spectrum and frequency indexes for real-valued input signal""" npts = len(signal) padto = 1 << (npts - 1).bit_length() # print 'length of signal {}, pad to {}'.format(npts, padto) npts = padto sp = np.fft.rfft(signal, n=padto) / npts # print('sp len ', len(sp)) freq = np.arange((npts / 2) + 1) / (npts / rate) # print('freq len ', len(freq)) return freq, abs(sp)
[ "def", "calc_spectrum", "(", "signal", ",", "rate", ")", ":", "npts", "=", "len", "(", "signal", ")", "padto", "=", "1", "<<", "(", "npts", "-", "1", ")", ".", "bit_length", "(", ")", "# print 'length of signal {}, pad to {}'.format(npts, padto)", "npts", "=", "padto", "sp", "=", "np", ".", "fft", ".", "rfft", "(", "signal", ",", "n", "=", "padto", ")", "/", "npts", "# print('sp len ', len(sp))", "freq", "=", "np", ".", "arange", "(", "(", "npts", "/", "2", ")", "+", "1", ")", "/", "(", "npts", "/", "rate", ")", "# print('freq len ', len(freq))", "return", "freq", ",", "abs", "(", "sp", ")" ]
Return the spectrum and frequency indexes for real-valued input signal
[ "Return", "the", "spectrum", "and", "frequency", "indexes", "for", "real", "-", "valued", "input", "signal" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/tools/audiotools.py#L53-L64
train
portfors-lab/sparkle
sparkle/tools/audiotools.py
spectrogram
def spectrogram(source, nfft=512, overlap=90, window='hanning', caldb=93, calv=2.83): """ Produce a matrix of spectral intensity, uses matplotlib's specgram function. Output is in dB scale. :param source: filename of audiofile, or samplerate and vector of audio signal :type source: str or (int, numpy.ndarray) :param nfft: size of nfft window to use :type nfft: int :param overlap: percent overlap of window :type overlap: number :param window: Type of window to use, choices are hanning, hamming, blackman, bartlett or none (rectangular) :type window: string :returns: spec -- 2D array of intensities, freqs -- yaxis labels, bins -- time bin labels, duration -- duration of signal """ if isinstance(source, basestring): fs, wavdata = audioread(source) else: fs, wavdata = source # truncate to nears ms duration = float(len(wavdata)) / fs desired_npts = int((np.trunc(duration * 1000) / 1000) * fs) # print 'LENGTH {}, DESIRED {}'.format(len(wavdata), desired_npts) wavdata = wavdata[:desired_npts] duration = len(wavdata) / fs if VERBOSE: amp = rms(wavdata, fs) print 'RMS of input signal to spectrogram', amp # normalize if len(wavdata) > 0 and np.max(abs(wavdata)) != 0: wavdata = wavdata / np.max(abs(wavdata)) if window == 'hanning': winfnc = mlab.window_hanning elif window == 'hamming': winfnc = np.hamming(nfft) elif window == 'blackman': winfnc = np.blackman(nfft) elif window == 'bartlett': winfnc = np.bartlett(nfft) elif window == None or window == 'none': winfnc = mlab.window_none noverlap = int(nfft * (float(overlap) / 100)) Pxx, freqs, bins = mlab.specgram(wavdata, NFFT=nfft, Fs=fs, noverlap=noverlap, pad_to=nfft * 2, window=winfnc, detrend=mlab.detrend_none, sides='default', scale_by_freq=False) # log of zero is -inf, which is not great for plotting Pxx[Pxx == 0] = np.nan # convert to db scale for display spec = 20. * np.log10(Pxx) # set 0 to miniumum value in spec? # would be great to have spec in db SPL, and set any -inf to 0 spec[np.isnan(spec)] = np.nanmin(spec) return spec, freqs, bins, duration
python
def spectrogram(source, nfft=512, overlap=90, window='hanning', caldb=93, calv=2.83): """ Produce a matrix of spectral intensity, uses matplotlib's specgram function. Output is in dB scale. :param source: filename of audiofile, or samplerate and vector of audio signal :type source: str or (int, numpy.ndarray) :param nfft: size of nfft window to use :type nfft: int :param overlap: percent overlap of window :type overlap: number :param window: Type of window to use, choices are hanning, hamming, blackman, bartlett or none (rectangular) :type window: string :returns: spec -- 2D array of intensities, freqs -- yaxis labels, bins -- time bin labels, duration -- duration of signal """ if isinstance(source, basestring): fs, wavdata = audioread(source) else: fs, wavdata = source # truncate to nears ms duration = float(len(wavdata)) / fs desired_npts = int((np.trunc(duration * 1000) / 1000) * fs) # print 'LENGTH {}, DESIRED {}'.format(len(wavdata), desired_npts) wavdata = wavdata[:desired_npts] duration = len(wavdata) / fs if VERBOSE: amp = rms(wavdata, fs) print 'RMS of input signal to spectrogram', amp # normalize if len(wavdata) > 0 and np.max(abs(wavdata)) != 0: wavdata = wavdata / np.max(abs(wavdata)) if window == 'hanning': winfnc = mlab.window_hanning elif window == 'hamming': winfnc = np.hamming(nfft) elif window == 'blackman': winfnc = np.blackman(nfft) elif window == 'bartlett': winfnc = np.bartlett(nfft) elif window == None or window == 'none': winfnc = mlab.window_none noverlap = int(nfft * (float(overlap) / 100)) Pxx, freqs, bins = mlab.specgram(wavdata, NFFT=nfft, Fs=fs, noverlap=noverlap, pad_to=nfft * 2, window=winfnc, detrend=mlab.detrend_none, sides='default', scale_by_freq=False) # log of zero is -inf, which is not great for plotting Pxx[Pxx == 0] = np.nan # convert to db scale for display spec = 20. * np.log10(Pxx) # set 0 to miniumum value in spec? # would be great to have spec in db SPL, and set any -inf to 0 spec[np.isnan(spec)] = np.nanmin(spec) return spec, freqs, bins, duration
[ "def", "spectrogram", "(", "source", ",", "nfft", "=", "512", ",", "overlap", "=", "90", ",", "window", "=", "'hanning'", ",", "caldb", "=", "93", ",", "calv", "=", "2.83", ")", ":", "if", "isinstance", "(", "source", ",", "basestring", ")", ":", "fs", ",", "wavdata", "=", "audioread", "(", "source", ")", "else", ":", "fs", ",", "wavdata", "=", "source", "# truncate to nears ms", "duration", "=", "float", "(", "len", "(", "wavdata", ")", ")", "/", "fs", "desired_npts", "=", "int", "(", "(", "np", ".", "trunc", "(", "duration", "*", "1000", ")", "/", "1000", ")", "*", "fs", ")", "# print 'LENGTH {}, DESIRED {}'.format(len(wavdata), desired_npts)", "wavdata", "=", "wavdata", "[", ":", "desired_npts", "]", "duration", "=", "len", "(", "wavdata", ")", "/", "fs", "if", "VERBOSE", ":", "amp", "=", "rms", "(", "wavdata", ",", "fs", ")", "print", "'RMS of input signal to spectrogram'", ",", "amp", "# normalize", "if", "len", "(", "wavdata", ")", ">", "0", "and", "np", ".", "max", "(", "abs", "(", "wavdata", ")", ")", "!=", "0", ":", "wavdata", "=", "wavdata", "/", "np", ".", "max", "(", "abs", "(", "wavdata", ")", ")", "if", "window", "==", "'hanning'", ":", "winfnc", "=", "mlab", ".", "window_hanning", "elif", "window", "==", "'hamming'", ":", "winfnc", "=", "np", ".", "hamming", "(", "nfft", ")", "elif", "window", "==", "'blackman'", ":", "winfnc", "=", "np", ".", "blackman", "(", "nfft", ")", "elif", "window", "==", "'bartlett'", ":", "winfnc", "=", "np", ".", "bartlett", "(", "nfft", ")", "elif", "window", "==", "None", "or", "window", "==", "'none'", ":", "winfnc", "=", "mlab", ".", "window_none", "noverlap", "=", "int", "(", "nfft", "*", "(", "float", "(", "overlap", ")", "/", "100", ")", ")", "Pxx", ",", "freqs", ",", "bins", "=", "mlab", ".", "specgram", "(", "wavdata", ",", "NFFT", "=", "nfft", ",", "Fs", "=", "fs", ",", "noverlap", "=", "noverlap", ",", "pad_to", "=", "nfft", "*", "2", ",", "window", "=", "winfnc", ",", "detrend", "=", "mlab", ".", "detrend_none", ",", "sides", "=", "'default'", ",", "scale_by_freq", "=", "False", ")", "# log of zero is -inf, which is not great for plotting", "Pxx", "[", "Pxx", "==", "0", "]", "=", "np", ".", "nan", "# convert to db scale for display", "spec", "=", "20.", "*", "np", ".", "log10", "(", "Pxx", ")", "# set 0 to miniumum value in spec?", "# would be great to have spec in db SPL, and set any -inf to 0", "spec", "[", "np", ".", "isnan", "(", "spec", ")", "]", "=", "np", ".", "nanmin", "(", "spec", ")", "return", "spec", ",", "freqs", ",", "bins", ",", "duration" ]
Produce a matrix of spectral intensity, uses matplotlib's specgram function. Output is in dB scale. :param source: filename of audiofile, or samplerate and vector of audio signal :type source: str or (int, numpy.ndarray) :param nfft: size of nfft window to use :type nfft: int :param overlap: percent overlap of window :type overlap: number :param window: Type of window to use, choices are hanning, hamming, blackman, bartlett or none (rectangular) :type window: string :returns: spec -- 2D array of intensities, freqs -- yaxis labels, bins -- time bin labels, duration -- duration of signal
[ "Produce", "a", "matrix", "of", "spectral", "intensity", "uses", "matplotlib", "s", "specgram", "function", ".", "Output", "is", "in", "dB", "scale", "." ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/tools/audiotools.py#L159-L221
train
portfors-lab/sparkle
sparkle/tools/audiotools.py
convolve_filter
def convolve_filter(signal, impulse_response): """ Convovle the two input signals, if impulse_response is None, returns the unaltered signal """ if impulse_response is not None: # print 'interpolated calibration'#, self.calibration_frequencies adjusted_signal = fftconvolve(signal, impulse_response) adjusted_signal = adjusted_signal[ len(impulse_response) / 2:len(adjusted_signal) - len(impulse_response) / 2 + 1] return adjusted_signal else: return signal
python
def convolve_filter(signal, impulse_response): """ Convovle the two input signals, if impulse_response is None, returns the unaltered signal """ if impulse_response is not None: # print 'interpolated calibration'#, self.calibration_frequencies adjusted_signal = fftconvolve(signal, impulse_response) adjusted_signal = adjusted_signal[ len(impulse_response) / 2:len(adjusted_signal) - len(impulse_response) / 2 + 1] return adjusted_signal else: return signal
[ "def", "convolve_filter", "(", "signal", ",", "impulse_response", ")", ":", "if", "impulse_response", "is", "not", "None", ":", "# print 'interpolated calibration'#, self.calibration_frequencies", "adjusted_signal", "=", "fftconvolve", "(", "signal", ",", "impulse_response", ")", "adjusted_signal", "=", "adjusted_signal", "[", "len", "(", "impulse_response", ")", "/", "2", ":", "len", "(", "adjusted_signal", ")", "-", "len", "(", "impulse_response", ")", "/", "2", "+", "1", "]", "return", "adjusted_signal", "else", ":", "return", "signal" ]
Convovle the two input signals, if impulse_response is None, returns the unaltered signal
[ "Convovle", "the", "two", "input", "signals", "if", "impulse_response", "is", "None", "returns", "the", "unaltered", "signal" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/tools/audiotools.py#L279-L291
train
portfors-lab/sparkle
sparkle/tools/audiotools.py
attenuation_curve
def attenuation_curve(signal, resp, fs, calf, smooth_pts=99): """ Calculate an attenuation roll-off curve, from a signal and its recording :param signal: ouput signal delivered to the generation hardware :type signal: numpy.ndarray :param resp: recording of given signal, as recieved from microphone :type resp: numpy.ndarray :param fs: input and output samplerate (should be the same) :type fs: int :param smooth_pts: amount of averaging to use on the result :type smooth_pts: int :returns: numpy.ndarray -- attenuation vector """ # remove dc offset y = resp - np.mean(resp) x = signal # frequencies present in calibration spectrum npts = len(y) fq = np.arange(npts / 2 + 1) / (float(npts) / fs) # convert time signals to frequency domain Y = np.fft.rfft(y) X = np.fft.rfft(x) # take the magnitude of signals Ymag = np.sqrt(Y.real ** 2 + Y.imag ** 2) # equivalent to abs(Y) Xmag = np.sqrt(X.real ** 2 + X.imag ** 2) # convert to decibel scale YmagdB = 20 * np.log10(Ymag) XmagdB = 20 * np.log10(Xmag) # now we can substract to get attenuation curve diffdB = XmagdB - YmagdB # may want to smooth results here? diffdB = smooth(diffdB, smooth_pts) # shift by the given calibration frequency to align attenutation # with reference point set by user fidx = (np.abs(fq - calf)).argmin() diffdB -= diffdB[fidx] return diffdB
python
def attenuation_curve(signal, resp, fs, calf, smooth_pts=99): """ Calculate an attenuation roll-off curve, from a signal and its recording :param signal: ouput signal delivered to the generation hardware :type signal: numpy.ndarray :param resp: recording of given signal, as recieved from microphone :type resp: numpy.ndarray :param fs: input and output samplerate (should be the same) :type fs: int :param smooth_pts: amount of averaging to use on the result :type smooth_pts: int :returns: numpy.ndarray -- attenuation vector """ # remove dc offset y = resp - np.mean(resp) x = signal # frequencies present in calibration spectrum npts = len(y) fq = np.arange(npts / 2 + 1) / (float(npts) / fs) # convert time signals to frequency domain Y = np.fft.rfft(y) X = np.fft.rfft(x) # take the magnitude of signals Ymag = np.sqrt(Y.real ** 2 + Y.imag ** 2) # equivalent to abs(Y) Xmag = np.sqrt(X.real ** 2 + X.imag ** 2) # convert to decibel scale YmagdB = 20 * np.log10(Ymag) XmagdB = 20 * np.log10(Xmag) # now we can substract to get attenuation curve diffdB = XmagdB - YmagdB # may want to smooth results here? diffdB = smooth(diffdB, smooth_pts) # shift by the given calibration frequency to align attenutation # with reference point set by user fidx = (np.abs(fq - calf)).argmin() diffdB -= diffdB[fidx] return diffdB
[ "def", "attenuation_curve", "(", "signal", ",", "resp", ",", "fs", ",", "calf", ",", "smooth_pts", "=", "99", ")", ":", "# remove dc offset", "y", "=", "resp", "-", "np", ".", "mean", "(", "resp", ")", "x", "=", "signal", "# frequencies present in calibration spectrum", "npts", "=", "len", "(", "y", ")", "fq", "=", "np", ".", "arange", "(", "npts", "/", "2", "+", "1", ")", "/", "(", "float", "(", "npts", ")", "/", "fs", ")", "# convert time signals to frequency domain", "Y", "=", "np", ".", "fft", ".", "rfft", "(", "y", ")", "X", "=", "np", ".", "fft", ".", "rfft", "(", "x", ")", "# take the magnitude of signals", "Ymag", "=", "np", ".", "sqrt", "(", "Y", ".", "real", "**", "2", "+", "Y", ".", "imag", "**", "2", ")", "# equivalent to abs(Y)", "Xmag", "=", "np", ".", "sqrt", "(", "X", ".", "real", "**", "2", "+", "X", ".", "imag", "**", "2", ")", "# convert to decibel scale", "YmagdB", "=", "20", "*", "np", ".", "log10", "(", "Ymag", ")", "XmagdB", "=", "20", "*", "np", ".", "log10", "(", "Xmag", ")", "# now we can substract to get attenuation curve", "diffdB", "=", "XmagdB", "-", "YmagdB", "# may want to smooth results here?", "diffdB", "=", "smooth", "(", "diffdB", ",", "smooth_pts", ")", "# shift by the given calibration frequency to align attenutation", "# with reference point set by user", "fidx", "=", "(", "np", ".", "abs", "(", "fq", "-", "calf", ")", ")", ".", "argmin", "(", ")", "diffdB", "-=", "diffdB", "[", "fidx", "]", "return", "diffdB" ]
Calculate an attenuation roll-off curve, from a signal and its recording :param signal: ouput signal delivered to the generation hardware :type signal: numpy.ndarray :param resp: recording of given signal, as recieved from microphone :type resp: numpy.ndarray :param fs: input and output samplerate (should be the same) :type fs: int :param smooth_pts: amount of averaging to use on the result :type smooth_pts: int :returns: numpy.ndarray -- attenuation vector
[ "Calculate", "an", "attenuation", "roll", "-", "off", "curve", "from", "a", "signal", "and", "its", "recording" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/tools/audiotools.py#L351-L396
train
portfors-lab/sparkle
sparkle/tools/audiotools.py
calibrate_signal
def calibrate_signal(signal, resp, fs, frange): """Given original signal and recording, spits out a calibrated signal""" # remove dc offset from recorded response (synthesized orignal shouldn't have one) dc = np.mean(resp) resp = resp - dc npts = len(signal) f0 = np.ceil(frange[0] / (float(fs) / npts)) f1 = np.floor(frange[1] / (float(fs) / npts)) y = resp # y = y/np.amax(y) # normalize Y = np.fft.rfft(y) x = signal # x = x/np.amax(x) # normalize X = np.fft.rfft(x) H = Y / X # still issues warning because all of Y/X is executed to selected answers from # H = np.where(X.real!=0, Y/X, 1) # H[:f0].real = 1 # H[f1:].real = 1 # H = smooth(H) A = X / H return np.fft.irfft(A)
python
def calibrate_signal(signal, resp, fs, frange): """Given original signal and recording, spits out a calibrated signal""" # remove dc offset from recorded response (synthesized orignal shouldn't have one) dc = np.mean(resp) resp = resp - dc npts = len(signal) f0 = np.ceil(frange[0] / (float(fs) / npts)) f1 = np.floor(frange[1] / (float(fs) / npts)) y = resp # y = y/np.amax(y) # normalize Y = np.fft.rfft(y) x = signal # x = x/np.amax(x) # normalize X = np.fft.rfft(x) H = Y / X # still issues warning because all of Y/X is executed to selected answers from # H = np.where(X.real!=0, Y/X, 1) # H[:f0].real = 1 # H[f1:].real = 1 # H = smooth(H) A = X / H return np.fft.irfft(A)
[ "def", "calibrate_signal", "(", "signal", ",", "resp", ",", "fs", ",", "frange", ")", ":", "# remove dc offset from recorded response (synthesized orignal shouldn't have one)", "dc", "=", "np", ".", "mean", "(", "resp", ")", "resp", "=", "resp", "-", "dc", "npts", "=", "len", "(", "signal", ")", "f0", "=", "np", ".", "ceil", "(", "frange", "[", "0", "]", "/", "(", "float", "(", "fs", ")", "/", "npts", ")", ")", "f1", "=", "np", ".", "floor", "(", "frange", "[", "1", "]", "/", "(", "float", "(", "fs", ")", "/", "npts", ")", ")", "y", "=", "resp", "# y = y/np.amax(y) # normalize", "Y", "=", "np", ".", "fft", ".", "rfft", "(", "y", ")", "x", "=", "signal", "# x = x/np.amax(x) # normalize", "X", "=", "np", ".", "fft", ".", "rfft", "(", "x", ")", "H", "=", "Y", "/", "X", "# still issues warning because all of Y/X is executed to selected answers from", "# H = np.where(X.real!=0, Y/X, 1)", "# H[:f0].real = 1", "# H[f1:].real = 1", "# H = smooth(H)", "A", "=", "X", "/", "H", "return", "np", ".", "fft", ".", "irfft", "(", "A", ")" ]
Given original signal and recording, spits out a calibrated signal
[ "Given", "original", "signal", "and", "recording", "spits", "out", "a", "calibrated", "signal" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/tools/audiotools.py#L399-L427
train
portfors-lab/sparkle
sparkle/tools/audiotools.py
multiply_frequencies
def multiply_frequencies(signal, fs, frange, calibration_frequencies, attendB): """Given a vector of dB attenuations, adjust signal by multiplication in the frequency domain""" npts = len(signal) padto = 1 << (npts - 1).bit_length() X = np.fft.rfft(signal, n=padto) npts = padto f = np.arange((npts / 2) + 1) / (npts / fs) fidx_low = (np.abs(f - frange[0])).argmin() fidx_high = (np.abs(f - frange[1])).argmin() cal_func = interp1d(calibration_frequencies, attendB) roi = f[fidx_low:fidx_high] Hroi = cal_func(roi) H = np.zeros((len(X),)) H[fidx_low:fidx_high] = Hroi H = smooth(H) # print 'H dB max', np.amax(H) H = 10 ** ((H).astype(float) / 20) # print 'H amp max', np.amax(H) # Xadjusted = X.copy() # Xadjusted[fidx_low:fidx_high] *= H # Xadjusted = smooth(Xadjusted) Xadjusted = X * H # print 'X max', np.amax(abs(X)) # print 'Xadjusted max', np.amax(abs(Xadjusted)) signal_calibrated = np.fft.irfft(Xadjusted) return signal_calibrated[:len(signal)]
python
def multiply_frequencies(signal, fs, frange, calibration_frequencies, attendB): """Given a vector of dB attenuations, adjust signal by multiplication in the frequency domain""" npts = len(signal) padto = 1 << (npts - 1).bit_length() X = np.fft.rfft(signal, n=padto) npts = padto f = np.arange((npts / 2) + 1) / (npts / fs) fidx_low = (np.abs(f - frange[0])).argmin() fidx_high = (np.abs(f - frange[1])).argmin() cal_func = interp1d(calibration_frequencies, attendB) roi = f[fidx_low:fidx_high] Hroi = cal_func(roi) H = np.zeros((len(X),)) H[fidx_low:fidx_high] = Hroi H = smooth(H) # print 'H dB max', np.amax(H) H = 10 ** ((H).astype(float) / 20) # print 'H amp max', np.amax(H) # Xadjusted = X.copy() # Xadjusted[fidx_low:fidx_high] *= H # Xadjusted = smooth(Xadjusted) Xadjusted = X * H # print 'X max', np.amax(abs(X)) # print 'Xadjusted max', np.amax(abs(Xadjusted)) signal_calibrated = np.fft.irfft(Xadjusted) return signal_calibrated[:len(signal)]
[ "def", "multiply_frequencies", "(", "signal", ",", "fs", ",", "frange", ",", "calibration_frequencies", ",", "attendB", ")", ":", "npts", "=", "len", "(", "signal", ")", "padto", "=", "1", "<<", "(", "npts", "-", "1", ")", ".", "bit_length", "(", ")", "X", "=", "np", ".", "fft", ".", "rfft", "(", "signal", ",", "n", "=", "padto", ")", "npts", "=", "padto", "f", "=", "np", ".", "arange", "(", "(", "npts", "/", "2", ")", "+", "1", ")", "/", "(", "npts", "/", "fs", ")", "fidx_low", "=", "(", "np", ".", "abs", "(", "f", "-", "frange", "[", "0", "]", ")", ")", ".", "argmin", "(", ")", "fidx_high", "=", "(", "np", ".", "abs", "(", "f", "-", "frange", "[", "1", "]", ")", ")", ".", "argmin", "(", ")", "cal_func", "=", "interp1d", "(", "calibration_frequencies", ",", "attendB", ")", "roi", "=", "f", "[", "fidx_low", ":", "fidx_high", "]", "Hroi", "=", "cal_func", "(", "roi", ")", "H", "=", "np", ".", "zeros", "(", "(", "len", "(", "X", ")", ",", ")", ")", "H", "[", "fidx_low", ":", "fidx_high", "]", "=", "Hroi", "H", "=", "smooth", "(", "H", ")", "# print 'H dB max', np.amax(H)", "H", "=", "10", "**", "(", "(", "H", ")", ".", "astype", "(", "float", ")", "/", "20", ")", "# print 'H amp max', np.amax(H)", "# Xadjusted = X.copy()", "# Xadjusted[fidx_low:fidx_high] *= H", "# Xadjusted = smooth(Xadjusted)", "Xadjusted", "=", "X", "*", "H", "# print 'X max', np.amax(abs(X))", "# print 'Xadjusted max', np.amax(abs(Xadjusted))", "signal_calibrated", "=", "np", ".", "fft", ".", "irfft", "(", "Xadjusted", ")", "return", "signal_calibrated", "[", ":", "len", "(", "signal", ")", "]" ]
Given a vector of dB attenuations, adjust signal by multiplication in the frequency domain
[ "Given", "a", "vector", "of", "dB", "attenuations", "adjust", "signal", "by", "multiplication", "in", "the", "frequency", "domain" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/tools/audiotools.py#L430-L465
train
portfors-lab/sparkle
sparkle/tools/audiotools.py
audioread
def audioread(filename): """Reads an audio signal from file. Supported formats : wav :param filename: filename of the audiofile to load :type filename: str :returns: int, numpy.ndarray -- samplerate, array containing the audio signal """ try: if '.wav' in filename.lower(): fs, signal = wv.read(filename) elif '.call' in filename.lower(): with open(filename, 'rb') as f: signal = np.fromfile(f, dtype=np.int16) fs = 333333 else: raise IOError("Unsupported audio format for file: {}".format(filename)) except: print u"Problem reading wav file" raise signal = signal.astype(float) return fs, signal
python
def audioread(filename): """Reads an audio signal from file. Supported formats : wav :param filename: filename of the audiofile to load :type filename: str :returns: int, numpy.ndarray -- samplerate, array containing the audio signal """ try: if '.wav' in filename.lower(): fs, signal = wv.read(filename) elif '.call' in filename.lower(): with open(filename, 'rb') as f: signal = np.fromfile(f, dtype=np.int16) fs = 333333 else: raise IOError("Unsupported audio format for file: {}".format(filename)) except: print u"Problem reading wav file" raise signal = signal.astype(float) return fs, signal
[ "def", "audioread", "(", "filename", ")", ":", "try", ":", "if", "'.wav'", "in", "filename", ".", "lower", "(", ")", ":", "fs", ",", "signal", "=", "wv", ".", "read", "(", "filename", ")", "elif", "'.call'", "in", "filename", ".", "lower", "(", ")", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "signal", "=", "np", ".", "fromfile", "(", "f", ",", "dtype", "=", "np", ".", "int16", ")", "fs", "=", "333333", "else", ":", "raise", "IOError", "(", "\"Unsupported audio format for file: {}\"", ".", "format", "(", "filename", ")", ")", "except", ":", "print", "u\"Problem reading wav file\"", "raise", "signal", "=", "signal", ".", "astype", "(", "float", ")", "return", "fs", ",", "signal" ]
Reads an audio signal from file. Supported formats : wav :param filename: filename of the audiofile to load :type filename: str :returns: int, numpy.ndarray -- samplerate, array containing the audio signal
[ "Reads", "an", "audio", "signal", "from", "file", "." ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/tools/audiotools.py#L485-L507
train
portfors-lab/sparkle
sparkle/tools/audiotools.py
audiorate
def audiorate(filename): """Determines the samplerate of the given audio recording file :param filename: filename of the audiofile :type filename: str :returns: int -- samplerate of the recording """ if '.wav' in filename.lower(): wf = wave.open(filename) fs = wf.getframerate() wf.close() elif '.call' in filename.lower(): fs = 333333 else: raise IOError("Unsupported audio format for file: {}".format(filename)) return fs
python
def audiorate(filename): """Determines the samplerate of the given audio recording file :param filename: filename of the audiofile :type filename: str :returns: int -- samplerate of the recording """ if '.wav' in filename.lower(): wf = wave.open(filename) fs = wf.getframerate() wf.close() elif '.call' in filename.lower(): fs = 333333 else: raise IOError("Unsupported audio format for file: {}".format(filename)) return fs
[ "def", "audiorate", "(", "filename", ")", ":", "if", "'.wav'", "in", "filename", ".", "lower", "(", ")", ":", "wf", "=", "wave", ".", "open", "(", "filename", ")", "fs", "=", "wf", ".", "getframerate", "(", ")", "wf", ".", "close", "(", ")", "elif", "'.call'", "in", "filename", ".", "lower", "(", ")", ":", "fs", "=", "333333", "else", ":", "raise", "IOError", "(", "\"Unsupported audio format for file: {}\"", ".", "format", "(", "filename", ")", ")", "return", "fs" ]
Determines the samplerate of the given audio recording file :param filename: filename of the audiofile :type filename: str :returns: int -- samplerate of the recording
[ "Determines", "the", "samplerate", "of", "the", "given", "audio", "recording", "file" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/tools/audiotools.py#L510-L526
train
JukeboxPipeline/jukeboxmaya
src/jukeboxmaya/addons/mayawidgettooltip/mayawidgettooltip.py
MayaWidgetToolTip.init_ui
def init_ui(self, ): """Create the tooltip in the sidebar :returns: None :rtype: None :raises: None """ self.sidebar = self.get_maya_sidebar() self.lay = self.sidebar.layout() self.tool_pb = QtGui.QPushButton("JB Wins") self.tooltip = JB_WindowToolTip() self.tooltip.install_tooltip(self.tool_pb) self.lay.addWidget(self.tool_pb) self.tool_pb.clicked.connect(self.tooltip.show)
python
def init_ui(self, ): """Create the tooltip in the sidebar :returns: None :rtype: None :raises: None """ self.sidebar = self.get_maya_sidebar() self.lay = self.sidebar.layout() self.tool_pb = QtGui.QPushButton("JB Wins") self.tooltip = JB_WindowToolTip() self.tooltip.install_tooltip(self.tool_pb) self.lay.addWidget(self.tool_pb) self.tool_pb.clicked.connect(self.tooltip.show)
[ "def", "init_ui", "(", "self", ",", ")", ":", "self", ".", "sidebar", "=", "self", ".", "get_maya_sidebar", "(", ")", "self", ".", "lay", "=", "self", ".", "sidebar", ".", "layout", "(", ")", "self", ".", "tool_pb", "=", "QtGui", ".", "QPushButton", "(", "\"JB Wins\"", ")", "self", ".", "tooltip", "=", "JB_WindowToolTip", "(", ")", "self", ".", "tooltip", ".", "install_tooltip", "(", "self", ".", "tool_pb", ")", "self", ".", "lay", ".", "addWidget", "(", "self", ".", "tool_pb", ")", "self", ".", "tool_pb", ".", "clicked", ".", "connect", "(", "self", ".", "tooltip", ".", "show", ")" ]
Create the tooltip in the sidebar :returns: None :rtype: None :raises: None
[ "Create", "the", "tooltip", "in", "the", "sidebar" ]
c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c
https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/addons/mayawidgettooltip/mayawidgettooltip.py#L40-L53
train
JukeboxPipeline/jukeboxmaya
src/jukeboxmaya/addons/mayawidgettooltip/mayawidgettooltip.py
MayaWidgetToolTip.uninit_ui
def uninit_ui(self): """Delete the tooltip :returns: None :rtype: None :raises: None """ self.lay.removeWidget(self.tool_pb) self.tooltip.deleteLater() self.tool_pb.deleteLater()
python
def uninit_ui(self): """Delete the tooltip :returns: None :rtype: None :raises: None """ self.lay.removeWidget(self.tool_pb) self.tooltip.deleteLater() self.tool_pb.deleteLater()
[ "def", "uninit_ui", "(", "self", ")", ":", "self", ".", "lay", ".", "removeWidget", "(", "self", ".", "tool_pb", ")", "self", ".", "tooltip", ".", "deleteLater", "(", ")", "self", ".", "tool_pb", ".", "deleteLater", "(", ")" ]
Delete the tooltip :returns: None :rtype: None :raises: None
[ "Delete", "the", "tooltip" ]
c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c
https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/addons/mayawidgettooltip/mayawidgettooltip.py#L55-L64
train
portfors-lab/sparkle
sparkle/data/open.py
open_acqdata
def open_acqdata(filename, user='unknown', filemode='w-'): """Opens and returns the correct AcquisitionData object according to filename extention. Supported extentions: * .hdf5, .h5 for sparkle data * .pst, .raw for batlab data. Both the .pst and .raw file must be co-located and share the same base file name, but only one should be provided to this function see :class:`AcquisitionData<sparkle.data.acqdata.AcquisitionData>` examples (if data file already exists):: data = open_acqdata('myexperiment.hdf5', filemode='r') print data.dataset_names() for batlab data:: data = open('mouse666.raw', filemode='r') print data.dataset_names() """ if filename.lower().endswith((".hdf5", ".h5")): return HDF5Data(filename, user, filemode) elif filename.lower().endswith((".pst", ".raw")): return BatlabData(filename, user, filemode) else: print "File format not supported: ", filename
python
def open_acqdata(filename, user='unknown', filemode='w-'): """Opens and returns the correct AcquisitionData object according to filename extention. Supported extentions: * .hdf5, .h5 for sparkle data * .pst, .raw for batlab data. Both the .pst and .raw file must be co-located and share the same base file name, but only one should be provided to this function see :class:`AcquisitionData<sparkle.data.acqdata.AcquisitionData>` examples (if data file already exists):: data = open_acqdata('myexperiment.hdf5', filemode='r') print data.dataset_names() for batlab data:: data = open('mouse666.raw', filemode='r') print data.dataset_names() """ if filename.lower().endswith((".hdf5", ".h5")): return HDF5Data(filename, user, filemode) elif filename.lower().endswith((".pst", ".raw")): return BatlabData(filename, user, filemode) else: print "File format not supported: ", filename
[ "def", "open_acqdata", "(", "filename", ",", "user", "=", "'unknown'", ",", "filemode", "=", "'w-'", ")", ":", "if", "filename", ".", "lower", "(", ")", ".", "endswith", "(", "(", "\".hdf5\"", ",", "\".h5\"", ")", ")", ":", "return", "HDF5Data", "(", "filename", ",", "user", ",", "filemode", ")", "elif", "filename", ".", "lower", "(", ")", ".", "endswith", "(", "(", "\".pst\"", ",", "\".raw\"", ")", ")", ":", "return", "BatlabData", "(", "filename", ",", "user", ",", "filemode", ")", "else", ":", "print", "\"File format not supported: \"", ",", "filename" ]
Opens and returns the correct AcquisitionData object according to filename extention. Supported extentions: * .hdf5, .h5 for sparkle data * .pst, .raw for batlab data. Both the .pst and .raw file must be co-located and share the same base file name, but only one should be provided to this function see :class:`AcquisitionData<sparkle.data.acqdata.AcquisitionData>` examples (if data file already exists):: data = open_acqdata('myexperiment.hdf5', filemode='r') print data.dataset_names() for batlab data:: data = open('mouse666.raw', filemode='r') print data.dataset_names()
[ "Opens", "and", "returns", "the", "correct", "AcquisitionData", "object", "according", "to", "filename", "extention", "." ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/data/open.py#L5-L29
train
portfors-lab/sparkle
sparkle/gui/stim/qstimulus.py
QStimulusModel.columnCount
def columnCount(self, parent=QtCore.QModelIndex()): """Determines the numbers of columns the view will draw Required by view, see :qtdoc:`subclassing<qabstractitemmodel.subclassing>` """ if parent.isValid(): return self._stim.columnCount(parent.row()) else: return self._stim.columnCount()
python
def columnCount(self, parent=QtCore.QModelIndex()): """Determines the numbers of columns the view will draw Required by view, see :qtdoc:`subclassing<qabstractitemmodel.subclassing>` """ if parent.isValid(): return self._stim.columnCount(parent.row()) else: return self._stim.columnCount()
[ "def", "columnCount", "(", "self", ",", "parent", "=", "QtCore", ".", "QModelIndex", "(", ")", ")", ":", "if", "parent", ".", "isValid", "(", ")", ":", "return", "self", ".", "_stim", ".", "columnCount", "(", "parent", ".", "row", "(", ")", ")", "else", ":", "return", "self", ".", "_stim", ".", "columnCount", "(", ")" ]
Determines the numbers of columns the view will draw Required by view, see :qtdoc:`subclassing<qabstractitemmodel.subclassing>`
[ "Determines", "the", "numbers", "of", "columns", "the", "view", "will", "draw" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/qstimulus.py#L53-L61
train
portfors-lab/sparkle
sparkle/gui/stim/qstimulus.py
QStimulusModel.removeItem
def removeItem(self, index): """Alias for removeComponent""" self._stim.removeComponent(index.row(), index.column())
python
def removeItem(self, index): """Alias for removeComponent""" self._stim.removeComponent(index.row(), index.column())
[ "def", "removeItem", "(", "self", ",", "index", ")", ":", "self", ".", "_stim", ".", "removeComponent", "(", "index", ".", "row", "(", ")", ",", "index", ".", "column", "(", ")", ")" ]
Alias for removeComponent
[ "Alias", "for", "removeComponent" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/qstimulus.py#L162-L164
train
portfors-lab/sparkle
sparkle/gui/stim/qstimulus.py
QStimulusModel.setEditor
def setEditor(self, name): """Sets the editor class for this Stimulus""" editor = get_stimulus_editor(name) self.editor = editor self._stim.setStimType(name)
python
def setEditor(self, name): """Sets the editor class for this Stimulus""" editor = get_stimulus_editor(name) self.editor = editor self._stim.setStimType(name)
[ "def", "setEditor", "(", "self", ",", "name", ")", ":", "editor", "=", "get_stimulus_editor", "(", "name", ")", "self", ".", "editor", "=", "editor", "self", ".", "_stim", ".", "setStimType", "(", "name", ")" ]
Sets the editor class for this Stimulus
[ "Sets", "the", "editor", "class", "for", "this", "Stimulus" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/qstimulus.py#L190-L194
train
portfors-lab/sparkle
sparkle/gui/stim/qstimulus.py
QStimulusModel.showEditor
def showEditor(self): """Creates and shows an editor for this Stimulus""" if self.editor is not None: editor = self.editor() editor.setModel(self) factory = get_stimulus_factory(self._stim.stimType()) editor.editingFinished.connect(factory.update) return editor else: logger = logging.getLogger('main') logger.warning('Erm, no editor available :(')
python
def showEditor(self): """Creates and shows an editor for this Stimulus""" if self.editor is not None: editor = self.editor() editor.setModel(self) factory = get_stimulus_factory(self._stim.stimType()) editor.editingFinished.connect(factory.update) return editor else: logger = logging.getLogger('main') logger.warning('Erm, no editor available :(')
[ "def", "showEditor", "(", "self", ")", ":", "if", "self", ".", "editor", "is", "not", "None", ":", "editor", "=", "self", ".", "editor", "(", ")", "editor", ".", "setModel", "(", "self", ")", "factory", "=", "get_stimulus_factory", "(", "self", ".", "_stim", ".", "stimType", "(", ")", ")", "editor", ".", "editingFinished", ".", "connect", "(", "factory", ".", "update", ")", "return", "editor", "else", ":", "logger", "=", "logging", ".", "getLogger", "(", "'main'", ")", "logger", ".", "warning", "(", "'Erm, no editor available :('", ")" ]
Creates and shows an editor for this Stimulus
[ "Creates", "and", "shows", "an", "editor", "for", "this", "Stimulus" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/qstimulus.py#L196-L206
train
portfors-lab/sparkle
sparkle/gui/stim/qstimulus.py
QStimulusModel.randomToggle
def randomToggle(self, randomize): """Sets the reorder function on this StimulusModel to a randomizer or none, alternately""" if randomize: self._stim.setReorderFunc(order_function('random'), 'random') else: self._stim.reorder = None
python
def randomToggle(self, randomize): """Sets the reorder function on this StimulusModel to a randomizer or none, alternately""" if randomize: self._stim.setReorderFunc(order_function('random'), 'random') else: self._stim.reorder = None
[ "def", "randomToggle", "(", "self", ",", "randomize", ")", ":", "if", "randomize", ":", "self", ".", "_stim", ".", "setReorderFunc", "(", "order_function", "(", "'random'", ")", ",", "'random'", ")", "else", ":", "self", ".", "_stim", ".", "reorder", "=", "None" ]
Sets the reorder function on this StimulusModel to a randomizer or none, alternately
[ "Sets", "the", "reorder", "function", "on", "this", "StimulusModel", "to", "a", "randomizer", "or", "none", "alternately" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/qstimulus.py#L220-L226
train
agramian/subprocess-manager
subprocess_manager/assert_variable_type.py
assert_variable_type
def assert_variable_type(variable, expected_type, raise_exception=True): """Return True if a variable is of a certain type or types. Otherwise raise a ValueError exception. Positional arguments: variable -- the variable to be checked expected_type -- the expected type or types of the variable raise_exception -- whether to raise an exception or just return False on failure, with error message """ # if expected type is not a list make it one if not isinstance(expected_type, list): expected_type = [expected_type] # make sure all entries in the expected_type list are types for t in expected_type: if not isinstance(t, type): raise ValueError('expected_type argument "%s" is not a type' %str(t)) # make sure raise_exception is a bool if not isinstance(raise_exception, bool): raise ValueError('raise_exception argument "%s" is not a bool' %str(raise_exception)) # check the type of the variable against the list # then raise an exception or return True if not len([(t) for t in expected_type if isinstance(variable, t)]): error_message = '"%s" is not an instance of type %s. It is of type %s' %(str(variable),' or '.join([str(t) for t in expected_type]), str(type(variable))) if raise_exception: raise ValueError(error_message) else: return False, error_message return True, None
python
def assert_variable_type(variable, expected_type, raise_exception=True): """Return True if a variable is of a certain type or types. Otherwise raise a ValueError exception. Positional arguments: variable -- the variable to be checked expected_type -- the expected type or types of the variable raise_exception -- whether to raise an exception or just return False on failure, with error message """ # if expected type is not a list make it one if not isinstance(expected_type, list): expected_type = [expected_type] # make sure all entries in the expected_type list are types for t in expected_type: if not isinstance(t, type): raise ValueError('expected_type argument "%s" is not a type' %str(t)) # make sure raise_exception is a bool if not isinstance(raise_exception, bool): raise ValueError('raise_exception argument "%s" is not a bool' %str(raise_exception)) # check the type of the variable against the list # then raise an exception or return True if not len([(t) for t in expected_type if isinstance(variable, t)]): error_message = '"%s" is not an instance of type %s. It is of type %s' %(str(variable),' or '.join([str(t) for t in expected_type]), str(type(variable))) if raise_exception: raise ValueError(error_message) else: return False, error_message return True, None
[ "def", "assert_variable_type", "(", "variable", ",", "expected_type", ",", "raise_exception", "=", "True", ")", ":", "# if expected type is not a list make it one", "if", "not", "isinstance", "(", "expected_type", ",", "list", ")", ":", "expected_type", "=", "[", "expected_type", "]", "# make sure all entries in the expected_type list are types", "for", "t", "in", "expected_type", ":", "if", "not", "isinstance", "(", "t", ",", "type", ")", ":", "raise", "ValueError", "(", "'expected_type argument \"%s\" is not a type'", "%", "str", "(", "t", ")", ")", "# make sure raise_exception is a bool", "if", "not", "isinstance", "(", "raise_exception", ",", "bool", ")", ":", "raise", "ValueError", "(", "'raise_exception argument \"%s\" is not a bool'", "%", "str", "(", "raise_exception", ")", ")", "# check the type of the variable against the list", "# then raise an exception or return True", "if", "not", "len", "(", "[", "(", "t", ")", "for", "t", "in", "expected_type", "if", "isinstance", "(", "variable", ",", "t", ")", "]", ")", ":", "error_message", "=", "'\"%s\" is not an instance of type %s. It is of type %s'", "%", "(", "str", "(", "variable", ")", ",", "' or '", ".", "join", "(", "[", "str", "(", "t", ")", "for", "t", "in", "expected_type", "]", ")", ",", "str", "(", "type", "(", "variable", ")", ")", ")", "if", "raise_exception", ":", "raise", "ValueError", "(", "error_message", ")", "else", ":", "return", "False", ",", "error_message", "return", "True", ",", "None" ]
Return True if a variable is of a certain type or types. Otherwise raise a ValueError exception. Positional arguments: variable -- the variable to be checked expected_type -- the expected type or types of the variable raise_exception -- whether to raise an exception or just return False on failure, with error message
[ "Return", "True", "if", "a", "variable", "is", "of", "a", "certain", "type", "or", "types", ".", "Otherwise", "raise", "a", "ValueError", "exception", "." ]
fff9ff2ddab644a86f96e1ccf5df142c482a8247
https://github.com/agramian/subprocess-manager/blob/fff9ff2ddab644a86f96e1ccf5df142c482a8247/subprocess_manager/assert_variable_type.py#L6-L34
train
portfors-lab/sparkle
sparkle/gui/stim/abstract_stim_editor.py
AbstractStimulusWidget.closeEvent
def closeEvent(self, event): """Verifies the stimulus before closing, warns user with a dialog if there are any problems""" self.ok.setText("Checking...") QtGui.QApplication.processEvents() self.model().cleanComponents() self.model().purgeAutoSelected() msg = self.model().verify() if not msg: msg = self.model().warning() if msg: warnBox = QtGui.QMessageBox( QtGui.QMessageBox.Warning, 'Warning - Invalid Settings', '{}. Do you want to change this?'.format(msg) ) yesButton = warnBox.addButton(self.tr('Edit'), QtGui.QMessageBox.YesRole) noButton = warnBox.addButton(self.tr('Ignore'), QtGui.QMessageBox.NoRole) warnBox.exec_() if warnBox.clickedButton() == yesButton: event.ignore() self.ok.setText("OK")
python
def closeEvent(self, event): """Verifies the stimulus before closing, warns user with a dialog if there are any problems""" self.ok.setText("Checking...") QtGui.QApplication.processEvents() self.model().cleanComponents() self.model().purgeAutoSelected() msg = self.model().verify() if not msg: msg = self.model().warning() if msg: warnBox = QtGui.QMessageBox( QtGui.QMessageBox.Warning, 'Warning - Invalid Settings', '{}. Do you want to change this?'.format(msg) ) yesButton = warnBox.addButton(self.tr('Edit'), QtGui.QMessageBox.YesRole) noButton = warnBox.addButton(self.tr('Ignore'), QtGui.QMessageBox.NoRole) warnBox.exec_() if warnBox.clickedButton() == yesButton: event.ignore() self.ok.setText("OK")
[ "def", "closeEvent", "(", "self", ",", "event", ")", ":", "self", ".", "ok", ".", "setText", "(", "\"Checking...\"", ")", "QtGui", ".", "QApplication", ".", "processEvents", "(", ")", "self", ".", "model", "(", ")", ".", "cleanComponents", "(", ")", "self", ".", "model", "(", ")", ".", "purgeAutoSelected", "(", ")", "msg", "=", "self", ".", "model", "(", ")", ".", "verify", "(", ")", "if", "not", "msg", ":", "msg", "=", "self", ".", "model", "(", ")", ".", "warning", "(", ")", "if", "msg", ":", "warnBox", "=", "QtGui", ".", "QMessageBox", "(", "QtGui", ".", "QMessageBox", ".", "Warning", ",", "'Warning - Invalid Settings'", ",", "'{}. Do you want to change this?'", ".", "format", "(", "msg", ")", ")", "yesButton", "=", "warnBox", ".", "addButton", "(", "self", ".", "tr", "(", "'Edit'", ")", ",", "QtGui", ".", "QMessageBox", ".", "YesRole", ")", "noButton", "=", "warnBox", ".", "addButton", "(", "self", ".", "tr", "(", "'Ignore'", ")", ",", "QtGui", ".", "QMessageBox", ".", "NoRole", ")", "warnBox", ".", "exec_", "(", ")", "if", "warnBox", ".", "clickedButton", "(", ")", "==", "yesButton", ":", "event", ".", "ignore", "(", ")", "self", ".", "ok", ".", "setText", "(", "\"OK\"", ")" ]
Verifies the stimulus before closing, warns user with a dialog if there are any problems
[ "Verifies", "the", "stimulus", "before", "closing", "warns", "user", "with", "a", "dialog", "if", "there", "are", "any", "problems" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/abstract_stim_editor.py#L51-L68
train
yamcs/yamcs-python
yamcs-client/yamcs/core/subscriptions.py
WebSocketSubscriptionManager.close
def close(self, reason=None): """ Stop consuming messages and perform an orderly shutdown. If ``reason`` is None, then this is considered a regular close. """ with self._closing: if self._closed: return self._websocket.close() self._consumer.join() self._consumer = None self._websocket = None self._closed = True for cb in self._close_callbacks: cb(self, reason)
python
def close(self, reason=None): """ Stop consuming messages and perform an orderly shutdown. If ``reason`` is None, then this is considered a regular close. """ with self._closing: if self._closed: return self._websocket.close() self._consumer.join() self._consumer = None self._websocket = None self._closed = True for cb in self._close_callbacks: cb(self, reason)
[ "def", "close", "(", "self", ",", "reason", "=", "None", ")", ":", "with", "self", ".", "_closing", ":", "if", "self", ".", "_closed", ":", "return", "self", ".", "_websocket", ".", "close", "(", ")", "self", ".", "_consumer", ".", "join", "(", ")", "self", ".", "_consumer", "=", "None", "self", ".", "_websocket", "=", "None", "self", ".", "_closed", "=", "True", "for", "cb", "in", "self", ".", "_close_callbacks", ":", "cb", "(", "self", ",", "reason", ")" ]
Stop consuming messages and perform an orderly shutdown. If ``reason`` is None, then this is considered a regular close.
[ "Stop", "consuming", "messages", "and", "perform", "an", "orderly", "shutdown", "." ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/core/subscriptions.py#L82-L100
train
portfors-lab/sparkle
sparkle/gui/trashcan.py
TrashWidget.dropEvent
def dropEvent(self, event): """Emits the itemTrashed signal, data contained in drag operation left to be garbage collected""" super(TrashWidget, self).dropEvent(event) self.itemTrashed.emit()
python
def dropEvent(self, event): """Emits the itemTrashed signal, data contained in drag operation left to be garbage collected""" super(TrashWidget, self).dropEvent(event) self.itemTrashed.emit()
[ "def", "dropEvent", "(", "self", ",", "event", ")", ":", "super", "(", "TrashWidget", ",", "self", ")", ".", "dropEvent", "(", "event", ")", "self", ".", "itemTrashed", ".", "emit", "(", ")" ]
Emits the itemTrashed signal, data contained in drag operation left to be garbage collected
[ "Emits", "the", "itemTrashed", "signal", "data", "contained", "in", "drag", "operation", "left", "to", "be", "garbage", "collected" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/trashcan.py#L45-L49
train
RedHatQE/Sentaku
src/sentaku/chooser.py
Chooser.choose
def choose(self, choose_from): """given a mapping of implementations choose one based on the current settings returns a key value pair """ for choice in self.elements: if choice in choose_from: return ImplementationChoice(choice, choose_from[choice]) raise LookupError(self.elements, choose_from.keys())
python
def choose(self, choose_from): """given a mapping of implementations choose one based on the current settings returns a key value pair """ for choice in self.elements: if choice in choose_from: return ImplementationChoice(choice, choose_from[choice]) raise LookupError(self.elements, choose_from.keys())
[ "def", "choose", "(", "self", ",", "choose_from", ")", ":", "for", "choice", "in", "self", ".", "elements", ":", "if", "choice", "in", "choose_from", ":", "return", "ImplementationChoice", "(", "choice", ",", "choose_from", "[", "choice", "]", ")", "raise", "LookupError", "(", "self", ".", "elements", ",", "choose_from", ".", "keys", "(", ")", ")" ]
given a mapping of implementations choose one based on the current settings returns a key value pair
[ "given", "a", "mapping", "of", "implementations", "choose", "one", "based", "on", "the", "current", "settings", "returns", "a", "key", "value", "pair" ]
b336cef5b6ee2db4e8dff28dcdb2be35a1f3d01c
https://github.com/RedHatQE/Sentaku/blob/b336cef5b6ee2db4e8dff28dcdb2be35a1f3d01c/src/sentaku/chooser.py#L28-L37
train
lowandrew/OLCTools
spadespipeline/compress.py
Compress.remove
def remove(self): """Removes unnecessary temporary files generated by the pipeline""" import shutil printtime('Removing large and/or temporary files', self.start) removefolder = list() for sample in self.metadata: # Use os.walk to iterate through all the files in the sample output directory for path, dirs, files in os.walk(sample.general.outputdirectory): for item in files: # Use regex to find files to remove if re.search(".fastq$", item) or re.search(".fastq.gz$", item) or re.search(".bam$", item) \ or re.search(".bt2$", item) or re.search(".tab$", item) or re.search("^before", item) \ or re.search("^baitedtargets", item) or re.search("_combined.csv$", item) \ or re.search("^scaffolds", item) or re.search(".fastg$", item) or re.search(".gfa$", item) \ or re.search(".bai$", item) or 'coregenome' in path or 'prophages' in path: # Keep the baitedtargets.fa, core genome, and merged metagenome files if item != 'baitedtargets.fa' and not re.search("coregenome", item) \ and not re.search("paired", item): # Remove the unnecessary files try: os.remove(os.path.join(path, item)) except IOError: pass # Clear out the folders for folder in removefolder: try: shutil.rmtree(folder) except (OSError, TypeError): pass
python
def remove(self): """Removes unnecessary temporary files generated by the pipeline""" import shutil printtime('Removing large and/or temporary files', self.start) removefolder = list() for sample in self.metadata: # Use os.walk to iterate through all the files in the sample output directory for path, dirs, files in os.walk(sample.general.outputdirectory): for item in files: # Use regex to find files to remove if re.search(".fastq$", item) or re.search(".fastq.gz$", item) or re.search(".bam$", item) \ or re.search(".bt2$", item) or re.search(".tab$", item) or re.search("^before", item) \ or re.search("^baitedtargets", item) or re.search("_combined.csv$", item) \ or re.search("^scaffolds", item) or re.search(".fastg$", item) or re.search(".gfa$", item) \ or re.search(".bai$", item) or 'coregenome' in path or 'prophages' in path: # Keep the baitedtargets.fa, core genome, and merged metagenome files if item != 'baitedtargets.fa' and not re.search("coregenome", item) \ and not re.search("paired", item): # Remove the unnecessary files try: os.remove(os.path.join(path, item)) except IOError: pass # Clear out the folders for folder in removefolder: try: shutil.rmtree(folder) except (OSError, TypeError): pass
[ "def", "remove", "(", "self", ")", ":", "import", "shutil", "printtime", "(", "'Removing large and/or temporary files'", ",", "self", ".", "start", ")", "removefolder", "=", "list", "(", ")", "for", "sample", "in", "self", ".", "metadata", ":", "# Use os.walk to iterate through all the files in the sample output directory", "for", "path", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "sample", ".", "general", ".", "outputdirectory", ")", ":", "for", "item", "in", "files", ":", "# Use regex to find files to remove", "if", "re", ".", "search", "(", "\".fastq$\"", ",", "item", ")", "or", "re", ".", "search", "(", "\".fastq.gz$\"", ",", "item", ")", "or", "re", ".", "search", "(", "\".bam$\"", ",", "item", ")", "or", "re", ".", "search", "(", "\".bt2$\"", ",", "item", ")", "or", "re", ".", "search", "(", "\".tab$\"", ",", "item", ")", "or", "re", ".", "search", "(", "\"^before\"", ",", "item", ")", "or", "re", ".", "search", "(", "\"^baitedtargets\"", ",", "item", ")", "or", "re", ".", "search", "(", "\"_combined.csv$\"", ",", "item", ")", "or", "re", ".", "search", "(", "\"^scaffolds\"", ",", "item", ")", "or", "re", ".", "search", "(", "\".fastg$\"", ",", "item", ")", "or", "re", ".", "search", "(", "\".gfa$\"", ",", "item", ")", "or", "re", ".", "search", "(", "\".bai$\"", ",", "item", ")", "or", "'coregenome'", "in", "path", "or", "'prophages'", "in", "path", ":", "# Keep the baitedtargets.fa, core genome, and merged metagenome files", "if", "item", "!=", "'baitedtargets.fa'", "and", "not", "re", ".", "search", "(", "\"coregenome\"", ",", "item", ")", "and", "not", "re", ".", "search", "(", "\"paired\"", ",", "item", ")", ":", "# Remove the unnecessary files", "try", ":", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "path", ",", "item", ")", ")", "except", "IOError", ":", "pass", "# Clear out the folders", "for", "folder", "in", "removefolder", ":", "try", ":", "shutil", ".", "rmtree", "(", "folder", ")", "except", "(", "OSError", ",", "TypeError", ")", ":", "pass" ]
Removes unnecessary temporary files generated by the pipeline
[ "Removes", "unnecessary", "temporary", "files", "generated", "by", "the", "pipeline" ]
88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a
https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/compress.py#L10-L38
train
jotacor/ComunioPy
ComunioPy/__init__.py
Comunio.load_info
def load_info(self): ''' Get info from logged account ''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/login.phtml',"User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/team_news.phtml',headers=headers).content soup = BeautifulSoup(req) self.title = soup.title.string estado = soup.find('div',{'id':'content'}).find('div',{'id':'manager'}).string if estado: print estado.strip() return [s.extract() for s in soup('strong')] if (soup.find('div',{'id':'userid'}) != None): self.myid = soup.find('div',{'id':'userid'}).p.text.strip()[2:] self.money = int(soup.find('div',{'id':'manager_money'}).p.text.strip().replace(".","")[:-2]) self.teamvalue = int(soup.find('div',{'id':'teamvalue'}).p.text.strip().replace(".","")[:-2]) self.community_id = soup.find('link')['href'][24:] self.username = soup.find('div',{'id':'username'}).p.a.text
python
def load_info(self): ''' Get info from logged account ''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/login.phtml',"User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/team_news.phtml',headers=headers).content soup = BeautifulSoup(req) self.title = soup.title.string estado = soup.find('div',{'id':'content'}).find('div',{'id':'manager'}).string if estado: print estado.strip() return [s.extract() for s in soup('strong')] if (soup.find('div',{'id':'userid'}) != None): self.myid = soup.find('div',{'id':'userid'}).p.text.strip()[2:] self.money = int(soup.find('div',{'id':'manager_money'}).p.text.strip().replace(".","")[:-2]) self.teamvalue = int(soup.find('div',{'id':'teamvalue'}).p.text.strip().replace(".","")[:-2]) self.community_id = soup.find('link')['href'][24:] self.username = soup.find('div',{'id':'username'}).p.a.text
[ "def", "load_info", "(", "self", ")", ":", "headers", "=", "{", "\"Content-type\"", ":", "\"application/x-www-form-urlencoded\"", ",", "\"Accept\"", ":", "\"text/plain\"", ",", "'Referer'", ":", "'http://'", "+", "self", ".", "domain", "+", "'/login.phtml'", ",", "\"User-Agent\"", ":", "user_agent", "}", "req", "=", "self", ".", "session", ".", "get", "(", "'http://'", "+", "self", ".", "domain", "+", "'/team_news.phtml'", ",", "headers", "=", "headers", ")", ".", "content", "soup", "=", "BeautifulSoup", "(", "req", ")", "self", ".", "title", "=", "soup", ".", "title", ".", "string", "estado", "=", "soup", ".", "find", "(", "'div'", ",", "{", "'id'", ":", "'content'", "}", ")", ".", "find", "(", "'div'", ",", "{", "'id'", ":", "'manager'", "}", ")", ".", "string", "if", "estado", ":", "print", "estado", ".", "strip", "(", ")", "return", "[", "s", ".", "extract", "(", ")", "for", "s", "in", "soup", "(", "'strong'", ")", "]", "if", "(", "soup", ".", "find", "(", "'div'", ",", "{", "'id'", ":", "'userid'", "}", ")", "!=", "None", ")", ":", "self", ".", "myid", "=", "soup", ".", "find", "(", "'div'", ",", "{", "'id'", ":", "'userid'", "}", ")", ".", "p", ".", "text", ".", "strip", "(", ")", "[", "2", ":", "]", "self", ".", "money", "=", "int", "(", "soup", ".", "find", "(", "'div'", ",", "{", "'id'", ":", "'manager_money'", "}", ")", ".", "p", ".", "text", ".", "strip", "(", ")", ".", "replace", "(", "\".\"", ",", "\"\"", ")", "[", ":", "-", "2", "]", ")", "self", ".", "teamvalue", "=", "int", "(", "soup", ".", "find", "(", "'div'", ",", "{", "'id'", ":", "'teamvalue'", "}", ")", ".", "p", ".", "text", ".", "strip", "(", ")", ".", "replace", "(", "\".\"", ",", "\"\"", ")", "[", ":", "-", "2", "]", ")", "self", ".", "community_id", "=", "soup", ".", "find", "(", "'link'", ")", "[", "'href'", "]", "[", "24", ":", "]", "self", ".", "username", "=", "soup", ".", "find", "(", "'div'", ",", "{", "'id'", ":", "'username'", "}", ")", ".", "p", ".", "a", ".", "text" ]
Get info from logged account
[ "Get", "info", "from", "logged", "account" ]
2dd71e3e197b497980ea7b9cfbec1da64dca3ed0
https://github.com/jotacor/ComunioPy/blob/2dd71e3e197b497980ea7b9cfbec1da64dca3ed0/ComunioPy/__init__.py#L43-L61
train
jotacor/ComunioPy
ComunioPy/__init__.py
Comunio.get_news
def get_news(self): '''Get all the news from first page''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/login.phtml',"User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/team_news.phtml',headers=headers).content soup = BeautifulSoup(req) news = [] for i in soup.find_all('div',{'class','article_content_text'}): news.append(i.text) return news
python
def get_news(self): '''Get all the news from first page''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/login.phtml',"User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/team_news.phtml',headers=headers).content soup = BeautifulSoup(req) news = [] for i in soup.find_all('div',{'class','article_content_text'}): news.append(i.text) return news
[ "def", "get_news", "(", "self", ")", ":", "headers", "=", "{", "\"Content-type\"", ":", "\"application/x-www-form-urlencoded\"", ",", "\"Accept\"", ":", "\"text/plain\"", ",", "'Referer'", ":", "'http://'", "+", "self", ".", "domain", "+", "'/login.phtml'", ",", "\"User-Agent\"", ":", "user_agent", "}", "req", "=", "self", ".", "session", ".", "get", "(", "'http://'", "+", "self", ".", "domain", "+", "'/team_news.phtml'", ",", "headers", "=", "headers", ")", ".", "content", "soup", "=", "BeautifulSoup", "(", "req", ")", "news", "=", "[", "]", "for", "i", "in", "soup", ".", "find_all", "(", "'div'", ",", "{", "'class'", ",", "'article_content_text'", "}", ")", ":", "news", ".", "append", "(", "i", ".", "text", ")", "return", "news" ]
Get all the news from first page
[ "Get", "all", "the", "news", "from", "first", "page" ]
2dd71e3e197b497980ea7b9cfbec1da64dca3ed0
https://github.com/jotacor/ComunioPy/blob/2dd71e3e197b497980ea7b9cfbec1da64dca3ed0/ComunioPy/__init__.py#L83-L91
train
jotacor/ComunioPy
ComunioPy/__init__.py
Comunio.logout
def logout(self): '''Logout from Comunio''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain","User-Agent": user_agent} self.session.get('http://'+self.domain+'/logout.phtml',headers=headers)
python
def logout(self): '''Logout from Comunio''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain","User-Agent": user_agent} self.session.get('http://'+self.domain+'/logout.phtml',headers=headers)
[ "def", "logout", "(", "self", ")", ":", "headers", "=", "{", "\"Content-type\"", ":", "\"application/x-www-form-urlencoded\"", ",", "\"Accept\"", ":", "\"text/plain\"", ",", "\"User-Agent\"", ":", "user_agent", "}", "self", ".", "session", ".", "get", "(", "'http://'", "+", "self", ".", "domain", "+", "'/logout.phtml'", ",", "headers", "=", "headers", ")" ]
Logout from Comunio
[ "Logout", "from", "Comunio" ]
2dd71e3e197b497980ea7b9cfbec1da64dca3ed0
https://github.com/jotacor/ComunioPy/blob/2dd71e3e197b497980ea7b9cfbec1da64dca3ed0/ComunioPy/__init__.py#L94-L97
train
jotacor/ComunioPy
ComunioPy/__init__.py
Comunio.standings
def standings(self): '''Get standings from the community's account''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain","User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/standings.phtml',headers=headers).content soup = BeautifulSoup(req) table = soup.find('table',{'id':'tablestandings'}).find_all('tr') clasificacion = [] [clasificacion.append(('%s\t%s\t%s\t%s\t%s')%(tablas.find('td').text,tablas.find('div')['id'],tablas.a.text,tablas.find_all('td')[3].text,tablas.find_all('td')[4].text)) for tablas in table[1:]] return clasificacion
python
def standings(self): '''Get standings from the community's account''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain","User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/standings.phtml',headers=headers).content soup = BeautifulSoup(req) table = soup.find('table',{'id':'tablestandings'}).find_all('tr') clasificacion = [] [clasificacion.append(('%s\t%s\t%s\t%s\t%s')%(tablas.find('td').text,tablas.find('div')['id'],tablas.a.text,tablas.find_all('td')[3].text,tablas.find_all('td')[4].text)) for tablas in table[1:]] return clasificacion
[ "def", "standings", "(", "self", ")", ":", "headers", "=", "{", "\"Content-type\"", ":", "\"application/x-www-form-urlencoded\"", ",", "\"Accept\"", ":", "\"text/plain\"", ",", "\"User-Agent\"", ":", "user_agent", "}", "req", "=", "self", ".", "session", ".", "get", "(", "'http://'", "+", "self", ".", "domain", "+", "'/standings.phtml'", ",", "headers", "=", "headers", ")", ".", "content", "soup", "=", "BeautifulSoup", "(", "req", ")", "table", "=", "soup", ".", "find", "(", "'table'", ",", "{", "'id'", ":", "'tablestandings'", "}", ")", ".", "find_all", "(", "'tr'", ")", "clasificacion", "=", "[", "]", "[", "clasificacion", ".", "append", "(", "(", "'%s\\t%s\\t%s\\t%s\\t%s'", ")", "%", "(", "tablas", ".", "find", "(", "'td'", ")", ".", "text", ",", "tablas", ".", "find", "(", "'div'", ")", "[", "'id'", "]", ",", "tablas", ".", "a", ".", "text", ",", "tablas", ".", "find_all", "(", "'td'", ")", "[", "3", "]", ".", "text", ",", "tablas", ".", "find_all", "(", "'td'", ")", "[", "4", "]", ".", "text", ")", ")", "for", "tablas", "in", "table", "[", "1", ":", "]", "]", "return", "clasificacion" ]
Get standings from the community's account
[ "Get", "standings", "from", "the", "community", "s", "account" ]
2dd71e3e197b497980ea7b9cfbec1da64dca3ed0
https://github.com/jotacor/ComunioPy/blob/2dd71e3e197b497980ea7b9cfbec1da64dca3ed0/ComunioPy/__init__.py#L100-L108
train
jotacor/ComunioPy
ComunioPy/__init__.py
Comunio.info_user
def info_user(self,userid): '''Get user info using a ID''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/standings.phtml',"User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/playerInfo.phtml?pid='+userid,headers=headers).content soup = BeautifulSoup(req) title = soup.title.string community = soup.find_all('table',border=0)[1].a.text info = [] info.append(title) info.append(community) for i in soup.find_all('table',border=0)[1].find_all('td')[1:]: info.append(i.text) for i in soup.find('table',cellpadding=2).find_all('tr')[1:]: cad = i.find_all('td') numero=cad[0].text nombre=cad[2].text.strip() team=cad[3].find('img')['alt'] precio=cad[4].text.replace(".","") puntos=cad[5].text posicion=cad[6].text info.append([numero,nombre,team,precio,puntos,posicion]) return info
python
def info_user(self,userid): '''Get user info using a ID''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/standings.phtml',"User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/playerInfo.phtml?pid='+userid,headers=headers).content soup = BeautifulSoup(req) title = soup.title.string community = soup.find_all('table',border=0)[1].a.text info = [] info.append(title) info.append(community) for i in soup.find_all('table',border=0)[1].find_all('td')[1:]: info.append(i.text) for i in soup.find('table',cellpadding=2).find_all('tr')[1:]: cad = i.find_all('td') numero=cad[0].text nombre=cad[2].text.strip() team=cad[3].find('img')['alt'] precio=cad[4].text.replace(".","") puntos=cad[5].text posicion=cad[6].text info.append([numero,nombre,team,precio,puntos,posicion]) return info
[ "def", "info_user", "(", "self", ",", "userid", ")", ":", "headers", "=", "{", "\"Content-type\"", ":", "\"application/x-www-form-urlencoded\"", ",", "\"Accept\"", ":", "\"text/plain\"", ",", "'Referer'", ":", "'http://'", "+", "self", ".", "domain", "+", "'/standings.phtml'", ",", "\"User-Agent\"", ":", "user_agent", "}", "req", "=", "self", ".", "session", ".", "get", "(", "'http://'", "+", "self", ".", "domain", "+", "'/playerInfo.phtml?pid='", "+", "userid", ",", "headers", "=", "headers", ")", ".", "content", "soup", "=", "BeautifulSoup", "(", "req", ")", "title", "=", "soup", ".", "title", ".", "string", "community", "=", "soup", ".", "find_all", "(", "'table'", ",", "border", "=", "0", ")", "[", "1", "]", ".", "a", ".", "text", "info", "=", "[", "]", "info", ".", "append", "(", "title", ")", "info", ".", "append", "(", "community", ")", "for", "i", "in", "soup", ".", "find_all", "(", "'table'", ",", "border", "=", "0", ")", "[", "1", "]", ".", "find_all", "(", "'td'", ")", "[", "1", ":", "]", ":", "info", ".", "append", "(", "i", ".", "text", ")", "for", "i", "in", "soup", ".", "find", "(", "'table'", ",", "cellpadding", "=", "2", ")", ".", "find_all", "(", "'tr'", ")", "[", "1", ":", "]", ":", "cad", "=", "i", ".", "find_all", "(", "'td'", ")", "numero", "=", "cad", "[", "0", "]", ".", "text", "nombre", "=", "cad", "[", "2", "]", ".", "text", ".", "strip", "(", ")", "team", "=", "cad", "[", "3", "]", ".", "find", "(", "'img'", ")", "[", "'alt'", "]", "precio", "=", "cad", "[", "4", "]", ".", "text", ".", "replace", "(", "\".\"", ",", "\"\"", ")", "puntos", "=", "cad", "[", "5", "]", ".", "text", "posicion", "=", "cad", "[", "6", "]", ".", "text", "info", ".", "append", "(", "[", "numero", ",", "nombre", ",", "team", ",", "precio", ",", "puntos", ",", "posicion", "]", ")", "return", "info" ]
Get user info using a ID
[ "Get", "user", "info", "using", "a", "ID" ]
2dd71e3e197b497980ea7b9cfbec1da64dca3ed0
https://github.com/jotacor/ComunioPy/blob/2dd71e3e197b497980ea7b9cfbec1da64dca3ed0/ComunioPy/__init__.py#L111-L132
train
jotacor/ComunioPy
ComunioPy/__init__.py
Comunio.lineup_user
def lineup_user(self,userid): '''Get user lineup using a ID''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/standings.phtml',"User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/playerInfo.phtml?pid='+userid,headers=headers).content soup = BeautifulSoup(req) info = [] for i in soup.find_all('td',{'class':'name_cont'}): info.append(i.text.strip()) return info
python
def lineup_user(self,userid): '''Get user lineup using a ID''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/standings.phtml',"User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/playerInfo.phtml?pid='+userid,headers=headers).content soup = BeautifulSoup(req) info = [] for i in soup.find_all('td',{'class':'name_cont'}): info.append(i.text.strip()) return info
[ "def", "lineup_user", "(", "self", ",", "userid", ")", ":", "headers", "=", "{", "\"Content-type\"", ":", "\"application/x-www-form-urlencoded\"", ",", "\"Accept\"", ":", "\"text/plain\"", ",", "'Referer'", ":", "'http://'", "+", "self", ".", "domain", "+", "'/standings.phtml'", ",", "\"User-Agent\"", ":", "user_agent", "}", "req", "=", "self", ".", "session", ".", "get", "(", "'http://'", "+", "self", ".", "domain", "+", "'/playerInfo.phtml?pid='", "+", "userid", ",", "headers", "=", "headers", ")", ".", "content", "soup", "=", "BeautifulSoup", "(", "req", ")", "info", "=", "[", "]", "for", "i", "in", "soup", ".", "find_all", "(", "'td'", ",", "{", "'class'", ":", "'name_cont'", "}", ")", ":", "info", ".", "append", "(", "i", ".", "text", ".", "strip", "(", ")", ")", "return", "info" ]
Get user lineup using a ID
[ "Get", "user", "lineup", "using", "a", "ID" ]
2dd71e3e197b497980ea7b9cfbec1da64dca3ed0
https://github.com/jotacor/ComunioPy/blob/2dd71e3e197b497980ea7b9cfbec1da64dca3ed0/ComunioPy/__init__.py#L135-L143
train
jotacor/ComunioPy
ComunioPy/__init__.py
Comunio.info_community
def info_community(self,teamid): '''Get comunity info using a ID''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/standings.phtml',"User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/teamInfo.phtml?tid='+teamid,headers=headers).content soup = BeautifulSoup(req) info = [] for i in soup.find('table',cellpadding=2).find_all('tr')[1:]: info.append('%s\t%s\t%s\t%s\t%s'%(i.find('td').text,i.find('a')['href'].split('pid=')[1],i.a.text,i.find_all('td')[2].text,i.find_all('td')[3].text)) return info
python
def info_community(self,teamid): '''Get comunity info using a ID''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/standings.phtml',"User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/teamInfo.phtml?tid='+teamid,headers=headers).content soup = BeautifulSoup(req) info = [] for i in soup.find('table',cellpadding=2).find_all('tr')[1:]: info.append('%s\t%s\t%s\t%s\t%s'%(i.find('td').text,i.find('a')['href'].split('pid=')[1],i.a.text,i.find_all('td')[2].text,i.find_all('td')[3].text)) return info
[ "def", "info_community", "(", "self", ",", "teamid", ")", ":", "headers", "=", "{", "\"Content-type\"", ":", "\"application/x-www-form-urlencoded\"", ",", "\"Accept\"", ":", "\"text/plain\"", ",", "'Referer'", ":", "'http://'", "+", "self", ".", "domain", "+", "'/standings.phtml'", ",", "\"User-Agent\"", ":", "user_agent", "}", "req", "=", "self", ".", "session", ".", "get", "(", "'http://'", "+", "self", ".", "domain", "+", "'/teamInfo.phtml?tid='", "+", "teamid", ",", "headers", "=", "headers", ")", ".", "content", "soup", "=", "BeautifulSoup", "(", "req", ")", "info", "=", "[", "]", "for", "i", "in", "soup", ".", "find", "(", "'table'", ",", "cellpadding", "=", "2", ")", ".", "find_all", "(", "'tr'", ")", "[", "1", ":", "]", ":", "info", ".", "append", "(", "'%s\\t%s\\t%s\\t%s\\t%s'", "%", "(", "i", ".", "find", "(", "'td'", ")", ".", "text", ",", "i", ".", "find", "(", "'a'", ")", "[", "'href'", "]", ".", "split", "(", "'pid='", ")", "[", "1", "]", ",", "i", ".", "a", ".", "text", ",", "i", ".", "find_all", "(", "'td'", ")", "[", "2", "]", ".", "text", ",", "i", ".", "find_all", "(", "'td'", ")", "[", "3", "]", ".", "text", ")", ")", "return", "info" ]
Get comunity info using a ID
[ "Get", "comunity", "info", "using", "a", "ID" ]
2dd71e3e197b497980ea7b9cfbec1da64dca3ed0
https://github.com/jotacor/ComunioPy/blob/2dd71e3e197b497980ea7b9cfbec1da64dca3ed0/ComunioPy/__init__.py#L146-L154
train
jotacor/ComunioPy
ComunioPy/__init__.py
Comunio.info_player
def info_player(self,pid): '''' Get info football player using a ID @return: [name,position,team,points,price] ''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/team_news.phtml',"User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/tradableInfo.phtml?tid='+pid,headers=headers).content soup = BeautifulSoup(req) info = [] info.append(soup.title.text.strip()) for i in soup.find('table',cellspacing=1).find_all('tr'): info.append(i.find_all('td')[1].text.replace(".","")) return info
python
def info_player(self,pid): '''' Get info football player using a ID @return: [name,position,team,points,price] ''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/team_news.phtml',"User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/tradableInfo.phtml?tid='+pid,headers=headers).content soup = BeautifulSoup(req) info = [] info.append(soup.title.text.strip()) for i in soup.find('table',cellspacing=1).find_all('tr'): info.append(i.find_all('td')[1].text.replace(".","")) return info
[ "def", "info_player", "(", "self", ",", "pid", ")", ":", "headers", "=", "{", "\"Content-type\"", ":", "\"application/x-www-form-urlencoded\"", ",", "\"Accept\"", ":", "\"text/plain\"", ",", "'Referer'", ":", "'http://'", "+", "self", ".", "domain", "+", "'/team_news.phtml'", ",", "\"User-Agent\"", ":", "user_agent", "}", "req", "=", "self", ".", "session", ".", "get", "(", "'http://'", "+", "self", ".", "domain", "+", "'/tradableInfo.phtml?tid='", "+", "pid", ",", "headers", "=", "headers", ")", ".", "content", "soup", "=", "BeautifulSoup", "(", "req", ")", "info", "=", "[", "]", "info", ".", "append", "(", "soup", ".", "title", ".", "text", ".", "strip", "(", ")", ")", "for", "i", "in", "soup", ".", "find", "(", "'table'", ",", "cellspacing", "=", "1", ")", ".", "find_all", "(", "'tr'", ")", ":", "info", ".", "append", "(", "i", ".", "find_all", "(", "'td'", ")", "[", "1", "]", ".", "text", ".", "replace", "(", "\".\"", ",", "\"\"", ")", ")", "return", "info" ]
Get info football player using a ID @return: [name,position,team,points,price]
[ "Get", "info", "football", "player", "using", "a", "ID" ]
2dd71e3e197b497980ea7b9cfbec1da64dca3ed0
https://github.com/jotacor/ComunioPy/blob/2dd71e3e197b497980ea7b9cfbec1da64dca3ed0/ComunioPy/__init__.py#L157-L169
train
jotacor/ComunioPy
ComunioPy/__init__.py
Comunio.info_player_id
def info_player_id(self,name): '''Get id using name football player''' number = 0 name=name.title().replace(" ", "+") headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/team_news.phtml',"User-Agent": user_agent} req = self.session.get('http://stats.comunio.es/search.php?name='+name,headers=headers).content soup = BeautifulSoup(req) for i in soup.find_all('a',{'class','nowrap'}): number = re.search("([0-9]+)-", str(i)).group(1) break # Solo devuelve la primera coincidencia return number
python
def info_player_id(self,name): '''Get id using name football player''' number = 0 name=name.title().replace(" ", "+") headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/team_news.phtml',"User-Agent": user_agent} req = self.session.get('http://stats.comunio.es/search.php?name='+name,headers=headers).content soup = BeautifulSoup(req) for i in soup.find_all('a',{'class','nowrap'}): number = re.search("([0-9]+)-", str(i)).group(1) break # Solo devuelve la primera coincidencia return number
[ "def", "info_player_id", "(", "self", ",", "name", ")", ":", "number", "=", "0", "name", "=", "name", ".", "title", "(", ")", ".", "replace", "(", "\" \"", ",", "\"+\"", ")", "headers", "=", "{", "\"Content-type\"", ":", "\"application/x-www-form-urlencoded\"", ",", "\"Accept\"", ":", "\"text/plain\"", ",", "'Referer'", ":", "'http://'", "+", "self", ".", "domain", "+", "'/team_news.phtml'", ",", "\"User-Agent\"", ":", "user_agent", "}", "req", "=", "self", ".", "session", ".", "get", "(", "'http://stats.comunio.es/search.php?name='", "+", "name", ",", "headers", "=", "headers", ")", ".", "content", "soup", "=", "BeautifulSoup", "(", "req", ")", "for", "i", "in", "soup", ".", "find_all", "(", "'a'", ",", "{", "'class'", ",", "'nowrap'", "}", ")", ":", "number", "=", "re", ".", "search", "(", "\"([0-9]+)-\"", ",", "str", "(", "i", ")", ")", ".", "group", "(", "1", ")", "break", "# Solo devuelve la primera coincidencia", "return", "number" ]
Get id using name football player
[ "Get", "id", "using", "name", "football", "player" ]
2dd71e3e197b497980ea7b9cfbec1da64dca3ed0
https://github.com/jotacor/ComunioPy/blob/2dd71e3e197b497980ea7b9cfbec1da64dca3ed0/ComunioPy/__init__.py#L172-L182
train
jotacor/ComunioPy
ComunioPy/__init__.py
Comunio.club
def club(self,cid): ''' Get info by real team using a ID @return: name,[player list] ''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/',"User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/clubInfo.phtml?cid='+cid,headers=headers).content soup = BeautifulSoup(req) plist = [] for i in soup.find('table',cellpadding=2).find_all('tr')[1:]: plist.append('%s\t%s\t%s\t%s\t%s'%(i.find_all('td')[0].text,i.find_all('td')[1].text,i.find_all('td')[2].text,i.find_all('td')[3].text,i.find_all('td')[4].text)) return soup.title.text,plist
python
def club(self,cid): ''' Get info by real team using a ID @return: name,[player list] ''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/',"User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/clubInfo.phtml?cid='+cid,headers=headers).content soup = BeautifulSoup(req) plist = [] for i in soup.find('table',cellpadding=2).find_all('tr')[1:]: plist.append('%s\t%s\t%s\t%s\t%s'%(i.find_all('td')[0].text,i.find_all('td')[1].text,i.find_all('td')[2].text,i.find_all('td')[3].text,i.find_all('td')[4].text)) return soup.title.text,plist
[ "def", "club", "(", "self", ",", "cid", ")", ":", "headers", "=", "{", "\"Content-type\"", ":", "\"application/x-www-form-urlencoded\"", ",", "\"Accept\"", ":", "\"text/plain\"", ",", "'Referer'", ":", "'http://'", "+", "self", ".", "domain", "+", "'/'", ",", "\"User-Agent\"", ":", "user_agent", "}", "req", "=", "self", ".", "session", ".", "get", "(", "'http://'", "+", "self", ".", "domain", "+", "'/clubInfo.phtml?cid='", "+", "cid", ",", "headers", "=", "headers", ")", ".", "content", "soup", "=", "BeautifulSoup", "(", "req", ")", "plist", "=", "[", "]", "for", "i", "in", "soup", ".", "find", "(", "'table'", ",", "cellpadding", "=", "2", ")", ".", "find_all", "(", "'tr'", ")", "[", "1", ":", "]", ":", "plist", ".", "append", "(", "'%s\\t%s\\t%s\\t%s\\t%s'", "%", "(", "i", ".", "find_all", "(", "'td'", ")", "[", "0", "]", ".", "text", ",", "i", ".", "find_all", "(", "'td'", ")", "[", "1", "]", ".", "text", ",", "i", ".", "find_all", "(", "'td'", ")", "[", "2", "]", ".", "text", ",", "i", ".", "find_all", "(", "'td'", ")", "[", "3", "]", ".", "text", ",", "i", ".", "find_all", "(", "'td'", ")", "[", "4", "]", ".", "text", ")", ")", "return", "soup", ".", "title", ".", "text", ",", "plist" ]
Get info by real team using a ID @return: name,[player list]
[ "Get", "info", "by", "real", "team", "using", "a", "ID" ]
2dd71e3e197b497980ea7b9cfbec1da64dca3ed0
https://github.com/jotacor/ComunioPy/blob/2dd71e3e197b497980ea7b9cfbec1da64dca3ed0/ComunioPy/__init__.py#L185-L196
train
jotacor/ComunioPy
ComunioPy/__init__.py
Comunio.team_id
def team_id(self,team): ''' Get team ID using a real team name @return: id ''' #UTF-8 comparison headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/',"User-Agent": user_agent} req = self.session.get('http://'+self.domain,headers=headers).content soup = BeautifulSoup(req) for i in soup.find('table',cellpadding=2).find_all('tr'): #Get teamid from the bets team1 = i.find('a')['title'] team2 = i.find_all('a')[1]['title'] if (team == team1): return i.find('a')['href'].split('cid=')[1] elif (team == team2): return i.find_all('a')[1]['href'].split('cid=')[1] return None
python
def team_id(self,team): ''' Get team ID using a real team name @return: id ''' #UTF-8 comparison headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/',"User-Agent": user_agent} req = self.session.get('http://'+self.domain,headers=headers).content soup = BeautifulSoup(req) for i in soup.find('table',cellpadding=2).find_all('tr'): #Get teamid from the bets team1 = i.find('a')['title'] team2 = i.find_all('a')[1]['title'] if (team == team1): return i.find('a')['href'].split('cid=')[1] elif (team == team2): return i.find_all('a')[1]['href'].split('cid=')[1] return None
[ "def", "team_id", "(", "self", ",", "team", ")", ":", "#UTF-8 comparison", "headers", "=", "{", "\"Content-type\"", ":", "\"application/x-www-form-urlencoded\"", ",", "\"Accept\"", ":", "\"text/plain\"", ",", "'Referer'", ":", "'http://'", "+", "self", ".", "domain", "+", "'/'", ",", "\"User-Agent\"", ":", "user_agent", "}", "req", "=", "self", ".", "session", ".", "get", "(", "'http://'", "+", "self", ".", "domain", ",", "headers", "=", "headers", ")", ".", "content", "soup", "=", "BeautifulSoup", "(", "req", ")", "for", "i", "in", "soup", ".", "find", "(", "'table'", ",", "cellpadding", "=", "2", ")", ".", "find_all", "(", "'tr'", ")", ":", "#Get teamid from the bets", "team1", "=", "i", ".", "find", "(", "'a'", ")", "[", "'title'", "]", "team2", "=", "i", ".", "find_all", "(", "'a'", ")", "[", "1", "]", "[", "'title'", "]", "if", "(", "team", "==", "team1", ")", ":", "return", "i", ".", "find", "(", "'a'", ")", "[", "'href'", "]", ".", "split", "(", "'cid='", ")", "[", "1", "]", "elif", "(", "team", "==", "team2", ")", ":", "return", "i", ".", "find_all", "(", "'a'", ")", "[", "1", "]", "[", "'href'", "]", ".", "split", "(", "'cid='", ")", "[", "1", "]", "return", "None" ]
Get team ID using a real team name @return: id
[ "Get", "team", "ID", "using", "a", "real", "team", "name" ]
2dd71e3e197b497980ea7b9cfbec1da64dca3ed0
https://github.com/jotacor/ComunioPy/blob/2dd71e3e197b497980ea7b9cfbec1da64dca3ed0/ComunioPy/__init__.py#L199-L216
train
jotacor/ComunioPy
ComunioPy/__init__.py
Comunio.user_id
def user_id(self, user): ''' Get userid from a name @return: id ''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/team_news.phtml',"User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/standings.phtml',headers=headers).content soup = BeautifulSoup(req) for i in soup.find('table',cellpadding=2).find_all('tr'): try: if (user == i.find_all('td')[2].text.encode('utf8')): return i.find('a')['href'].split('pid=')[1] except: continue return None
python
def user_id(self, user): ''' Get userid from a name @return: id ''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/team_news.phtml',"User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/standings.phtml',headers=headers).content soup = BeautifulSoup(req) for i in soup.find('table',cellpadding=2).find_all('tr'): try: if (user == i.find_all('td')[2].text.encode('utf8')): return i.find('a')['href'].split('pid=')[1] except: continue return None
[ "def", "user_id", "(", "self", ",", "user", ")", ":", "headers", "=", "{", "\"Content-type\"", ":", "\"application/x-www-form-urlencoded\"", ",", "\"Accept\"", ":", "\"text/plain\"", ",", "'Referer'", ":", "'http://'", "+", "self", ".", "domain", "+", "'/team_news.phtml'", ",", "\"User-Agent\"", ":", "user_agent", "}", "req", "=", "self", ".", "session", ".", "get", "(", "'http://'", "+", "self", ".", "domain", "+", "'/standings.phtml'", ",", "headers", "=", "headers", ")", ".", "content", "soup", "=", "BeautifulSoup", "(", "req", ")", "for", "i", "in", "soup", ".", "find", "(", "'table'", ",", "cellpadding", "=", "2", ")", ".", "find_all", "(", "'tr'", ")", ":", "try", ":", "if", "(", "user", "==", "i", ".", "find_all", "(", "'td'", ")", "[", "2", "]", ".", "text", ".", "encode", "(", "'utf8'", ")", ")", ":", "return", "i", ".", "find", "(", "'a'", ")", "[", "'href'", "]", ".", "split", "(", "'pid='", ")", "[", "1", "]", "except", ":", "continue", "return", "None" ]
Get userid from a name @return: id
[ "Get", "userid", "from", "a", "name" ]
2dd71e3e197b497980ea7b9cfbec1da64dca3ed0
https://github.com/jotacor/ComunioPy/blob/2dd71e3e197b497980ea7b9cfbec1da64dca3ed0/ComunioPy/__init__.py#L219-L233
train
jotacor/ComunioPy
ComunioPy/__init__.py
Comunio.players_onsale
def players_onsale(self, community_id, only_computer=False): ''' Returns the football players currently on sale @return: [[name, team, min_price, market_price, points, date, owner, position]] ''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/team_news.phtml',"User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/teamInfo.phtml?tid=' + community_id, headers=headers).content soup = BeautifulSoup(req) current_year = dt.today().year current_month = dt.today().month on_sale = [] year_flag = 0 for i in soup.find_all('table',{'class','tablecontent03'})[2].find_all('tr')[1:]: name = i.find_all('td')[0].text.strip() team = i.find('img')['alt'] min_price = i.find_all('td')[2].text.replace(".","").strip() market_price = i.find_all('td')[3].text.replace(".","").strip() points = i.find_all('td')[4].text.strip().strip() # Controlamos el cambio de año, ya que comunio no lo dá if current_month <= 7 and int(i.find_all('td')[5].text[3:5]) > 7: year_flag = 1 date = str(current_year-year_flag)+i.find_all('td')[5].text[3:5]+i.find_all('td')[5].text[:2] owner = i.find_all('td')[6].text.strip() position = i.find_all('td')[7].text.strip() # Comprobamos si solamente queremos los de la computadora o no if (only_computer and owner == 'Computer') or not only_computer: on_sale.append([name, team, min_price, market_price, points, date, owner, position]) return on_sale
python
def players_onsale(self, community_id, only_computer=False): ''' Returns the football players currently on sale @return: [[name, team, min_price, market_price, points, date, owner, position]] ''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/team_news.phtml',"User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/teamInfo.phtml?tid=' + community_id, headers=headers).content soup = BeautifulSoup(req) current_year = dt.today().year current_month = dt.today().month on_sale = [] year_flag = 0 for i in soup.find_all('table',{'class','tablecontent03'})[2].find_all('tr')[1:]: name = i.find_all('td')[0].text.strip() team = i.find('img')['alt'] min_price = i.find_all('td')[2].text.replace(".","").strip() market_price = i.find_all('td')[3].text.replace(".","").strip() points = i.find_all('td')[4].text.strip().strip() # Controlamos el cambio de año, ya que comunio no lo dá if current_month <= 7 and int(i.find_all('td')[5].text[3:5]) > 7: year_flag = 1 date = str(current_year-year_flag)+i.find_all('td')[5].text[3:5]+i.find_all('td')[5].text[:2] owner = i.find_all('td')[6].text.strip() position = i.find_all('td')[7].text.strip() # Comprobamos si solamente queremos los de la computadora o no if (only_computer and owner == 'Computer') or not only_computer: on_sale.append([name, team, min_price, market_price, points, date, owner, position]) return on_sale
[ "def", "players_onsale", "(", "self", ",", "community_id", ",", "only_computer", "=", "False", ")", ":", "headers", "=", "{", "\"Content-type\"", ":", "\"application/x-www-form-urlencoded\"", ",", "\"Accept\"", ":", "\"text/plain\"", ",", "'Referer'", ":", "'http://'", "+", "self", ".", "domain", "+", "'/team_news.phtml'", ",", "\"User-Agent\"", ":", "user_agent", "}", "req", "=", "self", ".", "session", ".", "get", "(", "'http://'", "+", "self", ".", "domain", "+", "'/teamInfo.phtml?tid='", "+", "community_id", ",", "headers", "=", "headers", ")", ".", "content", "soup", "=", "BeautifulSoup", "(", "req", ")", "current_year", "=", "dt", ".", "today", "(", ")", ".", "year", "current_month", "=", "dt", ".", "today", "(", ")", ".", "month", "on_sale", "=", "[", "]", "year_flag", "=", "0", "for", "i", "in", "soup", ".", "find_all", "(", "'table'", ",", "{", "'class'", ",", "'tablecontent03'", "}", ")", "[", "2", "]", ".", "find_all", "(", "'tr'", ")", "[", "1", ":", "]", ":", "name", "=", "i", ".", "find_all", "(", "'td'", ")", "[", "0", "]", ".", "text", ".", "strip", "(", ")", "team", "=", "i", ".", "find", "(", "'img'", ")", "[", "'alt'", "]", "min_price", "=", "i", ".", "find_all", "(", "'td'", ")", "[", "2", "]", ".", "text", ".", "replace", "(", "\".\"", ",", "\"\"", ")", ".", "strip", "(", ")", "market_price", "=", "i", ".", "find_all", "(", "'td'", ")", "[", "3", "]", ".", "text", ".", "replace", "(", "\".\"", ",", "\"\"", ")", ".", "strip", "(", ")", "points", "=", "i", ".", "find_all", "(", "'td'", ")", "[", "4", "]", ".", "text", ".", "strip", "(", ")", ".", "strip", "(", ")", "# Controlamos el cambio de año, ya que comunio no lo dá", "if", "current_month", "<=", "7", "and", "int", "(", "i", ".", "find_all", "(", "'td'", ")", "[", "5", "]", ".", "text", "[", "3", ":", "5", "]", ")", ">", "7", ":", "year_flag", "=", "1", "date", "=", "str", "(", "current_year", "-", "year_flag", ")", "+", "i", ".", "find_all", "(", "'td'", ")", "[", "5", "]", ".", "text", "[", "3", ":", "5", "]", "+", "i", ".", "find_all", "(", "'td'", ")", "[", "5", "]", ".", "text", "[", ":", "2", "]", "owner", "=", "i", ".", "find_all", "(", "'td'", ")", "[", "6", "]", ".", "text", ".", "strip", "(", ")", "position", "=", "i", ".", "find_all", "(", "'td'", ")", "[", "7", "]", ".", "text", ".", "strip", "(", ")", "# Comprobamos si solamente queremos los de la computadora o no", "if", "(", "only_computer", "and", "owner", "==", "'Computer'", ")", "or", "not", "only_computer", ":", "on_sale", ".", "append", "(", "[", "name", ",", "team", ",", "min_price", ",", "market_price", ",", "points", ",", "date", ",", "owner", ",", "position", "]", ")", "return", "on_sale" ]
Returns the football players currently on sale @return: [[name, team, min_price, market_price, points, date, owner, position]]
[ "Returns", "the", "football", "players", "currently", "on", "sale" ]
2dd71e3e197b497980ea7b9cfbec1da64dca3ed0
https://github.com/jotacor/ComunioPy/blob/2dd71e3e197b497980ea7b9cfbec1da64dca3ed0/ComunioPy/__init__.py#L236-L265
train
jotacor/ComunioPy
ComunioPy/__init__.py
Comunio.bids_to_you
def bids_to_you(self): ''' Get bids made to you @return: [[player,owner,team,money,date,datechange,status],] ''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/team_news.phtml',"User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/exchangemarket.phtml?viewoffers_x=',headers=headers).content soup = BeautifulSoup(req) table = [] for i in soup.find('table',{'class','tablecontent03'}).find_all('tr')[1:]: player,owner,team,price,bid_date,trans_date,status = self._parse_bid_table(i) table.append([player,owner,team,price,bid_date,trans_date,status]) return table
python
def bids_to_you(self): ''' Get bids made to you @return: [[player,owner,team,money,date,datechange,status],] ''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/team_news.phtml',"User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/exchangemarket.phtml?viewoffers_x=',headers=headers).content soup = BeautifulSoup(req) table = [] for i in soup.find('table',{'class','tablecontent03'}).find_all('tr')[1:]: player,owner,team,price,bid_date,trans_date,status = self._parse_bid_table(i) table.append([player,owner,team,price,bid_date,trans_date,status]) return table
[ "def", "bids_to_you", "(", "self", ")", ":", "headers", "=", "{", "\"Content-type\"", ":", "\"application/x-www-form-urlencoded\"", ",", "\"Accept\"", ":", "\"text/plain\"", ",", "'Referer'", ":", "'http://'", "+", "self", ".", "domain", "+", "'/team_news.phtml'", ",", "\"User-Agent\"", ":", "user_agent", "}", "req", "=", "self", ".", "session", ".", "get", "(", "'http://'", "+", "self", ".", "domain", "+", "'/exchangemarket.phtml?viewoffers_x='", ",", "headers", "=", "headers", ")", ".", "content", "soup", "=", "BeautifulSoup", "(", "req", ")", "table", "=", "[", "]", "for", "i", "in", "soup", ".", "find", "(", "'table'", ",", "{", "'class'", ",", "'tablecontent03'", "}", ")", ".", "find_all", "(", "'tr'", ")", "[", "1", ":", "]", ":", "player", ",", "owner", ",", "team", ",", "price", ",", "bid_date", ",", "trans_date", ",", "status", "=", "self", ".", "_parse_bid_table", "(", "i", ")", "table", ".", "append", "(", "[", "player", ",", "owner", ",", "team", ",", "price", ",", "bid_date", ",", "trans_date", ",", "status", "]", ")", "return", "table" ]
Get bids made to you @return: [[player,owner,team,money,date,datechange,status],]
[ "Get", "bids", "made", "to", "you" ]
2dd71e3e197b497980ea7b9cfbec1da64dca3ed0
https://github.com/jotacor/ComunioPy/blob/2dd71e3e197b497980ea7b9cfbec1da64dca3ed0/ComunioPy/__init__.py#L268-L280
train
jotacor/ComunioPy
ComunioPy/__init__.py
Comunio._parse_bid_table
def _parse_bid_table(self, table): ''' Convert table row values into strings @return: player, owner, team, price, bid_date, trans_date, status ''' player = table.find_all('td')[0].text owner = table.find_all('td')[1].text team = table.find('img')['alt'] price = int(table.find_all('td')[3].text.replace(".","")) bid_date = table.find_all('td')[4].text trans_date = table.find_all('td')[5].text status = table.find_all('td')[6].text return player,owner,team,price,bid_date,trans_date,status
python
def _parse_bid_table(self, table): ''' Convert table row values into strings @return: player, owner, team, price, bid_date, trans_date, status ''' player = table.find_all('td')[0].text owner = table.find_all('td')[1].text team = table.find('img')['alt'] price = int(table.find_all('td')[3].text.replace(".","")) bid_date = table.find_all('td')[4].text trans_date = table.find_all('td')[5].text status = table.find_all('td')[6].text return player,owner,team,price,bid_date,trans_date,status
[ "def", "_parse_bid_table", "(", "self", ",", "table", ")", ":", "player", "=", "table", ".", "find_all", "(", "'td'", ")", "[", "0", "]", ".", "text", "owner", "=", "table", ".", "find_all", "(", "'td'", ")", "[", "1", "]", ".", "text", "team", "=", "table", ".", "find", "(", "'img'", ")", "[", "'alt'", "]", "price", "=", "int", "(", "table", ".", "find_all", "(", "'td'", ")", "[", "3", "]", ".", "text", ".", "replace", "(", "\".\"", ",", "\"\"", ")", ")", "bid_date", "=", "table", ".", "find_all", "(", "'td'", ")", "[", "4", "]", ".", "text", "trans_date", "=", "table", ".", "find_all", "(", "'td'", ")", "[", "5", "]", ".", "text", "status", "=", "table", ".", "find_all", "(", "'td'", ")", "[", "6", "]", ".", "text", "return", "player", ",", "owner", ",", "team", ",", "price", ",", "bid_date", ",", "trans_date", ",", "status" ]
Convert table row values into strings @return: player, owner, team, price, bid_date, trans_date, status
[ "Convert", "table", "row", "values", "into", "strings" ]
2dd71e3e197b497980ea7b9cfbec1da64dca3ed0
https://github.com/jotacor/ComunioPy/blob/2dd71e3e197b497980ea7b9cfbec1da64dca3ed0/ComunioPy/__init__.py#L299-L311
train
stu-gott/pykira
pykira/receiver.py
KiraReceiver.run
def run(self): """Main loop of KIRA thread.""" while not self.stopped.isSet(): try: # if the current state is idle, just block and wait forever # if the current state is any other state, then a timeout of 200ms should # be reasonable in all cases. timeout = (self._state != 'idle') and 0.2 or None rdlist, _, _ = select.select([self._socket.fileno()], [], [], timeout) if not rdlist: if self._state != 'idle': self._state = 'idle' continue data = self._socket.recv(1024) if not data: # check if the socket is still valid try: os.fstat(recv._socket.fileno()) except socket.error: break continue code = utils.mangleIR(data, ignore_errors=True) codeName = self.codeMap.get(code) # some manufacturers repeat their IR codes several times in rapid # succession. by tracking the last code, we can eliminate redundant # state changes if codeName and (self._state != codeName): self._state = codeName for callback in self._callbacks: callback(codeName) except: time.sleep(0.1)
python
def run(self): """Main loop of KIRA thread.""" while not self.stopped.isSet(): try: # if the current state is idle, just block and wait forever # if the current state is any other state, then a timeout of 200ms should # be reasonable in all cases. timeout = (self._state != 'idle') and 0.2 or None rdlist, _, _ = select.select([self._socket.fileno()], [], [], timeout) if not rdlist: if self._state != 'idle': self._state = 'idle' continue data = self._socket.recv(1024) if not data: # check if the socket is still valid try: os.fstat(recv._socket.fileno()) except socket.error: break continue code = utils.mangleIR(data, ignore_errors=True) codeName = self.codeMap.get(code) # some manufacturers repeat their IR codes several times in rapid # succession. by tracking the last code, we can eliminate redundant # state changes if codeName and (self._state != codeName): self._state = codeName for callback in self._callbacks: callback(codeName) except: time.sleep(0.1)
[ "def", "run", "(", "self", ")", ":", "while", "not", "self", ".", "stopped", ".", "isSet", "(", ")", ":", "try", ":", "# if the current state is idle, just block and wait forever", "# if the current state is any other state, then a timeout of 200ms should", "# be reasonable in all cases.", "timeout", "=", "(", "self", ".", "_state", "!=", "'idle'", ")", "and", "0.2", "or", "None", "rdlist", ",", "_", ",", "_", "=", "select", ".", "select", "(", "[", "self", ".", "_socket", ".", "fileno", "(", ")", "]", ",", "[", "]", ",", "[", "]", ",", "timeout", ")", "if", "not", "rdlist", ":", "if", "self", ".", "_state", "!=", "'idle'", ":", "self", ".", "_state", "=", "'idle'", "continue", "data", "=", "self", ".", "_socket", ".", "recv", "(", "1024", ")", "if", "not", "data", ":", "# check if the socket is still valid", "try", ":", "os", ".", "fstat", "(", "recv", ".", "_socket", ".", "fileno", "(", ")", ")", "except", "socket", ".", "error", ":", "break", "continue", "code", "=", "utils", ".", "mangleIR", "(", "data", ",", "ignore_errors", "=", "True", ")", "codeName", "=", "self", ".", "codeMap", ".", "get", "(", "code", ")", "# some manufacturers repeat their IR codes several times in rapid", "# succession. by tracking the last code, we can eliminate redundant", "# state changes", "if", "codeName", "and", "(", "self", ".", "_state", "!=", "codeName", ")", ":", "self", ".", "_state", "=", "codeName", "for", "callback", "in", "self", ".", "_callbacks", ":", "callback", "(", "codeName", ")", "except", ":", "time", ".", "sleep", "(", "0.1", ")" ]
Main loop of KIRA thread.
[ "Main", "loop", "of", "KIRA", "thread", "." ]
b48522ceed694a5393ac4ed8c9a6f11c20f7b150
https://github.com/stu-gott/pykira/blob/b48522ceed694a5393ac4ed8c9a6f11c20f7b150/pykira/receiver.py#L46-L77
train
AllTheWayDown/turgles
turgles/geometry.py
convert_vec2_to_vec4
def convert_vec2_to_vec4(scale, data): """transforms an array of 2d coords into 4d""" it = iter(data) while True: yield next(it) * scale # x yield next(it) * scale # y yield 0.0 # z yield 1.0
python
def convert_vec2_to_vec4(scale, data): """transforms an array of 2d coords into 4d""" it = iter(data) while True: yield next(it) * scale # x yield next(it) * scale # y yield 0.0 # z yield 1.0
[ "def", "convert_vec2_to_vec4", "(", "scale", ",", "data", ")", ":", "it", "=", "iter", "(", "data", ")", "while", "True", ":", "yield", "next", "(", "it", ")", "*", "scale", "# x", "yield", "next", "(", "it", ")", "*", "scale", "# y", "yield", "0.0", "# z", "yield", "1.0" ]
transforms an array of 2d coords into 4d
[ "transforms", "an", "array", "of", "2d", "coords", "into", "4d" ]
1bb17abe9b3aa0953d9a8e9b05a23369c5bf8852
https://github.com/AllTheWayDown/turgles/blob/1bb17abe9b3aa0953d9a8e9b05a23369c5bf8852/turgles/geometry.py#L275-L282
train
AllTheWayDown/turgles
turgles/geometry.py
TurtleGeometry.calculate_edges
def calculate_edges(self, excludes): """Builds a vertex list adding barycentric coordinates to each vertex. Used to draw turtle borders efficiently, specialised to draw only the some edges. See below for references. http://stackoverflow.com/questions/18035719/drawing-a-border-on-a-2d-polygon-with-a-fragment-shader # NOQA http://codeflow.org/entries/2012/aug/02/easy-wireframe-display-with-barycentric-coordinates/ # NOQA http://strattonbrazil.blogspot.co.uk/2011/09/single-pass-wireframe-rendering_11.html # NOQA """ edges = [] MEW = 100.0 if excludes is None: excludes = [0] * len(self.indices) * 2 for i in range(0, len(self.indices), 3): # each triangle i0 = self.indices[i+0] * 4 i1 = self.indices[i+1] * 4 i2 = self.indices[i+2] * 4 e0 = excludes[i+0] e1 = excludes[i+1] e2 = excludes[i+2] p0 = self.vertices[i0:i0+4] p1 = self.vertices[i1:i1+4] p2 = self.vertices[i2:i2+4] v0 = self.vec2minus(p2, p1) v1 = self.vec2minus(p2, p0) v2 = self.vec2minus(p1, p0) area = fabs(v1[0]*v2[1] - v1[1] * v2[0]) c0 = (area/self.magnitude(v0), e1 * MEW, e2 * MEW) c1 = (e0 * MEW, area/self.magnitude(v1), e2 * MEW) c2 = (e0 * MEW, e1 * MEW, area/self.magnitude(v2)) edges.extend(p0) edges.extend(c0) edges.extend(p1) edges.extend(c1) edges.extend(p2) edges.extend(c2) return create_vertex_buffer(edges)
python
def calculate_edges(self, excludes): """Builds a vertex list adding barycentric coordinates to each vertex. Used to draw turtle borders efficiently, specialised to draw only the some edges. See below for references. http://stackoverflow.com/questions/18035719/drawing-a-border-on-a-2d-polygon-with-a-fragment-shader # NOQA http://codeflow.org/entries/2012/aug/02/easy-wireframe-display-with-barycentric-coordinates/ # NOQA http://strattonbrazil.blogspot.co.uk/2011/09/single-pass-wireframe-rendering_11.html # NOQA """ edges = [] MEW = 100.0 if excludes is None: excludes = [0] * len(self.indices) * 2 for i in range(0, len(self.indices), 3): # each triangle i0 = self.indices[i+0] * 4 i1 = self.indices[i+1] * 4 i2 = self.indices[i+2] * 4 e0 = excludes[i+0] e1 = excludes[i+1] e2 = excludes[i+2] p0 = self.vertices[i0:i0+4] p1 = self.vertices[i1:i1+4] p2 = self.vertices[i2:i2+4] v0 = self.vec2minus(p2, p1) v1 = self.vec2minus(p2, p0) v2 = self.vec2minus(p1, p0) area = fabs(v1[0]*v2[1] - v1[1] * v2[0]) c0 = (area/self.magnitude(v0), e1 * MEW, e2 * MEW) c1 = (e0 * MEW, area/self.magnitude(v1), e2 * MEW) c2 = (e0 * MEW, e1 * MEW, area/self.magnitude(v2)) edges.extend(p0) edges.extend(c0) edges.extend(p1) edges.extend(c1) edges.extend(p2) edges.extend(c2) return create_vertex_buffer(edges)
[ "def", "calculate_edges", "(", "self", ",", "excludes", ")", ":", "edges", "=", "[", "]", "MEW", "=", "100.0", "if", "excludes", "is", "None", ":", "excludes", "=", "[", "0", "]", "*", "len", "(", "self", ".", "indices", ")", "*", "2", "for", "i", "in", "range", "(", "0", ",", "len", "(", "self", ".", "indices", ")", ",", "3", ")", ":", "# each triangle", "i0", "=", "self", ".", "indices", "[", "i", "+", "0", "]", "*", "4", "i1", "=", "self", ".", "indices", "[", "i", "+", "1", "]", "*", "4", "i2", "=", "self", ".", "indices", "[", "i", "+", "2", "]", "*", "4", "e0", "=", "excludes", "[", "i", "+", "0", "]", "e1", "=", "excludes", "[", "i", "+", "1", "]", "e2", "=", "excludes", "[", "i", "+", "2", "]", "p0", "=", "self", ".", "vertices", "[", "i0", ":", "i0", "+", "4", "]", "p1", "=", "self", ".", "vertices", "[", "i1", ":", "i1", "+", "4", "]", "p2", "=", "self", ".", "vertices", "[", "i2", ":", "i2", "+", "4", "]", "v0", "=", "self", ".", "vec2minus", "(", "p2", ",", "p1", ")", "v1", "=", "self", ".", "vec2minus", "(", "p2", ",", "p0", ")", "v2", "=", "self", ".", "vec2minus", "(", "p1", ",", "p0", ")", "area", "=", "fabs", "(", "v1", "[", "0", "]", "*", "v2", "[", "1", "]", "-", "v1", "[", "1", "]", "*", "v2", "[", "0", "]", ")", "c0", "=", "(", "area", "/", "self", ".", "magnitude", "(", "v0", ")", ",", "e1", "*", "MEW", ",", "e2", "*", "MEW", ")", "c1", "=", "(", "e0", "*", "MEW", ",", "area", "/", "self", ".", "magnitude", "(", "v1", ")", ",", "e2", "*", "MEW", ")", "c2", "=", "(", "e0", "*", "MEW", ",", "e1", "*", "MEW", ",", "area", "/", "self", ".", "magnitude", "(", "v2", ")", ")", "edges", ".", "extend", "(", "p0", ")", "edges", ".", "extend", "(", "c0", ")", "edges", ".", "extend", "(", "p1", ")", "edges", ".", "extend", "(", "c1", ")", "edges", ".", "extend", "(", "p2", ")", "edges", ".", "extend", "(", "c2", ")", "return", "create_vertex_buffer", "(", "edges", ")" ]
Builds a vertex list adding barycentric coordinates to each vertex. Used to draw turtle borders efficiently, specialised to draw only the some edges. See below for references. http://stackoverflow.com/questions/18035719/drawing-a-border-on-a-2d-polygon-with-a-fragment-shader # NOQA http://codeflow.org/entries/2012/aug/02/easy-wireframe-display-with-barycentric-coordinates/ # NOQA http://strattonbrazil.blogspot.co.uk/2011/09/single-pass-wireframe-rendering_11.html # NOQA
[ "Builds", "a", "vertex", "list", "adding", "barycentric", "coordinates", "to", "each", "vertex", "." ]
1bb17abe9b3aa0953d9a8e9b05a23369c5bf8852
https://github.com/AllTheWayDown/turgles/blob/1bb17abe9b3aa0953d9a8e9b05a23369c5bf8852/turgles/geometry.py#L225-L262
train
NoviceLive/intellicoder
intellicoder/msbuild/locators.py
VCPath.get_bin
def get_bin(self, arch='x86'): """ Get binaries of Visual C++. """ bin_dir = os.path.join(self.vc_dir, 'bin') if arch == 'x86': arch = '' cl_path = os.path.join(bin_dir, arch, 'cl.exe') link_path = os.path.join(bin_dir, arch, 'link.exe') ml_name = 'ml.exe' if arch in ['x86_amd64', 'amd64']: ml_name = 'ml64.exe' ml_path = os.path.join(bin_dir, arch, ml_name) if os.path.isfile(cl_path) \ and os.path.isfile(link_path) \ and os.path.isfile(ml_path): logging.info(_('using cl.exe: %s'), cl_path) logging.info(_('using link.exe: %s'), link_path) logging.info(_('using %s: %s'), ml_name, ml_path) run_cl = partial(run_program, cl_path) run_link = partial(run_program, link_path) run_ml = partial(run_program, ml_path) return self.Bin(run_cl, run_link, run_ml) logging.debug(_('cl.exe not found: %s'), cl_path) logging.debug(_('link.exe not found: %s'), link_path) logging.debug(_('%s not found: %s'), ml_name, ml_path) return self.Bin(None, None, None)
python
def get_bin(self, arch='x86'): """ Get binaries of Visual C++. """ bin_dir = os.path.join(self.vc_dir, 'bin') if arch == 'x86': arch = '' cl_path = os.path.join(bin_dir, arch, 'cl.exe') link_path = os.path.join(bin_dir, arch, 'link.exe') ml_name = 'ml.exe' if arch in ['x86_amd64', 'amd64']: ml_name = 'ml64.exe' ml_path = os.path.join(bin_dir, arch, ml_name) if os.path.isfile(cl_path) \ and os.path.isfile(link_path) \ and os.path.isfile(ml_path): logging.info(_('using cl.exe: %s'), cl_path) logging.info(_('using link.exe: %s'), link_path) logging.info(_('using %s: %s'), ml_name, ml_path) run_cl = partial(run_program, cl_path) run_link = partial(run_program, link_path) run_ml = partial(run_program, ml_path) return self.Bin(run_cl, run_link, run_ml) logging.debug(_('cl.exe not found: %s'), cl_path) logging.debug(_('link.exe not found: %s'), link_path) logging.debug(_('%s not found: %s'), ml_name, ml_path) return self.Bin(None, None, None)
[ "def", "get_bin", "(", "self", ",", "arch", "=", "'x86'", ")", ":", "bin_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "vc_dir", ",", "'bin'", ")", "if", "arch", "==", "'x86'", ":", "arch", "=", "''", "cl_path", "=", "os", ".", "path", ".", "join", "(", "bin_dir", ",", "arch", ",", "'cl.exe'", ")", "link_path", "=", "os", ".", "path", ".", "join", "(", "bin_dir", ",", "arch", ",", "'link.exe'", ")", "ml_name", "=", "'ml.exe'", "if", "arch", "in", "[", "'x86_amd64'", ",", "'amd64'", "]", ":", "ml_name", "=", "'ml64.exe'", "ml_path", "=", "os", ".", "path", ".", "join", "(", "bin_dir", ",", "arch", ",", "ml_name", ")", "if", "os", ".", "path", ".", "isfile", "(", "cl_path", ")", "and", "os", ".", "path", ".", "isfile", "(", "link_path", ")", "and", "os", ".", "path", ".", "isfile", "(", "ml_path", ")", ":", "logging", ".", "info", "(", "_", "(", "'using cl.exe: %s'", ")", ",", "cl_path", ")", "logging", ".", "info", "(", "_", "(", "'using link.exe: %s'", ")", ",", "link_path", ")", "logging", ".", "info", "(", "_", "(", "'using %s: %s'", ")", ",", "ml_name", ",", "ml_path", ")", "run_cl", "=", "partial", "(", "run_program", ",", "cl_path", ")", "run_link", "=", "partial", "(", "run_program", ",", "link_path", ")", "run_ml", "=", "partial", "(", "run_program", ",", "ml_path", ")", "return", "self", ".", "Bin", "(", "run_cl", ",", "run_link", ",", "run_ml", ")", "logging", ".", "debug", "(", "_", "(", "'cl.exe not found: %s'", ")", ",", "cl_path", ")", "logging", ".", "debug", "(", "_", "(", "'link.exe not found: %s'", ")", ",", "link_path", ")", "logging", ".", "debug", "(", "_", "(", "'%s not found: %s'", ")", ",", "ml_name", ",", "ml_path", ")", "return", "self", ".", "Bin", "(", "None", ",", "None", ",", "None", ")" ]
Get binaries of Visual C++.
[ "Get", "binaries", "of", "Visual", "C", "++", "." ]
6cac5ebfce65c370dbebe47756a1789b120ef982
https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/msbuild/locators.py#L61-L87
train
NoviceLive/intellicoder
intellicoder/msbuild/locators.py
VCPath.get_inc
def get_inc(self): """ Get include directories of Visual C++. """ dirs = [] for part in ['', 'atlmfc']: include = os.path.join(self.vc_dir, part, 'include') if os.path.isdir(include): logging.info(_('using include: %s'), include) dirs.append(include) else: logging.debug(_('include not found: %s'), include) return dirs
python
def get_inc(self): """ Get include directories of Visual C++. """ dirs = [] for part in ['', 'atlmfc']: include = os.path.join(self.vc_dir, part, 'include') if os.path.isdir(include): logging.info(_('using include: %s'), include) dirs.append(include) else: logging.debug(_('include not found: %s'), include) return dirs
[ "def", "get_inc", "(", "self", ")", ":", "dirs", "=", "[", "]", "for", "part", "in", "[", "''", ",", "'atlmfc'", "]", ":", "include", "=", "os", ".", "path", ".", "join", "(", "self", ".", "vc_dir", ",", "part", ",", "'include'", ")", "if", "os", ".", "path", ".", "isdir", "(", "include", ")", ":", "logging", ".", "info", "(", "_", "(", "'using include: %s'", ")", ",", "include", ")", "dirs", ".", "append", "(", "include", ")", "else", ":", "logging", ".", "debug", "(", "_", "(", "'include not found: %s'", ")", ",", "include", ")", "return", "dirs" ]
Get include directories of Visual C++.
[ "Get", "include", "directories", "of", "Visual", "C", "++", "." ]
6cac5ebfce65c370dbebe47756a1789b120ef982
https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/msbuild/locators.py#L89-L101
train
NoviceLive/intellicoder
intellicoder/msbuild/locators.py
VCPath.get_lib
def get_lib(self, arch='x86'): """ Get lib directories of Visual C++. """ if arch == 'x86': arch = '' if arch == 'x64': arch = 'amd64' lib = os.path.join(self.vc_dir, 'lib', arch) if os.path.isdir(lib): logging.info(_('using lib: %s'), lib) return [lib] logging.debug(_('lib not found: %s'), lib) return []
python
def get_lib(self, arch='x86'): """ Get lib directories of Visual C++. """ if arch == 'x86': arch = '' if arch == 'x64': arch = 'amd64' lib = os.path.join(self.vc_dir, 'lib', arch) if os.path.isdir(lib): logging.info(_('using lib: %s'), lib) return [lib] logging.debug(_('lib not found: %s'), lib) return []
[ "def", "get_lib", "(", "self", ",", "arch", "=", "'x86'", ")", ":", "if", "arch", "==", "'x86'", ":", "arch", "=", "''", "if", "arch", "==", "'x64'", ":", "arch", "=", "'amd64'", "lib", "=", "os", ".", "path", ".", "join", "(", "self", ".", "vc_dir", ",", "'lib'", ",", "arch", ")", "if", "os", ".", "path", ".", "isdir", "(", "lib", ")", ":", "logging", ".", "info", "(", "_", "(", "'using lib: %s'", ")", ",", "lib", ")", "return", "[", "lib", "]", "logging", ".", "debug", "(", "_", "(", "'lib not found: %s'", ")", ",", "lib", ")", "return", "[", "]" ]
Get lib directories of Visual C++.
[ "Get", "lib", "directories", "of", "Visual", "C", "++", "." ]
6cac5ebfce65c370dbebe47756a1789b120ef982
https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/msbuild/locators.py#L103-L116
train
NoviceLive/intellicoder
intellicoder/msbuild/locators.py
VCPath.get_bin_and_lib
def get_bin_and_lib(self, x64=False, native=False): """ Get bin and lib. """ if x64: msvc = self.bin64 paths = self.lib64 else: msvc = self.bin32 paths = self.lib if native: arch = 'x64' if x64 else 'x86' paths += self.sdk.get_lib(arch, native=True) else: attr = 'lib64' if x64 else 'lib' paths += getattr(self.sdk, attr) return msvc, paths
python
def get_bin_and_lib(self, x64=False, native=False): """ Get bin and lib. """ if x64: msvc = self.bin64 paths = self.lib64 else: msvc = self.bin32 paths = self.lib if native: arch = 'x64' if x64 else 'x86' paths += self.sdk.get_lib(arch, native=True) else: attr = 'lib64' if x64 else 'lib' paths += getattr(self.sdk, attr) return msvc, paths
[ "def", "get_bin_and_lib", "(", "self", ",", "x64", "=", "False", ",", "native", "=", "False", ")", ":", "if", "x64", ":", "msvc", "=", "self", ".", "bin64", "paths", "=", "self", ".", "lib64", "else", ":", "msvc", "=", "self", ".", "bin32", "paths", "=", "self", ".", "lib", "if", "native", ":", "arch", "=", "'x64'", "if", "x64", "else", "'x86'", "paths", "+=", "self", ".", "sdk", ".", "get_lib", "(", "arch", ",", "native", "=", "True", ")", "else", ":", "attr", "=", "'lib64'", "if", "x64", "else", "'lib'", "paths", "+=", "getattr", "(", "self", ".", "sdk", ",", "attr", ")", "return", "msvc", ",", "paths" ]
Get bin and lib.
[ "Get", "bin", "and", "lib", "." ]
6cac5ebfce65c370dbebe47756a1789b120ef982
https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/msbuild/locators.py#L118-L134
train
NoviceLive/intellicoder
intellicoder/msbuild/locators.py
SDKPath.get_inc
def get_inc(self, native=False): """ Get include directories of Windows SDK. """ if self.sdk_version == 'v7.0A': include = os.path.join(self.sdk_dir, 'include') if os.path.isdir(include): logging.info(_('using include: %s'), include) return [include] logging.debug(_('include not found: %s'), include) return [] if self.sdk_version == 'v8.1': dirs = [] if native: parts = ['km', os.path.join('km', 'crt'), 'shared'] else: parts = ['um', 'winrt', 'shared'] for part in parts: include = os.path.join(self.sdk_dir, 'include', part) if os.path.isdir(include): logging.info(_('using include: %s'), include) dirs.append(include) else: logging.debug(_('inc not found: %s'), include) return dirs if self.sdk_version == 'v10.0': dirs = [] extra = os.path.join('include', '10.0.10240.0') for mode in ['um', 'ucrt', 'shared', 'winrt']: include = os.path.join(self.sdk_dir, extra, mode) if os.path.isdir(include): logging.info(_('using include: %s'), include) dirs.append(include) else: logging.debug(_('inc not found: %s'), include) return dirs message = 'unknown sdk version: {}'.format(self.sdk_version) raise RuntimeError(message)
python
def get_inc(self, native=False): """ Get include directories of Windows SDK. """ if self.sdk_version == 'v7.0A': include = os.path.join(self.sdk_dir, 'include') if os.path.isdir(include): logging.info(_('using include: %s'), include) return [include] logging.debug(_('include not found: %s'), include) return [] if self.sdk_version == 'v8.1': dirs = [] if native: parts = ['km', os.path.join('km', 'crt'), 'shared'] else: parts = ['um', 'winrt', 'shared'] for part in parts: include = os.path.join(self.sdk_dir, 'include', part) if os.path.isdir(include): logging.info(_('using include: %s'), include) dirs.append(include) else: logging.debug(_('inc not found: %s'), include) return dirs if self.sdk_version == 'v10.0': dirs = [] extra = os.path.join('include', '10.0.10240.0') for mode in ['um', 'ucrt', 'shared', 'winrt']: include = os.path.join(self.sdk_dir, extra, mode) if os.path.isdir(include): logging.info(_('using include: %s'), include) dirs.append(include) else: logging.debug(_('inc not found: %s'), include) return dirs message = 'unknown sdk version: {}'.format(self.sdk_version) raise RuntimeError(message)
[ "def", "get_inc", "(", "self", ",", "native", "=", "False", ")", ":", "if", "self", ".", "sdk_version", "==", "'v7.0A'", ":", "include", "=", "os", ".", "path", ".", "join", "(", "self", ".", "sdk_dir", ",", "'include'", ")", "if", "os", ".", "path", ".", "isdir", "(", "include", ")", ":", "logging", ".", "info", "(", "_", "(", "'using include: %s'", ")", ",", "include", ")", "return", "[", "include", "]", "logging", ".", "debug", "(", "_", "(", "'include not found: %s'", ")", ",", "include", ")", "return", "[", "]", "if", "self", ".", "sdk_version", "==", "'v8.1'", ":", "dirs", "=", "[", "]", "if", "native", ":", "parts", "=", "[", "'km'", ",", "os", ".", "path", ".", "join", "(", "'km'", ",", "'crt'", ")", ",", "'shared'", "]", "else", ":", "parts", "=", "[", "'um'", ",", "'winrt'", ",", "'shared'", "]", "for", "part", "in", "parts", ":", "include", "=", "os", ".", "path", ".", "join", "(", "self", ".", "sdk_dir", ",", "'include'", ",", "part", ")", "if", "os", ".", "path", ".", "isdir", "(", "include", ")", ":", "logging", ".", "info", "(", "_", "(", "'using include: %s'", ")", ",", "include", ")", "dirs", ".", "append", "(", "include", ")", "else", ":", "logging", ".", "debug", "(", "_", "(", "'inc not found: %s'", ")", ",", "include", ")", "return", "dirs", "if", "self", ".", "sdk_version", "==", "'v10.0'", ":", "dirs", "=", "[", "]", "extra", "=", "os", ".", "path", ".", "join", "(", "'include'", ",", "'10.0.10240.0'", ")", "for", "mode", "in", "[", "'um'", ",", "'ucrt'", ",", "'shared'", ",", "'winrt'", "]", ":", "include", "=", "os", ".", "path", ".", "join", "(", "self", ".", "sdk_dir", ",", "extra", ",", "mode", ")", "if", "os", ".", "path", ".", "isdir", "(", "include", ")", ":", "logging", ".", "info", "(", "_", "(", "'using include: %s'", ")", ",", "include", ")", "dirs", ".", "append", "(", "include", ")", "else", ":", "logging", ".", "debug", "(", "_", "(", "'inc not found: %s'", ")", ",", "include", ")", "return", "dirs", "message", "=", "'unknown sdk version: {}'", ".", "format", "(", "self", ".", "sdk_version", ")", "raise", "RuntimeError", "(", "message", ")" ]
Get include directories of Windows SDK.
[ "Get", "include", "directories", "of", "Windows", "SDK", "." ]
6cac5ebfce65c370dbebe47756a1789b120ef982
https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/msbuild/locators.py#L151-L188
train
NoviceLive/intellicoder
intellicoder/msbuild/locators.py
SDKPath.get_lib
def get_lib(self, arch='x86', native=False): """ Get lib directories of Windows SDK. """ if self.sdk_version == 'v7.0A': if arch == 'x86': arch = '' lib = os.path.join(self.sdk_dir, 'lib', arch) if os.path.isdir(lib): logging.info(_('using lib: %s'), lib) return [lib] logging.debug(_('lib not found: %s'), lib) return [] if self.sdk_version == 'v8.1': if native: extra = os.path.join('winv6.3', 'km') else: extra = os.path.join('winv6.3', 'um') lib = os.path.join(self.sdk_dir, 'lib', extra, arch) if os.path.isdir(lib): logging.info(_('using lib: %s'), lib) return [lib] logging.debug(_('lib not found: %s'), lib) return [] if self.sdk_version == 'v10.0': dirs = [] extra = os.path.join('lib', '10.0.10240.0') for mode in ['um', 'ucrt']: lib = os.path.join(self.sdk_dir, extra, mode, arch) if os.path.isdir(lib): logging.info(_('using lib: %s'), lib) dirs.append(lib) else: logging.debug(_('lib not found: %s'), lib) return dirs message = 'unknown sdk version: {}'.format(self.sdk_version) raise RuntimeError(message)
python
def get_lib(self, arch='x86', native=False): """ Get lib directories of Windows SDK. """ if self.sdk_version == 'v7.0A': if arch == 'x86': arch = '' lib = os.path.join(self.sdk_dir, 'lib', arch) if os.path.isdir(lib): logging.info(_('using lib: %s'), lib) return [lib] logging.debug(_('lib not found: %s'), lib) return [] if self.sdk_version == 'v8.1': if native: extra = os.path.join('winv6.3', 'km') else: extra = os.path.join('winv6.3', 'um') lib = os.path.join(self.sdk_dir, 'lib', extra, arch) if os.path.isdir(lib): logging.info(_('using lib: %s'), lib) return [lib] logging.debug(_('lib not found: %s'), lib) return [] if self.sdk_version == 'v10.0': dirs = [] extra = os.path.join('lib', '10.0.10240.0') for mode in ['um', 'ucrt']: lib = os.path.join(self.sdk_dir, extra, mode, arch) if os.path.isdir(lib): logging.info(_('using lib: %s'), lib) dirs.append(lib) else: logging.debug(_('lib not found: %s'), lib) return dirs message = 'unknown sdk version: {}'.format(self.sdk_version) raise RuntimeError(message)
[ "def", "get_lib", "(", "self", ",", "arch", "=", "'x86'", ",", "native", "=", "False", ")", ":", "if", "self", ".", "sdk_version", "==", "'v7.0A'", ":", "if", "arch", "==", "'x86'", ":", "arch", "=", "''", "lib", "=", "os", ".", "path", ".", "join", "(", "self", ".", "sdk_dir", ",", "'lib'", ",", "arch", ")", "if", "os", ".", "path", ".", "isdir", "(", "lib", ")", ":", "logging", ".", "info", "(", "_", "(", "'using lib: %s'", ")", ",", "lib", ")", "return", "[", "lib", "]", "logging", ".", "debug", "(", "_", "(", "'lib not found: %s'", ")", ",", "lib", ")", "return", "[", "]", "if", "self", ".", "sdk_version", "==", "'v8.1'", ":", "if", "native", ":", "extra", "=", "os", ".", "path", ".", "join", "(", "'winv6.3'", ",", "'km'", ")", "else", ":", "extra", "=", "os", ".", "path", ".", "join", "(", "'winv6.3'", ",", "'um'", ")", "lib", "=", "os", ".", "path", ".", "join", "(", "self", ".", "sdk_dir", ",", "'lib'", ",", "extra", ",", "arch", ")", "if", "os", ".", "path", ".", "isdir", "(", "lib", ")", ":", "logging", ".", "info", "(", "_", "(", "'using lib: %s'", ")", ",", "lib", ")", "return", "[", "lib", "]", "logging", ".", "debug", "(", "_", "(", "'lib not found: %s'", ")", ",", "lib", ")", "return", "[", "]", "if", "self", ".", "sdk_version", "==", "'v10.0'", ":", "dirs", "=", "[", "]", "extra", "=", "os", ".", "path", ".", "join", "(", "'lib'", ",", "'10.0.10240.0'", ")", "for", "mode", "in", "[", "'um'", ",", "'ucrt'", "]", ":", "lib", "=", "os", ".", "path", ".", "join", "(", "self", ".", "sdk_dir", ",", "extra", ",", "mode", ",", "arch", ")", "if", "os", ".", "path", ".", "isdir", "(", "lib", ")", ":", "logging", ".", "info", "(", "_", "(", "'using lib: %s'", ")", ",", "lib", ")", "dirs", ".", "append", "(", "lib", ")", "else", ":", "logging", ".", "debug", "(", "_", "(", "'lib not found: %s'", ")", ",", "lib", ")", "return", "dirs", "message", "=", "'unknown sdk version: {}'", ".", "format", "(", "self", ".", "sdk_version", ")", "raise", "RuntimeError", "(", "message", ")" ]
Get lib directories of Windows SDK.
[ "Get", "lib", "directories", "of", "Windows", "SDK", "." ]
6cac5ebfce65c370dbebe47756a1789b120ef982
https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/msbuild/locators.py#L190-L226
train
NoviceLive/intellicoder
intellicoder/msbuild/locators.py
VSPath.get_tool_dir
def get_tool_dir(): """ Get the directory of Visual Studio from environment variables. """ def _is_comntools(name): return re.match(r'vs\d+comntools', name.lower()) def _get_version_from_name(name): return (re.search(r'\d+', name).group(0), name) names = [name for name in os.environ if _is_comntools(name)] logging.debug(_('found vscomntools: %s'), names) versions = [_get_version_from_name(name) for name in names] logging.debug(_('extracted versions: %s'), versions) try: version = max(versions) except ValueError: raise OSError(_('Failed to find the VSCOMNTOOLS. ' 'Have you installed Visual Studio?')) else: logging.info(_('using version: %s'), version) vscomntools = os.environ[version[1]] logging.info(_('using vscomntools: %s'), vscomntools) return vscomntools
python
def get_tool_dir(): """ Get the directory of Visual Studio from environment variables. """ def _is_comntools(name): return re.match(r'vs\d+comntools', name.lower()) def _get_version_from_name(name): return (re.search(r'\d+', name).group(0), name) names = [name for name in os.environ if _is_comntools(name)] logging.debug(_('found vscomntools: %s'), names) versions = [_get_version_from_name(name) for name in names] logging.debug(_('extracted versions: %s'), versions) try: version = max(versions) except ValueError: raise OSError(_('Failed to find the VSCOMNTOOLS. ' 'Have you installed Visual Studio?')) else: logging.info(_('using version: %s'), version) vscomntools = os.environ[version[1]] logging.info(_('using vscomntools: %s'), vscomntools) return vscomntools
[ "def", "get_tool_dir", "(", ")", ":", "def", "_is_comntools", "(", "name", ")", ":", "return", "re", ".", "match", "(", "r'vs\\d+comntools'", ",", "name", ".", "lower", "(", ")", ")", "def", "_get_version_from_name", "(", "name", ")", ":", "return", "(", "re", ".", "search", "(", "r'\\d+'", ",", "name", ")", ".", "group", "(", "0", ")", ",", "name", ")", "names", "=", "[", "name", "for", "name", "in", "os", ".", "environ", "if", "_is_comntools", "(", "name", ")", "]", "logging", ".", "debug", "(", "_", "(", "'found vscomntools: %s'", ")", ",", "names", ")", "versions", "=", "[", "_get_version_from_name", "(", "name", ")", "for", "name", "in", "names", "]", "logging", ".", "debug", "(", "_", "(", "'extracted versions: %s'", ")", ",", "versions", ")", "try", ":", "version", "=", "max", "(", "versions", ")", "except", "ValueError", ":", "raise", "OSError", "(", "_", "(", "'Failed to find the VSCOMNTOOLS. '", "'Have you installed Visual Studio?'", ")", ")", "else", ":", "logging", ".", "info", "(", "_", "(", "'using version: %s'", ")", ",", "version", ")", "vscomntools", "=", "os", ".", "environ", "[", "version", "[", "1", "]", "]", "logging", ".", "info", "(", "_", "(", "'using vscomntools: %s'", ")", ",", "vscomntools", ")", "return", "vscomntools" ]
Get the directory of Visual Studio from environment variables.
[ "Get", "the", "directory", "of", "Visual", "Studio", "from", "environment", "variables", "." ]
6cac5ebfce65c370dbebe47756a1789b120ef982
https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/msbuild/locators.py#L242-L266
train
NoviceLive/intellicoder
intellicoder/msbuild/locators.py
VSPath.get_vs_dir_from_tool_dir
def get_vs_dir_from_tool_dir(self): """ Get the directory of Visual Studio from the directory Tools. """ index = self.tool_dir.find(r'Common7\Tools') return self.tool_dir[:index]
python
def get_vs_dir_from_tool_dir(self): """ Get the directory of Visual Studio from the directory Tools. """ index = self.tool_dir.find(r'Common7\Tools') return self.tool_dir[:index]
[ "def", "get_vs_dir_from_tool_dir", "(", "self", ")", ":", "index", "=", "self", ".", "tool_dir", ".", "find", "(", "r'Common7\\Tools'", ")", "return", "self", ".", "tool_dir", "[", ":", "index", "]" ]
Get the directory of Visual Studio from the directory Tools.
[ "Get", "the", "directory", "of", "Visual", "Studio", "from", "the", "directory", "Tools", "." ]
6cac5ebfce65c370dbebe47756a1789b120ef982
https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/msbuild/locators.py#L268-L274
train
NoviceLive/intellicoder
intellicoder/msbuild/locators.py
VSPath.get_vc_dir_from_vs_dir
def get_vc_dir_from_vs_dir(self): """ Get Visual C++ directory from Visual Studio directory. """ vc_dir = os.path.join(self.vs_dir, 'vc') if os.path.isdir(vc_dir): logging.info(_('using vc: %s'), vc_dir) return vc_dir logging.debug(_('vc not found: %s'), vc_dir) return ''
python
def get_vc_dir_from_vs_dir(self): """ Get Visual C++ directory from Visual Studio directory. """ vc_dir = os.path.join(self.vs_dir, 'vc') if os.path.isdir(vc_dir): logging.info(_('using vc: %s'), vc_dir) return vc_dir logging.debug(_('vc not found: %s'), vc_dir) return ''
[ "def", "get_vc_dir_from_vs_dir", "(", "self", ")", ":", "vc_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "vs_dir", ",", "'vc'", ")", "if", "os", ".", "path", ".", "isdir", "(", "vc_dir", ")", ":", "logging", ".", "info", "(", "_", "(", "'using vc: %s'", ")", ",", "vc_dir", ")", "return", "vc_dir", "logging", ".", "debug", "(", "_", "(", "'vc not found: %s'", ")", ",", "vc_dir", ")", "return", "''" ]
Get Visual C++ directory from Visual Studio directory.
[ "Get", "Visual", "C", "++", "directory", "from", "Visual", "Studio", "directory", "." ]
6cac5ebfce65c370dbebe47756a1789b120ef982
https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/msbuild/locators.py#L276-L285
train
NoviceLive/intellicoder
intellicoder/msbuild/locators.py
VSPath.get_sdk_version
def get_sdk_version(self): """Get the version of Windows SDK from VCVarsQueryRegistry.bat.""" name = 'VCVarsQueryRegistry.bat' path = os.path.join(self.tool_dir, name) batch = read_file(path) if not batch: raise RuntimeError(_('failed to find the SDK version')) regex = r'(?<=\\Microsoft SDKs\\Windows\\).+?(?=")' try: version = re.search(regex, batch).group() except AttributeError: return '' else: logging.debug(_('SDK version: %s'), version) return version
python
def get_sdk_version(self): """Get the version of Windows SDK from VCVarsQueryRegistry.bat.""" name = 'VCVarsQueryRegistry.bat' path = os.path.join(self.tool_dir, name) batch = read_file(path) if not batch: raise RuntimeError(_('failed to find the SDK version')) regex = r'(?<=\\Microsoft SDKs\\Windows\\).+?(?=")' try: version = re.search(regex, batch).group() except AttributeError: return '' else: logging.debug(_('SDK version: %s'), version) return version
[ "def", "get_sdk_version", "(", "self", ")", ":", "name", "=", "'VCVarsQueryRegistry.bat'", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "tool_dir", ",", "name", ")", "batch", "=", "read_file", "(", "path", ")", "if", "not", "batch", ":", "raise", "RuntimeError", "(", "_", "(", "'failed to find the SDK version'", ")", ")", "regex", "=", "r'(?<=\\\\Microsoft SDKs\\\\Windows\\\\).+?(?=\")'", "try", ":", "version", "=", "re", ".", "search", "(", "regex", ",", "batch", ")", ".", "group", "(", ")", "except", "AttributeError", ":", "return", "''", "else", ":", "logging", ".", "debug", "(", "_", "(", "'SDK version: %s'", ")", ",", "version", ")", "return", "version" ]
Get the version of Windows SDK from VCVarsQueryRegistry.bat.
[ "Get", "the", "version", "of", "Windows", "SDK", "from", "VCVarsQueryRegistry", ".", "bat", "." ]
6cac5ebfce65c370dbebe47756a1789b120ef982
https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/msbuild/locators.py#L287-L302
train
NoviceLive/intellicoder
intellicoder/msbuild/locators.py
VSPath.get_sdk_dir
def get_sdk_dir(self): """Get the directory of Windows SDK from registry.""" if not WINREG: return '' path = r'\Microsoft\Microsoft SDKs\Windows' for node in ['SOFTWARE', r'SOFTWARE\Wow6432Node']: for hkey in [HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER]: sub_key = node + path + '\\' + self.sdk_version try: key = OpenKey(hkey, sub_key) except OSError: logging.debug(_('key not found: %s'), sub_key) continue else: logging.info(_('using key: %s'), sub_key) value_name = 'InstallationFolder' try: value = QueryValueEx(key, value_name) except OSError: return '' logging.info(_('using dir: %s'), value[0]) return value[0] return ''
python
def get_sdk_dir(self): """Get the directory of Windows SDK from registry.""" if not WINREG: return '' path = r'\Microsoft\Microsoft SDKs\Windows' for node in ['SOFTWARE', r'SOFTWARE\Wow6432Node']: for hkey in [HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER]: sub_key = node + path + '\\' + self.sdk_version try: key = OpenKey(hkey, sub_key) except OSError: logging.debug(_('key not found: %s'), sub_key) continue else: logging.info(_('using key: %s'), sub_key) value_name = 'InstallationFolder' try: value = QueryValueEx(key, value_name) except OSError: return '' logging.info(_('using dir: %s'), value[0]) return value[0] return ''
[ "def", "get_sdk_dir", "(", "self", ")", ":", "if", "not", "WINREG", ":", "return", "''", "path", "=", "r'\\Microsoft\\Microsoft SDKs\\Windows'", "for", "node", "in", "[", "'SOFTWARE'", ",", "r'SOFTWARE\\Wow6432Node'", "]", ":", "for", "hkey", "in", "[", "HKEY_LOCAL_MACHINE", ",", "HKEY_CURRENT_USER", "]", ":", "sub_key", "=", "node", "+", "path", "+", "'\\\\'", "+", "self", ".", "sdk_version", "try", ":", "key", "=", "OpenKey", "(", "hkey", ",", "sub_key", ")", "except", "OSError", ":", "logging", ".", "debug", "(", "_", "(", "'key not found: %s'", ")", ",", "sub_key", ")", "continue", "else", ":", "logging", ".", "info", "(", "_", "(", "'using key: %s'", ")", ",", "sub_key", ")", "value_name", "=", "'InstallationFolder'", "try", ":", "value", "=", "QueryValueEx", "(", "key", ",", "value_name", ")", "except", "OSError", ":", "return", "''", "logging", ".", "info", "(", "_", "(", "'using dir: %s'", ")", ",", "value", "[", "0", "]", ")", "return", "value", "[", "0", "]", "return", "''" ]
Get the directory of Windows SDK from registry.
[ "Get", "the", "directory", "of", "Windows", "SDK", "from", "registry", "." ]
6cac5ebfce65c370dbebe47756a1789b120ef982
https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/msbuild/locators.py#L305-L327
train
lowandrew/OLCTools
spadespipeline/primer_finder_bbduk.py
PrimerFinder.main
def main(self): """ Run the necessary methods """ logging.info('Preparing metadata') # If this script is run as part of a pipeline, the metadata objects will already exist if not self.metadata: self.filer() else: self.objectprep() # Use the number of metadata objects to calculate the number of cores to use per sample in multi-threaded # methods with sequence calls to multi-threaded applications try: self.threads = int(self.cpus / len(self.metadata)) if self.cpus / len( self.metadata) > 1 else 1 except (TypeError, ZeroDivisionError): self.threads = self.cpus logging.info('Reading and formatting primers') self.primers() logging.info('Baiting .fastq files against primers') self.bait() logging.info('Baiting .fastq files against previously baited .fastq files') self.doublebait() logging.info('Assembling contigs from double-baited .fastq files') self.assemble_amplicon_spades() logging.info('Creating BLAST database') self.make_blastdb() logging.info('Running BLAST analyses') self.blastnthreads() logging.info('Parsing BLAST results') self.parseblast() logging.info('Clearing amplicon files from previous iterations') self.ampliconclear() logging.info('Creating reports') self.reporter()
python
def main(self): """ Run the necessary methods """ logging.info('Preparing metadata') # If this script is run as part of a pipeline, the metadata objects will already exist if not self.metadata: self.filer() else: self.objectprep() # Use the number of metadata objects to calculate the number of cores to use per sample in multi-threaded # methods with sequence calls to multi-threaded applications try: self.threads = int(self.cpus / len(self.metadata)) if self.cpus / len( self.metadata) > 1 else 1 except (TypeError, ZeroDivisionError): self.threads = self.cpus logging.info('Reading and formatting primers') self.primers() logging.info('Baiting .fastq files against primers') self.bait() logging.info('Baiting .fastq files against previously baited .fastq files') self.doublebait() logging.info('Assembling contigs from double-baited .fastq files') self.assemble_amplicon_spades() logging.info('Creating BLAST database') self.make_blastdb() logging.info('Running BLAST analyses') self.blastnthreads() logging.info('Parsing BLAST results') self.parseblast() logging.info('Clearing amplicon files from previous iterations') self.ampliconclear() logging.info('Creating reports') self.reporter()
[ "def", "main", "(", "self", ")", ":", "logging", ".", "info", "(", "'Preparing metadata'", ")", "# If this script is run as part of a pipeline, the metadata objects will already exist", "if", "not", "self", ".", "metadata", ":", "self", ".", "filer", "(", ")", "else", ":", "self", ".", "objectprep", "(", ")", "# Use the number of metadata objects to calculate the number of cores to use per sample in multi-threaded", "# methods with sequence calls to multi-threaded applications", "try", ":", "self", ".", "threads", "=", "int", "(", "self", ".", "cpus", "/", "len", "(", "self", ".", "metadata", ")", ")", "if", "self", ".", "cpus", "/", "len", "(", "self", ".", "metadata", ")", ">", "1", "else", "1", "except", "(", "TypeError", ",", "ZeroDivisionError", ")", ":", "self", ".", "threads", "=", "self", ".", "cpus", "logging", ".", "info", "(", "'Reading and formatting primers'", ")", "self", ".", "primers", "(", ")", "logging", ".", "info", "(", "'Baiting .fastq files against primers'", ")", "self", ".", "bait", "(", ")", "logging", ".", "info", "(", "'Baiting .fastq files against previously baited .fastq files'", ")", "self", ".", "doublebait", "(", ")", "logging", ".", "info", "(", "'Assembling contigs from double-baited .fastq files'", ")", "self", ".", "assemble_amplicon_spades", "(", ")", "logging", ".", "info", "(", "'Creating BLAST database'", ")", "self", ".", "make_blastdb", "(", ")", "logging", ".", "info", "(", "'Running BLAST analyses'", ")", "self", ".", "blastnthreads", "(", ")", "logging", ".", "info", "(", "'Parsing BLAST results'", ")", "self", ".", "parseblast", "(", ")", "logging", ".", "info", "(", "'Clearing amplicon files from previous iterations'", ")", "self", ".", "ampliconclear", "(", ")", "logging", ".", "info", "(", "'Creating reports'", ")", "self", ".", "reporter", "(", ")" ]
Run the necessary methods
[ "Run", "the", "necessary", "methods" ]
88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a
https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/primer_finder_bbduk.py#L29-L63
train
lowandrew/OLCTools
spadespipeline/primer_finder_bbduk.py
PrimerFinder.objectprep
def objectprep(self): """ If the script is being run as part of a pipeline, create and populate the objects for the current analysis """ for sample in self.metadata: setattr(sample, self.analysistype, GenObject()) # Set the destination folder sample[self.analysistype].outputdir = os.path.join(self.path, self.analysistype) # Make the destination folder make_path(sample[self.analysistype].outputdir) sample[self.analysistype].baitedfastq = os.path.join( sample[self.analysistype].outputdir, '{at}_targetMatches.fastq.gz'.format(at=self.analysistype)) # Set the file type for the downstream analysis sample[self.analysistype].filetype = self.filetype if self.filetype == 'fasta': sample[self.analysistype].assemblyfile = sample.general.bestassemblyfile
python
def objectprep(self): """ If the script is being run as part of a pipeline, create and populate the objects for the current analysis """ for sample in self.metadata: setattr(sample, self.analysistype, GenObject()) # Set the destination folder sample[self.analysistype].outputdir = os.path.join(self.path, self.analysistype) # Make the destination folder make_path(sample[self.analysistype].outputdir) sample[self.analysistype].baitedfastq = os.path.join( sample[self.analysistype].outputdir, '{at}_targetMatches.fastq.gz'.format(at=self.analysistype)) # Set the file type for the downstream analysis sample[self.analysistype].filetype = self.filetype if self.filetype == 'fasta': sample[self.analysistype].assemblyfile = sample.general.bestassemblyfile
[ "def", "objectprep", "(", "self", ")", ":", "for", "sample", "in", "self", ".", "metadata", ":", "setattr", "(", "sample", ",", "self", ".", "analysistype", ",", "GenObject", "(", ")", ")", "# Set the destination folder", "sample", "[", "self", ".", "analysistype", "]", ".", "outputdir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "self", ".", "analysistype", ")", "# Make the destination folder", "make_path", "(", "sample", "[", "self", ".", "analysistype", "]", ".", "outputdir", ")", "sample", "[", "self", ".", "analysistype", "]", ".", "baitedfastq", "=", "os", ".", "path", ".", "join", "(", "sample", "[", "self", ".", "analysistype", "]", ".", "outputdir", ",", "'{at}_targetMatches.fastq.gz'", ".", "format", "(", "at", "=", "self", ".", "analysistype", ")", ")", "# Set the file type for the downstream analysis", "sample", "[", "self", ".", "analysistype", "]", ".", "filetype", "=", "self", ".", "filetype", "if", "self", ".", "filetype", "==", "'fasta'", ":", "sample", "[", "self", ".", "analysistype", "]", ".", "assemblyfile", "=", "sample", ".", "general", ".", "bestassemblyfile" ]
If the script is being run as part of a pipeline, create and populate the objects for the current analysis
[ "If", "the", "script", "is", "being", "run", "as", "part", "of", "a", "pipeline", "create", "and", "populate", "the", "objects", "for", "the", "current", "analysis" ]
88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a
https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/primer_finder_bbduk.py#L148-L164
train
lowandrew/OLCTools
spadespipeline/primer_finder_bbduk.py
PrimerFinder.bait
def bait(self): """ Use bbduk to bait FASTQ reads from input files using the primer file as the target """ with progressbar(self.metadata) as bar: for sample in bar: if sample.general.bestassemblyfile != 'NA': # Only need to perform baiting on FASTQ files if sample[self.analysistype].filetype == 'fastq': # Make the system call - allow for single- or paired-end reads if len(sample.general.fastqfiles) == 2: # Create the command to run the baiting - ref: primer file, k: shortest primer length # in1, in2: paired inputs, hdist: number of mismatches, interleaved: use interleaved output # outm: single, zipped output file of reads that match the target file sample[self.analysistype].bbdukcmd = \ 'bbduk.sh ref={primerfile} k={klength} in1={forward} in2={reverse} ' \ 'hdist={mismatches} threads={threads} interleaved=t outm={outfile}' \ .format(primerfile=self.formattedprimers, klength=self.klength, forward=sample.general.trimmedcorrectedfastqfiles[0], reverse=sample.general.trimmedcorrectedfastqfiles[1], mismatches=self.mismatches, threads=str(self.cpus), outfile=sample[self.analysistype].baitedfastq) else: sample[self.analysistype].bbdukcmd = \ 'bbduk.sh ref={primerfile} k={klength} in={fastq} hdist={mismatches} ' \ 'threads={threads} interleaved=t outm={outfile}' \ .format(primerfile=self.formattedprimers, klength=self.klength, fastq=sample.general.trimmedcorrectedfastqfiles[0], mismatches=self.mismatches, threads=str(self.cpus), outfile=sample[self.analysistype].baitedfastq) # Run the system call (if necessary) if not os.path.isfile(sample[self.analysistype].baitedfastq): run_subprocess(sample[self.analysistype].bbdukcmd)
python
def bait(self): """ Use bbduk to bait FASTQ reads from input files using the primer file as the target """ with progressbar(self.metadata) as bar: for sample in bar: if sample.general.bestassemblyfile != 'NA': # Only need to perform baiting on FASTQ files if sample[self.analysistype].filetype == 'fastq': # Make the system call - allow for single- or paired-end reads if len(sample.general.fastqfiles) == 2: # Create the command to run the baiting - ref: primer file, k: shortest primer length # in1, in2: paired inputs, hdist: number of mismatches, interleaved: use interleaved output # outm: single, zipped output file of reads that match the target file sample[self.analysistype].bbdukcmd = \ 'bbduk.sh ref={primerfile} k={klength} in1={forward} in2={reverse} ' \ 'hdist={mismatches} threads={threads} interleaved=t outm={outfile}' \ .format(primerfile=self.formattedprimers, klength=self.klength, forward=sample.general.trimmedcorrectedfastqfiles[0], reverse=sample.general.trimmedcorrectedfastqfiles[1], mismatches=self.mismatches, threads=str(self.cpus), outfile=sample[self.analysistype].baitedfastq) else: sample[self.analysistype].bbdukcmd = \ 'bbduk.sh ref={primerfile} k={klength} in={fastq} hdist={mismatches} ' \ 'threads={threads} interleaved=t outm={outfile}' \ .format(primerfile=self.formattedprimers, klength=self.klength, fastq=sample.general.trimmedcorrectedfastqfiles[0], mismatches=self.mismatches, threads=str(self.cpus), outfile=sample[self.analysistype].baitedfastq) # Run the system call (if necessary) if not os.path.isfile(sample[self.analysistype].baitedfastq): run_subprocess(sample[self.analysistype].bbdukcmd)
[ "def", "bait", "(", "self", ")", ":", "with", "progressbar", "(", "self", ".", "metadata", ")", "as", "bar", ":", "for", "sample", "in", "bar", ":", "if", "sample", ".", "general", ".", "bestassemblyfile", "!=", "'NA'", ":", "# Only need to perform baiting on FASTQ files", "if", "sample", "[", "self", ".", "analysistype", "]", ".", "filetype", "==", "'fastq'", ":", "# Make the system call - allow for single- or paired-end reads", "if", "len", "(", "sample", ".", "general", ".", "fastqfiles", ")", "==", "2", ":", "# Create the command to run the baiting - ref: primer file, k: shortest primer length", "# in1, in2: paired inputs, hdist: number of mismatches, interleaved: use interleaved output", "# outm: single, zipped output file of reads that match the target file", "sample", "[", "self", ".", "analysistype", "]", ".", "bbdukcmd", "=", "'bbduk.sh ref={primerfile} k={klength} in1={forward} in2={reverse} '", "'hdist={mismatches} threads={threads} interleaved=t outm={outfile}'", ".", "format", "(", "primerfile", "=", "self", ".", "formattedprimers", ",", "klength", "=", "self", ".", "klength", ",", "forward", "=", "sample", ".", "general", ".", "trimmedcorrectedfastqfiles", "[", "0", "]", ",", "reverse", "=", "sample", ".", "general", ".", "trimmedcorrectedfastqfiles", "[", "1", "]", ",", "mismatches", "=", "self", ".", "mismatches", ",", "threads", "=", "str", "(", "self", ".", "cpus", ")", ",", "outfile", "=", "sample", "[", "self", ".", "analysistype", "]", ".", "baitedfastq", ")", "else", ":", "sample", "[", "self", ".", "analysistype", "]", ".", "bbdukcmd", "=", "'bbduk.sh ref={primerfile} k={klength} in={fastq} hdist={mismatches} '", "'threads={threads} interleaved=t outm={outfile}'", ".", "format", "(", "primerfile", "=", "self", ".", "formattedprimers", ",", "klength", "=", "self", ".", "klength", ",", "fastq", "=", "sample", ".", "general", ".", "trimmedcorrectedfastqfiles", "[", "0", "]", ",", "mismatches", "=", "self", ".", "mismatches", ",", "threads", "=", "str", "(", "self", ".", "cpus", ")", ",", "outfile", "=", "sample", "[", "self", ".", "analysistype", "]", ".", "baitedfastq", ")", "# Run the system call (if necessary)", "if", "not", "os", ".", "path", ".", "isfile", "(", "sample", "[", "self", ".", "analysistype", "]", ".", "baitedfastq", ")", ":", "run_subprocess", "(", "sample", "[", "self", ".", "analysistype", "]", ".", "bbdukcmd", ")" ]
Use bbduk to bait FASTQ reads from input files using the primer file as the target
[ "Use", "bbduk", "to", "bait", "FASTQ", "reads", "from", "input", "files", "using", "the", "primer", "file", "as", "the", "target" ]
88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a
https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/primer_finder_bbduk.py#L201-L237
train
lowandrew/OLCTools
spadespipeline/primer_finder_bbduk.py
PrimerFinder.doublebait
def doublebait(self): """ In order to ensure that there is enough sequence data to bridge the gap between the two primers, the paired .fastq files produced above will be used to bait the original input .fastq files """ with progressbar(self.metadata) as bar: for sample in bar: if sample.general.bestassemblyfile != 'NA': if sample[self.analysistype].filetype == 'fastq': sample[self.analysistype].doublebaitedfastq = os.path.join( sample[self.analysistype].outputdir, '{at}_doubletargetMatches.fastq.gz'.format(at=self.analysistype)) # Make the system call if len(sample.general.fastqfiles) == 2: # Create the command to run the baiting sample[self.analysistype].bbdukcmd2 = \ 'bbduk.sh ref={baitfile} in1={forward} in2={reverse} hdist={mismatches} ' \ 'threads={threads} interleaved=t outm={outfile}' \ .format(baitfile=sample[self.analysistype].baitedfastq, forward=sample.general.trimmedcorrectedfastqfiles[0], reverse=sample.general.trimmedcorrectedfastqfiles[1], mismatches=self.mismatches, threads=str(self.cpus), outfile=sample[self.analysistype].doublebaitedfastq) else: sample[self.analysistype].bbdukcmd2 = \ 'bbduk.sh ref={baitfile} in={fastq} hdist={mismatches} threads={threads} ' \ 'interleaved=t outm={outfile}' \ .format(baitfile=sample[self.analysistype].baitedfastq, fastq=sample.general.trimmedcorrectedfastqfiles[0], mismatches=self.mismatches, threads=str(self.cpus), outfile=sample[self.analysistype].doublebaitedfastq) # Run the system call (if necessary) if not os.path.isfile(sample[self.analysistype].doublebaitedfastq): run_subprocess(sample[self.analysistype].bbdukcmd2)
python
def doublebait(self): """ In order to ensure that there is enough sequence data to bridge the gap between the two primers, the paired .fastq files produced above will be used to bait the original input .fastq files """ with progressbar(self.metadata) as bar: for sample in bar: if sample.general.bestassemblyfile != 'NA': if sample[self.analysistype].filetype == 'fastq': sample[self.analysistype].doublebaitedfastq = os.path.join( sample[self.analysistype].outputdir, '{at}_doubletargetMatches.fastq.gz'.format(at=self.analysistype)) # Make the system call if len(sample.general.fastqfiles) == 2: # Create the command to run the baiting sample[self.analysistype].bbdukcmd2 = \ 'bbduk.sh ref={baitfile} in1={forward} in2={reverse} hdist={mismatches} ' \ 'threads={threads} interleaved=t outm={outfile}' \ .format(baitfile=sample[self.analysistype].baitedfastq, forward=sample.general.trimmedcorrectedfastqfiles[0], reverse=sample.general.trimmedcorrectedfastqfiles[1], mismatches=self.mismatches, threads=str(self.cpus), outfile=sample[self.analysistype].doublebaitedfastq) else: sample[self.analysistype].bbdukcmd2 = \ 'bbduk.sh ref={baitfile} in={fastq} hdist={mismatches} threads={threads} ' \ 'interleaved=t outm={outfile}' \ .format(baitfile=sample[self.analysistype].baitedfastq, fastq=sample.general.trimmedcorrectedfastqfiles[0], mismatches=self.mismatches, threads=str(self.cpus), outfile=sample[self.analysistype].doublebaitedfastq) # Run the system call (if necessary) if not os.path.isfile(sample[self.analysistype].doublebaitedfastq): run_subprocess(sample[self.analysistype].bbdukcmd2)
[ "def", "doublebait", "(", "self", ")", ":", "with", "progressbar", "(", "self", ".", "metadata", ")", "as", "bar", ":", "for", "sample", "in", "bar", ":", "if", "sample", ".", "general", ".", "bestassemblyfile", "!=", "'NA'", ":", "if", "sample", "[", "self", ".", "analysistype", "]", ".", "filetype", "==", "'fastq'", ":", "sample", "[", "self", ".", "analysistype", "]", ".", "doublebaitedfastq", "=", "os", ".", "path", ".", "join", "(", "sample", "[", "self", ".", "analysistype", "]", ".", "outputdir", ",", "'{at}_doubletargetMatches.fastq.gz'", ".", "format", "(", "at", "=", "self", ".", "analysistype", ")", ")", "# Make the system call", "if", "len", "(", "sample", ".", "general", ".", "fastqfiles", ")", "==", "2", ":", "# Create the command to run the baiting", "sample", "[", "self", ".", "analysistype", "]", ".", "bbdukcmd2", "=", "'bbduk.sh ref={baitfile} in1={forward} in2={reverse} hdist={mismatches} '", "'threads={threads} interleaved=t outm={outfile}'", ".", "format", "(", "baitfile", "=", "sample", "[", "self", ".", "analysistype", "]", ".", "baitedfastq", ",", "forward", "=", "sample", ".", "general", ".", "trimmedcorrectedfastqfiles", "[", "0", "]", ",", "reverse", "=", "sample", ".", "general", ".", "trimmedcorrectedfastqfiles", "[", "1", "]", ",", "mismatches", "=", "self", ".", "mismatches", ",", "threads", "=", "str", "(", "self", ".", "cpus", ")", ",", "outfile", "=", "sample", "[", "self", ".", "analysistype", "]", ".", "doublebaitedfastq", ")", "else", ":", "sample", "[", "self", ".", "analysistype", "]", ".", "bbdukcmd2", "=", "'bbduk.sh ref={baitfile} in={fastq} hdist={mismatches} threads={threads} '", "'interleaved=t outm={outfile}'", ".", "format", "(", "baitfile", "=", "sample", "[", "self", ".", "analysistype", "]", ".", "baitedfastq", ",", "fastq", "=", "sample", ".", "general", ".", "trimmedcorrectedfastqfiles", "[", "0", "]", ",", "mismatches", "=", "self", ".", "mismatches", ",", "threads", "=", "str", "(", "self", ".", "cpus", ")", ",", "outfile", "=", "sample", "[", "self", ".", "analysistype", "]", ".", "doublebaitedfastq", ")", "# Run the system call (if necessary)", "if", "not", "os", ".", "path", ".", "isfile", "(", "sample", "[", "self", ".", "analysistype", "]", ".", "doublebaitedfastq", ")", ":", "run_subprocess", "(", "sample", "[", "self", ".", "analysistype", "]", ".", "bbdukcmd2", ")" ]
In order to ensure that there is enough sequence data to bridge the gap between the two primers, the paired .fastq files produced above will be used to bait the original input .fastq files
[ "In", "order", "to", "ensure", "that", "there", "is", "enough", "sequence", "data", "to", "bridge", "the", "gap", "between", "the", "two", "primers", "the", "paired", ".", "fastq", "files", "produced", "above", "will", "be", "used", "to", "bait", "the", "original", "input", ".", "fastq", "files" ]
88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a
https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/primer_finder_bbduk.py#L239-L274
train
lowandrew/OLCTools
spadespipeline/primer_finder_bbduk.py
PrimerFinder.assemble_amplicon_spades
def assemble_amplicon_spades(self): """ Use SPAdes to assemble the amplicons using the double-baited .fastq files """ for _ in self.metadata: # Send the threads to the merge method. :args is empty as I'm using threads = Thread(target=self.assemble, args=()) # Set the daemon to true - something to do with thread management threads.setDaemon(True) # Start the threading threads.start() for sample in self.metadata: if sample.general.bestassemblyfile != 'NA': if sample[self.analysistype].filetype == 'fastq': sample[self.analysistype].spadesoutput = os.path.join( sample[self.analysistype].outputdir, self.analysistype) # Removed --careful, as there was an issue with the .fastq reads following baiting - something to # do with the names, or the interleaving. Subsequent testing showed no real changes to assemblies if len(sample.general.fastqfiles) == 2: sample[self.analysistype].spadescommand = \ 'spades.py -k {klength} --only-assembler --12 {fastq} -o {outfile} -t {threads}'\ .format(klength=self.kmers, fastq=sample[self.analysistype].doublebaitedfastq, outfile=sample[self.analysistype].spadesoutput, threads=self.threads) else: sample[self.analysistype].spadescommand = \ 'spades.py -k {klength} --only-assembler -s {fastq} -o {outfile} -t {threads}' \ .format(klength=self.kmers, fastq=sample[self.analysistype].doublebaitedfastq, outfile=sample[self.analysistype].spadesoutput, threads=self.threads) sample[self.analysistype].assemblyfile = os.path.join(sample[self.analysistype].spadesoutput, 'contigs.fasta') self.queue.put(sample) self.queue.join()
python
def assemble_amplicon_spades(self): """ Use SPAdes to assemble the amplicons using the double-baited .fastq files """ for _ in self.metadata: # Send the threads to the merge method. :args is empty as I'm using threads = Thread(target=self.assemble, args=()) # Set the daemon to true - something to do with thread management threads.setDaemon(True) # Start the threading threads.start() for sample in self.metadata: if sample.general.bestassemblyfile != 'NA': if sample[self.analysistype].filetype == 'fastq': sample[self.analysistype].spadesoutput = os.path.join( sample[self.analysistype].outputdir, self.analysistype) # Removed --careful, as there was an issue with the .fastq reads following baiting - something to # do with the names, or the interleaving. Subsequent testing showed no real changes to assemblies if len(sample.general.fastqfiles) == 2: sample[self.analysistype].spadescommand = \ 'spades.py -k {klength} --only-assembler --12 {fastq} -o {outfile} -t {threads}'\ .format(klength=self.kmers, fastq=sample[self.analysistype].doublebaitedfastq, outfile=sample[self.analysistype].spadesoutput, threads=self.threads) else: sample[self.analysistype].spadescommand = \ 'spades.py -k {klength} --only-assembler -s {fastq} -o {outfile} -t {threads}' \ .format(klength=self.kmers, fastq=sample[self.analysistype].doublebaitedfastq, outfile=sample[self.analysistype].spadesoutput, threads=self.threads) sample[self.analysistype].assemblyfile = os.path.join(sample[self.analysistype].spadesoutput, 'contigs.fasta') self.queue.put(sample) self.queue.join()
[ "def", "assemble_amplicon_spades", "(", "self", ")", ":", "for", "_", "in", "self", ".", "metadata", ":", "# Send the threads to the merge method. :args is empty as I'm using", "threads", "=", "Thread", "(", "target", "=", "self", ".", "assemble", ",", "args", "=", "(", ")", ")", "# Set the daemon to true - something to do with thread management", "threads", ".", "setDaemon", "(", "True", ")", "# Start the threading", "threads", ".", "start", "(", ")", "for", "sample", "in", "self", ".", "metadata", ":", "if", "sample", ".", "general", ".", "bestassemblyfile", "!=", "'NA'", ":", "if", "sample", "[", "self", ".", "analysistype", "]", ".", "filetype", "==", "'fastq'", ":", "sample", "[", "self", ".", "analysistype", "]", ".", "spadesoutput", "=", "os", ".", "path", ".", "join", "(", "sample", "[", "self", ".", "analysistype", "]", ".", "outputdir", ",", "self", ".", "analysistype", ")", "# Removed --careful, as there was an issue with the .fastq reads following baiting - something to", "# do with the names, or the interleaving. Subsequent testing showed no real changes to assemblies", "if", "len", "(", "sample", ".", "general", ".", "fastqfiles", ")", "==", "2", ":", "sample", "[", "self", ".", "analysistype", "]", ".", "spadescommand", "=", "'spades.py -k {klength} --only-assembler --12 {fastq} -o {outfile} -t {threads}'", ".", "format", "(", "klength", "=", "self", ".", "kmers", ",", "fastq", "=", "sample", "[", "self", ".", "analysistype", "]", ".", "doublebaitedfastq", ",", "outfile", "=", "sample", "[", "self", ".", "analysistype", "]", ".", "spadesoutput", ",", "threads", "=", "self", ".", "threads", ")", "else", ":", "sample", "[", "self", ".", "analysistype", "]", ".", "spadescommand", "=", "'spades.py -k {klength} --only-assembler -s {fastq} -o {outfile} -t {threads}'", ".", "format", "(", "klength", "=", "self", ".", "kmers", ",", "fastq", "=", "sample", "[", "self", ".", "analysistype", "]", ".", "doublebaitedfastq", ",", "outfile", "=", "sample", "[", "self", ".", "analysistype", "]", ".", "spadesoutput", ",", "threads", "=", "self", ".", "threads", ")", "sample", "[", "self", ".", "analysistype", "]", ".", "assemblyfile", "=", "os", ".", "path", ".", "join", "(", "sample", "[", "self", ".", "analysistype", "]", ".", "spadesoutput", ",", "'contigs.fasta'", ")", "self", ".", "queue", ".", "put", "(", "sample", ")", "self", ".", "queue", ".", "join", "(", ")" ]
Use SPAdes to assemble the amplicons using the double-baited .fastq files
[ "Use", "SPAdes", "to", "assemble", "the", "amplicons", "using", "the", "double", "-", "baited", ".", "fastq", "files" ]
88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a
https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/primer_finder_bbduk.py#L310-L345
train
lowandrew/OLCTools
spadespipeline/primer_finder_bbduk.py
PrimerFinder.make_blastdb
def make_blastdb(self): """ Create a BLAST database of the primer file """ # remove the path and the file extension for easier future globbing db = os.path.splitext(self.formattedprimers)[0] nhr = '{db}.nhr'.format(db=db) # add nhr for searching if not os.path.isfile(str(nhr)): # Create the databases command = 'makeblastdb -in {primerfile} -parse_seqids -max_file_sz 2GB -dbtype nucl -out {outfile}'\ .format(primerfile=self.formattedprimers, outfile=db) run_subprocess(command)
python
def make_blastdb(self): """ Create a BLAST database of the primer file """ # remove the path and the file extension for easier future globbing db = os.path.splitext(self.formattedprimers)[0] nhr = '{db}.nhr'.format(db=db) # add nhr for searching if not os.path.isfile(str(nhr)): # Create the databases command = 'makeblastdb -in {primerfile} -parse_seqids -max_file_sz 2GB -dbtype nucl -out {outfile}'\ .format(primerfile=self.formattedprimers, outfile=db) run_subprocess(command)
[ "def", "make_blastdb", "(", "self", ")", ":", "# remove the path and the file extension for easier future globbing", "db", "=", "os", ".", "path", ".", "splitext", "(", "self", ".", "formattedprimers", ")", "[", "0", "]", "nhr", "=", "'{db}.nhr'", ".", "format", "(", "db", "=", "db", ")", "# add nhr for searching", "if", "not", "os", ".", "path", ".", "isfile", "(", "str", "(", "nhr", ")", ")", ":", "# Create the databases", "command", "=", "'makeblastdb -in {primerfile} -parse_seqids -max_file_sz 2GB -dbtype nucl -out {outfile}'", ".", "format", "(", "primerfile", "=", "self", ".", "formattedprimers", ",", "outfile", "=", "db", ")", "run_subprocess", "(", "command", ")" ]
Create a BLAST database of the primer file
[ "Create", "a", "BLAST", "database", "of", "the", "primer", "file" ]
88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a
https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/primer_finder_bbduk.py#L357-L369
train
lowandrew/OLCTools
spadespipeline/primer_finder_bbduk.py
PrimerFinder.ampliconclear
def ampliconclear(self): """ Clear previously created amplicon files to prepare for the appending of data to fresh files """ for sample in self.metadata: # Set the name of the amplicon FASTA file sample[self.analysistype].ampliconfile = os.path.join( sample[self.analysistype].outputdir, '{sn}_amplicons.fa'.format(sn=sample.name)) try: os.remove(sample[self.analysistype].ampliconfile) except IOError: pass
python
def ampliconclear(self): """ Clear previously created amplicon files to prepare for the appending of data to fresh files """ for sample in self.metadata: # Set the name of the amplicon FASTA file sample[self.analysistype].ampliconfile = os.path.join( sample[self.analysistype].outputdir, '{sn}_amplicons.fa'.format(sn=sample.name)) try: os.remove(sample[self.analysistype].ampliconfile) except IOError: pass
[ "def", "ampliconclear", "(", "self", ")", ":", "for", "sample", "in", "self", ".", "metadata", ":", "# Set the name of the amplicon FASTA file", "sample", "[", "self", ".", "analysistype", "]", ".", "ampliconfile", "=", "os", ".", "path", ".", "join", "(", "sample", "[", "self", ".", "analysistype", "]", ".", "outputdir", ",", "'{sn}_amplicons.fa'", ".", "format", "(", "sn", "=", "sample", ".", "name", ")", ")", "try", ":", "os", ".", "remove", "(", "sample", "[", "self", ".", "analysistype", "]", ".", "ampliconfile", ")", "except", "IOError", ":", "pass" ]
Clear previously created amplicon files to prepare for the appending of data to fresh files
[ "Clear", "previously", "created", "amplicon", "files", "to", "prepare", "for", "the", "appending", "of", "data", "to", "fresh", "files" ]
88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a
https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/primer_finder_bbduk.py#L596-L607
train
kevinconway/venvctrl
venvctrl/venv/base.py
VenvFile.writeline
def writeline(self, line, line_number): """Rewrite a single line in the file. Args: line (str): The new text to write to the file. line_number (int): The line of the file to rewrite. Numbering starts at 0. """ tmp_file = tempfile.TemporaryFile('w+') if not line.endswith(os.linesep): line += os.linesep try: with open(self.path, 'r') as file_handle: for count, new_line in enumerate(file_handle): if count == line_number: new_line = line tmp_file.write(new_line) tmp_file.seek(0) with open(self.path, 'w') as file_handle: for new_line in tmp_file: file_handle.write(new_line) finally: tmp_file.close()
python
def writeline(self, line, line_number): """Rewrite a single line in the file. Args: line (str): The new text to write to the file. line_number (int): The line of the file to rewrite. Numbering starts at 0. """ tmp_file = tempfile.TemporaryFile('w+') if not line.endswith(os.linesep): line += os.linesep try: with open(self.path, 'r') as file_handle: for count, new_line in enumerate(file_handle): if count == line_number: new_line = line tmp_file.write(new_line) tmp_file.seek(0) with open(self.path, 'w') as file_handle: for new_line in tmp_file: file_handle.write(new_line) finally: tmp_file.close()
[ "def", "writeline", "(", "self", ",", "line", ",", "line_number", ")", ":", "tmp_file", "=", "tempfile", ".", "TemporaryFile", "(", "'w+'", ")", "if", "not", "line", ".", "endswith", "(", "os", ".", "linesep", ")", ":", "line", "+=", "os", ".", "linesep", "try", ":", "with", "open", "(", "self", ".", "path", ",", "'r'", ")", "as", "file_handle", ":", "for", "count", ",", "new_line", "in", "enumerate", "(", "file_handle", ")", ":", "if", "count", "==", "line_number", ":", "new_line", "=", "line", "tmp_file", ".", "write", "(", "new_line", ")", "tmp_file", ".", "seek", "(", "0", ")", "with", "open", "(", "self", ".", "path", ",", "'w'", ")", "as", "file_handle", ":", "for", "new_line", "in", "tmp_file", ":", "file_handle", ".", "write", "(", "new_line", ")", "finally", ":", "tmp_file", ".", "close", "(", ")" ]
Rewrite a single line in the file. Args: line (str): The new text to write to the file. line_number (int): The line of the file to rewrite. Numbering starts at 0.
[ "Rewrite", "a", "single", "line", "in", "the", "file", "." ]
36d4e0e4d5ebced6385a6ade1198f4769ff2df41
https://github.com/kevinconway/venvctrl/blob/36d4e0e4d5ebced6385a6ade1198f4769ff2df41/venvctrl/venv/base.py#L70-L102
train
kevinconway/venvctrl
venvctrl/venv/base.py
VenvDir.paths
def paths(self): """Get an iter of VenvPaths within the directory.""" contents = os.listdir(self.path) contents = (os.path.join(self.path, path) for path in contents) contents = (VenvPath(path) for path in contents) return contents
python
def paths(self): """Get an iter of VenvPaths within the directory.""" contents = os.listdir(self.path) contents = (os.path.join(self.path, path) for path in contents) contents = (VenvPath(path) for path in contents) return contents
[ "def", "paths", "(", "self", ")", ":", "contents", "=", "os", ".", "listdir", "(", "self", ".", "path", ")", "contents", "=", "(", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "path", ")", "for", "path", "in", "contents", ")", "contents", "=", "(", "VenvPath", "(", "path", ")", "for", "path", "in", "contents", ")", "return", "contents" ]
Get an iter of VenvPaths within the directory.
[ "Get", "an", "iter", "of", "VenvPaths", "within", "the", "directory", "." ]
36d4e0e4d5ebced6385a6ade1198f4769ff2df41
https://github.com/kevinconway/venvctrl/blob/36d4e0e4d5ebced6385a6ade1198f4769ff2df41/venvctrl/venv/base.py#L110-L115
train
kevinconway/venvctrl
venvctrl/venv/base.py
BinFile.shebang
def shebang(self): """Get the file shebang if is has one.""" with open(self.path, 'rb') as file_handle: hashtag = file_handle.read(2) if hashtag == b'#!': file_handle.seek(0) return file_handle.readline().decode('utf8') return None
python
def shebang(self): """Get the file shebang if is has one.""" with open(self.path, 'rb') as file_handle: hashtag = file_handle.read(2) if hashtag == b'#!': file_handle.seek(0) return file_handle.readline().decode('utf8') return None
[ "def", "shebang", "(", "self", ")", ":", "with", "open", "(", "self", ".", "path", ",", "'rb'", ")", "as", "file_handle", ":", "hashtag", "=", "file_handle", ".", "read", "(", "2", ")", "if", "hashtag", "==", "b'#!'", ":", "file_handle", ".", "seek", "(", "0", ")", "return", "file_handle", ".", "readline", "(", ")", ".", "decode", "(", "'utf8'", ")", "return", "None" ]
Get the file shebang if is has one.
[ "Get", "the", "file", "shebang", "if", "is", "has", "one", "." ]
36d4e0e4d5ebced6385a6ade1198f4769ff2df41
https://github.com/kevinconway/venvctrl/blob/36d4e0e4d5ebced6385a6ade1198f4769ff2df41/venvctrl/venv/base.py#L151-L160
train
kevinconway/venvctrl
venvctrl/venv/base.py
BinFile.shebang
def shebang(self, new_shebang): """Write a new shebang to the file. Raises: ValueError: If the file has no shebang to modify. ValueError: If the new shebang is invalid. """ if not self.shebang: raise ValueError('Cannot modify a shebang if it does not exist.') if not new_shebang.startswith('#!'): raise ValueError('Invalid shebang.') self.writeline(new_shebang, 0)
python
def shebang(self, new_shebang): """Write a new shebang to the file. Raises: ValueError: If the file has no shebang to modify. ValueError: If the new shebang is invalid. """ if not self.shebang: raise ValueError('Cannot modify a shebang if it does not exist.') if not new_shebang.startswith('#!'): raise ValueError('Invalid shebang.') self.writeline(new_shebang, 0)
[ "def", "shebang", "(", "self", ",", "new_shebang", ")", ":", "if", "not", "self", ".", "shebang", ":", "raise", "ValueError", "(", "'Cannot modify a shebang if it does not exist.'", ")", "if", "not", "new_shebang", ".", "startswith", "(", "'#!'", ")", ":", "raise", "ValueError", "(", "'Invalid shebang.'", ")", "self", ".", "writeline", "(", "new_shebang", ",", "0", ")" ]
Write a new shebang to the file. Raises: ValueError: If the file has no shebang to modify. ValueError: If the new shebang is invalid.
[ "Write", "a", "new", "shebang", "to", "the", "file", "." ]
36d4e0e4d5ebced6385a6ade1198f4769ff2df41
https://github.com/kevinconway/venvctrl/blob/36d4e0e4d5ebced6385a6ade1198f4769ff2df41/venvctrl/venv/base.py#L163-L178
train
kevinconway/venvctrl
venvctrl/venv/base.py
ActivateFile._find_vpath
def _find_vpath(self): """Find the VIRTUAL_ENV path entry.""" with open(self.path, 'r') as file_handle: for count, line in enumerate(file_handle): match = self.read_pattern.match(line) if match: return match.group(1), count return None, None
python
def _find_vpath(self): """Find the VIRTUAL_ENV path entry.""" with open(self.path, 'r') as file_handle: for count, line in enumerate(file_handle): match = self.read_pattern.match(line) if match: return match.group(1), count return None, None
[ "def", "_find_vpath", "(", "self", ")", ":", "with", "open", "(", "self", ".", "path", ",", "'r'", ")", "as", "file_handle", ":", "for", "count", ",", "line", "in", "enumerate", "(", "file_handle", ")", ":", "match", "=", "self", ".", "read_pattern", ".", "match", "(", "line", ")", "if", "match", ":", "return", "match", ".", "group", "(", "1", ")", ",", "count", "return", "None", ",", "None" ]
Find the VIRTUAL_ENV path entry.
[ "Find", "the", "VIRTUAL_ENV", "path", "entry", "." ]
36d4e0e4d5ebced6385a6ade1198f4769ff2df41
https://github.com/kevinconway/venvctrl/blob/36d4e0e4d5ebced6385a6ade1198f4769ff2df41/venvctrl/venv/base.py#L188-L199
train
kevinconway/venvctrl
venvctrl/venv/base.py
ActivateFile.vpath
def vpath(self, new_vpath): """Change the path to the virtual environment.""" _, line_number = self._find_vpath() new_vpath = self.write_pattern.format(new_vpath) self.writeline(new_vpath, line_number)
python
def vpath(self, new_vpath): """Change the path to the virtual environment.""" _, line_number = self._find_vpath() new_vpath = self.write_pattern.format(new_vpath) self.writeline(new_vpath, line_number)
[ "def", "vpath", "(", "self", ",", "new_vpath", ")", ":", "_", ",", "line_number", "=", "self", ".", "_find_vpath", "(", ")", "new_vpath", "=", "self", ".", "write_pattern", ".", "format", "(", "new_vpath", ")", "self", ".", "writeline", "(", "new_vpath", ",", "line_number", ")" ]
Change the path to the virtual environment.
[ "Change", "the", "path", "to", "the", "virtual", "environment", "." ]
36d4e0e4d5ebced6385a6ade1198f4769ff2df41
https://github.com/kevinconway/venvctrl/blob/36d4e0e4d5ebced6385a6ade1198f4769ff2df41/venvctrl/venv/base.py#L207-L211
train
portfors-lab/sparkle
sparkle/gui/stim/components/qcomponents.py
wrapComponent
def wrapComponent(comp): """Wraps a StimulusComponent with a class containing methods for painting and editing. Class will in fact, be the same as the component provided, but will also be a subclass of QStimulusComponent :param comp: Component to wrap :type comp: subclass of AbstractStimulusComponent :returns: sublass of AbstractStimulusComponent and QStimulusComponent """ # if already wrapped, return object if hasattr(comp, 'paint'): return comp # to avoid manually creating a mapping, get all classes in # this module, assume they are the class name appended with Q current_module = sys.modules[__name__] module_classes = {name[1:]: obj for name, obj in inspect.getmembers(sys.modules[__name__], inspect.isclass) if obj.__module__ == __name__} # print __name__, module_classes stimclass = comp.__class__.__name__ qclass = module_classes.get(stimclass, QStimulusComponent) return qclass(comp)
python
def wrapComponent(comp): """Wraps a StimulusComponent with a class containing methods for painting and editing. Class will in fact, be the same as the component provided, but will also be a subclass of QStimulusComponent :param comp: Component to wrap :type comp: subclass of AbstractStimulusComponent :returns: sublass of AbstractStimulusComponent and QStimulusComponent """ # if already wrapped, return object if hasattr(comp, 'paint'): return comp # to avoid manually creating a mapping, get all classes in # this module, assume they are the class name appended with Q current_module = sys.modules[__name__] module_classes = {name[1:]: obj for name, obj in inspect.getmembers(sys.modules[__name__], inspect.isclass) if obj.__module__ == __name__} # print __name__, module_classes stimclass = comp.__class__.__name__ qclass = module_classes.get(stimclass, QStimulusComponent) return qclass(comp)
[ "def", "wrapComponent", "(", "comp", ")", ":", "# if already wrapped, return object", "if", "hasattr", "(", "comp", ",", "'paint'", ")", ":", "return", "comp", "# to avoid manually creating a mapping, get all classes in ", "# this module, assume they are the class name appended with Q", "current_module", "=", "sys", ".", "modules", "[", "__name__", "]", "module_classes", "=", "{", "name", "[", "1", ":", "]", ":", "obj", "for", "name", ",", "obj", "in", "inspect", ".", "getmembers", "(", "sys", ".", "modules", "[", "__name__", "]", ",", "inspect", ".", "isclass", ")", "if", "obj", ".", "__module__", "==", "__name__", "}", "# print __name__, module_classes", "stimclass", "=", "comp", ".", "__class__", ".", "__name__", "qclass", "=", "module_classes", ".", "get", "(", "stimclass", ",", "QStimulusComponent", ")", "return", "qclass", "(", "comp", ")" ]
Wraps a StimulusComponent with a class containing methods for painting and editing. Class will in fact, be the same as the component provided, but will also be a subclass of QStimulusComponent :param comp: Component to wrap :type comp: subclass of AbstractStimulusComponent :returns: sublass of AbstractStimulusComponent and QStimulusComponent
[ "Wraps", "a", "StimulusComponent", "with", "a", "class", "containing", "methods", "for", "painting", "and", "editing", ".", "Class", "will", "in", "fact", "be", "the", "same", "as", "the", "component", "provided", "but", "will", "also", "be", "a", "subclass", "of", "QStimulusComponent" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/components/qcomponents.py#L20-L41
train
portfors-lab/sparkle
sparkle/gui/stim/components/qcomponents.py
QStimulusComponent.paint
def paint(self, painter, rect, palette): """Draws a generic visual representation for this component Re-implement this to get a custom graphic in builder editor :param painter: Use this class to do the drawing :type painter: :qtdoc:`QPainter` :param rect: boundary of the delegate for this component, painting should be done inside this boundary :type rect: :qtdoc:`QRect` :param palette: contains color groups to use, if wanted :type palette: :qtdoc:`QPalette` """ painter.save() image = img.default() painter.drawImage(rect, image) # set text color painter.setPen(QtGui.QPen(QtCore.Qt.red)) painter.drawText(rect, QtCore.Qt.AlignLeft, self.__class__.__name__) painter.restore()
python
def paint(self, painter, rect, palette): """Draws a generic visual representation for this component Re-implement this to get a custom graphic in builder editor :param painter: Use this class to do the drawing :type painter: :qtdoc:`QPainter` :param rect: boundary of the delegate for this component, painting should be done inside this boundary :type rect: :qtdoc:`QRect` :param palette: contains color groups to use, if wanted :type palette: :qtdoc:`QPalette` """ painter.save() image = img.default() painter.drawImage(rect, image) # set text color painter.setPen(QtGui.QPen(QtCore.Qt.red)) painter.drawText(rect, QtCore.Qt.AlignLeft, self.__class__.__name__) painter.restore()
[ "def", "paint", "(", "self", ",", "painter", ",", "rect", ",", "palette", ")", ":", "painter", ".", "save", "(", ")", "image", "=", "img", ".", "default", "(", ")", "painter", ".", "drawImage", "(", "rect", ",", "image", ")", "# set text color", "painter", ".", "setPen", "(", "QtGui", ".", "QPen", "(", "QtCore", ".", "Qt", ".", "red", ")", ")", "painter", ".", "drawText", "(", "rect", ",", "QtCore", ".", "Qt", ".", "AlignLeft", ",", "self", ".", "__class__", ".", "__name__", ")", "painter", ".", "restore", "(", ")" ]
Draws a generic visual representation for this component Re-implement this to get a custom graphic in builder editor :param painter: Use this class to do the drawing :type painter: :qtdoc:`QPainter` :param rect: boundary of the delegate for this component, painting should be done inside this boundary :type rect: :qtdoc:`QRect` :param palette: contains color groups to use, if wanted :type palette: :qtdoc:`QPalette`
[ "Draws", "a", "generic", "visual", "representation", "for", "this", "component" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/components/qcomponents.py#L56-L77
train
Frzk/Ellis
ellis/filter.py
Filter.replace_tags
def replace_tags(cls, raw_filter): """ Searches for known tags in the given string and replaces them with the corresponding regular expression. *raw_filter* is an (optionnaly tagged) regular expression. Returns the regular expression with known tags replaces by the corresponding regular expression. """ for k, v in iter(cls.known_tags.items()): raw_filter = raw_filter.replace(k, v) return raw_filter
python
def replace_tags(cls, raw_filter): """ Searches for known tags in the given string and replaces them with the corresponding regular expression. *raw_filter* is an (optionnaly tagged) regular expression. Returns the regular expression with known tags replaces by the corresponding regular expression. """ for k, v in iter(cls.known_tags.items()): raw_filter = raw_filter.replace(k, v) return raw_filter
[ "def", "replace_tags", "(", "cls", ",", "raw_filter", ")", ":", "for", "k", ",", "v", "in", "iter", "(", "cls", ".", "known_tags", ".", "items", "(", ")", ")", ":", "raw_filter", "=", "raw_filter", ".", "replace", "(", "k", ",", "v", ")", "return", "raw_filter" ]
Searches for known tags in the given string and replaces them with the corresponding regular expression. *raw_filter* is an (optionnaly tagged) regular expression. Returns the regular expression with known tags replaces by the corresponding regular expression.
[ "Searches", "for", "known", "tags", "in", "the", "given", "string", "and", "replaces", "them", "with", "the", "corresponding", "regular", "expression", "." ]
39ce8987cbc503354cf1f45927344186a8b18363
https://github.com/Frzk/Ellis/blob/39ce8987cbc503354cf1f45927344186a8b18363/ellis/filter.py#L72-L85
train
Frzk/Ellis
ellis/filter.py
Filter.from_string
def from_string(cls, raw_filter, rule_limit): """ Creates a new Filter instance from the given string. *raw_filter* is the raw filter : a string that may contain several regular expressions (separated by a newline char) and tags. *rule_limit* is the Rule's limit above which the Action is executed. Raises :class:`exceptions.ValueError` if the given string could not be compiled in at least one suitable :class:`re.RegexObject`. Returns a new :class:`Filter` instance. """ parsed_filter = cls.replace_tags(raw_filter) regexes = cls.build_regex_list(parsed_filter, rule_limit) return cls(regexes)
python
def from_string(cls, raw_filter, rule_limit): """ Creates a new Filter instance from the given string. *raw_filter* is the raw filter : a string that may contain several regular expressions (separated by a newline char) and tags. *rule_limit* is the Rule's limit above which the Action is executed. Raises :class:`exceptions.ValueError` if the given string could not be compiled in at least one suitable :class:`re.RegexObject`. Returns a new :class:`Filter` instance. """ parsed_filter = cls.replace_tags(raw_filter) regexes = cls.build_regex_list(parsed_filter, rule_limit) return cls(regexes)
[ "def", "from_string", "(", "cls", ",", "raw_filter", ",", "rule_limit", ")", ":", "parsed_filter", "=", "cls", ".", "replace_tags", "(", "raw_filter", ")", "regexes", "=", "cls", ".", "build_regex_list", "(", "parsed_filter", ",", "rule_limit", ")", "return", "cls", "(", "regexes", ")" ]
Creates a new Filter instance from the given string. *raw_filter* is the raw filter : a string that may contain several regular expressions (separated by a newline char) and tags. *rule_limit* is the Rule's limit above which the Action is executed. Raises :class:`exceptions.ValueError` if the given string could not be compiled in at least one suitable :class:`re.RegexObject`. Returns a new :class:`Filter` instance.
[ "Creates", "a", "new", "Filter", "instance", "from", "the", "given", "string", "." ]
39ce8987cbc503354cf1f45927344186a8b18363
https://github.com/Frzk/Ellis/blob/39ce8987cbc503354cf1f45927344186a8b18363/ellis/filter.py#L135-L152
train
portfors-lab/sparkle
sparkle/gui/dialogs/view_dlg.py
ViewSettingsDialog.values
def values(self): """Gets user inputs :returns: dict of inputs: | *'fontsz'*: int -- font size for text throughout the GUI | *'display_attributes'*: dict -- what attributes of stimuli to report as they are being presented """ result = {} result['fontsz'] = self.ui.fontszSpnbx.value() result['display_attributes'] = self.ui.detailWidget.getCheckedDetails() return result
python
def values(self): """Gets user inputs :returns: dict of inputs: | *'fontsz'*: int -- font size for text throughout the GUI | *'display_attributes'*: dict -- what attributes of stimuli to report as they are being presented """ result = {} result['fontsz'] = self.ui.fontszSpnbx.value() result['display_attributes'] = self.ui.detailWidget.getCheckedDetails() return result
[ "def", "values", "(", "self", ")", ":", "result", "=", "{", "}", "result", "[", "'fontsz'", "]", "=", "self", ".", "ui", ".", "fontszSpnbx", ".", "value", "(", ")", "result", "[", "'display_attributes'", "]", "=", "self", ".", "ui", ".", "detailWidget", ".", "getCheckedDetails", "(", ")", "return", "result" ]
Gets user inputs :returns: dict of inputs: | *'fontsz'*: int -- font size for text throughout the GUI | *'display_attributes'*: dict -- what attributes of stimuli to report as they are being presented
[ "Gets", "user", "inputs" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/dialogs/view_dlg.py#L21-L31
train
wylee/runcommands
runcommands/util/misc.py
flatten_args
def flatten_args(args: list, join=False, *, empty=(None, [], (), '')) -> list: """Flatten args and remove empty items. Args: args: A list of items (typically but not necessarily strings), which may contain sub-lists, that will be flattened into a single list with empty items removed. Empty items include ``None`` and empty lists, tuples, and strings. join: If ``True`` or a string, the final flattened list will be joined into a single string. The default join string is a space. empty: Items that are considered empty. Returns: list|str: The list of args flattened with empty items removed and the remaining items converted to strings. If ``join`` is specified, the list of flattened args will be joined into a single string. Examples:: >>> flatten_args([]) [] >>> flatten_args(()) [] >>> flatten_args([(), (), [(), ()]]) [] >>> flatten_args(['executable', '--flag' if True else None, ('--option', 'value'), [None]]) ['executable', '--flag', '--option', 'value'] >>> flatten_args(['executable', '--option', 0]) ['executable', '--option', '0'] """ flat_args = [] non_empty_args = (arg for arg in args if arg not in empty) for arg in non_empty_args: if isinstance(arg, (list, tuple)): flat_args.extend(flatten_args(arg)) else: flat_args.append(str(arg)) if join: join = ' ' if join is True else join flat_args = join.join(flat_args) return flat_args
python
def flatten_args(args: list, join=False, *, empty=(None, [], (), '')) -> list: """Flatten args and remove empty items. Args: args: A list of items (typically but not necessarily strings), which may contain sub-lists, that will be flattened into a single list with empty items removed. Empty items include ``None`` and empty lists, tuples, and strings. join: If ``True`` or a string, the final flattened list will be joined into a single string. The default join string is a space. empty: Items that are considered empty. Returns: list|str: The list of args flattened with empty items removed and the remaining items converted to strings. If ``join`` is specified, the list of flattened args will be joined into a single string. Examples:: >>> flatten_args([]) [] >>> flatten_args(()) [] >>> flatten_args([(), (), [(), ()]]) [] >>> flatten_args(['executable', '--flag' if True else None, ('--option', 'value'), [None]]) ['executable', '--flag', '--option', 'value'] >>> flatten_args(['executable', '--option', 0]) ['executable', '--option', '0'] """ flat_args = [] non_empty_args = (arg for arg in args if arg not in empty) for arg in non_empty_args: if isinstance(arg, (list, tuple)): flat_args.extend(flatten_args(arg)) else: flat_args.append(str(arg)) if join: join = ' ' if join is True else join flat_args = join.join(flat_args) return flat_args
[ "def", "flatten_args", "(", "args", ":", "list", ",", "join", "=", "False", ",", "*", ",", "empty", "=", "(", "None", ",", "[", "]", ",", "(", ")", ",", "''", ")", ")", "->", "list", ":", "flat_args", "=", "[", "]", "non_empty_args", "=", "(", "arg", "for", "arg", "in", "args", "if", "arg", "not", "in", "empty", ")", "for", "arg", "in", "non_empty_args", ":", "if", "isinstance", "(", "arg", ",", "(", "list", ",", "tuple", ")", ")", ":", "flat_args", ".", "extend", "(", "flatten_args", "(", "arg", ")", ")", "else", ":", "flat_args", ".", "append", "(", "str", "(", "arg", ")", ")", "if", "join", ":", "join", "=", "' '", "if", "join", "is", "True", "else", "join", "flat_args", "=", "join", ".", "join", "(", "flat_args", ")", "return", "flat_args" ]
Flatten args and remove empty items. Args: args: A list of items (typically but not necessarily strings), which may contain sub-lists, that will be flattened into a single list with empty items removed. Empty items include ``None`` and empty lists, tuples, and strings. join: If ``True`` or a string, the final flattened list will be joined into a single string. The default join string is a space. empty: Items that are considered empty. Returns: list|str: The list of args flattened with empty items removed and the remaining items converted to strings. If ``join`` is specified, the list of flattened args will be joined into a single string. Examples:: >>> flatten_args([]) [] >>> flatten_args(()) [] >>> flatten_args([(), (), [(), ()]]) [] >>> flatten_args(['executable', '--flag' if True else None, ('--option', 'value'), [None]]) ['executable', '--flag', '--option', 'value'] >>> flatten_args(['executable', '--option', 0]) ['executable', '--option', '0']
[ "Flatten", "args", "and", "remove", "empty", "items", "." ]
b1d7c262885b9ced7ab89b63562f5464ca9970fe
https://github.com/wylee/runcommands/blob/b1d7c262885b9ced7ab89b63562f5464ca9970fe/runcommands/util/misc.py#L18-L61
train
wylee/runcommands
runcommands/util/misc.py
load_object
def load_object(obj) -> object: """Load an object. Args: obj (str|object): Load the indicated object if this is a string; otherwise, return the object as is. To load a module, pass a dotted path like 'package.module'; to load an an object from a module pass a path like 'package.module:name'. Returns: object """ if isinstance(obj, str): if ':' in obj: module_name, obj_name = obj.split(':') if not module_name: module_name = '.' else: module_name = obj obj = importlib.import_module(module_name) if obj_name: attrs = obj_name.split('.') for attr in attrs: obj = getattr(obj, attr) return obj
python
def load_object(obj) -> object: """Load an object. Args: obj (str|object): Load the indicated object if this is a string; otherwise, return the object as is. To load a module, pass a dotted path like 'package.module'; to load an an object from a module pass a path like 'package.module:name'. Returns: object """ if isinstance(obj, str): if ':' in obj: module_name, obj_name = obj.split(':') if not module_name: module_name = '.' else: module_name = obj obj = importlib.import_module(module_name) if obj_name: attrs = obj_name.split('.') for attr in attrs: obj = getattr(obj, attr) return obj
[ "def", "load_object", "(", "obj", ")", "->", "object", ":", "if", "isinstance", "(", "obj", ",", "str", ")", ":", "if", "':'", "in", "obj", ":", "module_name", ",", "obj_name", "=", "obj", ".", "split", "(", "':'", ")", "if", "not", "module_name", ":", "module_name", "=", "'.'", "else", ":", "module_name", "=", "obj", "obj", "=", "importlib", ".", "import_module", "(", "module_name", ")", "if", "obj_name", ":", "attrs", "=", "obj_name", ".", "split", "(", "'.'", ")", "for", "attr", "in", "attrs", ":", "obj", "=", "getattr", "(", "obj", ",", "attr", ")", "return", "obj" ]
Load an object. Args: obj (str|object): Load the indicated object if this is a string; otherwise, return the object as is. To load a module, pass a dotted path like 'package.module'; to load an an object from a module pass a path like 'package.module:name'. Returns: object
[ "Load", "an", "object", "." ]
b1d7c262885b9ced7ab89b63562f5464ca9970fe
https://github.com/wylee/runcommands/blob/b1d7c262885b9ced7ab89b63562f5464ca9970fe/runcommands/util/misc.py#L87-L114
train
Frzk/Ellis
ellis_actions/shell_commander.py
ShellCommander.escape_args
def escape_args(cls, *args): """ Transforms the given list of unescaped arguments into a suitable, shell-escaped str that is ready to be append to the command. Removes whitespaces and shell metacharacters for each argument in given args. """ escaped_args = [shlex.quote(str(arg)) for arg in args] return " ".join(escaped_args)
python
def escape_args(cls, *args): """ Transforms the given list of unescaped arguments into a suitable, shell-escaped str that is ready to be append to the command. Removes whitespaces and shell metacharacters for each argument in given args. """ escaped_args = [shlex.quote(str(arg)) for arg in args] return " ".join(escaped_args)
[ "def", "escape_args", "(", "cls", ",", "*", "args", ")", ":", "escaped_args", "=", "[", "shlex", ".", "quote", "(", "str", "(", "arg", ")", ")", "for", "arg", "in", "args", "]", "return", "\" \"", ".", "join", "(", "escaped_args", ")" ]
Transforms the given list of unescaped arguments into a suitable, shell-escaped str that is ready to be append to the command. Removes whitespaces and shell metacharacters for each argument in given args.
[ "Transforms", "the", "given", "list", "of", "unescaped", "arguments", "into", "a", "suitable", "shell", "-", "escaped", "str", "that", "is", "ready", "to", "be", "append", "to", "the", "command", "." ]
39ce8987cbc503354cf1f45927344186a8b18363
https://github.com/Frzk/Ellis/blob/39ce8987cbc503354cf1f45927344186a8b18363/ellis_actions/shell_commander.py#L52-L63
train
ArabellaTech/django-basic-cms
basic_cms/templatetags/pages_tags.py
pages_admin_menu
def pages_admin_menu(context, page): """Render the admin table of pages.""" request = context.get('request', None) expanded = False if request and "tree_expanded" in request.COOKIES: cookie_string = urllib.unquote(request.COOKIES['tree_expanded']) if cookie_string: ids = [int(id) for id in urllib.unquote(request.COOKIES['tree_expanded']).split(',')] if page.id in ids: expanded = True context.update({'expanded': expanded, 'page': page}) return context
python
def pages_admin_menu(context, page): """Render the admin table of pages.""" request = context.get('request', None) expanded = False if request and "tree_expanded" in request.COOKIES: cookie_string = urllib.unquote(request.COOKIES['tree_expanded']) if cookie_string: ids = [int(id) for id in urllib.unquote(request.COOKIES['tree_expanded']).split(',')] if page.id in ids: expanded = True context.update({'expanded': expanded, 'page': page}) return context
[ "def", "pages_admin_menu", "(", "context", ",", "page", ")", ":", "request", "=", "context", ".", "get", "(", "'request'", ",", "None", ")", "expanded", "=", "False", "if", "request", "and", "\"tree_expanded\"", "in", "request", ".", "COOKIES", ":", "cookie_string", "=", "urllib", ".", "unquote", "(", "request", ".", "COOKIES", "[", "'tree_expanded'", "]", ")", "if", "cookie_string", ":", "ids", "=", "[", "int", "(", "id", ")", "for", "id", "in", "urllib", ".", "unquote", "(", "request", ".", "COOKIES", "[", "'tree_expanded'", "]", ")", ".", "split", "(", "','", ")", "]", "if", "page", ".", "id", "in", "ids", ":", "expanded", "=", "True", "context", ".", "update", "(", "{", "'expanded'", ":", "expanded", ",", "'page'", ":", "page", "}", ")", "return", "context" ]
Render the admin table of pages.
[ "Render", "the", "admin", "table", "of", "pages", "." ]
863f3c6098606f663994930cd8e7723ad0c07caf
https://github.com/ArabellaTech/django-basic-cms/blob/863f3c6098606f663994930cd8e7723ad0c07caf/basic_cms/templatetags/pages_tags.py#L129-L142
train
adamrehn/ue4cli
ue4cli/Utility.py
Utility.findArgs
def findArgs(args, prefixes): """ Extracts the list of arguments that start with any of the specified prefix values """ return list([ arg for arg in args if len([p for p in prefixes if arg.lower().startswith(p.lower())]) > 0 ])
python
def findArgs(args, prefixes): """ Extracts the list of arguments that start with any of the specified prefix values """ return list([ arg for arg in args if len([p for p in prefixes if arg.lower().startswith(p.lower())]) > 0 ])
[ "def", "findArgs", "(", "args", ",", "prefixes", ")", ":", "return", "list", "(", "[", "arg", "for", "arg", "in", "args", "if", "len", "(", "[", "p", "for", "p", "in", "prefixes", "if", "arg", ".", "lower", "(", ")", ".", "startswith", "(", "p", ".", "lower", "(", ")", ")", "]", ")", ">", "0", "]", ")" ]
Extracts the list of arguments that start with any of the specified prefix values
[ "Extracts", "the", "list", "of", "arguments", "that", "start", "with", "any", "of", "the", "specified", "prefix", "values" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/Utility.py#L86-L93
train
adamrehn/ue4cli
ue4cli/Utility.py
Utility.stripArgs
def stripArgs(args, blacklist): """ Removes any arguments in the supplied list that are contained in the specified blacklist """ blacklist = [b.lower() for b in blacklist] return list([arg for arg in args if arg.lower() not in blacklist])
python
def stripArgs(args, blacklist): """ Removes any arguments in the supplied list that are contained in the specified blacklist """ blacklist = [b.lower() for b in blacklist] return list([arg for arg in args if arg.lower() not in blacklist])
[ "def", "stripArgs", "(", "args", ",", "blacklist", ")", ":", "blacklist", "=", "[", "b", ".", "lower", "(", ")", "for", "b", "in", "blacklist", "]", "return", "list", "(", "[", "arg", "for", "arg", "in", "args", "if", "arg", ".", "lower", "(", ")", "not", "in", "blacklist", "]", ")" ]
Removes any arguments in the supplied list that are contained in the specified blacklist
[ "Removes", "any", "arguments", "in", "the", "supplied", "list", "that", "are", "contained", "in", "the", "specified", "blacklist" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/Utility.py#L103-L108
train
adamrehn/ue4cli
ue4cli/Utility.py
Utility.capture
def capture(command, input=None, cwd=None, shell=False, raiseOnError=False): """ Executes a child process and captures its output """ # Attempt to execute the child process proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, shell=shell, universal_newlines=True) (stdout, stderr) = proc.communicate(input) # If the child process failed and we were asked to raise an exception, do so if raiseOnError == True and proc.returncode != 0: raise Exception( 'child process ' + str(command) + ' failed with exit code ' + str(proc.returncode) + '\nstdout: "' + stdout + '"' + '\nstderr: "' + stderr + '"' ) return CommandOutput(proc.returncode, stdout, stderr)
python
def capture(command, input=None, cwd=None, shell=False, raiseOnError=False): """ Executes a child process and captures its output """ # Attempt to execute the child process proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, shell=shell, universal_newlines=True) (stdout, stderr) = proc.communicate(input) # If the child process failed and we were asked to raise an exception, do so if raiseOnError == True and proc.returncode != 0: raise Exception( 'child process ' + str(command) + ' failed with exit code ' + str(proc.returncode) + '\nstdout: "' + stdout + '"' + '\nstderr: "' + stderr + '"' ) return CommandOutput(proc.returncode, stdout, stderr)
[ "def", "capture", "(", "command", ",", "input", "=", "None", ",", "cwd", "=", "None", ",", "shell", "=", "False", ",", "raiseOnError", "=", "False", ")", ":", "# Attempt to execute the child process", "proc", "=", "subprocess", ".", "Popen", "(", "command", ",", "stdin", "=", "subprocess", ".", "PIPE", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "cwd", "=", "cwd", ",", "shell", "=", "shell", ",", "universal_newlines", "=", "True", ")", "(", "stdout", ",", "stderr", ")", "=", "proc", ".", "communicate", "(", "input", ")", "# If the child process failed and we were asked to raise an exception, do so", "if", "raiseOnError", "==", "True", "and", "proc", ".", "returncode", "!=", "0", ":", "raise", "Exception", "(", "'child process '", "+", "str", "(", "command", ")", "+", "' failed with exit code '", "+", "str", "(", "proc", ".", "returncode", ")", "+", "'\\nstdout: \"'", "+", "stdout", "+", "'\"'", "+", "'\\nstderr: \"'", "+", "stderr", "+", "'\"'", ")", "return", "CommandOutput", "(", "proc", ".", "returncode", ",", "stdout", ",", "stderr", ")" ]
Executes a child process and captures its output
[ "Executes", "a", "child", "process", "and", "captures", "its", "output" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/Utility.py#L111-L129
train
adamrehn/ue4cli
ue4cli/Utility.py
Utility.run
def run(command, cwd=None, shell=False, raiseOnError=False): """ Executes a child process and waits for it to complete """ returncode = subprocess.call(command, cwd=cwd, shell=shell) if raiseOnError == True and returncode != 0: raise Exception('child process ' + str(command) + ' failed with exit code ' + str(returncode)) return returncode
python
def run(command, cwd=None, shell=False, raiseOnError=False): """ Executes a child process and waits for it to complete """ returncode = subprocess.call(command, cwd=cwd, shell=shell) if raiseOnError == True and returncode != 0: raise Exception('child process ' + str(command) + ' failed with exit code ' + str(returncode)) return returncode
[ "def", "run", "(", "command", ",", "cwd", "=", "None", ",", "shell", "=", "False", ",", "raiseOnError", "=", "False", ")", ":", "returncode", "=", "subprocess", ".", "call", "(", "command", ",", "cwd", "=", "cwd", ",", "shell", "=", "shell", ")", "if", "raiseOnError", "==", "True", "and", "returncode", "!=", "0", ":", "raise", "Exception", "(", "'child process '", "+", "str", "(", "command", ")", "+", "' failed with exit code '", "+", "str", "(", "returncode", ")", ")", "return", "returncode" ]
Executes a child process and waits for it to complete
[ "Executes", "a", "child", "process", "and", "waits", "for", "it", "to", "complete" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/Utility.py#L132-L139
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase.setEngineRootOverride
def setEngineRootOverride(self, rootDir): """ Sets a user-specified directory as the root engine directory, overriding any auto-detection """ # Set the new root directory ConfigurationManager.setConfigKey('rootDirOverride', os.path.abspath(rootDir)) # Check that the specified directory is valid and warn the user if it is not try: self.getEngineVersion() except: print('Warning: the specified directory does not appear to contain a valid version of the Unreal Engine.')
python
def setEngineRootOverride(self, rootDir): """ Sets a user-specified directory as the root engine directory, overriding any auto-detection """ # Set the new root directory ConfigurationManager.setConfigKey('rootDirOverride', os.path.abspath(rootDir)) # Check that the specified directory is valid and warn the user if it is not try: self.getEngineVersion() except: print('Warning: the specified directory does not appear to contain a valid version of the Unreal Engine.')
[ "def", "setEngineRootOverride", "(", "self", ",", "rootDir", ")", ":", "# Set the new root directory", "ConfigurationManager", ".", "setConfigKey", "(", "'rootDirOverride'", ",", "os", ".", "path", ".", "abspath", "(", "rootDir", ")", ")", "# Check that the specified directory is valid and warn the user if it is not", "try", ":", "self", ".", "getEngineVersion", "(", ")", "except", ":", "print", "(", "'Warning: the specified directory does not appear to contain a valid version of the Unreal Engine.'", ")" ]
Sets a user-specified directory as the root engine directory, overriding any auto-detection
[ "Sets", "a", "user", "-", "specified", "directory", "as", "the", "root", "engine", "directory", "overriding", "any", "auto", "-", "detection" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L33-L45
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase.getEngineRoot
def getEngineRoot(self): """ Returns the root directory location of the latest installed version of UE4 """ if not hasattr(self, '_engineRoot'): self._engineRoot = self._getEngineRoot() return self._engineRoot
python
def getEngineRoot(self): """ Returns the root directory location of the latest installed version of UE4 """ if not hasattr(self, '_engineRoot'): self._engineRoot = self._getEngineRoot() return self._engineRoot
[ "def", "getEngineRoot", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_engineRoot'", ")", ":", "self", ".", "_engineRoot", "=", "self", ".", "_getEngineRoot", "(", ")", "return", "self", ".", "_engineRoot" ]
Returns the root directory location of the latest installed version of UE4
[ "Returns", "the", "root", "directory", "location", "of", "the", "latest", "installed", "version", "of", "UE4" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L53-L59
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase.getEngineVersion
def getEngineVersion(self, outputFormat = 'full'): """ Returns the version number of the latest installed version of UE4 """ version = self._getEngineVersionDetails() formats = { 'major': version['MajorVersion'], 'minor': version['MinorVersion'], 'patch': version['PatchVersion'], 'full': '{}.{}.{}'.format(version['MajorVersion'], version['MinorVersion'], version['PatchVersion']), 'short': '{}.{}'.format(version['MajorVersion'], version['MinorVersion']) } # Verify that the requested output format is valid if outputFormat not in formats: raise Exception('unreconised version output format "{}"'.format(outputFormat)) return formats[outputFormat]
python
def getEngineVersion(self, outputFormat = 'full'): """ Returns the version number of the latest installed version of UE4 """ version = self._getEngineVersionDetails() formats = { 'major': version['MajorVersion'], 'minor': version['MinorVersion'], 'patch': version['PatchVersion'], 'full': '{}.{}.{}'.format(version['MajorVersion'], version['MinorVersion'], version['PatchVersion']), 'short': '{}.{}'.format(version['MajorVersion'], version['MinorVersion']) } # Verify that the requested output format is valid if outputFormat not in formats: raise Exception('unreconised version output format "{}"'.format(outputFormat)) return formats[outputFormat]
[ "def", "getEngineVersion", "(", "self", ",", "outputFormat", "=", "'full'", ")", ":", "version", "=", "self", ".", "_getEngineVersionDetails", "(", ")", "formats", "=", "{", "'major'", ":", "version", "[", "'MajorVersion'", "]", ",", "'minor'", ":", "version", "[", "'MinorVersion'", "]", ",", "'patch'", ":", "version", "[", "'PatchVersion'", "]", ",", "'full'", ":", "'{}.{}.{}'", ".", "format", "(", "version", "[", "'MajorVersion'", "]", ",", "version", "[", "'MinorVersion'", "]", ",", "version", "[", "'PatchVersion'", "]", ")", ",", "'short'", ":", "'{}.{}'", ".", "format", "(", "version", "[", "'MajorVersion'", "]", ",", "version", "[", "'MinorVersion'", "]", ")", "}", "# Verify that the requested output format is valid", "if", "outputFormat", "not", "in", "formats", ":", "raise", "Exception", "(", "'unreconised version output format \"{}\"'", ".", "format", "(", "outputFormat", ")", ")", "return", "formats", "[", "outputFormat", "]" ]
Returns the version number of the latest installed version of UE4
[ "Returns", "the", "version", "number", "of", "the", "latest", "installed", "version", "of", "UE4" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L61-L78
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase.getEngineChangelist
def getEngineChangelist(self): """ Returns the compatible Perforce changelist identifier for the latest installed version of UE4 """ # Newer versions of the engine use the key "CompatibleChangelist", older ones use "Changelist" version = self._getEngineVersionDetails() if 'CompatibleChangelist' in version: return int(version['CompatibleChangelist']) else: return int(version['Changelist'])
python
def getEngineChangelist(self): """ Returns the compatible Perforce changelist identifier for the latest installed version of UE4 """ # Newer versions of the engine use the key "CompatibleChangelist", older ones use "Changelist" version = self._getEngineVersionDetails() if 'CompatibleChangelist' in version: return int(version['CompatibleChangelist']) else: return int(version['Changelist'])
[ "def", "getEngineChangelist", "(", "self", ")", ":", "# Newer versions of the engine use the key \"CompatibleChangelist\", older ones use \"Changelist\"", "version", "=", "self", ".", "_getEngineVersionDetails", "(", ")", "if", "'CompatibleChangelist'", "in", "version", ":", "return", "int", "(", "version", "[", "'CompatibleChangelist'", "]", ")", "else", ":", "return", "int", "(", "version", "[", "'Changelist'", "]", ")" ]
Returns the compatible Perforce changelist identifier for the latest installed version of UE4
[ "Returns", "the", "compatible", "Perforce", "changelist", "identifier", "for", "the", "latest", "installed", "version", "of", "UE4" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L80-L90
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase.isInstalledBuild
def isInstalledBuild(self): """ Determines if the Engine is an Installed Build """ sentinelFile = os.path.join(self.getEngineRoot(), 'Engine', 'Build', 'InstalledBuild.txt') return os.path.exists(sentinelFile)
python
def isInstalledBuild(self): """ Determines if the Engine is an Installed Build """ sentinelFile = os.path.join(self.getEngineRoot(), 'Engine', 'Build', 'InstalledBuild.txt') return os.path.exists(sentinelFile)
[ "def", "isInstalledBuild", "(", "self", ")", ":", "sentinelFile", "=", "os", ".", "path", ".", "join", "(", "self", ".", "getEngineRoot", "(", ")", ",", "'Engine'", ",", "'Build'", ",", "'InstalledBuild.txt'", ")", "return", "os", ".", "path", ".", "exists", "(", "sentinelFile", ")" ]
Determines if the Engine is an Installed Build
[ "Determines", "if", "the", "Engine", "is", "an", "Installed", "Build" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L92-L97
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase.getEditorBinary
def getEditorBinary(self, cmdVersion=False): """ Determines the location of the UE4Editor binary """ return os.path.join(self.getEngineRoot(), 'Engine', 'Binaries', self.getPlatformIdentifier(), 'UE4Editor' + self._editorPathSuffix(cmdVersion))
python
def getEditorBinary(self, cmdVersion=False): """ Determines the location of the UE4Editor binary """ return os.path.join(self.getEngineRoot(), 'Engine', 'Binaries', self.getPlatformIdentifier(), 'UE4Editor' + self._editorPathSuffix(cmdVersion))
[ "def", "getEditorBinary", "(", "self", ",", "cmdVersion", "=", "False", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "getEngineRoot", "(", ")", ",", "'Engine'", ",", "'Binaries'", ",", "self", ".", "getPlatformIdentifier", "(", ")", ",", "'UE4Editor'", "+", "self", ".", "_editorPathSuffix", "(", "cmdVersion", ")", ")" ]
Determines the location of the UE4Editor binary
[ "Determines", "the", "location", "of", "the", "UE4Editor", "binary" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L99-L103
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase.getProjectDescriptor
def getProjectDescriptor(self, dir): """ Detects the .uproject descriptor file for the Unreal project in the specified directory """ for project in glob.glob(os.path.join(dir, '*.uproject')): return os.path.realpath(project) # No project detected raise UnrealManagerException('could not detect an Unreal project in the current directory')
python
def getProjectDescriptor(self, dir): """ Detects the .uproject descriptor file for the Unreal project in the specified directory """ for project in glob.glob(os.path.join(dir, '*.uproject')): return os.path.realpath(project) # No project detected raise UnrealManagerException('could not detect an Unreal project in the current directory')
[ "def", "getProjectDescriptor", "(", "self", ",", "dir", ")", ":", "for", "project", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "dir", ",", "'*.uproject'", ")", ")", ":", "return", "os", ".", "path", ".", "realpath", "(", "project", ")", "# No project detected", "raise", "UnrealManagerException", "(", "'could not detect an Unreal project in the current directory'", ")" ]
Detects the .uproject descriptor file for the Unreal project in the specified directory
[ "Detects", "the", ".", "uproject", "descriptor", "file", "for", "the", "Unreal", "project", "in", "the", "specified", "directory" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L123-L131
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase.getPluginDescriptor
def getPluginDescriptor(self, dir): """ Detects the .uplugin descriptor file for the Unreal plugin in the specified directory """ for plugin in glob.glob(os.path.join(dir, '*.uplugin')): return os.path.realpath(plugin) # No plugin detected raise UnrealManagerException('could not detect an Unreal plugin in the current directory')
python
def getPluginDescriptor(self, dir): """ Detects the .uplugin descriptor file for the Unreal plugin in the specified directory """ for plugin in glob.glob(os.path.join(dir, '*.uplugin')): return os.path.realpath(plugin) # No plugin detected raise UnrealManagerException('could not detect an Unreal plugin in the current directory')
[ "def", "getPluginDescriptor", "(", "self", ",", "dir", ")", ":", "for", "plugin", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "dir", ",", "'*.uplugin'", ")", ")", ":", "return", "os", ".", "path", ".", "realpath", "(", "plugin", ")", "# No plugin detected", "raise", "UnrealManagerException", "(", "'could not detect an Unreal plugin in the current directory'", ")" ]
Detects the .uplugin descriptor file for the Unreal plugin in the specified directory
[ "Detects", "the", ".", "uplugin", "descriptor", "file", "for", "the", "Unreal", "plugin", "in", "the", "specified", "directory" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L133-L141
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase.getDescriptor
def getDescriptor(self, dir): """ Detects the descriptor file for either an Unreal project or an Unreal plugin in the specified directory """ try: return self.getProjectDescriptor(dir) except: try: return self.getPluginDescriptor(dir) except: raise UnrealManagerException('could not detect an Unreal project or plugin in the directory "{}"'.format(dir))
python
def getDescriptor(self, dir): """ Detects the descriptor file for either an Unreal project or an Unreal plugin in the specified directory """ try: return self.getProjectDescriptor(dir) except: try: return self.getPluginDescriptor(dir) except: raise UnrealManagerException('could not detect an Unreal project or plugin in the directory "{}"'.format(dir))
[ "def", "getDescriptor", "(", "self", ",", "dir", ")", ":", "try", ":", "return", "self", ".", "getProjectDescriptor", "(", "dir", ")", "except", ":", "try", ":", "return", "self", ".", "getPluginDescriptor", "(", "dir", ")", "except", ":", "raise", "UnrealManagerException", "(", "'could not detect an Unreal project or plugin in the directory \"{}\"'", ".", "format", "(", "dir", ")", ")" ]
Detects the descriptor file for either an Unreal project or an Unreal plugin in the specified directory
[ "Detects", "the", "descriptor", "file", "for", "either", "an", "Unreal", "project", "or", "an", "Unreal", "plugin", "in", "the", "specified", "directory" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L143-L153
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase.listThirdPartyLibs
def listThirdPartyLibs(self, configuration = 'Development'): """ Lists the supported Unreal-bundled third-party libraries """ interrogator = self._getUE4BuildInterrogator() return interrogator.list(self.getPlatformIdentifier(), configuration, self._getLibraryOverrides())
python
def listThirdPartyLibs(self, configuration = 'Development'): """ Lists the supported Unreal-bundled third-party libraries """ interrogator = self._getUE4BuildInterrogator() return interrogator.list(self.getPlatformIdentifier(), configuration, self._getLibraryOverrides())
[ "def", "listThirdPartyLibs", "(", "self", ",", "configuration", "=", "'Development'", ")", ":", "interrogator", "=", "self", ".", "_getUE4BuildInterrogator", "(", ")", "return", "interrogator", ".", "list", "(", "self", ".", "getPlatformIdentifier", "(", ")", ",", "configuration", ",", "self", ".", "_getLibraryOverrides", "(", ")", ")" ]
Lists the supported Unreal-bundled third-party libraries
[ "Lists", "the", "supported", "Unreal", "-", "bundled", "third", "-", "party", "libraries" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L173-L178
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase.getThirdpartyLibs
def getThirdpartyLibs(self, libs, configuration = 'Development', includePlatformDefaults = True): """ Retrieves the ThirdPartyLibraryDetails instance for Unreal-bundled versions of the specified third-party libraries """ if includePlatformDefaults == True: libs = self._defaultThirdpartyLibs() + libs interrogator = self._getUE4BuildInterrogator() return interrogator.interrogate(self.getPlatformIdentifier(), configuration, libs, self._getLibraryOverrides())
python
def getThirdpartyLibs(self, libs, configuration = 'Development', includePlatformDefaults = True): """ Retrieves the ThirdPartyLibraryDetails instance for Unreal-bundled versions of the specified third-party libraries """ if includePlatformDefaults == True: libs = self._defaultThirdpartyLibs() + libs interrogator = self._getUE4BuildInterrogator() return interrogator.interrogate(self.getPlatformIdentifier(), configuration, libs, self._getLibraryOverrides())
[ "def", "getThirdpartyLibs", "(", "self", ",", "libs", ",", "configuration", "=", "'Development'", ",", "includePlatformDefaults", "=", "True", ")", ":", "if", "includePlatformDefaults", "==", "True", ":", "libs", "=", "self", ".", "_defaultThirdpartyLibs", "(", ")", "+", "libs", "interrogator", "=", "self", ".", "_getUE4BuildInterrogator", "(", ")", "return", "interrogator", ".", "interrogate", "(", "self", ".", "getPlatformIdentifier", "(", ")", ",", "configuration", ",", "libs", ",", "self", ".", "_getLibraryOverrides", "(", ")", ")" ]
Retrieves the ThirdPartyLibraryDetails instance for Unreal-bundled versions of the specified third-party libraries
[ "Retrieves", "the", "ThirdPartyLibraryDetails", "instance", "for", "Unreal", "-", "bundled", "versions", "of", "the", "specified", "third", "-", "party", "libraries" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L180-L187
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase.getThirdPartyLibCompilerFlags
def getThirdPartyLibCompilerFlags(self, libs): """ Retrieves the compiler flags for building against the Unreal-bundled versions of the specified third-party libraries """ fmt = PrintingFormat.singleLine() if libs[0] == '--multiline': fmt = PrintingFormat.multiLine() libs = libs[1:] platformDefaults = True if libs[0] == '--nodefaults': platformDefaults = False libs = libs[1:] details = self.getThirdpartyLibs(libs, includePlatformDefaults=platformDefaults) return details.getCompilerFlags(self.getEngineRoot(), fmt)
python
def getThirdPartyLibCompilerFlags(self, libs): """ Retrieves the compiler flags for building against the Unreal-bundled versions of the specified third-party libraries """ fmt = PrintingFormat.singleLine() if libs[0] == '--multiline': fmt = PrintingFormat.multiLine() libs = libs[1:] platformDefaults = True if libs[0] == '--nodefaults': platformDefaults = False libs = libs[1:] details = self.getThirdpartyLibs(libs, includePlatformDefaults=platformDefaults) return details.getCompilerFlags(self.getEngineRoot(), fmt)
[ "def", "getThirdPartyLibCompilerFlags", "(", "self", ",", "libs", ")", ":", "fmt", "=", "PrintingFormat", ".", "singleLine", "(", ")", "if", "libs", "[", "0", "]", "==", "'--multiline'", ":", "fmt", "=", "PrintingFormat", ".", "multiLine", "(", ")", "libs", "=", "libs", "[", "1", ":", "]", "platformDefaults", "=", "True", "if", "libs", "[", "0", "]", "==", "'--nodefaults'", ":", "platformDefaults", "=", "False", "libs", "=", "libs", "[", "1", ":", "]", "details", "=", "self", ".", "getThirdpartyLibs", "(", "libs", ",", "includePlatformDefaults", "=", "platformDefaults", ")", "return", "details", ".", "getCompilerFlags", "(", "self", ".", "getEngineRoot", "(", ")", ",", "fmt", ")" ]
Retrieves the compiler flags for building against the Unreal-bundled versions of the specified third-party libraries
[ "Retrieves", "the", "compiler", "flags", "for", "building", "against", "the", "Unreal", "-", "bundled", "versions", "of", "the", "specified", "third", "-", "party", "libraries" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L189-L204
train