repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
the01/python-paps | paps/si/app/sensor.py | Sensor._shutdown_listen_socket | def _shutdown_listen_socket(self):
"""
Shutdown listening socket
:rtype: None
"""
self.debug("()")
if self._listen_socket in self._listening:
self._listening.remove(self._listen_socket)
if self._listen_socket:
self._listen_socket.close()
... | python | def _shutdown_listen_socket(self):
"""
Shutdown listening socket
:rtype: None
"""
self.debug("()")
if self._listen_socket in self._listening:
self._listening.remove(self._listen_socket)
if self._listen_socket:
self._listen_socket.close()
... | [
"def",
"_shutdown_listen_socket",
"(",
"self",
")",
":",
"self",
".",
"debug",
"(",
"\"()\"",
")",
"if",
"self",
".",
"_listen_socket",
"in",
"self",
".",
"_listening",
":",
"self",
".",
"_listening",
".",
"remove",
"(",
"self",
".",
"_listen_socket",
")",... | Shutdown listening socket
:rtype: None | [
"Shutdown",
"listening",
"socket"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensor.py#L125-L136 |
the01/python-paps | paps/si/app/sensor.py | Sensor._send | def _send(self, ip, port, data):
"""
Send an UDP message
:param ip: Ip to send to
:type ip: str
:param port: Port to send to
:type port: int
:return: Number of bytes sent
:rtype: int
"""
return self._listen_socket.sendto(data, (ip, port)) | python | def _send(self, ip, port, data):
"""
Send an UDP message
:param ip: Ip to send to
:type ip: str
:param port: Port to send to
:type port: int
:return: Number of bytes sent
:rtype: int
"""
return self._listen_socket.sendto(data, (ip, port)) | [
"def",
"_send",
"(",
"self",
",",
"ip",
",",
"port",
",",
"data",
")",
":",
"return",
"self",
".",
"_listen_socket",
".",
"sendto",
"(",
"data",
",",
"(",
"ip",
",",
"port",
")",
")"
] | Send an UDP message
:param ip: Ip to send to
:type ip: str
:param port: Port to send to
:type port: int
:return: Number of bytes sent
:rtype: int | [
"Send",
"an",
"UDP",
"message"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensor.py#L138-L149 |
the01/python-paps | paps/si/app/sensor.py | Sensor._send_packet | def _send_packet(
self, ip, port, packet,
update_timestamp=True, acknowledge_packet=True
):
"""
Send a packet
:param ip: Ip to send to
:type ip: str
:param port: Port to send to
:type port: int
:param packet: Packet to be transmitted
... | python | def _send_packet(
self, ip, port, packet,
update_timestamp=True, acknowledge_packet=True
):
"""
Send a packet
:param ip: Ip to send to
:type ip: str
:param port: Port to send to
:type port: int
:param packet: Packet to be transmitted
... | [
"def",
"_send_packet",
"(",
"self",
",",
"ip",
",",
"port",
",",
"packet",
",",
"update_timestamp",
"=",
"True",
",",
"acknowledge_packet",
"=",
"True",
")",
":",
"if",
"acknowledge_packet",
":",
"packet",
".",
"header",
".",
"sequence_number",
"=",
"self",
... | Send a packet
:param ip: Ip to send to
:type ip: str
:param port: Port to send to
:type port: int
:param packet: Packet to be transmitted
:type packet: APPMessage
:param update_timestamp: Should update timestamp to current
:type update_timestamp: bool
... | [
"Send",
"a",
"packet"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensor.py#L151-L187 |
the01/python-paps | paps/si/app/sensor.py | Sensor._send_ack | def _send_ack(self, ip, port, packet, update_timestamp=True):
"""
Send an ack packet
:param ip: Ip to send to
:type ip: str
:param port: Port to send to
:type port: int
:param packet: Packet to be acknowledged
:type packet: APPMessage
:param updat... | python | def _send_ack(self, ip, port, packet, update_timestamp=True):
"""
Send an ack packet
:param ip: Ip to send to
:type ip: str
:param port: Port to send to
:type port: int
:param packet: Packet to be acknowledged
:type packet: APPMessage
:param updat... | [
"def",
"_send_ack",
"(",
"self",
",",
"ip",
",",
"port",
",",
"packet",
",",
"update_timestamp",
"=",
"True",
")",
":",
"# TODO: maybe wait a bit, so the ack could get attached to another",
"# packet",
"ack",
"=",
"APPMessage",
"(",
"message_type",
"=",
"MsgType",
"... | Send an ack packet
:param ip: Ip to send to
:type ip: str
:param port: Port to send to
:type port: int
:param packet: Packet to be acknowledged
:type packet: APPMessage
:param update_timestamp: Should update timestamp to current
:type update_timestamp: bo... | [
"Send",
"an",
"ack",
"packet"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensor.py#L189-L210 |
the01/python-paps | paps/si/app/sensor.py | Sensor._get_packet | def _get_packet(self, socket):
"""
Read packet and put it into inbox
:param socket: Socket to read from
:type socket: socket.socket
:return: Read packet
:rtype: APPMessage
"""
data, (ip, port) = socket.recvfrom(self._buffer_size)
packet, remainder... | python | def _get_packet(self, socket):
"""
Read packet and put it into inbox
:param socket: Socket to read from
:type socket: socket.socket
:return: Read packet
:rtype: APPMessage
"""
data, (ip, port) = socket.recvfrom(self._buffer_size)
packet, remainder... | [
"def",
"_get_packet",
"(",
"self",
",",
"socket",
")",
":",
"data",
",",
"(",
"ip",
",",
"port",
")",
"=",
"socket",
".",
"recvfrom",
"(",
"self",
".",
"_buffer_size",
")",
"packet",
",",
"remainder",
"=",
"self",
".",
"_unpack",
"(",
"data",
")",
... | Read packet and put it into inbox
:param socket: Socket to read from
:type socket: socket.socket
:return: Read packet
:rtype: APPMessage | [
"Read",
"packet",
"and",
"put",
"it",
"into",
"inbox"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensor.py#L232-L257 |
the01/python-paps | paps/si/app/sensor.py | Sensor._receiving | def _receiving(self):
"""
Receiving loop
:rtype: None
"""
while self._is_running:
try:
rlist, wlist, xlist = select.select(
self._listening, [], [],
self._select_timeout
)
except:
... | python | def _receiving(self):
"""
Receiving loop
:rtype: None
"""
while self._is_running:
try:
rlist, wlist, xlist = select.select(
self._listening, [], [],
self._select_timeout
)
except:
... | [
"def",
"_receiving",
"(",
"self",
")",
":",
"while",
"self",
".",
"_is_running",
":",
"try",
":",
"rlist",
",",
"wlist",
",",
"xlist",
"=",
"select",
".",
"select",
"(",
"self",
".",
"_listening",
",",
"[",
"]",
",",
"[",
"]",
",",
"self",
".",
"... | Receiving loop
:rtype: None | [
"Receiving",
"loop"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensor.py#L272-L291 |
the01/python-paps | paps/si/app/sensor.py | Sensor._acking | def _acking(self, params=None):
"""
Packet acknowledge and retry loop
:param params: Ignore
:type params: None
:rtype: None
"""
while self._is_running:
try:
t, num_try, (ip, port), packet = self._to_ack.get(
timeout... | python | def _acking(self, params=None):
"""
Packet acknowledge and retry loop
:param params: Ignore
:type params: None
:rtype: None
"""
while self._is_running:
try:
t, num_try, (ip, port), packet = self._to_ack.get(
timeout... | [
"def",
"_acking",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"while",
"self",
".",
"_is_running",
":",
"try",
":",
"t",
",",
"num_try",
",",
"(",
"ip",
",",
"port",
")",
",",
"packet",
"=",
"self",
".",
"_to_ack",
".",
"get",
"(",
"timeou... | Packet acknowledge and retry loop
:param params: Ignore
:type params: None
:rtype: None | [
"Packet",
"acknowledge",
"and",
"retry",
"loop"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensor.py#L293-L337 |
the01/python-paps | paps/si/app/sensor.py | Sensor.start | def start(self, blocking=False):
"""
Start the interface
:param blocking: Should the call block until stop() is called
(default: False)
:type blocking: bool
:rtype: None
:raises SensorStartException: Failed to start
"""
try:
self._... | python | def start(self, blocking=False):
"""
Start the interface
:param blocking: Should the call block until stop() is called
(default: False)
:type blocking: bool
:rtype: None
:raises SensorStartException: Failed to start
"""
try:
self._... | [
"def",
"start",
"(",
"self",
",",
"blocking",
"=",
"False",
")",
":",
"try",
":",
"self",
".",
"_init_listen_socket",
"(",
")",
"except",
":",
"self",
".",
"exception",
"(",
"u\"Failed to init listen socket ({}:{})\"",
".",
"format",
"(",
"self",
".",
"_list... | Start the interface
:param blocking: Should the call block until stop() is called
(default: False)
:type blocking: bool
:rtype: None
:raises SensorStartException: Failed to start | [
"Start",
"the",
"interface"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensor.py#L339-L372 |
the01/python-paps | paps/si/app/sensor.py | Sensor.stop | def stop(self):
"""
Stop the interface
:rtype: None
"""
should_sleep = self._is_running
super(Sensor, self).stop()
if should_sleep:
# Make sure everything has enough time to exit
time.sleep(max(self._select_timeout, self._retransmit_timeou... | python | def stop(self):
"""
Stop the interface
:rtype: None
"""
should_sleep = self._is_running
super(Sensor, self).stop()
if should_sleep:
# Make sure everything has enough time to exit
time.sleep(max(self._select_timeout, self._retransmit_timeou... | [
"def",
"stop",
"(",
"self",
")",
":",
"should_sleep",
"=",
"self",
".",
"_is_running",
"super",
"(",
"Sensor",
",",
"self",
")",
".",
"stop",
"(",
")",
"if",
"should_sleep",
":",
"# Make sure everything has enough time to exit",
"time",
".",
"sleep",
"(",
"m... | Stop the interface
:rtype: None | [
"Stop",
"the",
"interface"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensor.py#L374-L386 |
MacHu-GWU/angora-project | angora/baseclass/classtree.py | gencode | def gencode(data, output=None, tab=" ", indent=0, overwrite=False):
"""Generate code.
:param data: must be list of class data, see a valid data example below
:param output: default None, the python script file name you want to create
:param tab: default " "
:param indent: global indent se... | python | def gencode(data, output=None, tab=" ", indent=0, overwrite=False):
"""Generate code.
:param data: must be list of class data, see a valid data example below
:param output: default None, the python script file name you want to create
:param tab: default " "
:param indent: global indent se... | [
"def",
"gencode",
"(",
"data",
",",
"output",
"=",
"None",
",",
"tab",
"=",
"\" \"",
",",
"indent",
"=",
"0",
",",
"overwrite",
"=",
"False",
")",
":",
"codegen",
"=",
"CodeGenerator",
"(",
"tab",
"=",
"tab",
",",
"indent",
"=",
"indent",
")",
"... | Generate code.
:param data: must be list of class data, see a valid data example below
:param output: default None, the python script file name you want to create
:param tab: default " "
:param indent: global indent setting
:param overwrite: if True, silently overwrite the output file
... | [
"Generate",
"code",
".",
":",
"param",
"data",
":",
"must",
"be",
"list",
"of",
"class",
"data",
"see",
"a",
"valid",
"data",
"example",
"below",
":",
"param",
"output",
":",
"default",
"None",
"the",
"python",
"script",
"file",
"name",
"you",
"want",
... | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/baseclass/classtree.py#L251-L323 |
MacHu-GWU/angora-project | angora/baseclass/classtree.py | CodeGenerator.repr_def_class | def repr_def_class(self, class_data):
"""Create code like this::
class Person(Base):
def __init__(self, person_id=None, name=None):
self.person_id = person_id
self.name = name
"""
classname = self.formatted_classname(cl... | python | def repr_def_class(self, class_data):
"""Create code like this::
class Person(Base):
def __init__(self, person_id=None, name=None):
self.person_id = person_id
self.name = name
"""
classname = self.formatted_classname(cl... | [
"def",
"repr_def_class",
"(",
"self",
",",
"class_data",
")",
":",
"classname",
"=",
"self",
".",
"formatted_classname",
"(",
"class_data",
"[",
"\"classname\"",
"]",
")",
"if",
"classname",
"not",
"in",
"self",
".",
"classes",
":",
"self",
".",
"lines",
"... | Create code like this::
class Person(Base):
def __init__(self, person_id=None, name=None):
self.person_id = person_id
self.name = name | [
"Create",
"code",
"like",
"this",
"::",
"class",
"Person",
"(",
"Base",
")",
":",
"def",
"__init__",
"(",
"self",
"person_id",
"=",
"None",
"name",
"=",
"None",
")",
":",
"self",
".",
"person_id",
"=",
"person_id",
"self",
".",
"name",
"=",
"name"
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/baseclass/classtree.py#L131-L159 |
MacHu-GWU/angora-project | angora/baseclass/classtree.py | CodeGenerator.repr_new_instance | def repr_new_instance(self, class_data):
"""Create code like this::
person = Person(name='Jack', person_id=1)
"""
classname = self.formatted_classname(class_data["classname"])
instancename = self.formatted_instancename(class_data["classname"])
arguments = lis... | python | def repr_new_instance(self, class_data):
"""Create code like this::
person = Person(name='Jack', person_id=1)
"""
classname = self.formatted_classname(class_data["classname"])
instancename = self.formatted_instancename(class_data["classname"])
arguments = lis... | [
"def",
"repr_new_instance",
"(",
"self",
",",
"class_data",
")",
":",
"classname",
"=",
"self",
".",
"formatted_classname",
"(",
"class_data",
"[",
"\"classname\"",
"]",
")",
"instancename",
"=",
"self",
".",
"formatted_instancename",
"(",
"class_data",
"[",
"\"... | Create code like this::
person = Person(name='Jack', person_id=1) | [
"Create",
"code",
"like",
"this",
"::",
"person",
"=",
"Person",
"(",
"name",
"=",
"Jack",
"person_id",
"=",
"1",
")"
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/baseclass/classtree.py#L161-L172 |
MacHu-GWU/angora-project | angora/baseclass/classtree.py | CodeGenerator.repr_setattr | def repr_setattr(self, class_data):
"""Create code like this::
person = Person(name='Jack', person_id=1)
self.name____Jack = person
self.person_id____1 = person
person = Person(name='Paul', person_id=2)
sel... | python | def repr_setattr(self, class_data):
"""Create code like this::
person = Person(name='Jack', person_id=1)
self.name____Jack = person
self.person_id____1 = person
person = Person(name='Paul', person_id=2)
sel... | [
"def",
"repr_setattr",
"(",
"self",
",",
"class_data",
")",
":",
"def",
"get_indexable_attributes",
"(",
"class_data",
")",
":",
"def",
"isvalid",
"(",
"text",
")",
":",
"for",
"char",
"in",
"r\"\"\"~`!#%^&*()+=[]{}|\\:;\"'/.,<> \"\"\"",
":",
"if",
"char",
"in",... | Create code like this::
person = Person(name='Jack', person_id=1)
self.name____Jack = person
self.person_id____1 = person
person = Person(name='Paul', person_id=2)
self.name____Paul = person
self.pe... | [
"Create",
"code",
"like",
"this",
"::",
"person",
"=",
"Person",
"(",
"name",
"=",
"Jack",
"person_id",
"=",
"1",
")",
"self",
".",
"name____Jack",
"=",
"person",
"self",
".",
"person_id____1",
"=",
"person",
"person",
"=",
"Person",
"(",
"name",
"=",
... | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/baseclass/classtree.py#L174-L219 |
MacHu-GWU/angora-project | angora/baseclass/classtree.py | CodeGenerator.repr_class_data | def repr_class_data(self, class_data):
"""Create code like this::
class Person(classtree.Base):
def __init__(self, name=None, person_id=None):
self.name = name
self.person_id = person_id
class Pers... | python | def repr_class_data(self, class_data):
"""Create code like this::
class Person(classtree.Base):
def __init__(self, name=None, person_id=None):
self.name = name
self.person_id = person_id
class Pers... | [
"def",
"repr_class_data",
"(",
"self",
",",
"class_data",
")",
":",
"if",
"\"subclass\"",
"in",
"class_data",
":",
"for",
"subclass_data",
"in",
"class_data",
"[",
"\"subclass\"",
"]",
":",
"self",
".",
"repr_class_data",
"(",
"subclass_data",
")",
"self",
"."... | Create code like this::
class Person(classtree.Base):
def __init__(self, name=None, person_id=None):
self.name = name
self.person_id = person_id
class PersonCollection(classtree.Base):
def ... | [
"Create",
"code",
"like",
"this",
"::",
"class",
"Person",
"(",
"classtree",
".",
"Base",
")",
":",
"def",
"__init__",
"(",
"self",
"name",
"=",
"None",
"person_id",
"=",
"None",
")",
":",
"self",
".",
"name",
"=",
"name",
"self",
".",
"person_id",
"... | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/baseclass/classtree.py#L221-L248 |
carlcarl/grabflickr | grabflickr/grabflickr.py | read_config | def read_config():
"""Read the config from CONFIG_PATH(Default: ~/.grabflickr.conf)
This will prompt for API key and secret if it not exists.
After, it sets the global variable `api_key` and `api_secret`.
"""
parser = SafeConfigParser()
parser.read(CONFIG_PATH)
if not parser.has_section('fli... | python | def read_config():
"""Read the config from CONFIG_PATH(Default: ~/.grabflickr.conf)
This will prompt for API key and secret if it not exists.
After, it sets the global variable `api_key` and `api_secret`.
"""
parser = SafeConfigParser()
parser.read(CONFIG_PATH)
if not parser.has_section('fli... | [
"def",
"read_config",
"(",
")",
":",
"parser",
"=",
"SafeConfigParser",
"(",
")",
"parser",
".",
"read",
"(",
"CONFIG_PATH",
")",
"if",
"not",
"parser",
".",
"has_section",
"(",
"'flickr'",
")",
":",
"logger",
".",
"info",
"(",
"'Seems you don\\'t set API ke... | Read the config from CONFIG_PATH(Default: ~/.grabflickr.conf)
This will prompt for API key and secret if it not exists.
After, it sets the global variable `api_key` and `api_secret`. | [
"Read",
"the",
"config",
"from",
"CONFIG_PATH",
"(",
"Default",
":",
"~",
"/",
".",
"grabflickr",
".",
"conf",
")",
"This",
"will",
"prompt",
"for",
"API",
"key",
"and",
"secret",
"if",
"it",
"not",
"exists",
".",
"After",
"it",
"sets",
"the",
"global"... | train | https://github.com/carlcarl/grabflickr/blob/e9cb2365de80c1819cfd5083c032d0d985f3c614/grabflickr/grabflickr.py#L38-L50 |
carlcarl/grabflickr | grabflickr/grabflickr.py | enter_api_key | def enter_api_key(parser=None):
"""Prompt for API key and secret
Then write them to CONFIG_PATH(Default: ~/.grabflickr.conf)
:param parser: Config parser
:type parser: SafeConfigParser
"""
if parser is None:
parser = SafeConfigParser()
parser.add_section('flickr')
global api_key... | python | def enter_api_key(parser=None):
"""Prompt for API key and secret
Then write them to CONFIG_PATH(Default: ~/.grabflickr.conf)
:param parser: Config parser
:type parser: SafeConfigParser
"""
if parser is None:
parser = SafeConfigParser()
parser.add_section('flickr')
global api_key... | [
"def",
"enter_api_key",
"(",
"parser",
"=",
"None",
")",
":",
"if",
"parser",
"is",
"None",
":",
"parser",
"=",
"SafeConfigParser",
"(",
")",
"parser",
".",
"add_section",
"(",
"'flickr'",
")",
"global",
"api_key",
",",
"api_secret",
"api_key",
"=",
"raw_i... | Prompt for API key and secret
Then write them to CONFIG_PATH(Default: ~/.grabflickr.conf)
:param parser: Config parser
:type parser: SafeConfigParser | [
"Prompt",
"for",
"API",
"key",
"and",
"secret",
"Then",
"write",
"them",
"to",
"CONFIG_PATH",
"(",
"Default",
":",
"~",
"/",
".",
"grabflickr",
".",
"conf",
")"
] | train | https://github.com/carlcarl/grabflickr/blob/e9cb2365de80c1819cfd5083c032d0d985f3c614/grabflickr/grabflickr.py#L53-L69 |
carlcarl/grabflickr | grabflickr/grabflickr.py | _get_request_args | def _get_request_args(method, **kwargs):
"""Use `method` and other settings to produce a flickr API arguments.
Here also use json as the return type.
:param method: The method provided by flickr,
ex: flickr.photosets.getPhotos
:type method: str
:param kwargs: Other settings
:type kw... | python | def _get_request_args(method, **kwargs):
"""Use `method` and other settings to produce a flickr API arguments.
Here also use json as the return type.
:param method: The method provided by flickr,
ex: flickr.photosets.getPhotos
:type method: str
:param kwargs: Other settings
:type kw... | [
"def",
"_get_request_args",
"(",
"method",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"[",
"(",
"'api_key'",
",",
"api_key",
")",
",",
"(",
"'format'",
",",
"'json'",
")",
",",
"(",
"'method'",
",",
"method",
")",
",",
"(",
"'nojsoncallback'",
"... | Use `method` and other settings to produce a flickr API arguments.
Here also use json as the return type.
:param method: The method provided by flickr,
ex: flickr.photosets.getPhotos
:type method: str
:param kwargs: Other settings
:type kwargs: dict
:return: An argument list used fo... | [
"Use",
"method",
"and",
"other",
"settings",
"to",
"produce",
"a",
"flickr",
"API",
"arguments",
".",
"Here",
"also",
"use",
"json",
"as",
"the",
"return",
"type",
"."
] | train | https://github.com/carlcarl/grabflickr/blob/e9cb2365de80c1819cfd5083c032d0d985f3c614/grabflickr/grabflickr.py#L72-L96 |
carlcarl/grabflickr | grabflickr/grabflickr.py | _get_api_sig | def _get_api_sig(args):
"""Flickr API need a hash string which made using post arguments
:param args: Arguments of the flickr request
:type args: list of sets
:return: api_sig, ex: ('api_sig', 'abcdefg')
:rtype: tuple
"""
tmp_sig = api_secret
for i in args:
tmp_sig = tmp_sig + i... | python | def _get_api_sig(args):
"""Flickr API need a hash string which made using post arguments
:param args: Arguments of the flickr request
:type args: list of sets
:return: api_sig, ex: ('api_sig', 'abcdefg')
:rtype: tuple
"""
tmp_sig = api_secret
for i in args:
tmp_sig = tmp_sig + i... | [
"def",
"_get_api_sig",
"(",
"args",
")",
":",
"tmp_sig",
"=",
"api_secret",
"for",
"i",
"in",
"args",
":",
"tmp_sig",
"=",
"tmp_sig",
"+",
"i",
"[",
"0",
"]",
"+",
"i",
"[",
"1",
"]",
"api_sig",
"=",
"hashlib",
".",
"md5",
"(",
"tmp_sig",
".",
"e... | Flickr API need a hash string which made using post arguments
:param args: Arguments of the flickr request
:type args: list of sets
:return: api_sig, ex: ('api_sig', 'abcdefg')
:rtype: tuple | [
"Flickr",
"API",
"need",
"a",
"hash",
"string",
"which",
"made",
"using",
"post",
"arguments"
] | train | https://github.com/carlcarl/grabflickr/blob/e9cb2365de80c1819cfd5083c032d0d985f3c614/grabflickr/grabflickr.py#L99-L111 |
carlcarl/grabflickr | grabflickr/grabflickr.py | create_dir | def create_dir(path):
"""Create dir with the path
:param path: The path to be created
:type path: str
"""
if os.path.exists(path):
if not os.path.isdir(path):
logger.error('%s is not a directory', path)
sys.exit(1)
else: # ignore
pass
else:
... | python | def create_dir(path):
"""Create dir with the path
:param path: The path to be created
:type path: str
"""
if os.path.exists(path):
if not os.path.isdir(path):
logger.error('%s is not a directory', path)
sys.exit(1)
else: # ignore
pass
else:
... | [
"def",
"create_dir",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"logger",
".",
"error",
"(",
"'%s is not a directory'",
",",
"path",
")"... | Create dir with the path
:param path: The path to be created
:type path: str | [
"Create",
"dir",
"with",
"the",
"path"
] | train | https://github.com/carlcarl/grabflickr/blob/e9cb2365de80c1819cfd5083c032d0d985f3c614/grabflickr/grabflickr.py#L114-L128 |
carlcarl/grabflickr | grabflickr/grabflickr.py | get_photos_info | def get_photos_info(photoset_id):
"""Request the photos information with the photoset id
:param photoset_id: The photoset id of flickr
:type photoset_id: str
:return: photos information
:rtype: list
"""
args = _get_request_args(
'flickr.photosets.getPhotos',
photoset_id=phot... | python | def get_photos_info(photoset_id):
"""Request the photos information with the photoset id
:param photoset_id: The photoset id of flickr
:type photoset_id: str
:return: photos information
:rtype: list
"""
args = _get_request_args(
'flickr.photosets.getPhotos',
photoset_id=phot... | [
"def",
"get_photos_info",
"(",
"photoset_id",
")",
":",
"args",
"=",
"_get_request_args",
"(",
"'flickr.photosets.getPhotos'",
",",
"photoset_id",
"=",
"photoset_id",
")",
"resp",
"=",
"requests",
".",
"post",
"(",
"API_URL",
",",
"data",
"=",
"args",
")",
"re... | Request the photos information with the photoset id
:param photoset_id: The photoset id of flickr
:type photoset_id: str
:return: photos information
:rtype: list | [
"Request",
"the",
"photos",
"information",
"with",
"the",
"photoset",
"id"
] | train | https://github.com/carlcarl/grabflickr/blob/e9cb2365de80c1819cfd5083c032d0d985f3c614/grabflickr/grabflickr.py#L131-L147 |
carlcarl/grabflickr | grabflickr/grabflickr.py | get_photo_url | def get_photo_url(photo_id):
"""Request the photo download url with the photo id
:param photo_id: The photo id of flickr
:type photo_id: str
:return: Photo download url
:rtype: str
"""
args = _get_request_args(
'flickr.photos.getSizes',
photo_id=photo_id
)
resp = requ... | python | def get_photo_url(photo_id):
"""Request the photo download url with the photo id
:param photo_id: The photo id of flickr
:type photo_id: str
:return: Photo download url
:rtype: str
"""
args = _get_request_args(
'flickr.photos.getSizes',
photo_id=photo_id
)
resp = requ... | [
"def",
"get_photo_url",
"(",
"photo_id",
")",
":",
"args",
"=",
"_get_request_args",
"(",
"'flickr.photos.getSizes'",
",",
"photo_id",
"=",
"photo_id",
")",
"resp",
"=",
"requests",
".",
"post",
"(",
"API_URL",
",",
"data",
"=",
"args",
")",
"resp_json",
"="... | Request the photo download url with the photo id
:param photo_id: The photo id of flickr
:type photo_id: str
:return: Photo download url
:rtype: str | [
"Request",
"the",
"photo",
"download",
"url",
"with",
"the",
"photo",
"id",
":",
"param",
"photo_id",
":",
"The",
"photo",
"id",
"of",
"flickr",
":",
"type",
"photo_id",
":",
"str",
":",
"return",
":",
"Photo",
"download",
"url",
":",
"rtype",
":",
"st... | train | https://github.com/carlcarl/grabflickr/blob/e9cb2365de80c1819cfd5083c032d0d985f3c614/grabflickr/grabflickr.py#L150-L170 |
carlcarl/grabflickr | grabflickr/grabflickr.py | download_photo_async | def download_photo_async(photo):
"""Download a photo to the the path(global varialbe `directory`)
:param photo: The photo information include id and title
:type photo: dict
"""
photo_id = photo['id']
photo_title = photo['title']
download_url = get_photo_url(photo_id)
photo_format = down... | python | def download_photo_async(photo):
"""Download a photo to the the path(global varialbe `directory`)
:param photo: The photo information include id and title
:type photo: dict
"""
photo_id = photo['id']
photo_title = photo['title']
download_url = get_photo_url(photo_id)
photo_format = down... | [
"def",
"download_photo_async",
"(",
"photo",
")",
":",
"photo_id",
"=",
"photo",
"[",
"'id'",
"]",
"photo_title",
"=",
"photo",
"[",
"'title'",
"]",
"download_url",
"=",
"get_photo_url",
"(",
"photo_id",
")",
"photo_format",
"=",
"download_url",
".",
"split",
... | Download a photo to the the path(global varialbe `directory`)
:param photo: The photo information include id and title
:type photo: dict | [
"Download",
"a",
"photo",
"to",
"the",
"the",
"path",
"(",
"global",
"varialbe",
"directory",
")"
] | train | https://github.com/carlcarl/grabflickr/blob/e9cb2365de80c1819cfd5083c032d0d985f3c614/grabflickr/grabflickr.py#L173-L196 |
carlcarl/grabflickr | grabflickr/grabflickr.py | single_download_photos | def single_download_photos(photos):
"""Use single process to download photos
:param photos: The photos to be downloaded
:type photos: list of dicts
"""
global counter
counter = len(photos)
for photo in photos:
download_photo(photo) | python | def single_download_photos(photos):
"""Use single process to download photos
:param photos: The photos to be downloaded
:type photos: list of dicts
"""
global counter
counter = len(photos)
for photo in photos:
download_photo(photo) | [
"def",
"single_download_photos",
"(",
"photos",
")",
":",
"global",
"counter",
"counter",
"=",
"len",
"(",
"photos",
")",
"for",
"photo",
"in",
"photos",
":",
"download_photo",
"(",
"photo",
")"
] | Use single process to download photos
:param photos: The photos to be downloaded
:type photos: list of dicts | [
"Use",
"single",
"process",
"to",
"download",
"photos"
] | train | https://github.com/carlcarl/grabflickr/blob/e9cb2365de80c1819cfd5083c032d0d985f3c614/grabflickr/grabflickr.py#L224-L233 |
carlcarl/grabflickr | grabflickr/grabflickr.py | event_download_photos | def event_download_photos(photos):
"""Use asynchronous I/O to download photos
:param photos: The photos to be downloaded
:type photos: list of dicts
"""
try:
assert gevent
assert grequests
except NameError:
logger.error('You need install gevent module. Aborting...')
... | python | def event_download_photos(photos):
"""Use asynchronous I/O to download photos
:param photos: The photos to be downloaded
:type photos: list of dicts
"""
try:
assert gevent
assert grequests
except NameError:
logger.error('You need install gevent module. Aborting...')
... | [
"def",
"event_download_photos",
"(",
"photos",
")",
":",
"try",
":",
"assert",
"gevent",
"assert",
"grequests",
"except",
"NameError",
":",
"logger",
".",
"error",
"(",
"'You need install gevent module. Aborting...'",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"glo... | Use asynchronous I/O to download photos
:param photos: The photos to be downloaded
:type photos: list of dicts | [
"Use",
"asynchronous",
"I",
"/",
"O",
"to",
"download",
"photos"
] | train | https://github.com/carlcarl/grabflickr/blob/e9cb2365de80c1819cfd5083c032d0d985f3c614/grabflickr/grabflickr.py#L236-L253 |
carlcarl/grabflickr | grabflickr/grabflickr.py | multithread_download_photos | def multithread_download_photos(photos):
"""Use multiple threads to download photos
:param photos: The photos to be downloaded
:type photos: list of dicts
"""
from concurrent import futures
global counter
counter = len(photos)
cpu_num = multiprocessing.cpu_count()
with futures.Threa... | python | def multithread_download_photos(photos):
"""Use multiple threads to download photos
:param photos: The photos to be downloaded
:type photos: list of dicts
"""
from concurrent import futures
global counter
counter = len(photos)
cpu_num = multiprocessing.cpu_count()
with futures.Threa... | [
"def",
"multithread_download_photos",
"(",
"photos",
")",
":",
"from",
"concurrent",
"import",
"futures",
"global",
"counter",
"counter",
"=",
"len",
"(",
"photos",
")",
"cpu_num",
"=",
"multiprocessing",
".",
"cpu_count",
"(",
")",
"with",
"futures",
".",
"Th... | Use multiple threads to download photos
:param photos: The photos to be downloaded
:type photos: list of dicts | [
"Use",
"multiple",
"threads",
"to",
"download",
"photos"
] | train | https://github.com/carlcarl/grabflickr/blob/e9cb2365de80c1819cfd5083c032d0d985f3c614/grabflickr/grabflickr.py#L256-L268 |
carlcarl/grabflickr | grabflickr/grabflickr.py | init_logger | def init_logger():
"""Initialize the logger and set its format
"""
formatter = logging.Formatter('%(levelname)s: %(message)s')
console = logging.StreamHandler(stream=sys.stdout)
console.setLevel(logging.INFO)
console.setFormatter(formatter)
logger.addHandler(console) | python | def init_logger():
"""Initialize the logger and set its format
"""
formatter = logging.Formatter('%(levelname)s: %(message)s')
console = logging.StreamHandler(stream=sys.stdout)
console.setLevel(logging.INFO)
console.setFormatter(formatter)
logger.addHandler(console) | [
"def",
"init_logger",
"(",
")",
":",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"'%(levelname)s: %(message)s'",
")",
"console",
"=",
"logging",
".",
"StreamHandler",
"(",
"stream",
"=",
"sys",
".",
"stdout",
")",
"console",
".",
"setLevel",
"(",
"lo... | Initialize the logger and set its format | [
"Initialize",
"the",
"logger",
"and",
"set",
"its",
"format"
] | train | https://github.com/carlcarl/grabflickr/blob/e9cb2365de80c1819cfd5083c032d0d985f3c614/grabflickr/grabflickr.py#L271-L278 |
carlcarl/grabflickr | grabflickr/grabflickr.py | _parse_cli_args | def _parse_cli_args():
"""Parse the arguments from CLI using ArgumentParser
:return: The arguments parsed by ArgumentParser
:rtype: Namespace
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'-g',
help='The photoset id to be downloaded',
metavar='<photoset_id>'... | python | def _parse_cli_args():
"""Parse the arguments from CLI using ArgumentParser
:return: The arguments parsed by ArgumentParser
:rtype: Namespace
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'-g',
help='The photoset id to be downloaded',
metavar='<photoset_id>'... | [
"def",
"_parse_cli_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'-g'",
",",
"help",
"=",
"'The photoset id to be downloaded'",
",",
"metavar",
"=",
"'<photoset_id>'",
")",
"parser",
".",
... | Parse the arguments from CLI using ArgumentParser
:return: The arguments parsed by ArgumentParser
:rtype: Namespace | [
"Parse",
"the",
"arguments",
"from",
"CLI",
"using",
"ArgumentParser",
":",
"return",
":",
"The",
"arguments",
"parsed",
"by",
"ArgumentParser",
":",
"rtype",
":",
"Namespace"
] | train | https://github.com/carlcarl/grabflickr/blob/e9cb2365de80c1819cfd5083c032d0d985f3c614/grabflickr/grabflickr.py#L281-L335 |
carlcarl/grabflickr | grabflickr/grabflickr.py | _gevent_patch | def _gevent_patch():
"""Patch the modules with gevent
:return: Default is GEVENT. If it not supports gevent then return MULTITHREAD
:rtype: int
"""
try:
assert gevent
assert grequests
except NameError:
logger.warn('gevent not exist, fallback to multiprocess...')
... | python | def _gevent_patch():
"""Patch the modules with gevent
:return: Default is GEVENT. If it not supports gevent then return MULTITHREAD
:rtype: int
"""
try:
assert gevent
assert grequests
except NameError:
logger.warn('gevent not exist, fallback to multiprocess...')
... | [
"def",
"_gevent_patch",
"(",
")",
":",
"try",
":",
"assert",
"gevent",
"assert",
"grequests",
"except",
"NameError",
":",
"logger",
".",
"warn",
"(",
"'gevent not exist, fallback to multiprocess...'",
")",
"return",
"MULTITHREAD",
"else",
":",
"monkey",
".",
"patc... | Patch the modules with gevent
:return: Default is GEVENT. If it not supports gevent then return MULTITHREAD
:rtype: int | [
"Patch",
"the",
"modules",
"with",
"gevent"
] | train | https://github.com/carlcarl/grabflickr/blob/e9cb2365de80c1819cfd5083c032d0d985f3c614/grabflickr/grabflickr.py#L349-L363 |
carlcarl/grabflickr | grabflickr/grabflickr.py | main | def main():
"""The main procedure
"""
init_logger()
args = _parse_cli_args()
if args.u:
enter_api_key()
return
if args.O == GEVENT:
args.O = _gevent_patch()
set_image_size_mode(args.s)
photoset_id = args.g
global directory
directory = args.d if args.d ... | python | def main():
"""The main procedure
"""
init_logger()
args = _parse_cli_args()
if args.u:
enter_api_key()
return
if args.O == GEVENT:
args.O = _gevent_patch()
set_image_size_mode(args.s)
photoset_id = args.g
global directory
directory = args.d if args.d ... | [
"def",
"main",
"(",
")",
":",
"init_logger",
"(",
")",
"args",
"=",
"_parse_cli_args",
"(",
")",
"if",
"args",
".",
"u",
":",
"enter_api_key",
"(",
")",
"return",
"if",
"args",
".",
"O",
"==",
"GEVENT",
":",
"args",
".",
"O",
"=",
"_gevent_patch",
... | The main procedure | [
"The",
"main",
"procedure"
] | train | https://github.com/carlcarl/grabflickr/blob/e9cb2365de80c1819cfd5083c032d0d985f3c614/grabflickr/grabflickr.py#L366-L396 |
bobbyesh/word-fencer | wordfencer/parser.py | is_cjk_punctuation | def is_cjk_punctuation(char):
"""Returns true if char is a punctuation mark in a CJK language."""
lower = int('0x3000', 16)
higher = int('0x300F', 16)
return ord(char) >= lower and ord(char) <= higher | python | def is_cjk_punctuation(char):
"""Returns true if char is a punctuation mark in a CJK language."""
lower = int('0x3000', 16)
higher = int('0x300F', 16)
return ord(char) >= lower and ord(char) <= higher | [
"def",
"is_cjk_punctuation",
"(",
"char",
")",
":",
"lower",
"=",
"int",
"(",
"'0x3000'",
",",
"16",
")",
"higher",
"=",
"int",
"(",
"'0x300F'",
",",
"16",
")",
"return",
"ord",
"(",
"char",
")",
">=",
"lower",
"and",
"ord",
"(",
"char",
")",
"<=",... | Returns true if char is a punctuation mark in a CJK language. | [
"Returns",
"true",
"if",
"char",
"is",
"a",
"punctuation",
"mark",
"in",
"a",
"CJK",
"language",
"."
] | train | https://github.com/bobbyesh/word-fencer/blob/267b9770611bf9f19ec5dd6e5190ef185ed0bfb4/wordfencer/parser.py#L34-L38 |
bobbyesh/word-fencer | wordfencer/parser.py | parser_factory | def parser_factory(lang):
"""Returns a Parser object specific to the language specified by :param:`lang`.
:param lang: A string naming the desired parser. See the keys in :var:`class_`
for valid strings.
:Example:
>>> chinese_parser = parser_factory('zh-Hans')
>>> isinstance(chinese_parser, ... | python | def parser_factory(lang):
"""Returns a Parser object specific to the language specified by :param:`lang`.
:param lang: A string naming the desired parser. See the keys in :var:`class_`
for valid strings.
:Example:
>>> chinese_parser = parser_factory('zh-Hans')
>>> isinstance(chinese_parser, ... | [
"def",
"parser_factory",
"(",
"lang",
")",
":",
"class_",
"=",
"{",
"'zh-Hans'",
":",
"ChineseSimplifiedParser",
",",
"'zh-Hant'",
":",
"ChineseTraditionalParser",
",",
"'zh'",
":",
"ChineseParser",
",",
"'yue-Hans'",
":",
"CantoneseSimplifiedParser",
",",
"'yue-Han... | Returns a Parser object specific to the language specified by :param:`lang`.
:param lang: A string naming the desired parser. See the keys in :var:`class_`
for valid strings.
:Example:
>>> chinese_parser = parser_factory('zh-Hans')
>>> isinstance(chinese_parser, ChineseSimplifiedParser)
True... | [
"Returns",
"a",
"Parser",
"object",
"specific",
"to",
"the",
"language",
"specified",
"by",
":",
"param",
":",
"lang",
"."
] | train | https://github.com/bobbyesh/word-fencer/blob/267b9770611bf9f19ec5dd6e5190ef185ed0bfb4/wordfencer/parser.py#L41-L69 |
bobbyesh/word-fencer | wordfencer/parser.py | Parser.parse | def parse(self, string, all_combos=False):
"""Returns a list of words created from segmenting :arg:`string`.
..note: When a series of characters could match a shorter dictionary entry or
longer entry, the longer one is always selected.
"""
if not all_combos:
return ... | python | def parse(self, string, all_combos=False):
"""Returns a list of words created from segmenting :arg:`string`.
..note: When a series of characters could match a shorter dictionary entry or
longer entry, the longer one is always selected.
"""
if not all_combos:
return ... | [
"def",
"parse",
"(",
"self",
",",
"string",
",",
"all_combos",
"=",
"False",
")",
":",
"if",
"not",
"all_combos",
":",
"return",
"self",
".",
"default_parse",
"(",
"string",
")",
"else",
":",
"return",
"self",
".",
"all_combinations",
"(",
"string",
")"
... | Returns a list of words created from segmenting :arg:`string`.
..note: When a series of characters could match a shorter dictionary entry or
longer entry, the longer one is always selected. | [
"Returns",
"a",
"list",
"of",
"words",
"created",
"from",
"segmenting",
":",
"arg",
":",
"string",
"."
] | train | https://github.com/bobbyesh/word-fencer/blob/267b9770611bf9f19ec5dd6e5190ef185ed0bfb4/wordfencer/parser.py#L104-L113 |
bobbyesh/word-fencer | wordfencer/parser.py | Parser.default_parse | def default_parse(self, string):
"""Returns a list of words created from segmenting :arg:`string`.
..note: When a series of characters could match a shorter dictionary entry or
longer entry, the longer one is always selected.
"""
results = list()
while(string):
... | python | def default_parse(self, string):
"""Returns a list of words created from segmenting :arg:`string`.
..note: When a series of characters could match a shorter dictionary entry or
longer entry, the longer one is always selected.
"""
results = list()
while(string):
... | [
"def",
"default_parse",
"(",
"self",
",",
"string",
")",
":",
"results",
"=",
"list",
"(",
")",
"while",
"(",
"string",
")",
":",
"token",
"=",
"self",
".",
"longest",
"(",
"string",
")",
"results",
".",
"append",
"(",
"token",
")",
"string",
"=",
... | Returns a list of words created from segmenting :arg:`string`.
..note: When a series of characters could match a shorter dictionary entry or
longer entry, the longer one is always selected. | [
"Returns",
"a",
"list",
"of",
"words",
"created",
"from",
"segmenting",
":",
"arg",
":",
"string",
"."
] | train | https://github.com/bobbyesh/word-fencer/blob/267b9770611bf9f19ec5dd6e5190ef185ed0bfb4/wordfencer/parser.py#L116-L127 |
bobbyesh/word-fencer | wordfencer/parser.py | Parser.force_populate | def force_populate(self):
"""
Populates the parser with the entire contents of the
word reference file.
"""
if not os.path.exists(self.ref):
raise FileNotFoundError("The reference file path '{}' does not exists.".format(self.ref))
with open(self.ref, 'r') as f... | python | def force_populate(self):
"""
Populates the parser with the entire contents of the
word reference file.
"""
if not os.path.exists(self.ref):
raise FileNotFoundError("The reference file path '{}' does not exists.".format(self.ref))
with open(self.ref, 'r') as f... | [
"def",
"force_populate",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"ref",
")",
":",
"raise",
"FileNotFoundError",
"(",
"\"The reference file path '{}' does not exists.\"",
".",
"format",
"(",
"self",
".",
"ref",
... | Populates the parser with the entire contents of the
word reference file. | [
"Populates",
"the",
"parser",
"with",
"the",
"entire",
"contents",
"of",
"the",
"word",
"reference",
"file",
"."
] | train | https://github.com/bobbyesh/word-fencer/blob/267b9770611bf9f19ec5dd6e5190ef185ed0bfb4/wordfencer/parser.py#L156-L167 |
emencia/emencia-django-countries | emencia/django/countries/managers.py | CountryManager.leveled | def leveled(self):
"""Return all countries with a level set"""
# Compatibility support for Django<1.6
safe_get_queryset = (self.get_query_set if hasattr(self, 'get_query_set') else self.get_queryset)
return safe_get_queryset.exclude(level=0) | python | def leveled(self):
"""Return all countries with a level set"""
# Compatibility support for Django<1.6
safe_get_queryset = (self.get_query_set if hasattr(self, 'get_query_set') else self.get_queryset)
return safe_get_queryset.exclude(level=0) | [
"def",
"leveled",
"(",
"self",
")",
":",
"# Compatibility support for Django<1.6",
"safe_get_queryset",
"=",
"(",
"self",
".",
"get_query_set",
"if",
"hasattr",
"(",
"self",
",",
"'get_query_set'",
")",
"else",
"self",
".",
"get_queryset",
")",
"return",
"safe_get... | Return all countries with a level set | [
"Return",
"all",
"countries",
"with",
"a",
"level",
"set"
] | train | https://github.com/emencia/emencia-django-countries/blob/5ae8719f4b43caeca2c69c9e37e6d6bc5d7b0290/emencia/django/countries/managers.py#L7-L13 |
kenlowrie/pylib | kenl380/pylib/pylib.py | pushd | def pushd(dir=None, throw_if_dir_invalid=True):
"""Push the current working directory (CWD) onto a stack, set CWD to 'dir'
Save the CWD onto a global stack so that we can return to it later. If dir
is None, the function simply stores the CWD onto the stack and returns.
Use :py:meth:`popd()` to restore ... | python | def pushd(dir=None, throw_if_dir_invalid=True):
"""Push the current working directory (CWD) onto a stack, set CWD to 'dir'
Save the CWD onto a global stack so that we can return to it later. If dir
is None, the function simply stores the CWD onto the stack and returns.
Use :py:meth:`popd()` to restore ... | [
"def",
"pushd",
"(",
"dir",
"=",
"None",
",",
"throw_if_dir_invalid",
"=",
"True",
")",
":",
"global",
"_pushdstack",
"from",
"os",
"import",
"getcwd",
",",
"chdir",
"if",
"dir",
"is",
"None",
":",
"dir",
"=",
"getcwd",
"(",
")",
"if",
"not",
"isinstan... | Push the current working directory (CWD) onto a stack, set CWD to 'dir'
Save the CWD onto a global stack so that we can return to it later. If dir
is None, the function simply stores the CWD onto the stack and returns.
Use :py:meth:`popd()` to restore the original directory.
Parameters
----------
... | [
"Push",
"the",
"current",
"working",
"directory",
"(",
"CWD",
")",
"onto",
"a",
"stack",
"set",
"CWD",
"to",
"dir"
] | train | https://github.com/kenlowrie/pylib/blob/3c288889ab27fc29b065016853faecd0a14c4224/kenl380/pylib/pylib.py#L399-L460 |
kenlowrie/pylib | kenl380/pylib/pylib.py | popd | def popd(pop_all=False, throw_if_dir_invalid=True):
"""Restore current working directory to previous directory.
The previous directory is whatever it was when last :py:meth:`pushd()` was
*last* called. :py:meth:`pushd()` creates a stack, so each call to popd()
simply sets the CWD back to what it was ... | python | def popd(pop_all=False, throw_if_dir_invalid=True):
"""Restore current working directory to previous directory.
The previous directory is whatever it was when last :py:meth:`pushd()` was
*last* called. :py:meth:`pushd()` creates a stack, so each call to popd()
simply sets the CWD back to what it was ... | [
"def",
"popd",
"(",
"pop_all",
"=",
"False",
",",
"throw_if_dir_invalid",
"=",
"True",
")",
":",
"global",
"_pushdstack",
"from",
"os",
"import",
"chdir",
"if",
"len",
"(",
"_pushdstack",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"popd() called on a... | Restore current working directory to previous directory.
The previous directory is whatever it was when last :py:meth:`pushd()` was
*last* called. :py:meth:`pushd()` creates a stack, so each call to popd()
simply sets the CWD back to what it was on the prior pushd() call.
Parameters
----------
... | [
"Restore",
"current",
"working",
"directory",
"to",
"previous",
"directory",
"."
] | train | https://github.com/kenlowrie/pylib/blob/3c288889ab27fc29b065016853faecd0a14c4224/kenl380/pylib/pylib.py#L462-L520 |
kenlowrie/pylib | kenl380/pylib/pylib.py | context.pyVersionStr | def pyVersionStr(self):
"""Version of Python running my script
Returns
-------
str
A descriptive string containing the version of Python running
this script.
"""
from sys import version_info
return "Python Interpreter Version: {}.{}.{}".f... | python | def pyVersionStr(self):
"""Version of Python running my script
Returns
-------
str
A descriptive string containing the version of Python running
this script.
"""
from sys import version_info
return "Python Interpreter Version: {}.{}.{}".f... | [
"def",
"pyVersionStr",
"(",
"self",
")",
":",
"from",
"sys",
"import",
"version_info",
"return",
"\"Python Interpreter Version: {}.{}.{}\"",
".",
"format",
"(",
"version_info",
".",
"major",
",",
"version_info",
".",
"minor",
",",
"version_info",
".",
"micro",
")"... | Version of Python running my script
Returns
-------
str
A descriptive string containing the version of Python running
this script. | [
"Version",
"of",
"Python",
"running",
"my",
"script"
] | train | https://github.com/kenlowrie/pylib/blob/3c288889ab27fc29b065016853faecd0a14c4224/kenl380/pylib/pylib.py#L123-L136 |
kenlowrie/pylib | kenl380/pylib/pylib.py | ntpx.all | def all(self):
"""Returns a tuple containing all elements of the object
This method returns all elements of the path in the form of a tuple.
e.g.: `(abs_path, drive_letter, path_only, rootname, extension,
filesize, time_in_seconds)`.
Returns
-------
tuple
... | python | def all(self):
"""Returns a tuple containing all elements of the object
This method returns all elements of the path in the form of a tuple.
e.g.: `(abs_path, drive_letter, path_only, rootname, extension,
filesize, time_in_seconds)`.
Returns
-------
tuple
... | [
"def",
"all",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"_full",
",",
"self",
".",
"_driv",
",",
"self",
".",
"_path",
",",
"self",
".",
"_name",
",",
"self",
".",
"_ext",
",",
"self",
".",
"_size",
",",
"self",
".",
"_time",
")"
] | Returns a tuple containing all elements of the object
This method returns all elements of the path in the form of a tuple.
e.g.: `(abs_path, drive_letter, path_only, rootname, extension,
filesize, time_in_seconds)`.
Returns
-------
tuple
All elements of t... | [
"Returns",
"a",
"tuple",
"containing",
"all",
"elements",
"of",
"the",
"object"
] | train | https://github.com/kenlowrie/pylib/blob/3c288889ab27fc29b065016853faecd0a14c4224/kenl380/pylib/pylib.py#L237-L255 |
kenlowrie/pylib | kenl380/pylib/pylib.py | ntpx.format | def format(self, fmt):
"""Returns string representing the items specified in the format string
The format string can contain:
.. code::
d - drive letter
p - path
n - name
x - extension
z - file size
t - file time in secon... | python | def format(self, fmt):
"""Returns string representing the items specified in the format string
The format string can contain:
.. code::
d - drive letter
p - path
n - name
x - extension
z - file size
t - file time in secon... | [
"def",
"format",
"(",
"self",
",",
"fmt",
")",
":",
"val",
"=",
"''",
"for",
"x",
"in",
"fmt",
":",
"if",
"x",
"==",
"'d'",
":",
"val",
"+=",
"self",
".",
"_driv",
"elif",
"x",
"==",
"'p'",
":",
"val",
"+=",
"self",
".",
"_path",
"elif",
"x",... | Returns string representing the items specified in the format string
The format string can contain:
.. code::
d - drive letter
p - path
n - name
x - extension
z - file size
t - file time in seconds
And, you can string th... | [
"Returns",
"string",
"representing",
"the",
"items",
"specified",
"in",
"the",
"format",
"string"
] | train | https://github.com/kenlowrie/pylib/blob/3c288889ab27fc29b065016853faecd0a14c4224/kenl380/pylib/pylib.py#L257-L309 |
codenerix/django-codenerix-extensions | codenerix_extensions/views.py | GenCreateBridge.form_valid_bridge | def form_valid_bridge(self, form, field, model, related_field, error_message):
"""
call from form_valid.
@form: it is form of form_valid (type: form)
@field: name of the form field referring to the brigde (type: string)
@model: form's model (type class)
@related_field: na... | python | def form_valid_bridge(self, form, field, model, related_field, error_message):
"""
call from form_valid.
@form: it is form of form_valid (type: form)
@field: name of the form field referring to the brigde (type: string)
@model: form's model (type class)
@related_field: na... | [
"def",
"form_valid_bridge",
"(",
"self",
",",
"form",
",",
"field",
",",
"model",
",",
"related_field",
",",
"error_message",
")",
":",
"# get instance of selected external object",
"external",
"=",
"form",
".",
"cleaned_data",
"[",
"field",
"]",
"related_object",
... | call from form_valid.
@form: it is form of form_valid (type: form)
@field: name of the form field referring to the brigde (type: string)
@model: form's model (type class)
@related_field: name of the related_name of the brigde (type: string)
@error_message: list of message errors ... | [
"call",
"from",
"form_valid",
"."
] | train | https://github.com/codenerix/django-codenerix-extensions/blob/e9c1d6f99f3e05833ab103bed2689ec34d64e591/codenerix_extensions/views.py#L33-L79 |
codenerix/django-codenerix-extensions | codenerix_extensions/views.py | GenUpdateBridge.form_valid_bridge | def form_valid_bridge(self, form, field, model, related_field, error_message):
"""
call from form_valid.
@form: it is form of form_valid (type: form)
@field: name of the form field referring to the brigde (type: string)
@model: form's model (type class)
@related_field: na... | python | def form_valid_bridge(self, form, field, model, related_field, error_message):
"""
call from form_valid.
@form: it is form of form_valid (type: form)
@field: name of the form field referring to the brigde (type: string)
@model: form's model (type class)
@related_field: na... | [
"def",
"form_valid_bridge",
"(",
"self",
",",
"form",
",",
"field",
",",
"model",
",",
"related_field",
",",
"error_message",
")",
":",
"# get instance of selected external object",
"external",
"=",
"form",
".",
"cleaned_data",
"[",
"field",
"]",
"object_edit",
"=... | call from form_valid.
@form: it is form of form_valid (type: form)
@field: name of the form field referring to the brigde (type: string)
@model: form's model (type class)
@related_field: name of the related_name of the brigde (type: string)
@error_message: list of message errors ... | [
"call",
"from",
"form_valid",
"."
] | train | https://github.com/codenerix/django-codenerix-extensions/blob/e9c1d6f99f3e05833ab103bed2689ec34d64e591/codenerix_extensions/views.py#L83-L126 |
lvh/maxims | maxims/caching.py | cached | def cached(attr):
"""
In-memory caching for a nullary callable.
"""
def decorator(f):
@functools.wraps(f)
def decorated(self):
try:
return getattr(self, attr)
except AttributeError:
value = f(self)
setattr(self, attr... | python | def cached(attr):
"""
In-memory caching for a nullary callable.
"""
def decorator(f):
@functools.wraps(f)
def decorated(self):
try:
return getattr(self, attr)
except AttributeError:
value = f(self)
setattr(self, attr... | [
"def",
"cached",
"(",
"attr",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"decorated",
"(",
"self",
")",
":",
"try",
":",
"return",
"getattr",
"(",
"self",
",",
"attr",
")",
"except",
"A... | In-memory caching for a nullary callable. | [
"In",
"-",
"memory",
"caching",
"for",
"a",
"nullary",
"callable",
"."
] | train | https://github.com/lvh/maxims/blob/5c53b25d2cc4ccecbfe90193ade9ce0dbfbe4623/maxims/caching.py#L7-L22 |
OpenGov/carpenter | carpenter/blocks/cellanalyzer.py | get_cell_type | def get_cell_type(cell):
'''
Returns a type to be used in table cell analysis. This is either
'basestring' or '(int, float)'.
'''
cell_type = None
if isinstance(cell, basestring) and cell:
cell_type = basestring
elif isinstance(cell, (int, float)):
cell_type = (int, float)
... | python | def get_cell_type(cell):
'''
Returns a type to be used in table cell analysis. This is either
'basestring' or '(int, float)'.
'''
cell_type = None
if isinstance(cell, basestring) and cell:
cell_type = basestring
elif isinstance(cell, (int, float)):
cell_type = (int, float)
... | [
"def",
"get_cell_type",
"(",
"cell",
")",
":",
"cell_type",
"=",
"None",
"if",
"isinstance",
"(",
"cell",
",",
"basestring",
")",
"and",
"cell",
":",
"cell_type",
"=",
"basestring",
"elif",
"isinstance",
"(",
"cell",
",",
"(",
"int",
",",
"float",
")",
... | Returns a type to be used in table cell analysis. This is either
'basestring' or '(int, float)'. | [
"Returns",
"a",
"type",
"to",
"be",
"used",
"in",
"table",
"cell",
"analysis",
".",
"This",
"is",
"either",
"basestring",
"or",
"(",
"int",
"float",
")",
"."
] | train | https://github.com/OpenGov/carpenter/blob/0ab3c54c05133b9b0468c63e834a7ce3a6fb575b/carpenter/blocks/cellanalyzer.py#L30-L41 |
OpenGov/carpenter | carpenter/blocks/cellanalyzer.py | check_cell_type | def check_cell_type(cell, cell_type):
'''
Checks the cell type to see if it represents the cell_type passed in.
Args:
cell_type: The type id for a cell match or None for empty match.
'''
if cell_type == None or cell_type == type(None):
return cell == None or (isinstance(cell, basest... | python | def check_cell_type(cell, cell_type):
'''
Checks the cell type to see if it represents the cell_type passed in.
Args:
cell_type: The type id for a cell match or None for empty match.
'''
if cell_type == None or cell_type == type(None):
return cell == None or (isinstance(cell, basest... | [
"def",
"check_cell_type",
"(",
"cell",
",",
"cell_type",
")",
":",
"if",
"cell_type",
"==",
"None",
"or",
"cell_type",
"==",
"type",
"(",
"None",
")",
":",
"return",
"cell",
"==",
"None",
"or",
"(",
"isinstance",
"(",
"cell",
",",
"basestring",
")",
"a... | Checks the cell type to see if it represents the cell_type passed in.
Args:
cell_type: The type id for a cell match or None for empty match. | [
"Checks",
"the",
"cell",
"type",
"to",
"see",
"if",
"it",
"represents",
"the",
"cell_type",
"passed",
"in",
"."
] | train | https://github.com/OpenGov/carpenter/blob/0ab3c54c05133b9b0468c63e834a7ce3a6fb575b/carpenter/blocks/cellanalyzer.py#L44-L54 |
OpenGov/carpenter | carpenter/blocks/cellanalyzer.py | auto_convert_cell_no_flags | def auto_convert_cell_no_flags(cell, units=None, parens_as_neg=True):
'''
Performs a first step conversion of the cell to check
it's type or try to convert if a valid conversion exists.
This version of conversion doesn't flag changes nor store
cell units.
Args:
units: The dictionary hol... | python | def auto_convert_cell_no_flags(cell, units=None, parens_as_neg=True):
'''
Performs a first step conversion of the cell to check
it's type or try to convert if a valid conversion exists.
This version of conversion doesn't flag changes nor store
cell units.
Args:
units: The dictionary hol... | [
"def",
"auto_convert_cell_no_flags",
"(",
"cell",
",",
"units",
"=",
"None",
",",
"parens_as_neg",
"=",
"True",
")",
":",
"units",
"=",
"units",
"if",
"units",
"!=",
"None",
"else",
"{",
"}",
"return",
"auto_convert_cell",
"(",
"flagable",
"=",
"Flagable",
... | Performs a first step conversion of the cell to check
it's type or try to convert if a valid conversion exists.
This version of conversion doesn't flag changes nor store
cell units.
Args:
units: The dictionary holder for cell units.
parens_as_neg: Converts numerics surrounded by parens ... | [
"Performs",
"a",
"first",
"step",
"conversion",
"of",
"the",
"cell",
"to",
"check",
"it",
"s",
"type",
"or",
"try",
"to",
"convert",
"if",
"a",
"valid",
"conversion",
"exists",
".",
"This",
"version",
"of",
"conversion",
"doesn",
"t",
"flag",
"changes",
... | train | https://github.com/OpenGov/carpenter/blob/0ab3c54c05133b9b0468c63e834a7ce3a6fb575b/carpenter/blocks/cellanalyzer.py#L56-L70 |
OpenGov/carpenter | carpenter/blocks/cellanalyzer.py | auto_convert_cell | def auto_convert_cell(flagable, cell, position, worksheet, flags, units, parens_as_neg=True):
'''
Performs a first step conversion of the cell to check
it's type or try to convert if a valid conversion exists.
Args:
parens_as_neg: Converts numerics surrounded by parens to negative values
''... | python | def auto_convert_cell(flagable, cell, position, worksheet, flags, units, parens_as_neg=True):
'''
Performs a first step conversion of the cell to check
it's type or try to convert if a valid conversion exists.
Args:
parens_as_neg: Converts numerics surrounded by parens to negative values
''... | [
"def",
"auto_convert_cell",
"(",
"flagable",
",",
"cell",
",",
"position",
",",
"worksheet",
",",
"flags",
",",
"units",
",",
"parens_as_neg",
"=",
"True",
")",
":",
"conversion",
"=",
"cell",
"# Is an numeric?",
"if",
"isinstance",
"(",
"cell",
",",
"(",
... | Performs a first step conversion of the cell to check
it's type or try to convert if a valid conversion exists.
Args:
parens_as_neg: Converts numerics surrounded by parens to negative values | [
"Performs",
"a",
"first",
"step",
"conversion",
"of",
"the",
"cell",
"to",
"check",
"it",
"s",
"type",
"or",
"try",
"to",
"convert",
"if",
"a",
"valid",
"conversion",
"exists",
"."
] | train | https://github.com/OpenGov/carpenter/blob/0ab3c54c05133b9b0468c63e834a7ce3a6fb575b/carpenter/blocks/cellanalyzer.py#L72-L107 |
OpenGov/carpenter | carpenter/blocks/cellanalyzer.py | auto_convert_string_cell | def auto_convert_string_cell(flagable, cell_str, position, worksheet, flags,
units, parens_as_neg=True):
'''
Handles the string case of cell and attempts auto-conversion
for auto_convert_cell.
Args:
parens_as_neg: Converts numerics surrounded by parens to negative v... | python | def auto_convert_string_cell(flagable, cell_str, position, worksheet, flags,
units, parens_as_neg=True):
'''
Handles the string case of cell and attempts auto-conversion
for auto_convert_cell.
Args:
parens_as_neg: Converts numerics surrounded by parens to negative v... | [
"def",
"auto_convert_string_cell",
"(",
"flagable",
",",
"cell_str",
",",
"position",
",",
"worksheet",
",",
"flags",
",",
"units",
",",
"parens_as_neg",
"=",
"True",
")",
":",
"conversion",
"=",
"cell_str",
".",
"strip",
"(",
")",
"# Wrapped?",
"if",
"re",
... | Handles the string case of cell and attempts auto-conversion
for auto_convert_cell.
Args:
parens_as_neg: Converts numerics surrounded by parens to negative values | [
"Handles",
"the",
"string",
"case",
"of",
"cell",
"and",
"attempts",
"auto",
"-",
"conversion",
"for",
"auto_convert_cell",
"."
] | train | https://github.com/OpenGov/carpenter/blob/0ab3c54c05133b9b0468c63e834a7ce3a6fb575b/carpenter/blocks/cellanalyzer.py#L109-L151 |
OpenGov/carpenter | carpenter/blocks/cellanalyzer.py | auto_convert_numeric_string_cell | def auto_convert_numeric_string_cell(flagable, cell_str, position, worksheet, flags, units):
'''
Handles the string containing numeric case of cell and attempts
auto-conversion for auto_convert_cell.
'''
def numerify_str(cell_str, flag_level='minor', flag_text=""):
'''
Differentiates... | python | def auto_convert_numeric_string_cell(flagable, cell_str, position, worksheet, flags, units):
'''
Handles the string containing numeric case of cell and attempts
auto-conversion for auto_convert_cell.
'''
def numerify_str(cell_str, flag_level='minor', flag_text=""):
'''
Differentiates... | [
"def",
"auto_convert_numeric_string_cell",
"(",
"flagable",
",",
"cell_str",
",",
"position",
",",
"worksheet",
",",
"flags",
",",
"units",
")",
":",
"def",
"numerify_str",
"(",
"cell_str",
",",
"flag_level",
"=",
"'minor'",
",",
"flag_text",
"=",
"\"\"",
")",... | Handles the string containing numeric case of cell and attempts
auto-conversion for auto_convert_cell. | [
"Handles",
"the",
"string",
"containing",
"numeric",
"case",
"of",
"cell",
"and",
"attempts",
"auto",
"-",
"conversion",
"for",
"auto_convert_cell",
"."
] | train | https://github.com/OpenGov/carpenter/blob/0ab3c54c05133b9b0468c63e834a7ce3a6fb575b/carpenter/blocks/cellanalyzer.py#L153-L242 |
universalcore/unicore.hub.client | unicore/hub/client/appclient.py | App.set | def set(self, field, value):
"""
Sets the value of an app field.
:param str field:
The name of the app field. Trying to set immutable fields
``uuid`` or ``key`` will raise a ValueError.
:param value:
The new value of the app field.
:raises: Va... | python | def set(self, field, value):
"""
Sets the value of an app field.
:param str field:
The name of the app field. Trying to set immutable fields
``uuid`` or ``key`` will raise a ValueError.
:param value:
The new value of the app field.
:raises: Va... | [
"def",
"set",
"(",
"self",
",",
"field",
",",
"value",
")",
":",
"if",
"field",
"==",
"'uuid'",
":",
"raise",
"ValueError",
"(",
"'uuid cannot be set'",
")",
"elif",
"field",
"==",
"'key'",
":",
"raise",
"ValueError",
"(",
"'key cannot be set. Use \\'reset_key... | Sets the value of an app field.
:param str field:
The name of the app field. Trying to set immutable fields
``uuid`` or ``key`` will raise a ValueError.
:param value:
The new value of the app field.
:raises: ValueError | [
"Sets",
"the",
"value",
"of",
"an",
"app",
"field",
"."
] | train | https://github.com/universalcore/unicore.hub.client/blob/c706f4d31e493bd4e7ea8236780a9b271b850b8b/unicore/hub/client/appclient.py#L66-L83 |
universalcore/unicore.hub.client | unicore/hub/client/appclient.py | App.reset_key | def reset_key(self):
"""
Resets the app's key on the `unicore.hub` server.
:returns: str -- the new key
"""
new_key = self.client.reset_app_key(self.get('uuid'))
self.data['key'] = new_key
return new_key | python | def reset_key(self):
"""
Resets the app's key on the `unicore.hub` server.
:returns: str -- the new key
"""
new_key = self.client.reset_app_key(self.get('uuid'))
self.data['key'] = new_key
return new_key | [
"def",
"reset_key",
"(",
"self",
")",
":",
"new_key",
"=",
"self",
".",
"client",
".",
"reset_app_key",
"(",
"self",
".",
"get",
"(",
"'uuid'",
")",
")",
"self",
".",
"data",
"[",
"'key'",
"]",
"=",
"new_key",
"return",
"new_key"
] | Resets the app's key on the `unicore.hub` server.
:returns: str -- the new key | [
"Resets",
"the",
"app",
"s",
"key",
"on",
"the",
"unicore",
".",
"hub",
"server",
"."
] | train | https://github.com/universalcore/unicore.hub.client/blob/c706f4d31e493bd4e7ea8236780a9b271b850b8b/unicore/hub/client/appclient.py#L97-L105 |
mddub/everytrail_export | everytrail_export/scraper.py | trip_name_to_directory_name | def trip_name_to_directory_name(name):
"""Convert a name like "Mt. Tam: Ridgecrest Blvd to Alpine Lake via..." to
something like "mt-tam-ridgecrest-blvd-to-alpi".
"""
out = name.lower()
out = re.sub('[:/\ ]', '-', out)
out = re.sub('[.,]', '', out)
out = re.sub('--+', '-', out)
out = out... | python | def trip_name_to_directory_name(name):
"""Convert a name like "Mt. Tam: Ridgecrest Blvd to Alpine Lake via..." to
something like "mt-tam-ridgecrest-blvd-to-alpi".
"""
out = name.lower()
out = re.sub('[:/\ ]', '-', out)
out = re.sub('[.,]', '', out)
out = re.sub('--+', '-', out)
out = out... | [
"def",
"trip_name_to_directory_name",
"(",
"name",
")",
":",
"out",
"=",
"name",
".",
"lower",
"(",
")",
"out",
"=",
"re",
".",
"sub",
"(",
"'[:/\\ ]'",
",",
"'-'",
",",
"out",
")",
"out",
"=",
"re",
".",
"sub",
"(",
"'[.,]'",
",",
"''",
",",
"ou... | Convert a name like "Mt. Tam: Ridgecrest Blvd to Alpine Lake via..." to
something like "mt-tam-ridgecrest-blvd-to-alpi". | [
"Convert",
"a",
"name",
"like",
"Mt",
".",
"Tam",
":",
"Ridgecrest",
"Blvd",
"to",
"Alpine",
"Lake",
"via",
"...",
"to",
"something",
"like",
"mt",
"-",
"tam",
"-",
"ridgecrest",
"-",
"blvd",
"-",
"to",
"-",
"alpi",
"."
] | train | https://github.com/mddub/everytrail_export/blob/1fd7729e64f0d78726f8a0ebf464711c39179d6c/everytrail_export/scraper.py#L32-L41 |
mikerhodes/actionqueues | actionqueues/exceptionfactory.py | DoublingBackoffExceptionFactory.raise_exception | def raise_exception(self, original_exception=None):
"""Raise a retry exception if under the max retries. After, raise the
original_exception provided to this method or a generic Exception if
none provided.
"""
if self._executed_retries < self._max_retries:
curr_backof... | python | def raise_exception(self, original_exception=None):
"""Raise a retry exception if under the max retries. After, raise the
original_exception provided to this method or a generic Exception if
none provided.
"""
if self._executed_retries < self._max_retries:
curr_backof... | [
"def",
"raise_exception",
"(",
"self",
",",
"original_exception",
"=",
"None",
")",
":",
"if",
"self",
".",
"_executed_retries",
"<",
"self",
".",
"_max_retries",
":",
"curr_backoff",
"=",
"self",
".",
"_ms_backoff",
"self",
".",
"_executed_retries",
"+=",
"1"... | Raise a retry exception if under the max retries. After, raise the
original_exception provided to this method or a generic Exception if
none provided. | [
"Raise",
"a",
"retry",
"exception",
"if",
"under",
"the",
"max",
"retries",
".",
"After",
"raise",
"the",
"original_exception",
"provided",
"to",
"this",
"method",
"or",
"a",
"generic",
"Exception",
"if",
"none",
"provided",
"."
] | train | https://github.com/mikerhodes/actionqueues/blob/a7a78ab116abe88af95b5315dc9f34d40ce81eb2/actionqueues/exceptionfactory.py#L20-L31 |
datakortet/dkfileutils | dkfileutils/listfiles.py | read_skipfile | def read_skipfile(dirname='.', defaults=None):
"""The .skipfile should contain one entry per line,
listing files/directories that should be skipped by
:func:`list_files`.
"""
if defaults is None:
defaults = ['Makefile', 'make.bat', 'atlassian-ide-plugin.xml']
try:
return de... | python | def read_skipfile(dirname='.', defaults=None):
"""The .skipfile should contain one entry per line,
listing files/directories that should be skipped by
:func:`list_files`.
"""
if defaults is None:
defaults = ['Makefile', 'make.bat', 'atlassian-ide-plugin.xml']
try:
return de... | [
"def",
"read_skipfile",
"(",
"dirname",
"=",
"'.'",
",",
"defaults",
"=",
"None",
")",
":",
"if",
"defaults",
"is",
"None",
":",
"defaults",
"=",
"[",
"'Makefile'",
",",
"'make.bat'",
",",
"'atlassian-ide-plugin.xml'",
"]",
"try",
":",
"return",
"defaults",
... | The .skipfile should contain one entry per line,
listing files/directories that should be skipped by
:func:`list_files`. | [
"The",
".",
"skipfile",
"should",
"contain",
"one",
"entry",
"per",
"line",
"listing",
"files",
"/",
"directories",
"that",
"should",
"be",
"skipped",
"by",
":",
"func",
":",
"list_files",
"."
] | train | https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/listfiles.py#L13-L25 |
datakortet/dkfileutils | dkfileutils/listfiles.py | list_files | def list_files(dirname='.', digest=True):
"""Yield (digest, fname) tuples for all interesting files
in `dirname`.
"""
skipdirs = ['__pycache__', '.git', '.svn', 'htmlcov', 'dist', 'build',
'.idea', 'tasks', 'static', 'media', 'data', 'migrations',
'.doctrees', '_static... | python | def list_files(dirname='.', digest=True):
"""Yield (digest, fname) tuples for all interesting files
in `dirname`.
"""
skipdirs = ['__pycache__', '.git', '.svn', 'htmlcov', 'dist', 'build',
'.idea', 'tasks', 'static', 'media', 'data', 'migrations',
'.doctrees', '_static... | [
"def",
"list_files",
"(",
"dirname",
"=",
"'.'",
",",
"digest",
"=",
"True",
")",
":",
"skipdirs",
"=",
"[",
"'__pycache__'",
",",
"'.git'",
",",
"'.svn'",
",",
"'htmlcov'",
",",
"'dist'",
",",
"'build'",
",",
"'.idea'",
",",
"'tasks'",
",",
"'static'",
... | Yield (digest, fname) tuples for all interesting files
in `dirname`. | [
"Yield",
"(",
"digest",
"fname",
")",
"tuples",
"for",
"all",
"interesting",
"files",
"in",
"dirname",
"."
] | train | https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/listfiles.py#L28-L82 |
datakortet/dkfileutils | dkfileutils/listfiles.py | main | def main(): # pragma: nocover
"""Print checksum and file name for all files in the directory.
"""
p = argparse.ArgumentParser(add_help="Recursively list interesting files.")
p.add_argument(
'directory', nargs="?", default="",
help="The directory to process (current dir if omitted)."
... | python | def main(): # pragma: nocover
"""Print checksum and file name for all files in the directory.
"""
p = argparse.ArgumentParser(add_help="Recursively list interesting files.")
p.add_argument(
'directory', nargs="?", default="",
help="The directory to process (current dir if omitted)."
... | [
"def",
"main",
"(",
")",
":",
"# pragma: nocover",
"p",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"add_help",
"=",
"\"Recursively list interesting files.\"",
")",
"p",
".",
"add_argument",
"(",
"'directory'",
",",
"nargs",
"=",
"\"?\"",
",",
"default",
"=",
... | Print checksum and file name for all files in the directory. | [
"Print",
"checksum",
"and",
"file",
"name",
"for",
"all",
"files",
"in",
"the",
"directory",
"."
] | train | https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/listfiles.py#L85-L106 |
timeyyy/apptools | peasoup/pidutil.py | process_exists | def process_exists(pid=None):
"""
Evaluates a Pid Value defaults to the currently foucsed window
against the current open programs,
if there is a match returns the process name and pid
otherwise returns None, None
"""
if not pid:
pid = current_pid()
elif callable(pid):
pi... | python | def process_exists(pid=None):
"""
Evaluates a Pid Value defaults to the currently foucsed window
against the current open programs,
if there is a match returns the process name and pid
otherwise returns None, None
"""
if not pid:
pid = current_pid()
elif callable(pid):
pi... | [
"def",
"process_exists",
"(",
"pid",
"=",
"None",
")",
":",
"if",
"not",
"pid",
":",
"pid",
"=",
"current_pid",
"(",
")",
"elif",
"callable",
"(",
"pid",
")",
":",
"pid",
"=",
"pid",
"(",
")",
"if",
"pid",
"and",
"psutil",
".",
"pid_exists",
"(",
... | Evaluates a Pid Value defaults to the currently foucsed window
against the current open programs,
if there is a match returns the process name and pid
otherwise returns None, None | [
"Evaluates",
"a",
"Pid",
"Value",
"defaults",
"to",
"the",
"currently",
"foucsed",
"window",
"against",
"the",
"current",
"open",
"programs",
"if",
"there",
"is",
"a",
"match",
"returns",
"the",
"process",
"name",
"and",
"pid",
"otherwise",
"returns",
"None",
... | train | https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/pidutil.py#L22-L39 |
timeyyy/apptools | peasoup/pidutil.py | move_active_window | def move_active_window(x, y):
"""
Moves the active window to a given position given the window_id and absolute co ordinates,
--sync option auto passed in, will wait until actually moved before giving control back to us
will do nothing if the window is maximized
"""
window_id = get_window_id()
... | python | def move_active_window(x, y):
"""
Moves the active window to a given position given the window_id and absolute co ordinates,
--sync option auto passed in, will wait until actually moved before giving control back to us
will do nothing if the window is maximized
"""
window_id = get_window_id()
... | [
"def",
"move_active_window",
"(",
"x",
",",
"y",
")",
":",
"window_id",
"=",
"get_window_id",
"(",
")",
"cmd",
"=",
"[",
"'xdotool'",
",",
"'windowmove'",
",",
"window_id",
",",
"str",
"(",
"x",
")",
",",
"str",
"(",
"y",
")",
"]",
"subprocess",
".",... | Moves the active window to a given position given the window_id and absolute co ordinates,
--sync option auto passed in, will wait until actually moved before giving control back to us
will do nothing if the window is maximized | [
"Moves",
"the",
"active",
"window",
"to",
"a",
"given",
"position",
"given",
"the",
"window_id",
"and",
"absolute",
"co",
"ordinates",
"--",
"sync",
"option",
"auto",
"passed",
"in",
"will",
"wait",
"until",
"actually",
"moved",
"before",
"giving",
"control",
... | train | https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/pidutil.py#L66-L75 |
timeyyy/apptools | peasoup/pidutil.py | get_active_window_pos | def get_active_window_pos():
'''screen coordinates massaged so that movewindow command works to
restore the window to the same position
returns x, y
'''
# http://stackoverflow.com/questions/26050788/in-bash-on-ubuntu-14-04-unity-how-can-i-get-the-total-size-of-an-open-window-i/26060527#26060527
... | python | def get_active_window_pos():
'''screen coordinates massaged so that movewindow command works to
restore the window to the same position
returns x, y
'''
# http://stackoverflow.com/questions/26050788/in-bash-on-ubuntu-14-04-unity-how-can-i-get-the-total-size-of-an-open-window-i/26060527#26060527
... | [
"def",
"get_active_window_pos",
"(",
")",
":",
"# http://stackoverflow.com/questions/26050788/in-bash-on-ubuntu-14-04-unity-how-can-i-get-the-total-size-of-an-open-window-i/26060527#26060527",
"cmd",
"=",
"[",
"'xdotool'",
",",
"'getactivewindow'",
",",
"'getwindowgeometry'",
"]",
"res... | screen coordinates massaged so that movewindow command works to
restore the window to the same position
returns x, y | [
"screen",
"coordinates",
"massaged",
"so",
"that",
"movewindow",
"command",
"works",
"to",
"restore",
"the",
"window",
"to",
"the",
"same",
"position",
"returns",
"x",
"y"
] | train | https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/pidutil.py#L77-L99 |
timeyyy/apptools | peasoup/pidutil.py | listpid | def listpid(toggle='basic'): # Add method to exclude elements from list
'''list pids'''
proc=psutil.process_iter()# evalute if its better to keep one instance of this or generate here?
if toggle=='basic':
host=gethostname()
host2=os.getenv('HOME').split(sep='/' )[-1]
for row in pro... | python | def listpid(toggle='basic'): # Add method to exclude elements from list
'''list pids'''
proc=psutil.process_iter()# evalute if its better to keep one instance of this or generate here?
if toggle=='basic':
host=gethostname()
host2=os.getenv('HOME').split(sep='/' )[-1]
for row in pro... | [
"def",
"listpid",
"(",
"toggle",
"=",
"'basic'",
")",
":",
"# Add method to exclude elements from list",
"proc",
"=",
"psutil",
".",
"process_iter",
"(",
")",
"# evalute if its better to keep one instance of this or generate here?",
"if",
"toggle",
"==",
"'basic'",
":",
"... | list pids | [
"list",
"pids"
] | train | https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/pidutil.py#L103-L124 |
timeyyy/apptools | peasoup/pidutil.py | get_active_title | def get_active_title():
'''returns the window title of the active window'''
if os.name == 'posix':
cmd = ['xdotool','getactivewindow','getwindowname']
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
title = proc.communicate()[0].decode('utf-8')
else:
... | python | def get_active_title():
'''returns the window title of the active window'''
if os.name == 'posix':
cmd = ['xdotool','getactivewindow','getwindowname']
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
title = proc.communicate()[0].decode('utf-8')
else:
... | [
"def",
"get_active_title",
"(",
")",
":",
"if",
"os",
".",
"name",
"==",
"'posix'",
":",
"cmd",
"=",
"[",
"'xdotool'",
",",
"'getactivewindow'",
",",
"'getwindowname'",
"]",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"stdout",
"=",
"subpro... | returns the window title of the active window | [
"returns",
"the",
"window",
"title",
"of",
"the",
"active",
"window"
] | train | https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/pidutil.py#L166-L174 |
timeyyy/apptools | peasoup/pidutil.py | get_processes | def get_processes():
'''returns process names owned by the user'''
user = getpass.getuser()
for proc in psutil.process_iter():
if proc.username() != user:
continue
pname = psutil.Process(proc.pid).name()
if os.name == 'nt':
pname = pname[:-4] # remov... | python | def get_processes():
'''returns process names owned by the user'''
user = getpass.getuser()
for proc in psutil.process_iter():
if proc.username() != user:
continue
pname = psutil.Process(proc.pid).name()
if os.name == 'nt':
pname = pname[:-4] # remov... | [
"def",
"get_processes",
"(",
")",
":",
"user",
"=",
"getpass",
".",
"getuser",
"(",
")",
"for",
"proc",
"in",
"psutil",
".",
"process_iter",
"(",
")",
":",
"if",
"proc",
".",
"username",
"(",
")",
"!=",
"user",
":",
"continue",
"pname",
"=",
"psutil"... | returns process names owned by the user | [
"returns",
"process",
"names",
"owned",
"by",
"the",
"user"
] | train | https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/pidutil.py#L176-L185 |
timeyyy/apptools | peasoup/pidutil.py | get_titles | def get_titles():
'''returns titles of all open windows'''
if os.name == 'posix':
for proc in get_processes():
cmd = ['xdotool','search','--name', proc]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
window_ids = proc.communicate()[0].dec... | python | def get_titles():
'''returns titles of all open windows'''
if os.name == 'posix':
for proc in get_processes():
cmd = ['xdotool','search','--name', proc]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
window_ids = proc.communicate()[0].dec... | [
"def",
"get_titles",
"(",
")",
":",
"if",
"os",
".",
"name",
"==",
"'posix'",
":",
"for",
"proc",
"in",
"get_processes",
"(",
")",
":",
"cmd",
"=",
"[",
"'xdotool'",
",",
"'search'",
",",
"'--name'",
",",
"proc",
"]",
"proc",
"=",
"subprocess",
".",
... | returns titles of all open windows | [
"returns",
"titles",
"of",
"all",
"open",
"windows"
] | train | https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/pidutil.py#L187-L208 |
mirukan/whratio | whratio/ratio.py | get_gcd | def get_gcd(a, b):
"Return greatest common divisor for a and b."
while a:
a, b = b % a, a
return b | python | def get_gcd(a, b):
"Return greatest common divisor for a and b."
while a:
a, b = b % a, a
return b | [
"def",
"get_gcd",
"(",
"a",
",",
"b",
")",
":",
"while",
"a",
":",
"a",
",",
"b",
"=",
"b",
"%",
"a",
",",
"a",
"return",
"b"
] | Return greatest common divisor for a and b. | [
"Return",
"greatest",
"common",
"divisor",
"for",
"a",
"and",
"b",
"."
] | train | https://github.com/mirukan/whratio/blob/e19cf7346351649d196d2eb3369870841f7bfea5/whratio/ratio.py#L8-L12 |
mirukan/whratio | whratio/ratio.py | as_int | def as_int(width, height):
"Return an integer ratio tuple like (16, 9)."
gcd = get_gcd(width, height)
return int(width / gcd), int(height / gcd) | python | def as_int(width, height):
"Return an integer ratio tuple like (16, 9)."
gcd = get_gcd(width, height)
return int(width / gcd), int(height / gcd) | [
"def",
"as_int",
"(",
"width",
",",
"height",
")",
":",
"gcd",
"=",
"get_gcd",
"(",
"width",
",",
"height",
")",
"return",
"int",
"(",
"width",
"/",
"gcd",
")",
",",
"int",
"(",
"height",
"/",
"gcd",
")"
] | Return an integer ratio tuple like (16, 9). | [
"Return",
"an",
"integer",
"ratio",
"tuple",
"like",
"(",
"16",
"9",
")",
"."
] | train | https://github.com/mirukan/whratio/blob/e19cf7346351649d196d2eb3369870841f7bfea5/whratio/ratio.py#L15-L18 |
tBaxter/tango-articles | build/lib/articles/signals.py | auto_tweet | def auto_tweet(sender, instance, *args, **kwargs):
"""
Allows auto-tweeting newly created object to twitter
on accounts configured in settings.
You MUST create an app to allow oAuth authentication to work:
-- https://dev.twitter.com/apps/
You also must set the app to "Read and Write" access le... | python | def auto_tweet(sender, instance, *args, **kwargs):
"""
Allows auto-tweeting newly created object to twitter
on accounts configured in settings.
You MUST create an app to allow oAuth authentication to work:
-- https://dev.twitter.com/apps/
You also must set the app to "Read and Write" access le... | [
"def",
"auto_tweet",
"(",
"sender",
",",
"instance",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"twitter",
"or",
"getattr",
"(",
"settings",
",",
"'TWITTER_SETTINGS'",
")",
"is",
"False",
":",
"#print 'WARNING: Twitter account not config... | Allows auto-tweeting newly created object to twitter
on accounts configured in settings.
You MUST create an app to allow oAuth authentication to work:
-- https://dev.twitter.com/apps/
You also must set the app to "Read and Write" access level,
and create an access token. Whew. | [
"Allows",
"auto",
"-",
"tweeting",
"newly",
"created",
"object",
"to",
"twitter",
"on",
"accounts",
"configured",
"in",
"settings",
"."
] | train | https://github.com/tBaxter/tango-articles/blob/93818dcca1b62042a4fc19af63474691b0fe931c/build/lib/articles/signals.py#L10-L52 |
lvh/txgeonames | txgeonames/client.py | GeonamesClient.postalCodeLookup | def postalCodeLookup(self, countryCode, postalCode):
"""
Looks up locations for this country and postal code.
"""
params = {"country": countryCode, "postalcode": postalCode}
d = self._call("postalCodeLookupJSON", params)
d.addCallback(operator.itemgetter("postalcodes"))
... | python | def postalCodeLookup(self, countryCode, postalCode):
"""
Looks up locations for this country and postal code.
"""
params = {"country": countryCode, "postalcode": postalCode}
d = self._call("postalCodeLookupJSON", params)
d.addCallback(operator.itemgetter("postalcodes"))
... | [
"def",
"postalCodeLookup",
"(",
"self",
",",
"countryCode",
",",
"postalCode",
")",
":",
"params",
"=",
"{",
"\"country\"",
":",
"countryCode",
",",
"\"postalcode\"",
":",
"postalCode",
"}",
"d",
"=",
"self",
".",
"_call",
"(",
"\"postalCodeLookupJSON\"",
",",... | Looks up locations for this country and postal code. | [
"Looks",
"up",
"locations",
"for",
"this",
"country",
"and",
"postal",
"code",
"."
] | train | https://github.com/lvh/txgeonames/blob/0f1e6dbba0ee2c32563e12c9b8d654626848fb18/txgeonames/client.py#L34-L41 |
listen-lavender/webcrawl | webcrawl/prettyprint.py | _print | def _print(*args):
"""
Print txt by coding GBK.
*args
list, list of printing contents
"""
if not CFG.debug:
return
if not args:
return
encoding = 'gbk'
args = [_cs(a, encoding) for a in args]
f_back = None
try:
raise Exception
... | python | def _print(*args):
"""
Print txt by coding GBK.
*args
list, list of printing contents
"""
if not CFG.debug:
return
if not args:
return
encoding = 'gbk'
args = [_cs(a, encoding) for a in args]
f_back = None
try:
raise Exception
... | [
"def",
"_print",
"(",
"*",
"args",
")",
":",
"if",
"not",
"CFG",
".",
"debug",
":",
"return",
"if",
"not",
"args",
":",
"return",
"encoding",
"=",
"'gbk'",
"args",
"=",
"[",
"_cs",
"(",
"a",
",",
"encoding",
")",
"for",
"a",
"in",
"args",
"]",
... | Print txt by coding GBK.
*args
list, list of printing contents | [
"Print",
"txt",
"by",
"coding",
"GBK",
"."
] | train | https://github.com/listen-lavender/webcrawl/blob/905dcfa6e6934aac764045660c0efcef28eae1e6/webcrawl/prettyprint.py#L20-L50 |
listen-lavender/webcrawl | webcrawl/prettyprint.py | _print_err | def _print_err(*args):
"""
Print errors.
*args
list, list of printing contents
"""
if not CFG.debug:
return
if not args:
return
encoding = 'utf8' if os.name == 'posix' else 'gbk'
args = [_cs(a, encoding) for a in args]
f_back = None
try... | python | def _print_err(*args):
"""
Print errors.
*args
list, list of printing contents
"""
if not CFG.debug:
return
if not args:
return
encoding = 'utf8' if os.name == 'posix' else 'gbk'
args = [_cs(a, encoding) for a in args]
f_back = None
try... | [
"def",
"_print_err",
"(",
"*",
"args",
")",
":",
"if",
"not",
"CFG",
".",
"debug",
":",
"return",
"if",
"not",
"args",
":",
"return",
"encoding",
"=",
"'utf8'",
"if",
"os",
".",
"name",
"==",
"'posix'",
"else",
"'gbk'",
"args",
"=",
"[",
"_cs",
"("... | Print errors.
*args
list, list of printing contents | [
"Print",
"errors",
"."
] | train | https://github.com/listen-lavender/webcrawl/blob/905dcfa6e6934aac764045660c0efcef28eae1e6/webcrawl/prettyprint.py#L53-L76 |
listen-lavender/webcrawl | webcrawl/prettyprint.py | logprint | def logprint(logname, category, level='INFO', backupCount=15):
"""
Print logs by datetime.
logname
string, file name
category
string, category path of logs file in log directory
level
string, restrict whether logs to be printed or not
backupCoun... | python | def logprint(logname, category, level='INFO', backupCount=15):
"""
Print logs by datetime.
logname
string, file name
category
string, category path of logs file in log directory
level
string, restrict whether logs to be printed or not
backupCoun... | [
"def",
"logprint",
"(",
"logname",
",",
"category",
",",
"level",
"=",
"'INFO'",
",",
"backupCount",
"=",
"15",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"CFG",
".",
"dir",
",",
"category",
".",
"strip",
"(",
"'/'",
")",
",",
"l... | Print logs by datetime.
logname
string, file name
category
string, category path of logs file in log directory
level
string, restrict whether logs to be printed or not
backupCount
int, how many backups can be reserved | [
"Print",
"logs",
"by",
"datetime",
"."
] | train | https://github.com/listen-lavender/webcrawl/blob/905dcfa6e6934aac764045660c0efcef28eae1e6/webcrawl/prettyprint.py#L79-L182 |
listen-lavender/webcrawl | webcrawl/prettyprint.py | fileprint | def fileprint(filename, category, level=logging.DEBUG, maxBytes=1024*10124*100,
backupCount=0):
"""
Print files by file size.
filename
string, file name
category
string, category path of logs file in log directory
level
enumerated type of l... | python | def fileprint(filename, category, level=logging.DEBUG, maxBytes=1024*10124*100,
backupCount=0):
"""
Print files by file size.
filename
string, file name
category
string, category path of logs file in log directory
level
enumerated type of l... | [
"def",
"fileprint",
"(",
"filename",
",",
"category",
",",
"level",
"=",
"logging",
".",
"DEBUG",
",",
"maxBytes",
"=",
"1024",
"*",
"10124",
"*",
"100",
",",
"backupCount",
"=",
"0",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"CFG... | Print files by file size.
filename
string, file name
category
string, category path of logs file in log directory
level
enumerated type of logging module, restrict whether logs to be printed or not
maxBytes
int, max limit of file size
back... | [
"Print",
"files",
"by",
"file",
"size",
"."
] | train | https://github.com/listen-lavender/webcrawl/blob/905dcfa6e6934aac764045660c0efcef28eae1e6/webcrawl/prettyprint.py#L185-L236 |
eugene-eeo/signalsdb | signalsdb/api.py | explain | def explain(code, signals=SIGNALS):
"""
Explain what a given integer signal *code* does,
including it's signal name.
:param code: An integer signal.
:param signals: A database of signals.
"""
if code not in signals:
raise NoSuchSignal(code)
signal, action, description = signals[... | python | def explain(code, signals=SIGNALS):
"""
Explain what a given integer signal *code* does,
including it's signal name.
:param code: An integer signal.
:param signals: A database of signals.
"""
if code not in signals:
raise NoSuchSignal(code)
signal, action, description = signals[... | [
"def",
"explain",
"(",
"code",
",",
"signals",
"=",
"SIGNALS",
")",
":",
"if",
"code",
"not",
"in",
"signals",
":",
"raise",
"NoSuchSignal",
"(",
"code",
")",
"signal",
",",
"action",
",",
"description",
"=",
"signals",
"[",
"code",
"]",
"return",
"{",... | Explain what a given integer signal *code* does,
including it's signal name.
:param code: An integer signal.
:param signals: A database of signals. | [
"Explain",
"what",
"a",
"given",
"integer",
"signal",
"*",
"code",
"*",
"does",
"including",
"it",
"s",
"signal",
"name",
"."
] | train | https://github.com/eugene-eeo/signalsdb/blob/d6129c5790c89dec20bc8bfde66ef7b909a38146/signalsdb/api.py#L22-L38 |
eugene-eeo/signalsdb | signalsdb/api.py | search | def search(signal='', action='', signals=SIGNALS):
"""
Search the signals DB for signal named *signal*,
and which action matches *action* in a case
insensitive way.
:param signal: Regex for signal name.
:param action: Regex for default action.
:param signals: Database of signals.
"""
... | python | def search(signal='', action='', signals=SIGNALS):
"""
Search the signals DB for signal named *signal*,
and which action matches *action* in a case
insensitive way.
:param signal: Regex for signal name.
:param action: Regex for default action.
:param signals: Database of signals.
"""
... | [
"def",
"search",
"(",
"signal",
"=",
"''",
",",
"action",
"=",
"''",
",",
"signals",
"=",
"SIGNALS",
")",
":",
"sig_re",
"=",
"re",
".",
"compile",
"(",
"signal",
",",
"re",
".",
"IGNORECASE",
")",
"act_re",
"=",
"re",
".",
"compile",
"(",
"action"... | Search the signals DB for signal named *signal*,
and which action matches *action* in a case
insensitive way.
:param signal: Regex for signal name.
:param action: Regex for default action.
:param signals: Database of signals. | [
"Search",
"the",
"signals",
"DB",
"for",
"signal",
"named",
"*",
"signal",
"*",
"and",
"which",
"action",
"matches",
"*",
"action",
"*",
"in",
"a",
"case",
"insensitive",
"way",
"."
] | train | https://github.com/eugene-eeo/signalsdb/blob/d6129c5790c89dec20bc8bfde66ef7b909a38146/signalsdb/api.py#L41-L58 |
DaveMcEwan/ndim | ndim_bezier.py | pt_on_bezier_curve | def pt_on_bezier_curve(P=[(0.0, 0.0)], t=0.5):
'''Return point at t on bezier curve defined by control points P.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
assert isinstance(i, float)
... | python | def pt_on_bezier_curve(P=[(0.0, 0.0)], t=0.5):
'''Return point at t on bezier curve defined by control points P.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
assert isinstance(i, float)
... | [
"def",
"pt_on_bezier_curve",
"(",
"P",
"=",
"[",
"(",
"0.0",
",",
"0.0",
")",
"]",
",",
"t",
"=",
"0.5",
")",
":",
"assert",
"isinstance",
"(",
"P",
",",
"list",
")",
"assert",
"len",
"(",
"P",
")",
">",
"0",
"for",
"p",
"in",
"P",
":",
"asse... | Return point at t on bezier curve defined by control points P. | [
"Return",
"point",
"at",
"t",
"on",
"bezier",
"curve",
"defined",
"by",
"control",
"points",
"P",
"."
] | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_bezier.py#L6-L29 |
DaveMcEwan/ndim | ndim_bezier.py | pts_on_bezier_curve | def pts_on_bezier_curve(P=[(0.0, 0.0)], n_seg=0):
'''Return list N+1 points representing N line segments on bezier curve
defined by control points P.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
... | python | def pts_on_bezier_curve(P=[(0.0, 0.0)], n_seg=0):
'''Return list N+1 points representing N line segments on bezier curve
defined by control points P.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
... | [
"def",
"pts_on_bezier_curve",
"(",
"P",
"=",
"[",
"(",
"0.0",
",",
"0.0",
")",
"]",
",",
"n_seg",
"=",
"0",
")",
":",
"assert",
"isinstance",
"(",
"P",
",",
"list",
")",
"assert",
"len",
"(",
"P",
")",
">",
"0",
"for",
"p",
"in",
"P",
":",
"a... | Return list N+1 points representing N line segments on bezier curve
defined by control points P. | [
"Return",
"list",
"N",
"+",
"1",
"points",
"representing",
"N",
"line",
"segments",
"on",
"bezier",
"curve",
"defined",
"by",
"control",
"points",
"P",
"."
] | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_bezier.py#L32-L46 |
DaveMcEwan/ndim | ndim_bezier.py | bezier_curve_approx_len | def bezier_curve_approx_len(P=[(0.0, 0.0)]):
'''Return approximate length of a bezier curve defined by control points P.
Segment curve into N lines where N is the order of the curve, and accumulate
the length of the segments.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
ass... | python | def bezier_curve_approx_len(P=[(0.0, 0.0)]):
'''Return approximate length of a bezier curve defined by control points P.
Segment curve into N lines where N is the order of the curve, and accumulate
the length of the segments.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
ass... | [
"def",
"bezier_curve_approx_len",
"(",
"P",
"=",
"[",
"(",
"0.0",
",",
"0.0",
")",
"]",
")",
":",
"assert",
"isinstance",
"(",
"P",
",",
"list",
")",
"assert",
"len",
"(",
"P",
")",
">",
"0",
"for",
"p",
"in",
"P",
":",
"assert",
"isinstance",
"(... | Return approximate length of a bezier curve defined by control points P.
Segment curve into N lines where N is the order of the curve, and accumulate
the length of the segments. | [
"Return",
"approximate",
"length",
"of",
"a",
"bezier",
"curve",
"defined",
"by",
"control",
"points",
"P",
".",
"Segment",
"curve",
"into",
"N",
"lines",
"where",
"N",
"is",
"the",
"order",
"of",
"the",
"curve",
"and",
"accumulate",
"the",
"length",
"of",... | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_bezier.py#L49-L64 |
DaveMcEwan/ndim | ndim_bezier.py | dir_on_bezier_curve | def dir_on_bezier_curve(P=[(0.0, 0.0)], t=0.5):
'''Return direction at t on bezier curve defined by control points P.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be com... | python | def dir_on_bezier_curve(P=[(0.0, 0.0)], t=0.5):
'''Return direction at t on bezier curve defined by control points P.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be com... | [
"def",
"dir_on_bezier_curve",
"(",
"P",
"=",
"[",
"(",
"0.0",
",",
"0.0",
")",
"]",
",",
"t",
"=",
"0.5",
")",
":",
"assert",
"isinstance",
"(",
"P",
",",
"list",
")",
"assert",
"len",
"(",
"P",
")",
">",
"0",
"if",
"not",
"len",
"(",
"P",
")... | Return direction at t on bezier curve defined by control points P.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
screen over the viewer's right shoulder. | [
"Return",
"direction",
"at",
"t",
"on",
"bezier",
"curve",
"defined",
"by",
"control",
"points",
"P",
".",
"List",
"of",
"vectors",
"per",
"pair",
"of",
"dimensions",
"are",
"returned",
"in",
"radians",
".",
"E",
".",
"g",
".",
"Where",
"X",
"is",
"rig... | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_bezier.py#L67-L101 |
pwyliu/clancy | clancy/engage.py | engage | def engage(args, password):
"""
Construct payloads and POST to Red October
"""
if args['create']:
payload = {'Name': args['--user'], 'Password': password}
goodquit_json(api_call('create', args, payload))
elif args['delegate']:
payload = {
'Name': args['--user'], ... | python | def engage(args, password):
"""
Construct payloads and POST to Red October
"""
if args['create']:
payload = {'Name': args['--user'], 'Password': password}
goodquit_json(api_call('create', args, payload))
elif args['delegate']:
payload = {
'Name': args['--user'], ... | [
"def",
"engage",
"(",
"args",
",",
"password",
")",
":",
"if",
"args",
"[",
"'create'",
"]",
":",
"payload",
"=",
"{",
"'Name'",
":",
"args",
"[",
"'--user'",
"]",
",",
"'Password'",
":",
"password",
"}",
"goodquit_json",
"(",
"api_call",
"(",
"'create... | Construct payloads and POST to Red October | [
"Construct",
"payloads",
"and",
"POST",
"to",
"Red",
"October"
] | train | https://github.com/pwyliu/clancy/blob/cb15a5e2bb735ffce7a84b8413b04faa78c5039c/clancy/engage.py#L7-L56 |
honzamach/pynspect | pynspect/gparser.py | PynspectFilterParser.build | def build(self):
"""
Build/rebuild the parser object
"""
self.logger = logging.getLogger('ply_parser')
self.lexer = PynspectFilterLexer()
self.lexer.build()
# Skip the first item in self.lexer.tokens, which is the 'EXP_ALL' token
# to get rid of followin... | python | def build(self):
"""
Build/rebuild the parser object
"""
self.logger = logging.getLogger('ply_parser')
self.lexer = PynspectFilterLexer()
self.lexer.build()
# Skip the first item in self.lexer.tokens, which is the 'EXP_ALL' token
# to get rid of followin... | [
"def",
"build",
"(",
"self",
")",
":",
"self",
".",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'ply_parser'",
")",
"self",
".",
"lexer",
"=",
"PynspectFilterLexer",
"(",
")",
"self",
".",
"lexer",
".",
"build",
"(",
")",
"# Skip the first item in se... | Build/rebuild the parser object | [
"Build",
"/",
"rebuild",
"the",
"parser",
"object"
] | train | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/gparser.py#L193-L217 |
honzamach/pynspect | pynspect/gparser.py | PynspectFilterParser.parse | def parse(self, data, filename='', debuglevel=0):
"""
Parse given data.
data:
A string containing the filter definition
filename:
Name of the file being parsed (for meaningful
error messages)
debuglevel:
... | python | def parse(self, data, filename='', debuglevel=0):
"""
Parse given data.
data:
A string containing the filter definition
filename:
Name of the file being parsed (for meaningful
error messages)
debuglevel:
... | [
"def",
"parse",
"(",
"self",
",",
"data",
",",
"filename",
"=",
"''",
",",
"debuglevel",
"=",
"0",
")",
":",
"self",
".",
"lexer",
".",
"filename",
"=",
"filename",
"self",
".",
"lexer",
".",
"reset_lineno",
"(",
")",
"if",
"not",
"data",
"or",
"da... | Parse given data.
data:
A string containing the filter definition
filename:
Name of the file being parsed (for meaningful
error messages)
debuglevel:
Debug level to yacc | [
"Parse",
"given",
"data",
"."
] | train | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/gparser.py#L219-L235 |
honzamach/pynspect | pynspect/gparser.py | PynspectFilterParser._create_factor_rule | def _create_factor_rule(tok):
"""
Simple helper method for creating factor node objects based on node name.
"""
if tok[0] == 'IPV4':
return IPV4Rule(tok[1])
if tok[0] == 'IPV6':
return IPV6Rule(tok[1])
if tok[0] == 'DATETIME':
return Da... | python | def _create_factor_rule(tok):
"""
Simple helper method for creating factor node objects based on node name.
"""
if tok[0] == 'IPV4':
return IPV4Rule(tok[1])
if tok[0] == 'IPV6':
return IPV6Rule(tok[1])
if tok[0] == 'DATETIME':
return Da... | [
"def",
"_create_factor_rule",
"(",
"tok",
")",
":",
"if",
"tok",
"[",
"0",
"]",
"==",
"'IPV4'",
":",
"return",
"IPV4Rule",
"(",
"tok",
"[",
"1",
"]",
")",
"if",
"tok",
"[",
"0",
"]",
"==",
"'IPV6'",
":",
"return",
"IPV6Rule",
"(",
"tok",
"[",
"1"... | Simple helper method for creating factor node objects based on node name. | [
"Simple",
"helper",
"method",
"for",
"creating",
"factor",
"node",
"objects",
"based",
"on",
"node",
"name",
"."
] | train | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/gparser.py#L242-L260 |
honzamach/pynspect | pynspect/gparser.py | PynspectFilterParser.p_expression | def p_expression(tok):
"""expression : xor_expression OP_OR expression
| xor_expression"""
if len(tok) == 4:
tok[0] = LogicalBinOpRule(tok[2], tok[1], tok[3])
else:
tok[0] = tok[1] | python | def p_expression(tok):
"""expression : xor_expression OP_OR expression
| xor_expression"""
if len(tok) == 4:
tok[0] = LogicalBinOpRule(tok[2], tok[1], tok[3])
else:
tok[0] = tok[1] | [
"def",
"p_expression",
"(",
"tok",
")",
":",
"if",
"len",
"(",
"tok",
")",
"==",
"4",
":",
"tok",
"[",
"0",
"]",
"=",
"LogicalBinOpRule",
"(",
"tok",
"[",
"2",
"]",
",",
"tok",
"[",
"1",
"]",
",",
"tok",
"[",
"3",
"]",
")",
"else",
":",
"to... | expression : xor_expression OP_OR expression
| xor_expression | [
"expression",
":",
"xor_expression",
"OP_OR",
"expression",
"|",
"xor_expression"
] | train | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/gparser.py#L272-L278 |
honzamach/pynspect | pynspect/gparser.py | PynspectFilterParser.p_xor_expression | def p_xor_expression(tok):
"""xor_expression : and_expression OP_XOR xor_expression
| and_expression"""
if len(tok) == 4:
tok[0] = LogicalBinOpRule(tok[2], tok[1], tok[3])
else:
tok[0] = tok[1] | python | def p_xor_expression(tok):
"""xor_expression : and_expression OP_XOR xor_expression
| and_expression"""
if len(tok) == 4:
tok[0] = LogicalBinOpRule(tok[2], tok[1], tok[3])
else:
tok[0] = tok[1] | [
"def",
"p_xor_expression",
"(",
"tok",
")",
":",
"if",
"len",
"(",
"tok",
")",
"==",
"4",
":",
"tok",
"[",
"0",
"]",
"=",
"LogicalBinOpRule",
"(",
"tok",
"[",
"2",
"]",
",",
"tok",
"[",
"1",
"]",
",",
"tok",
"[",
"3",
"]",
")",
"else",
":",
... | xor_expression : and_expression OP_XOR xor_expression
| and_expression | [
"xor_expression",
":",
"and_expression",
"OP_XOR",
"xor_expression",
"|",
"and_expression"
] | train | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/gparser.py#L281-L287 |
honzamach/pynspect | pynspect/gparser.py | PynspectFilterParser.p_and_expression | def p_and_expression(tok):
"""and_expression : or_p_expression OP_AND and_expression
| or_p_expression"""
if len(tok) == 4:
tok[0] = LogicalBinOpRule(tok[2], tok[1], tok[3])
else:
tok[0] = tok[1] | python | def p_and_expression(tok):
"""and_expression : or_p_expression OP_AND and_expression
| or_p_expression"""
if len(tok) == 4:
tok[0] = LogicalBinOpRule(tok[2], tok[1], tok[3])
else:
tok[0] = tok[1] | [
"def",
"p_and_expression",
"(",
"tok",
")",
":",
"if",
"len",
"(",
"tok",
")",
"==",
"4",
":",
"tok",
"[",
"0",
"]",
"=",
"LogicalBinOpRule",
"(",
"tok",
"[",
"2",
"]",
",",
"tok",
"[",
"1",
"]",
",",
"tok",
"[",
"3",
"]",
")",
"else",
":",
... | and_expression : or_p_expression OP_AND and_expression
| or_p_expression | [
"and_expression",
":",
"or_p_expression",
"OP_AND",
"and_expression",
"|",
"or_p_expression"
] | train | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/gparser.py#L290-L296 |
honzamach/pynspect | pynspect/gparser.py | PynspectFilterParser.p_or_p_expression | def p_or_p_expression(tok):
"""or_p_expression : xor_p_expression OP_OR_P or_p_expression
| xor_p_expression"""
if len(tok) == 4:
tok[0] = LogicalBinOpRule(tok[2], tok[1], tok[3])
else:
tok[0] = tok[1] | python | def p_or_p_expression(tok):
"""or_p_expression : xor_p_expression OP_OR_P or_p_expression
| xor_p_expression"""
if len(tok) == 4:
tok[0] = LogicalBinOpRule(tok[2], tok[1], tok[3])
else:
tok[0] = tok[1] | [
"def",
"p_or_p_expression",
"(",
"tok",
")",
":",
"if",
"len",
"(",
"tok",
")",
"==",
"4",
":",
"tok",
"[",
"0",
"]",
"=",
"LogicalBinOpRule",
"(",
"tok",
"[",
"2",
"]",
",",
"tok",
"[",
"1",
"]",
",",
"tok",
"[",
"3",
"]",
")",
"else",
":",
... | or_p_expression : xor_p_expression OP_OR_P or_p_expression
| xor_p_expression | [
"or_p_expression",
":",
"xor_p_expression",
"OP_OR_P",
"or_p_expression",
"|",
"xor_p_expression"
] | train | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/gparser.py#L299-L305 |
honzamach/pynspect | pynspect/gparser.py | PynspectFilterParser.p_xor_p_expression | def p_xor_p_expression(tok):
"""xor_p_expression : and_p_expression OP_XOR_P xor_p_expression
| and_p_expression"""
if len(tok) == 4:
tok[0] = LogicalBinOpRule(tok[2], tok[1], tok[3])
else:
tok[0] = tok[1] | python | def p_xor_p_expression(tok):
"""xor_p_expression : and_p_expression OP_XOR_P xor_p_expression
| and_p_expression"""
if len(tok) == 4:
tok[0] = LogicalBinOpRule(tok[2], tok[1], tok[3])
else:
tok[0] = tok[1] | [
"def",
"p_xor_p_expression",
"(",
"tok",
")",
":",
"if",
"len",
"(",
"tok",
")",
"==",
"4",
":",
"tok",
"[",
"0",
"]",
"=",
"LogicalBinOpRule",
"(",
"tok",
"[",
"2",
"]",
",",
"tok",
"[",
"1",
"]",
",",
"tok",
"[",
"3",
"]",
")",
"else",
":",... | xor_p_expression : and_p_expression OP_XOR_P xor_p_expression
| and_p_expression | [
"xor_p_expression",
":",
"and_p_expression",
"OP_XOR_P",
"xor_p_expression",
"|",
"and_p_expression"
] | train | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/gparser.py#L308-L314 |
honzamach/pynspect | pynspect/gparser.py | PynspectFilterParser.p_and_p_expression | def p_and_p_expression(tok):
"""and_p_expression : not_expression OP_AND_P and_p_expression
| not_expression"""
if len(tok) == 4:
tok[0] = LogicalBinOpRule(tok[2], tok[1], tok[3])
else:
tok[0] = tok[1] | python | def p_and_p_expression(tok):
"""and_p_expression : not_expression OP_AND_P and_p_expression
| not_expression"""
if len(tok) == 4:
tok[0] = LogicalBinOpRule(tok[2], tok[1], tok[3])
else:
tok[0] = tok[1] | [
"def",
"p_and_p_expression",
"(",
"tok",
")",
":",
"if",
"len",
"(",
"tok",
")",
"==",
"4",
":",
"tok",
"[",
"0",
"]",
"=",
"LogicalBinOpRule",
"(",
"tok",
"[",
"2",
"]",
",",
"tok",
"[",
"1",
"]",
",",
"tok",
"[",
"3",
"]",
")",
"else",
":",... | and_p_expression : not_expression OP_AND_P and_p_expression
| not_expression | [
"and_p_expression",
":",
"not_expression",
"OP_AND_P",
"and_p_expression",
"|",
"not_expression"
] | train | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/gparser.py#L318-L324 |
honzamach/pynspect | pynspect/gparser.py | PynspectFilterParser.p_not_expression | def p_not_expression(tok):
"""not_expression : OP_NOT ex_expression
| ex_expression"""
if len(tok) == 3:
tok[0] = UnaryOperationRule(tok[1], tok[2])
else:
tok[0] = tok[1] | python | def p_not_expression(tok):
"""not_expression : OP_NOT ex_expression
| ex_expression"""
if len(tok) == 3:
tok[0] = UnaryOperationRule(tok[1], tok[2])
else:
tok[0] = tok[1] | [
"def",
"p_not_expression",
"(",
"tok",
")",
":",
"if",
"len",
"(",
"tok",
")",
"==",
"3",
":",
"tok",
"[",
"0",
"]",
"=",
"UnaryOperationRule",
"(",
"tok",
"[",
"1",
"]",
",",
"tok",
"[",
"2",
"]",
")",
"else",
":",
"tok",
"[",
"0",
"]",
"=",... | not_expression : OP_NOT ex_expression
| ex_expression | [
"not_expression",
":",
"OP_NOT",
"ex_expression",
"|",
"ex_expression"
] | train | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/gparser.py#L327-L333 |
honzamach/pynspect | pynspect/gparser.py | PynspectFilterParser.p_ex_expression | def p_ex_expression(tok):
"""ex_expression : OP_EXISTS cmp_expression
| cmp_expression"""
if len(tok) == 3:
tok[0] = UnaryOperationRule(tok[1], tok[2])
else:
tok[0] = tok[1] | python | def p_ex_expression(tok):
"""ex_expression : OP_EXISTS cmp_expression
| cmp_expression"""
if len(tok) == 3:
tok[0] = UnaryOperationRule(tok[1], tok[2])
else:
tok[0] = tok[1] | [
"def",
"p_ex_expression",
"(",
"tok",
")",
":",
"if",
"len",
"(",
"tok",
")",
"==",
"3",
":",
"tok",
"[",
"0",
"]",
"=",
"UnaryOperationRule",
"(",
"tok",
"[",
"1",
"]",
",",
"tok",
"[",
"2",
"]",
")",
"else",
":",
"tok",
"[",
"0",
"]",
"=",
... | ex_expression : OP_EXISTS cmp_expression
| cmp_expression | [
"ex_expression",
":",
"OP_EXISTS",
"cmp_expression",
"|",
"cmp_expression"
] | train | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/gparser.py#L336-L342 |
honzamach/pynspect | pynspect/gparser.py | PynspectFilterParser.p_cmp_expression | def p_cmp_expression(tok):
"""cmp_expression : term OP_LIKE cmp_expression
| term OP_IN cmp_expression
| term OP_IS cmp_expression
| term OP_EQ cmp_expression
| term OP_NE cmp_expression
... | python | def p_cmp_expression(tok):
"""cmp_expression : term OP_LIKE cmp_expression
| term OP_IN cmp_expression
| term OP_IS cmp_expression
| term OP_EQ cmp_expression
| term OP_NE cmp_expression
... | [
"def",
"p_cmp_expression",
"(",
"tok",
")",
":",
"if",
"len",
"(",
"tok",
")",
"==",
"4",
":",
"tok",
"[",
"0",
"]",
"=",
"ComparisonBinOpRule",
"(",
"tok",
"[",
"2",
"]",
",",
"tok",
"[",
"1",
"]",
",",
"tok",
"[",
"3",
"]",
")",
"else",
":"... | cmp_expression : term OP_LIKE cmp_expression
| term OP_IN cmp_expression
| term OP_IS cmp_expression
| term OP_EQ cmp_expression
| term OP_NE cmp_expression
| term OP_GT cmp_expression
... | [
"cmp_expression",
":",
"term",
"OP_LIKE",
"cmp_expression",
"|",
"term",
"OP_IN",
"cmp_expression",
"|",
"term",
"OP_IS",
"cmp_expression",
"|",
"term",
"OP_EQ",
"cmp_expression",
"|",
"term",
"OP_NE",
"cmp_expression",
"|",
"term",
"OP_GT",
"cmp_expression",
"|",
... | train | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/gparser.py#L346-L360 |
honzamach/pynspect | pynspect/gparser.py | PynspectFilterParser.p_term | def p_term(tok):
"""term : factor OP_PLUS term
| factor OP_MINUS term
| factor OP_TIMES term
| factor OP_DIVIDE term
| factor OP_MODULO term
| factor"""
if len(tok) == 4:
tok[0] = MathBinOpRule(tok[2], tok[1], to... | python | def p_term(tok):
"""term : factor OP_PLUS term
| factor OP_MINUS term
| factor OP_TIMES term
| factor OP_DIVIDE term
| factor OP_MODULO term
| factor"""
if len(tok) == 4:
tok[0] = MathBinOpRule(tok[2], tok[1], to... | [
"def",
"p_term",
"(",
"tok",
")",
":",
"if",
"len",
"(",
"tok",
")",
"==",
"4",
":",
"tok",
"[",
"0",
"]",
"=",
"MathBinOpRule",
"(",
"tok",
"[",
"2",
"]",
",",
"tok",
"[",
"1",
"]",
",",
"tok",
"[",
"3",
"]",
")",
"else",
":",
"tok",
"["... | term : factor OP_PLUS term
| factor OP_MINUS term
| factor OP_TIMES term
| factor OP_DIVIDE term
| factor OP_MODULO term
| factor | [
"term",
":",
"factor",
"OP_PLUS",
"term",
"|",
"factor",
"OP_MINUS",
"term",
"|",
"factor",
"OP_TIMES",
"term",
"|",
"factor",
"OP_DIVIDE",
"term",
"|",
"factor",
"OP_MODULO",
"term",
"|",
"factor"
] | train | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/gparser.py#L363-L373 |
honzamach/pynspect | pynspect/gparser.py | PynspectFilterParser.p_factor | def p_factor(self, tok):
"""factor : IPV4
| IPV6
| DATETIME
| TIMEDELTA
| INTEGER
| FLOAT
| VARIABLE
| CONSTANT
| FUNCTION RPAREN
| FUNCTION expressio... | python | def p_factor(self, tok):
"""factor : IPV4
| IPV6
| DATETIME
| TIMEDELTA
| INTEGER
| FLOAT
| VARIABLE
| CONSTANT
| FUNCTION RPAREN
| FUNCTION expressio... | [
"def",
"p_factor",
"(",
"self",
",",
"tok",
")",
":",
"if",
"len",
"(",
"tok",
")",
"==",
"2",
":",
"tok",
"[",
"0",
"]",
"=",
"self",
".",
"_create_factor_rule",
"(",
"tok",
"[",
"1",
"]",
")",
"elif",
"len",
"(",
"tok",
")",
"==",
"3",
":",... | factor : IPV4
| IPV6
| DATETIME
| TIMEDELTA
| INTEGER
| FLOAT
| VARIABLE
| CONSTANT
| FUNCTION RPAREN
| FUNCTION expression RPAREN
| LBRACK ... | [
"factor",
":",
"IPV4",
"|",
"IPV6",
"|",
"DATETIME",
"|",
"TIMEDELTA",
"|",
"INTEGER",
"|",
"FLOAT",
"|",
"VARIABLE",
"|",
"CONSTANT",
"|",
"FUNCTION",
"RPAREN",
"|",
"FUNCTION",
"expression",
"RPAREN",
"|",
"LBRACK",
"list",
"RBRACK",
"|",
"LPAREN",
"expr... | train | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/gparser.py#L375-L395 |
honzamach/pynspect | pynspect/gparser.py | PynspectFilterParser.p_list | def p_list(self, tok):
"""list : IPV4
| IPV6
| DATETIME
| TIMEDELTA
| INTEGER
| FLOAT
| VARIABLE
| CONSTANT
| IPV4 COMMA list
| IPV6 COMMA list
| DATETI... | python | def p_list(self, tok):
"""list : IPV4
| IPV6
| DATETIME
| TIMEDELTA
| INTEGER
| FLOAT
| VARIABLE
| CONSTANT
| IPV4 COMMA list
| IPV6 COMMA list
| DATETI... | [
"def",
"p_list",
"(",
"self",
",",
"tok",
")",
":",
"node",
"=",
"self",
".",
"_create_factor_rule",
"(",
"tok",
"[",
"1",
"]",
")",
"if",
"len",
"(",
"tok",
")",
"==",
"2",
":",
"tok",
"[",
"0",
"]",
"=",
"ListRule",
"(",
"[",
"node",
"]",
"... | list : IPV4
| IPV6
| DATETIME
| TIMEDELTA
| INTEGER
| FLOAT
| VARIABLE
| CONSTANT
| IPV4 COMMA list
| IPV6 COMMA list
| DATETIME COMMA list
| TI... | [
"list",
":",
"IPV4",
"|",
"IPV6",
"|",
"DATETIME",
"|",
"TIMEDELTA",
"|",
"INTEGER",
"|",
"FLOAT",
"|",
"VARIABLE",
"|",
"CONSTANT",
"|",
"IPV4",
"COMMA",
"list",
"|",
"IPV6",
"COMMA",
"list",
"|",
"DATETIME",
"COMMA",
"list",
"|",
"TIMEDELTA",
"COMMA",
... | train | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/gparser.py#L397-L418 |
bitlabstudio/django-unshorten | unshorten/utils.py | unshorten_url | def unshorten_url(short_url):
"""Unshortens the short_url or returns None if not possible."""
short_url = short_url.strip()
if not short_url.startswith('http'):
short_url = 'http://{0}'.format(short_url)
try:
cached_url = UnshortenURL.objects.get(short_url=short_url)
except Unshorte... | python | def unshorten_url(short_url):
"""Unshortens the short_url or returns None if not possible."""
short_url = short_url.strip()
if not short_url.startswith('http'):
short_url = 'http://{0}'.format(short_url)
try:
cached_url = UnshortenURL.objects.get(short_url=short_url)
except Unshorte... | [
"def",
"unshorten_url",
"(",
"short_url",
")",
":",
"short_url",
"=",
"short_url",
".",
"strip",
"(",
")",
"if",
"not",
"short_url",
".",
"startswith",
"(",
"'http'",
")",
":",
"short_url",
"=",
"'http://{0}'",
".",
"format",
"(",
"short_url",
")",
"try",
... | Unshortens the short_url or returns None if not possible. | [
"Unshortens",
"the",
"short_url",
"or",
"returns",
"None",
"if",
"not",
"possible",
"."
] | train | https://github.com/bitlabstudio/django-unshorten/blob/6d184de908bb9df3aad5ac3fd9732d976afb6953/unshorten/utils.py#L8-L31 |
hobson/pug-dj | pug/dj/crawler/views.py | CrawlerRPC.stop | def stop(self, spider_name=None):
"""Stop the named running spider, or the first spider found, if spider_name is None"""
if spider_name is None:
spider_name = self.spider_name
else:
self.spider_name = spider_name
if self.spider_name is None:
self.spide... | python | def stop(self, spider_name=None):
"""Stop the named running spider, or the first spider found, if spider_name is None"""
if spider_name is None:
spider_name = self.spider_name
else:
self.spider_name = spider_name
if self.spider_name is None:
self.spide... | [
"def",
"stop",
"(",
"self",
",",
"spider_name",
"=",
"None",
")",
":",
"if",
"spider_name",
"is",
"None",
":",
"spider_name",
"=",
"self",
".",
"spider_name",
"else",
":",
"self",
".",
"spider_name",
"=",
"spider_name",
"if",
"self",
".",
"spider_name",
... | Stop the named running spider, or the first spider found, if spider_name is None | [
"Stop",
"the",
"named",
"running",
"spider",
"or",
"the",
"first",
"spider",
"found",
"if",
"spider_name",
"is",
"None"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/crawler/views.py#L16-L24 |
hobson/pug-dj | pug/dj/crawler/views.py | CrawlerRPC.get_spider_stats | def get_spider_stats(self, spider_name):
"""get-spider-stats <spider> - get stats of a running spider"""
if spider_name is None:
spider_name = self.spider_name
else:
self.spider_name = spider_name
if self.spider_name is None:
self.spider_name = self.li... | python | def get_spider_stats(self, spider_name):
"""get-spider-stats <spider> - get stats of a running spider"""
if spider_name is None:
spider_name = self.spider_name
else:
self.spider_name = spider_name
if self.spider_name is None:
self.spider_name = self.li... | [
"def",
"get_spider_stats",
"(",
"self",
",",
"spider_name",
")",
":",
"if",
"spider_name",
"is",
"None",
":",
"spider_name",
"=",
"self",
".",
"spider_name",
"else",
":",
"self",
".",
"spider_name",
"=",
"spider_name",
"if",
"self",
".",
"spider_name",
"is",... | get-spider-stats <spider> - get stats of a running spider | [
"get",
"-",
"spider",
"-",
"stats",
"<spider",
">",
"-",
"get",
"stats",
"of",
"a",
"running",
"spider"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/crawler/views.py#L38-L46 |
FlorianLudwig/rueckenwind | rw/gen.py | coroutine | def coroutine(func, replace_callback=True):
"""Decorator for asynchronous generators.
Any generator that yields objects from this module must be wrapped
in either this decorator or `engine`.
Coroutines may "return" by raising the special exception
`Return(value) <Return>`. In Python 3.3+, it is a... | python | def coroutine(func, replace_callback=True):
"""Decorator for asynchronous generators.
Any generator that yields objects from this module must be wrapped
in either this decorator or `engine`.
Coroutines may "return" by raising the special exception
`Return(value) <Return>`. In Python 3.3+, it is a... | [
"def",
"coroutine",
"(",
"func",
",",
"replace_callback",
"=",
"True",
")",
":",
"re",
"=",
"tornado",
".",
"gen",
".",
"_make_coroutine_wrapper",
"(",
"func",
",",
"replace_callback",
"=",
"True",
")",
"re",
".",
"_rw_wrapped_function",
"=",
"func",
"return... | Decorator for asynchronous generators.
Any generator that yields objects from this module must be wrapped
in either this decorator or `engine`.
Coroutines may "return" by raising the special exception
`Return(value) <Return>`. In Python 3.3+, it is also possible for
the function to simply use the... | [
"Decorator",
"for",
"asynchronous",
"generators",
"."
] | train | https://github.com/FlorianLudwig/rueckenwind/blob/47fec7af05ea10b3cf6d59b9f7bf4d12c02dddea/rw/gen.py#L5-L31 |
BlackEarth/bf | bf/pdf.py | PDF.gswrite | def gswrite(self, fn=None, device='jpeg', res=600, alpha=4, quality=90, gs=None):
"use ghostscript to create output file(s) from the PDF"
gs = (gs or self.gs or os.environ.get('gs') or 'gs')
# count the number of pages
if fn is None:
fn = os.path.splitext(self.fn)[0] + DEVIC... | python | def gswrite(self, fn=None, device='jpeg', res=600, alpha=4, quality=90, gs=None):
"use ghostscript to create output file(s) from the PDF"
gs = (gs or self.gs or os.environ.get('gs') or 'gs')
# count the number of pages
if fn is None:
fn = os.path.splitext(self.fn)[0] + DEVIC... | [
"def",
"gswrite",
"(",
"self",
",",
"fn",
"=",
"None",
",",
"device",
"=",
"'jpeg'",
",",
"res",
"=",
"600",
",",
"alpha",
"=",
"4",
",",
"quality",
"=",
"90",
",",
"gs",
"=",
"None",
")",
":",
"gs",
"=",
"(",
"gs",
"or",
"self",
".",
"gs",
... | use ghostscript to create output file(s) from the PDF | [
"use",
"ghostscript",
"to",
"create",
"output",
"file",
"(",
"s",
")",
"from",
"the",
"PDF"
] | train | https://github.com/BlackEarth/bf/blob/376041168874bbd6dee5ccfeece4a9e553223316/bf/pdf.py#L11-L60 |
salimm/pylods | pylods/backend/pylodsc/mapper.py | CObjectMapper.copy | def copy(self):
'''
makes a clone copy of the mapper. It won't clone the serializers or deserializers and it won't copy the events
'''
try:
tmp = self.__class__()
except Exception:
tmp = self.__class__(self._pdict)
tmp._serializers = ... | python | def copy(self):
'''
makes a clone copy of the mapper. It won't clone the serializers or deserializers and it won't copy the events
'''
try:
tmp = self.__class__()
except Exception:
tmp = self.__class__(self._pdict)
tmp._serializers = ... | [
"def",
"copy",
"(",
"self",
")",
":",
"try",
":",
"tmp",
"=",
"self",
".",
"__class__",
"(",
")",
"except",
"Exception",
":",
"tmp",
"=",
"self",
".",
"__class__",
"(",
"self",
".",
"_pdict",
")",
"tmp",
".",
"_serializers",
"=",
"self",
".",
"_ser... | makes a clone copy of the mapper. It won't clone the serializers or deserializers and it won't copy the events | [
"makes",
"a",
"clone",
"copy",
"of",
"the",
"mapper",
".",
"It",
"won",
"t",
"clone",
"the",
"serializers",
"or",
"deserializers",
"and",
"it",
"won",
"t",
"copy",
"the",
"events"
] | train | https://github.com/salimm/pylods/blob/d089e2a9afb1fa8cb6c754933fc574b512757c40/pylods/backend/pylodsc/mapper.py#L95-L107 |
edeposit/edeposit.amqp.ltp | src/edeposit/amqp/ltp/checksum_generator.py | _get_required_fn | def _get_required_fn(fn, root_path):
"""
Definition of the MD5 file requires, that all paths will be absolute
for the package directory, not for the filesystem.
This function converts filesystem-absolute paths to package-absolute paths.
Args:
fn (str): Local/absolute path to the file.
... | python | def _get_required_fn(fn, root_path):
"""
Definition of the MD5 file requires, that all paths will be absolute
for the package directory, not for the filesystem.
This function converts filesystem-absolute paths to package-absolute paths.
Args:
fn (str): Local/absolute path to the file.
... | [
"def",
"_get_required_fn",
"(",
"fn",
",",
"root_path",
")",
":",
"if",
"not",
"fn",
".",
"startswith",
"(",
"root_path",
")",
":",
"raise",
"ValueError",
"(",
"\"Both paths have to be absolute or local!\"",
")",
"replacer",
"=",
"\"/\"",
"if",
"root_path",
".",... | Definition of the MD5 file requires, that all paths will be absolute
for the package directory, not for the filesystem.
This function converts filesystem-absolute paths to package-absolute paths.
Args:
fn (str): Local/absolute path to the file.
root_path (str): Local/absolute path to the p... | [
"Definition",
"of",
"the",
"MD5",
"file",
"requires",
"that",
"all",
"paths",
"will",
"be",
"absolute",
"for",
"the",
"package",
"directory",
"not",
"for",
"the",
"filesystem",
"."
] | train | https://github.com/edeposit/edeposit.amqp.ltp/blob/df9ac7ec6cbdbeaaeed438ca66df75ea967b6d8e/src/edeposit/amqp/ltp/checksum_generator.py#L21-L44 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.