repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
citruz/beacontools | beacontools/scanner.py | Monitor.terminate | def terminate(self):
"""Signal runner to stop and join thread."""
self.toggle_scan(False)
self.keep_going = False
self.join() | python | def terminate(self):
"""Signal runner to stop and join thread."""
self.toggle_scan(False)
self.keep_going = False
self.join() | [
"def",
"terminate",
"(",
"self",
")",
":",
"self",
".",
"toggle_scan",
"(",
"False",
")",
"self",
".",
"keep_going",
"=",
"False",
"self",
".",
"join",
"(",
")"
] | Signal runner to stop and join thread. | [
"Signal",
"runner",
"to",
"stop",
"and",
"join",
"thread",
"."
] | 15a83e9750d0a4393f8a36868e07f6d9458253fe | https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/scanner.py#L240-L244 | train |
citruz/beacontools | beacontools/utils.py | data_to_uuid | def data_to_uuid(data):
"""Convert an array of binary data to the iBeacon uuid format."""
string = data_to_hexstring(data)
return string[0:8]+'-'+string[8:12]+'-'+string[12:16]+'-'+string[16:20]+'-'+string[20:32] | python | def data_to_uuid(data):
"""Convert an array of binary data to the iBeacon uuid format."""
string = data_to_hexstring(data)
return string[0:8]+'-'+string[8:12]+'-'+string[12:16]+'-'+string[16:20]+'-'+string[20:32] | [
"def",
"data_to_uuid",
"(",
"data",
")",
":",
"string",
"=",
"data_to_hexstring",
"(",
"data",
")",
"return",
"string",
"[",
"0",
":",
"8",
"]",
"+",
"'-'",
"+",
"string",
"[",
"8",
":",
"12",
"]",
"+",
"'-'",
"+",
"string",
"[",
"12",
":",
"16",... | Convert an array of binary data to the iBeacon uuid format. | [
"Convert",
"an",
"array",
"of",
"binary",
"data",
"to",
"the",
"iBeacon",
"uuid",
"format",
"."
] | 15a83e9750d0a4393f8a36868e07f6d9458253fe | https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/utils.py#L24-L27 | train |
citruz/beacontools | beacontools/utils.py | bt_addr_to_string | def bt_addr_to_string(addr):
"""Convert a binary string to the hex representation."""
addr_str = array.array('B', addr)
addr_str.reverse()
hex_str = hexlify(addr_str.tostring()).decode('ascii')
# insert ":" seperator between the bytes
return ':'.join(a+b for a, b in zip(hex_str[::2], hex_str[1::... | python | def bt_addr_to_string(addr):
"""Convert a binary string to the hex representation."""
addr_str = array.array('B', addr)
addr_str.reverse()
hex_str = hexlify(addr_str.tostring()).decode('ascii')
# insert ":" seperator between the bytes
return ':'.join(a+b for a, b in zip(hex_str[::2], hex_str[1::... | [
"def",
"bt_addr_to_string",
"(",
"addr",
")",
":",
"addr_str",
"=",
"array",
".",
"array",
"(",
"'B'",
",",
"addr",
")",
"addr_str",
".",
"reverse",
"(",
")",
"hex_str",
"=",
"hexlify",
"(",
"addr_str",
".",
"tostring",
"(",
")",
")",
".",
"decode",
... | Convert a binary string to the hex representation. | [
"Convert",
"a",
"binary",
"string",
"to",
"the",
"hex",
"representation",
"."
] | 15a83e9750d0a4393f8a36868e07f6d9458253fe | https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/utils.py#L35-L41 | train |
citruz/beacontools | beacontools/utils.py | is_one_of | def is_one_of(obj, types):
"""Return true iff obj is an instance of one of the types."""
for type_ in types:
if isinstance(obj, type_):
return True
return False | python | def is_one_of(obj, types):
"""Return true iff obj is an instance of one of the types."""
for type_ in types:
if isinstance(obj, type_):
return True
return False | [
"def",
"is_one_of",
"(",
"obj",
",",
"types",
")",
":",
"for",
"type_",
"in",
"types",
":",
"if",
"isinstance",
"(",
"obj",
",",
"type_",
")",
":",
"return",
"True",
"return",
"False"
] | Return true iff obj is an instance of one of the types. | [
"Return",
"true",
"iff",
"obj",
"is",
"an",
"instance",
"of",
"one",
"of",
"the",
"types",
"."
] | 15a83e9750d0a4393f8a36868e07f6d9458253fe | https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/utils.py#L44-L49 | train |
citruz/beacontools | beacontools/utils.py | is_packet_type | def is_packet_type(cls):
"""Check if class is one the packet types."""
from .packet_types import EddystoneUIDFrame, EddystoneURLFrame, \
EddystoneEncryptedTLMFrame, EddystoneTLMFrame, \
EddystoneEIDFrame, IBeaconAdvertisement, \
... | python | def is_packet_type(cls):
"""Check if class is one the packet types."""
from .packet_types import EddystoneUIDFrame, EddystoneURLFrame, \
EddystoneEncryptedTLMFrame, EddystoneTLMFrame, \
EddystoneEIDFrame, IBeaconAdvertisement, \
... | [
"def",
"is_packet_type",
"(",
"cls",
")",
":",
"from",
".",
"packet_types",
"import",
"EddystoneUIDFrame",
",",
"EddystoneURLFrame",
",",
"EddystoneEncryptedTLMFrame",
",",
"EddystoneTLMFrame",
",",
"EddystoneEIDFrame",
",",
"IBeaconAdvertisement",
",",
"EstimoteTelemetry... | Check if class is one the packet types. | [
"Check",
"if",
"class",
"is",
"one",
"the",
"packet",
"types",
"."
] | 15a83e9750d0a4393f8a36868e07f6d9458253fe | https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/utils.py#L52-L60 | train |
citruz/beacontools | beacontools/utils.py | bin_to_int | def bin_to_int(string):
"""Convert a one element byte string to signed int for python 2 support."""
if isinstance(string, str):
return struct.unpack("b", string)[0]
else:
return struct.unpack("b", bytes([string]))[0] | python | def bin_to_int(string):
"""Convert a one element byte string to signed int for python 2 support."""
if isinstance(string, str):
return struct.unpack("b", string)[0]
else:
return struct.unpack("b", bytes([string]))[0] | [
"def",
"bin_to_int",
"(",
"string",
")",
":",
"if",
"isinstance",
"(",
"string",
",",
"str",
")",
":",
"return",
"struct",
".",
"unpack",
"(",
"\"b\"",
",",
"string",
")",
"[",
"0",
"]",
"else",
":",
"return",
"struct",
".",
"unpack",
"(",
"\"b\"",
... | Convert a one element byte string to signed int for python 2 support. | [
"Convert",
"a",
"one",
"element",
"byte",
"string",
"to",
"signed",
"int",
"for",
"python",
"2",
"support",
"."
] | 15a83e9750d0a4393f8a36868e07f6d9458253fe | https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/utils.py#L71-L76 | train |
citruz/beacontools | beacontools/utils.py | get_mode | def get_mode(device_filter):
"""Determine which beacons the scanner should look for."""
from .device_filters import IBeaconFilter, EddystoneFilter, BtAddrFilter, EstimoteFilter
if device_filter is None or len(device_filter) == 0:
return ScannerMode.MODE_ALL
mode = ScannerMode.MODE_NONE
for ... | python | def get_mode(device_filter):
"""Determine which beacons the scanner should look for."""
from .device_filters import IBeaconFilter, EddystoneFilter, BtAddrFilter, EstimoteFilter
if device_filter is None or len(device_filter) == 0:
return ScannerMode.MODE_ALL
mode = ScannerMode.MODE_NONE
for ... | [
"def",
"get_mode",
"(",
"device_filter",
")",
":",
"from",
".",
"device_filters",
"import",
"IBeaconFilter",
",",
"EddystoneFilter",
",",
"BtAddrFilter",
",",
"EstimoteFilter",
"if",
"device_filter",
"is",
"None",
"or",
"len",
"(",
"device_filter",
")",
"==",
"0... | Determine which beacons the scanner should look for. | [
"Determine",
"which",
"beacons",
"the",
"scanner",
"should",
"look",
"for",
"."
] | 15a83e9750d0a4393f8a36868e07f6d9458253fe | https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/utils.py#L79-L97 | train |
citruz/beacontools | beacontools/device_filters.py | DeviceFilter.matches | def matches(self, filter_props):
"""Check if the filter matches the supplied properties."""
if filter_props is None:
return False
found_one = False
for key, value in filter_props.items():
if key in self.properties and value != self.properties[key]:
... | python | def matches(self, filter_props):
"""Check if the filter matches the supplied properties."""
if filter_props is None:
return False
found_one = False
for key, value in filter_props.items():
if key in self.properties and value != self.properties[key]:
... | [
"def",
"matches",
"(",
"self",
",",
"filter_props",
")",
":",
"if",
"filter_props",
"is",
"None",
":",
"return",
"False",
"found_one",
"=",
"False",
"for",
"key",
",",
"value",
"in",
"filter_props",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"self... | Check if the filter matches the supplied properties. | [
"Check",
"if",
"the",
"filter",
"matches",
"the",
"supplied",
"properties",
"."
] | 15a83e9750d0a4393f8a36868e07f6d9458253fe | https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/device_filters.py#L13-L25 | train |
citruz/beacontools | beacontools/parser.py | parse_packet | def parse_packet(packet):
"""Parse a beacon advertisement packet."""
frame = parse_ltv_packet(packet)
if frame is None:
frame = parse_ibeacon_packet(packet)
return frame | python | def parse_packet(packet):
"""Parse a beacon advertisement packet."""
frame = parse_ltv_packet(packet)
if frame is None:
frame = parse_ibeacon_packet(packet)
return frame | [
"def",
"parse_packet",
"(",
"packet",
")",
":",
"frame",
"=",
"parse_ltv_packet",
"(",
"packet",
")",
"if",
"frame",
"is",
"None",
":",
"frame",
"=",
"parse_ibeacon_packet",
"(",
"packet",
")",
"return",
"frame"
] | Parse a beacon advertisement packet. | [
"Parse",
"a",
"beacon",
"advertisement",
"packet",
"."
] | 15a83e9750d0a4393f8a36868e07f6d9458253fe | https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/parser.py#L14-L19 | train |
citruz/beacontools | beacontools/parser.py | parse_ltv_packet | def parse_ltv_packet(packet):
"""Parse a tag-length-value style beacon packet."""
try:
frame = LTVFrame.parse(packet)
for ltv in frame:
if ltv['type'] == SERVICE_DATA_TYPE:
data = ltv['value']
if data["service_identifier"] == EDDYSTONE_UUID:
... | python | def parse_ltv_packet(packet):
"""Parse a tag-length-value style beacon packet."""
try:
frame = LTVFrame.parse(packet)
for ltv in frame:
if ltv['type'] == SERVICE_DATA_TYPE:
data = ltv['value']
if data["service_identifier"] == EDDYSTONE_UUID:
... | [
"def",
"parse_ltv_packet",
"(",
"packet",
")",
":",
"try",
":",
"frame",
"=",
"LTVFrame",
".",
"parse",
"(",
"packet",
")",
"for",
"ltv",
"in",
"frame",
":",
"if",
"ltv",
"[",
"'type'",
"]",
"==",
"SERVICE_DATA_TYPE",
":",
"data",
"=",
"ltv",
"[",
"'... | Parse a tag-length-value style beacon packet. | [
"Parse",
"a",
"tag",
"-",
"length",
"-",
"value",
"style",
"beacon",
"packet",
"."
] | 15a83e9750d0a4393f8a36868e07f6d9458253fe | https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/parser.py#L21-L38 | train |
citruz/beacontools | beacontools/parser.py | parse_eddystone_service_data | def parse_eddystone_service_data(data):
"""Parse Eddystone service data."""
if data['frame_type'] == EDDYSTONE_UID_FRAME:
return EddystoneUIDFrame(data['frame'])
elif data['frame_type'] == EDDYSTONE_TLM_FRAME:
if data['frame']['tlm_version'] == EDDYSTONE_TLM_ENCRYPTED:
return Ed... | python | def parse_eddystone_service_data(data):
"""Parse Eddystone service data."""
if data['frame_type'] == EDDYSTONE_UID_FRAME:
return EddystoneUIDFrame(data['frame'])
elif data['frame_type'] == EDDYSTONE_TLM_FRAME:
if data['frame']['tlm_version'] == EDDYSTONE_TLM_ENCRYPTED:
return Ed... | [
"def",
"parse_eddystone_service_data",
"(",
"data",
")",
":",
"if",
"data",
"[",
"'frame_type'",
"]",
"==",
"EDDYSTONE_UID_FRAME",
":",
"return",
"EddystoneUIDFrame",
"(",
"data",
"[",
"'frame'",
"]",
")",
"elif",
"data",
"[",
"'frame_type'",
"]",
"==",
"EDDYS... | Parse Eddystone service data. | [
"Parse",
"Eddystone",
"service",
"data",
"."
] | 15a83e9750d0a4393f8a36868e07f6d9458253fe | https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/parser.py#L40-L57 | train |
citruz/beacontools | beacontools/parser.py | parse_estimote_service_data | def parse_estimote_service_data(data):
"""Parse Estimote service data."""
if data['frame_type'] & 0xF == ESTIMOTE_TELEMETRY_FRAME:
protocol_version = (data['frame_type'] & 0xF0) >> 4
if data['frame']['subframe_type'] == ESTIMOTE_TELEMETRY_SUBFRAME_A:
return EstimoteTelemetryFrameA(da... | python | def parse_estimote_service_data(data):
"""Parse Estimote service data."""
if data['frame_type'] & 0xF == ESTIMOTE_TELEMETRY_FRAME:
protocol_version = (data['frame_type'] & 0xF0) >> 4
if data['frame']['subframe_type'] == ESTIMOTE_TELEMETRY_SUBFRAME_A:
return EstimoteTelemetryFrameA(da... | [
"def",
"parse_estimote_service_data",
"(",
"data",
")",
":",
"if",
"data",
"[",
"'frame_type'",
"]",
"&",
"0xF",
"==",
"ESTIMOTE_TELEMETRY_FRAME",
":",
"protocol_version",
"=",
"(",
"data",
"[",
"'frame_type'",
"]",
"&",
"0xF0",
")",
">>",
"4",
"if",
"data",... | Parse Estimote service data. | [
"Parse",
"Estimote",
"service",
"data",
"."
] | 15a83e9750d0a4393f8a36868e07f6d9458253fe | https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/parser.py#L59-L67 | train |
citruz/beacontools | beacontools/packet_types/estimote.py | EstimoteTelemetryFrameA.parse_motion_state | def parse_motion_state(val):
"""Convert motion state byte to seconds."""
number = val & 0b00111111
unit = (val & 0b11000000) >> 6
if unit == 1:
number *= 60 # minutes
elif unit == 2:
number *= 60 * 60 # hours
elif unit == 3 and number < 32:
... | python | def parse_motion_state(val):
"""Convert motion state byte to seconds."""
number = val & 0b00111111
unit = (val & 0b11000000) >> 6
if unit == 1:
number *= 60 # minutes
elif unit == 2:
number *= 60 * 60 # hours
elif unit == 3 and number < 32:
... | [
"def",
"parse_motion_state",
"(",
"val",
")",
":",
"number",
"=",
"val",
"&",
"0b00111111",
"unit",
"=",
"(",
"val",
"&",
"0b11000000",
")",
">>",
"6",
"if",
"unit",
"==",
"1",
":",
"number",
"*=",
"60",
"elif",
"unit",
"==",
"2",
":",
"number",
"*... | Convert motion state byte to seconds. | [
"Convert",
"motion",
"state",
"byte",
"to",
"seconds",
"."
] | 15a83e9750d0a4393f8a36868e07f6d9458253fe | https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/packet_types/estimote.py#L46-L59 | train |
Polyconseil/zbarlight | docs/conf.py | _Zbarlight.monkey_patch | def monkey_patch(cls):
"""Monkey path zbarlight C extension on Read The Docs"""
on_read_the_docs = os.environ.get('READTHEDOCS', False)
if on_read_the_docs:
sys.modules['zbarlight._zbarlight'] = cls | python | def monkey_patch(cls):
"""Monkey path zbarlight C extension on Read The Docs"""
on_read_the_docs = os.environ.get('READTHEDOCS', False)
if on_read_the_docs:
sys.modules['zbarlight._zbarlight'] = cls | [
"def",
"monkey_patch",
"(",
"cls",
")",
":",
"on_read_the_docs",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'READTHEDOCS'",
",",
"False",
")",
"if",
"on_read_the_docs",
":",
"sys",
".",
"modules",
"[",
"'zbarlight._zbarlight'",
"]",
"=",
"cls"
] | Monkey path zbarlight C extension on Read The Docs | [
"Monkey",
"path",
"zbarlight",
"C",
"extension",
"on",
"Read",
"The",
"Docs"
] | 97f46696516683af863d87935074e772e89b4292 | https://github.com/Polyconseil/zbarlight/blob/97f46696516683af863d87935074e772e89b4292/docs/conf.py#L23-L27 | train |
adafruit/Adafruit_CircuitPython_framebuf | adafruit_framebuf.py | MVLSBFormat.set_pixel | def set_pixel(framebuf, x, y, color):
"""Set a given pixel to a color."""
index = (y >> 3) * framebuf.stride + x
offset = y & 0x07
framebuf.buf[index] = (framebuf.buf[index] & ~(0x01 << offset)) | ((color != 0) << offset) | python | def set_pixel(framebuf, x, y, color):
"""Set a given pixel to a color."""
index = (y >> 3) * framebuf.stride + x
offset = y & 0x07
framebuf.buf[index] = (framebuf.buf[index] & ~(0x01 << offset)) | ((color != 0) << offset) | [
"def",
"set_pixel",
"(",
"framebuf",
",",
"x",
",",
"y",
",",
"color",
")",
":",
"index",
"=",
"(",
"y",
">>",
"3",
")",
"*",
"framebuf",
".",
"stride",
"+",
"x",
"offset",
"=",
"y",
"&",
"0x07",
"framebuf",
".",
"buf",
"[",
"index",
"]",
"=",
... | Set a given pixel to a color. | [
"Set",
"a",
"given",
"pixel",
"to",
"a",
"color",
"."
] | b9f62c4b71efa963150f9c5a0284b61c7add9d02 | https://github.com/adafruit/Adafruit_CircuitPython_framebuf/blob/b9f62c4b71efa963150f9c5a0284b61c7add9d02/adafruit_framebuf.py#L96-L100 | train |
adafruit/Adafruit_CircuitPython_framebuf | adafruit_framebuf.py | MVLSBFormat.get_pixel | def get_pixel(framebuf, x, y):
"""Get the color of a given pixel"""
index = (y >> 3) * framebuf.stride + x
offset = y & 0x07
return (framebuf.buf[index] >> offset) & 0x01 | python | def get_pixel(framebuf, x, y):
"""Get the color of a given pixel"""
index = (y >> 3) * framebuf.stride + x
offset = y & 0x07
return (framebuf.buf[index] >> offset) & 0x01 | [
"def",
"get_pixel",
"(",
"framebuf",
",",
"x",
",",
"y",
")",
":",
"index",
"=",
"(",
"y",
">>",
"3",
")",
"*",
"framebuf",
".",
"stride",
"+",
"x",
"offset",
"=",
"y",
"&",
"0x07",
"return",
"(",
"framebuf",
".",
"buf",
"[",
"index",
"]",
">>"... | Get the color of a given pixel | [
"Get",
"the",
"color",
"of",
"a",
"given",
"pixel"
] | b9f62c4b71efa963150f9c5a0284b61c7add9d02 | https://github.com/adafruit/Adafruit_CircuitPython_framebuf/blob/b9f62c4b71efa963150f9c5a0284b61c7add9d02/adafruit_framebuf.py#L103-L107 | train |
adafruit/Adafruit_CircuitPython_framebuf | adafruit_framebuf.py | FrameBuffer.pixel | def pixel(self, x, y, color=None):
"""If ``color`` is not given, get the color value of the specified pixel. If ``color`` is
given, set the specified pixel to the given color."""
if self.rotation == 1:
x, y = y, x
x = self.width - x - 1
if self.rotation == 2:
... | python | def pixel(self, x, y, color=None):
"""If ``color`` is not given, get the color value of the specified pixel. If ``color`` is
given, set the specified pixel to the given color."""
if self.rotation == 1:
x, y = y, x
x = self.width - x - 1
if self.rotation == 2:
... | [
"def",
"pixel",
"(",
"self",
",",
"x",
",",
"y",
",",
"color",
"=",
"None",
")",
":",
"if",
"self",
".",
"rotation",
"==",
"1",
":",
"x",
",",
"y",
"=",
"y",
",",
"x",
"x",
"=",
"self",
".",
"width",
"-",
"x",
"-",
"1",
"if",
"self",
".",... | If ``color`` is not given, get the color value of the specified pixel. If ``color`` is
given, set the specified pixel to the given color. | [
"If",
"color",
"is",
"not",
"given",
"get",
"the",
"color",
"value",
"of",
"the",
"specified",
"pixel",
".",
"If",
"color",
"is",
"given",
"set",
"the",
"specified",
"pixel",
"to",
"the",
"given",
"color",
"."
] | b9f62c4b71efa963150f9c5a0284b61c7add9d02 | https://github.com/adafruit/Adafruit_CircuitPython_framebuf/blob/b9f62c4b71efa963150f9c5a0284b61c7add9d02/adafruit_framebuf.py#L189-L207 | train |
adafruit/Adafruit_CircuitPython_framebuf | adafruit_framebuf.py | FrameBuffer.hline | def hline(self, x, y, width, color):
"""Draw a horizontal line up to a given length."""
self.rect(x, y, width, 1, color, fill=True) | python | def hline(self, x, y, width, color):
"""Draw a horizontal line up to a given length."""
self.rect(x, y, width, 1, color, fill=True) | [
"def",
"hline",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"color",
")",
":",
"self",
".",
"rect",
"(",
"x",
",",
"y",
",",
"width",
",",
"1",
",",
"color",
",",
"fill",
"=",
"True",
")"
] | Draw a horizontal line up to a given length. | [
"Draw",
"a",
"horizontal",
"line",
"up",
"to",
"a",
"given",
"length",
"."
] | b9f62c4b71efa963150f9c5a0284b61c7add9d02 | https://github.com/adafruit/Adafruit_CircuitPython_framebuf/blob/b9f62c4b71efa963150f9c5a0284b61c7add9d02/adafruit_framebuf.py#L209-L211 | train |
adafruit/Adafruit_CircuitPython_framebuf | adafruit_framebuf.py | FrameBuffer.vline | def vline(self, x, y, height, color):
"""Draw a vertical line up to a given length."""
self.rect(x, y, 1, height, color, fill=True) | python | def vline(self, x, y, height, color):
"""Draw a vertical line up to a given length."""
self.rect(x, y, 1, height, color, fill=True) | [
"def",
"vline",
"(",
"self",
",",
"x",
",",
"y",
",",
"height",
",",
"color",
")",
":",
"self",
".",
"rect",
"(",
"x",
",",
"y",
",",
"1",
",",
"height",
",",
"color",
",",
"fill",
"=",
"True",
")"
] | Draw a vertical line up to a given length. | [
"Draw",
"a",
"vertical",
"line",
"up",
"to",
"a",
"given",
"length",
"."
] | b9f62c4b71efa963150f9c5a0284b61c7add9d02 | https://github.com/adafruit/Adafruit_CircuitPython_framebuf/blob/b9f62c4b71efa963150f9c5a0284b61c7add9d02/adafruit_framebuf.py#L213-L215 | train |
adafruit/Adafruit_CircuitPython_framebuf | adafruit_framebuf.py | FrameBuffer.rect | def rect(self, x, y, width, height, color, *, fill=False):
"""Draw a rectangle at the given location, size and color. The ```rect``` method draws only
a 1 pixel outline."""
# pylint: disable=too-many-arguments
if self.rotation == 1:
x, y = y, x
width, height = hei... | python | def rect(self, x, y, width, height, color, *, fill=False):
"""Draw a rectangle at the given location, size and color. The ```rect``` method draws only
a 1 pixel outline."""
# pylint: disable=too-many-arguments
if self.rotation == 1:
x, y = y, x
width, height = hei... | [
"def",
"rect",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"color",
",",
"*",
",",
"fill",
"=",
"False",
")",
":",
"if",
"self",
".",
"rotation",
"==",
"1",
":",
"x",
",",
"y",
"=",
"y",
",",
"x",
"width",
",",
"heigh... | Draw a rectangle at the given location, size and color. The ```rect``` method draws only
a 1 pixel outline. | [
"Draw",
"a",
"rectangle",
"at",
"the",
"given",
"location",
"size",
"and",
"color",
".",
"The",
"rect",
"method",
"draws",
"only",
"a",
"1",
"pixel",
"outline",
"."
] | b9f62c4b71efa963150f9c5a0284b61c7add9d02 | https://github.com/adafruit/Adafruit_CircuitPython_framebuf/blob/b9f62c4b71efa963150f9c5a0284b61c7add9d02/adafruit_framebuf.py#L217-L247 | train |
adafruit/Adafruit_CircuitPython_framebuf | adafruit_framebuf.py | FrameBuffer.line | def line(self, x_0, y_0, x_1, y_1, color):
# pylint: disable=too-many-arguments
"""Bresenham's line algorithm"""
d_x = abs(x_1 - x_0)
d_y = abs(y_1 - y_0)
x, y = x_0, y_0
s_x = -1 if x_0 > x_1 else 1
s_y = -1 if y_0 > y_1 else 1
if d_x > d_y:
e... | python | def line(self, x_0, y_0, x_1, y_1, color):
# pylint: disable=too-many-arguments
"""Bresenham's line algorithm"""
d_x = abs(x_1 - x_0)
d_y = abs(y_1 - y_0)
x, y = x_0, y_0
s_x = -1 if x_0 > x_1 else 1
s_y = -1 if y_0 > y_1 else 1
if d_x > d_y:
e... | [
"def",
"line",
"(",
"self",
",",
"x_0",
",",
"y_0",
",",
"x_1",
",",
"y_1",
",",
"color",
")",
":",
"d_x",
"=",
"abs",
"(",
"x_1",
"-",
"x_0",
")",
"d_y",
"=",
"abs",
"(",
"y_1",
"-",
"y_0",
")",
"x",
",",
"y",
"=",
"x_0",
",",
"y_0",
"s_... | Bresenham's line algorithm | [
"Bresenham",
"s",
"line",
"algorithm"
] | b9f62c4b71efa963150f9c5a0284b61c7add9d02 | https://github.com/adafruit/Adafruit_CircuitPython_framebuf/blob/b9f62c4b71efa963150f9c5a0284b61c7add9d02/adafruit_framebuf.py#L249-L275 | train |
adafruit/Adafruit_CircuitPython_framebuf | adafruit_framebuf.py | FrameBuffer.scroll | def scroll(self, delta_x, delta_y):
"""shifts framebuf in x and y direction"""
if delta_x < 0:
shift_x = 0
xend = self.width + delta_x
dt_x = 1
else:
shift_x = self.width - 1
xend = delta_x - 1
dt_x = -1
if delta_y <... | python | def scroll(self, delta_x, delta_y):
"""shifts framebuf in x and y direction"""
if delta_x < 0:
shift_x = 0
xend = self.width + delta_x
dt_x = 1
else:
shift_x = self.width - 1
xend = delta_x - 1
dt_x = -1
if delta_y <... | [
"def",
"scroll",
"(",
"self",
",",
"delta_x",
",",
"delta_y",
")",
":",
"if",
"delta_x",
"<",
"0",
":",
"shift_x",
"=",
"0",
"xend",
"=",
"self",
".",
"width",
"+",
"delta_x",
"dt_x",
"=",
"1",
"else",
":",
"shift_x",
"=",
"self",
".",
"width",
"... | shifts framebuf in x and y direction | [
"shifts",
"framebuf",
"in",
"x",
"and",
"y",
"direction"
] | b9f62c4b71efa963150f9c5a0284b61c7add9d02 | https://github.com/adafruit/Adafruit_CircuitPython_framebuf/blob/b9f62c4b71efa963150f9c5a0284b61c7add9d02/adafruit_framebuf.py#L281-L305 | train |
adafruit/Adafruit_CircuitPython_framebuf | adafruit_framebuf.py | FrameBuffer.text | def text(self, string, x, y, color, *,
font_name="font5x8.bin"):
"""text is not yet implemented"""
if not self._font or self._font.font_name != font_name:
# load the font!
self._font = BitmapFont()
w = self._font.font_width
for i, char in enumerate(st... | python | def text(self, string, x, y, color, *,
font_name="font5x8.bin"):
"""text is not yet implemented"""
if not self._font or self._font.font_name != font_name:
# load the font!
self._font = BitmapFont()
w = self._font.font_width
for i, char in enumerate(st... | [
"def",
"text",
"(",
"self",
",",
"string",
",",
"x",
",",
"y",
",",
"color",
",",
"*",
",",
"font_name",
"=",
"\"font5x8.bin\"",
")",
":",
"if",
"not",
"self",
".",
"_font",
"or",
"self",
".",
"_font",
".",
"font_name",
"!=",
"font_name",
":",
"sel... | text is not yet implemented | [
"text",
"is",
"not",
"yet",
"implemented"
] | b9f62c4b71efa963150f9c5a0284b61c7add9d02 | https://github.com/adafruit/Adafruit_CircuitPython_framebuf/blob/b9f62c4b71efa963150f9c5a0284b61c7add9d02/adafruit_framebuf.py#L307-L317 | train |
loanzen/falcon-auth | falcon_auth/backends.py | AuthBackend.parse_auth_token_from_request | def parse_auth_token_from_request(self, auth_header):
"""
Parses and returns Auth token from the request header. Raises
`falcon.HTTPUnauthoried exception` with proper error message
"""
if not auth_header:
raise falcon.HTTPUnauthorized(
description='Mis... | python | def parse_auth_token_from_request(self, auth_header):
"""
Parses and returns Auth token from the request header. Raises
`falcon.HTTPUnauthoried exception` with proper error message
"""
if not auth_header:
raise falcon.HTTPUnauthorized(
description='Mis... | [
"def",
"parse_auth_token_from_request",
"(",
"self",
",",
"auth_header",
")",
":",
"if",
"not",
"auth_header",
":",
"raise",
"falcon",
".",
"HTTPUnauthorized",
"(",
"description",
"=",
"'Missing Authorization Header'",
")",
"parts",
"=",
"auth_header",
".",
"split",... | Parses and returns Auth token from the request header. Raises
`falcon.HTTPUnauthoried exception` with proper error message | [
"Parses",
"and",
"returns",
"Auth",
"token",
"from",
"the",
"request",
"header",
".",
"Raises",
"falcon",
".",
"HTTPUnauthoried",
"exception",
"with",
"proper",
"error",
"message"
] | b9063163fff8044a8579a6047a85f28f3b214fdf | https://github.com/loanzen/falcon-auth/blob/b9063163fff8044a8579a6047a85f28f3b214fdf/falcon_auth/backends.py#L52-L75 | train |
loanzen/falcon-auth | falcon_auth/backends.py | JWTAuthBackend.authenticate | def authenticate(self, req, resp, resource):
"""
Extract auth token from request `authorization` header, decode jwt token,
verify configured claims and return either a ``user``
object if successful else raise an `falcon.HTTPUnauthoried exception`
"""
payload = self._decod... | python | def authenticate(self, req, resp, resource):
"""
Extract auth token from request `authorization` header, decode jwt token,
verify configured claims and return either a ``user``
object if successful else raise an `falcon.HTTPUnauthoried exception`
"""
payload = self._decod... | [
"def",
"authenticate",
"(",
"self",
",",
"req",
",",
"resp",
",",
"resource",
")",
":",
"payload",
"=",
"self",
".",
"_decode_jwt_token",
"(",
"req",
")",
"user",
"=",
"self",
".",
"user_loader",
"(",
"payload",
")",
"if",
"not",
"user",
":",
"raise",
... | Extract auth token from request `authorization` header, decode jwt token,
verify configured claims and return either a ``user``
object if successful else raise an `falcon.HTTPUnauthoried exception` | [
"Extract",
"auth",
"token",
"from",
"request",
"authorization",
"header",
"decode",
"jwt",
"token",
"verify",
"configured",
"claims",
"and",
"return",
"either",
"a",
"user",
"object",
"if",
"successful",
"else",
"raise",
"an",
"falcon",
".",
"HTTPUnauthoried",
"... | b9063163fff8044a8579a6047a85f28f3b214fdf | https://github.com/loanzen/falcon-auth/blob/b9063163fff8044a8579a6047a85f28f3b214fdf/falcon_auth/backends.py#L213-L225 | train |
loanzen/falcon-auth | falcon_auth/backends.py | JWTAuthBackend.get_auth_token | def get_auth_token(self, user_payload):
"""
Create a JWT authentication token from ``user_payload``
Args:
user_payload(dict, required): A `dict` containing required information
to create authentication token
"""
now = datetime.utcnow()
payload... | python | def get_auth_token(self, user_payload):
"""
Create a JWT authentication token from ``user_payload``
Args:
user_payload(dict, required): A `dict` containing required information
to create authentication token
"""
now = datetime.utcnow()
payload... | [
"def",
"get_auth_token",
"(",
"self",
",",
"user_payload",
")",
":",
"now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"payload",
"=",
"{",
"'user'",
":",
"user_payload",
"}",
"if",
"'iat'",
"in",
"self",
".",
"verify_claims",
":",
"payload",
"[",
"'iat'"... | Create a JWT authentication token from ``user_payload``
Args:
user_payload(dict, required): A `dict` containing required information
to create authentication token | [
"Create",
"a",
"JWT",
"authentication",
"token",
"from",
"user_payload"
] | b9063163fff8044a8579a6047a85f28f3b214fdf | https://github.com/loanzen/falcon-auth/blob/b9063163fff8044a8579a6047a85f28f3b214fdf/falcon_auth/backends.py#L227-L258 | train |
loanzen/falcon-auth | falcon_auth/backends.py | TokenAuthBackend.get_auth_token | def get_auth_token(self, user_payload):
"""
Extracts token from the `user_payload`
"""
token = user_payload.get('token') or None
if not token:
raise ValueError('`user_payload` must provide api token')
return '{auth_header_prefix} {token}'.format(
... | python | def get_auth_token(self, user_payload):
"""
Extracts token from the `user_payload`
"""
token = user_payload.get('token') or None
if not token:
raise ValueError('`user_payload` must provide api token')
return '{auth_header_prefix} {token}'.format(
... | [
"def",
"get_auth_token",
"(",
"self",
",",
"user_payload",
")",
":",
"token",
"=",
"user_payload",
".",
"get",
"(",
"'token'",
")",
"or",
"None",
"if",
"not",
"token",
":",
"raise",
"ValueError",
"(",
"'`user_payload` must provide api token'",
")",
"return",
"... | Extracts token from the `user_payload` | [
"Extracts",
"token",
"from",
"the",
"user_payload"
] | b9063163fff8044a8579a6047a85f28f3b214fdf | https://github.com/loanzen/falcon-auth/blob/b9063163fff8044a8579a6047a85f28f3b214fdf/falcon_auth/backends.py#L379-L388 | train |
loanzen/falcon-auth | falcon_auth/backends.py | HawkAuthBackend.parse_auth_token_from_request | def parse_auth_token_from_request(self, auth_header):
"""
Parses and returns the Hawk Authorization header if it is present and well-formed.
Raises `falcon.HTTPUnauthoried exception` with proper error message
"""
if not auth_header:
raise falcon.HTTPUnauthorized(
... | python | def parse_auth_token_from_request(self, auth_header):
"""
Parses and returns the Hawk Authorization header if it is present and well-formed.
Raises `falcon.HTTPUnauthoried exception` with proper error message
"""
if not auth_header:
raise falcon.HTTPUnauthorized(
... | [
"def",
"parse_auth_token_from_request",
"(",
"self",
",",
"auth_header",
")",
":",
"if",
"not",
"auth_header",
":",
"raise",
"falcon",
".",
"HTTPUnauthorized",
"(",
"description",
"=",
"'Missing Authorization Header'",
")",
"try",
":",
"auth_header_prefix",
",",
"_"... | Parses and returns the Hawk Authorization header if it is present and well-formed.
Raises `falcon.HTTPUnauthoried exception` with proper error message | [
"Parses",
"and",
"returns",
"the",
"Hawk",
"Authorization",
"header",
"if",
"it",
"is",
"present",
"and",
"well",
"-",
"formed",
".",
"Raises",
"falcon",
".",
"HTTPUnauthoried",
"exception",
"with",
"proper",
"error",
"message"
] | b9063163fff8044a8579a6047a85f28f3b214fdf | https://github.com/loanzen/falcon-auth/blob/b9063163fff8044a8579a6047a85f28f3b214fdf/falcon_auth/backends.py#L442-L462 | train |
gmarull/qtmodern | qtmodern/styles.py | _apply_base_theme | def _apply_base_theme(app):
""" Apply base theme to the application.
Args:
app (QApplication): QApplication instance.
"""
if QT_VERSION < (5,):
app.setStyle('plastique')
else:
app.setStyle('Fusion')
with open(_STYLESHEET) as stylesheet:
app.setStyleShee... | python | def _apply_base_theme(app):
""" Apply base theme to the application.
Args:
app (QApplication): QApplication instance.
"""
if QT_VERSION < (5,):
app.setStyle('plastique')
else:
app.setStyle('Fusion')
with open(_STYLESHEET) as stylesheet:
app.setStyleShee... | [
"def",
"_apply_base_theme",
"(",
"app",
")",
":",
"if",
"QT_VERSION",
"<",
"(",
"5",
",",
")",
":",
"app",
".",
"setStyle",
"(",
"'plastique'",
")",
"else",
":",
"app",
".",
"setStyle",
"(",
"'Fusion'",
")",
"with",
"open",
"(",
"_STYLESHEET",
")",
"... | Apply base theme to the application.
Args:
app (QApplication): QApplication instance. | [
"Apply",
"base",
"theme",
"to",
"the",
"application",
"."
] | b58b24c5bcfa0b81c7b1af5a7dfdc0fae660ce0f | https://github.com/gmarull/qtmodern/blob/b58b24c5bcfa0b81c7b1af5a7dfdc0fae660ce0f/qtmodern/styles.py#L11-L24 | train |
gmarull/qtmodern | qtmodern/styles.py | dark | def dark(app):
""" Apply Dark Theme to the Qt application instance.
Args:
app (QApplication): QApplication instance.
"""
_apply_base_theme(app)
darkPalette = QPalette()
# base
darkPalette.setColor(QPalette.WindowText, QColor(180, 180, 180))
darkPalette.setColor(QPalet... | python | def dark(app):
""" Apply Dark Theme to the Qt application instance.
Args:
app (QApplication): QApplication instance.
"""
_apply_base_theme(app)
darkPalette = QPalette()
# base
darkPalette.setColor(QPalette.WindowText, QColor(180, 180, 180))
darkPalette.setColor(QPalet... | [
"def",
"dark",
"(",
"app",
")",
":",
"_apply_base_theme",
"(",
"app",
")",
"darkPalette",
"=",
"QPalette",
"(",
")",
"darkPalette",
".",
"setColor",
"(",
"QPalette",
".",
"WindowText",
",",
"QColor",
"(",
"180",
",",
"180",
",",
"180",
")",
")",
"darkP... | Apply Dark Theme to the Qt application instance.
Args:
app (QApplication): QApplication instance. | [
"Apply",
"Dark",
"Theme",
"to",
"the",
"Qt",
"application",
"instance",
"."
] | b58b24c5bcfa0b81c7b1af5a7dfdc0fae660ce0f | https://github.com/gmarull/qtmodern/blob/b58b24c5bcfa0b81c7b1af5a7dfdc0fae660ce0f/qtmodern/styles.py#L27-L69 | train |
matthias-k/cyipopt | doc/source/sphinxext/inheritance_diagram.py | inheritance_diagram_directive | def inheritance_diagram_directive(name, arguments, options, content, lineno,
content_offset, block_text, state,
state_machine):
"""
Run when the inheritance_diagram directive is first encountered.
"""
node = inheritance_diagram()
c... | python | def inheritance_diagram_directive(name, arguments, options, content, lineno,
content_offset, block_text, state,
state_machine):
"""
Run when the inheritance_diagram directive is first encountered.
"""
node = inheritance_diagram()
c... | [
"def",
"inheritance_diagram_directive",
"(",
"name",
",",
"arguments",
",",
"options",
",",
"content",
",",
"lineno",
",",
"content_offset",
",",
"block_text",
",",
"state",
",",
"state_machine",
")",
":",
"node",
"=",
"inheritance_diagram",
"(",
")",
"class_nam... | Run when the inheritance_diagram directive is first encountered. | [
"Run",
"when",
"the",
"inheritance_diagram",
"directive",
"is",
"first",
"encountered",
"."
] | ed03f54de2e0b8c8ba4c0aa18ab9ab6c8846bc19 | https://github.com/matthias-k/cyipopt/blob/ed03f54de2e0b8c8ba4c0aa18ab9ab6c8846bc19/doc/source/sphinxext/inheritance_diagram.py#L293-L320 | train |
matthias-k/cyipopt | doc/source/sphinxext/inheritance_diagram.py | InheritanceGraph.run_dot | def run_dot(self, args, name, parts=0, urls={},
graph_options={}, node_options={}, edge_options={}):
"""
Run graphviz 'dot' over this graph, returning whatever 'dot'
writes to stdout.
*args* will be passed along as commandline arguments.
*name* is the name of th... | python | def run_dot(self, args, name, parts=0, urls={},
graph_options={}, node_options={}, edge_options={}):
"""
Run graphviz 'dot' over this graph, returning whatever 'dot'
writes to stdout.
*args* will be passed along as commandline arguments.
*name* is the name of th... | [
"def",
"run_dot",
"(",
"self",
",",
"args",
",",
"name",
",",
"parts",
"=",
"0",
",",
"urls",
"=",
"{",
"}",
",",
"graph_options",
"=",
"{",
"}",
",",
"node_options",
"=",
"{",
"}",
",",
"edge_options",
"=",
"{",
"}",
")",
":",
"try",
":",
"dot... | Run graphviz 'dot' over this graph, returning whatever 'dot'
writes to stdout.
*args* will be passed along as commandline arguments.
*name* is the name of the graph
*urls* is a dictionary mapping class names to http urls
Raises DotException for any of the many os and
... | [
"Run",
"graphviz",
"dot",
"over",
"this",
"graph",
"returning",
"whatever",
"dot",
"writes",
"to",
"stdout",
"."
] | ed03f54de2e0b8c8ba4c0aa18ab9ab6c8846bc19 | https://github.com/matthias-k/cyipopt/blob/ed03f54de2e0b8c8ba4c0aa18ab9ab6c8846bc19/doc/source/sphinxext/inheritance_diagram.py#L251-L284 | train |
schapman1974/tinymongo | setup.py | parse_md_to_rst | def parse_md_to_rst(file):
"""Read Markdown file and convert to ReStructured Text."""
try:
from m2r import parse_from_file
return parse_from_file(file).replace(
"artwork/", "http://198.27.119.65/"
)
except ImportError:
# m2r may not be installed in user environmen... | python | def parse_md_to_rst(file):
"""Read Markdown file and convert to ReStructured Text."""
try:
from m2r import parse_from_file
return parse_from_file(file).replace(
"artwork/", "http://198.27.119.65/"
)
except ImportError:
# m2r may not be installed in user environmen... | [
"def",
"parse_md_to_rst",
"(",
"file",
")",
":",
"try",
":",
"from",
"m2r",
"import",
"parse_from_file",
"return",
"parse_from_file",
"(",
"file",
")",
".",
"replace",
"(",
"\"artwork/\"",
",",
"\"http://198.27.119.65/\"",
")",
"except",
"ImportError",
":",
"ret... | Read Markdown file and convert to ReStructured Text. | [
"Read",
"Markdown",
"file",
"and",
"convert",
"to",
"ReStructured",
"Text",
"."
] | 993048059dc0aa789d879b69feb79a0f237a60b3 | https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/setup.py#L14-L23 | train |
schapman1974/tinymongo | tinymongo/results.py | DeleteResult.deleted_count | def deleted_count(self):
"""The number of documents deleted."""
if isinstance(self.raw_result, list):
return len(self.raw_result)
else:
return self.raw_result | python | def deleted_count(self):
"""The number of documents deleted."""
if isinstance(self.raw_result, list):
return len(self.raw_result)
else:
return self.raw_result | [
"def",
"deleted_count",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"raw_result",
",",
"list",
")",
":",
"return",
"len",
"(",
"self",
".",
"raw_result",
")",
"else",
":",
"return",
"self",
".",
"raw_result"
] | The number of documents deleted. | [
"The",
"number",
"of",
"documents",
"deleted",
"."
] | 993048059dc0aa789d879b69feb79a0f237a60b3 | https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/results.py#L107-L112 | train |
schapman1974/tinymongo | tinymongo/tinymongo.py | generate_id | def generate_id():
"""Generate new UUID"""
# TODO: Use six.string_type to Py3 compat
try:
return unicode(uuid1()).replace(u"-", u"")
except NameError:
return str(uuid1()).replace(u"-", u"") | python | def generate_id():
"""Generate new UUID"""
# TODO: Use six.string_type to Py3 compat
try:
return unicode(uuid1()).replace(u"-", u"")
except NameError:
return str(uuid1()).replace(u"-", u"") | [
"def",
"generate_id",
"(",
")",
":",
"try",
":",
"return",
"unicode",
"(",
"uuid1",
"(",
")",
")",
".",
"replace",
"(",
"u\"-\"",
",",
"u\"\"",
")",
"except",
"NameError",
":",
"return",
"str",
"(",
"uuid1",
"(",
")",
")",
".",
"replace",
"(",
"u\"... | Generate new UUID | [
"Generate",
"new",
"UUID"
] | 993048059dc0aa789d879b69feb79a0f237a60b3 | https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L806-L812 | train |
schapman1974/tinymongo | tinymongo/tinymongo.py | TinyMongoCollection.insert | def insert(self, docs, *args, **kwargs):
"""Backwards compatibility with insert"""
if isinstance(docs, list):
return self.insert_many(docs, *args, **kwargs)
else:
return self.insert_one(docs, *args, **kwargs) | python | def insert(self, docs, *args, **kwargs):
"""Backwards compatibility with insert"""
if isinstance(docs, list):
return self.insert_many(docs, *args, **kwargs)
else:
return self.insert_one(docs, *args, **kwargs) | [
"def",
"insert",
"(",
"self",
",",
"docs",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"docs",
",",
"list",
")",
":",
"return",
"self",
".",
"insert_many",
"(",
"docs",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"el... | Backwards compatibility with insert | [
"Backwards",
"compatibility",
"with",
"insert"
] | 993048059dc0aa789d879b69feb79a0f237a60b3 | https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L170-L175 | train |
schapman1974/tinymongo | tinymongo/tinymongo.py | TinyMongoCollection.update | def update(self, query, doc, *args, **kwargs):
"""BAckwards compatibility with update"""
if isinstance(doc, list):
return [
self.update_one(query, item, *args, **kwargs)
for item in doc
]
else:
return self.update_one(query, doc,... | python | def update(self, query, doc, *args, **kwargs):
"""BAckwards compatibility with update"""
if isinstance(doc, list):
return [
self.update_one(query, item, *args, **kwargs)
for item in doc
]
else:
return self.update_one(query, doc,... | [
"def",
"update",
"(",
"self",
",",
"query",
",",
"doc",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"doc",
",",
"list",
")",
":",
"return",
"[",
"self",
".",
"update_one",
"(",
"query",
",",
"item",
",",
"*",
"args",... | BAckwards compatibility with update | [
"BAckwards",
"compatibility",
"with",
"update"
] | 993048059dc0aa789d879b69feb79a0f237a60b3 | https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L406-L414 | train |
schapman1974/tinymongo | tinymongo/tinymongo.py | TinyMongoCollection.update_one | def update_one(self, query, doc):
"""
Updates one element of the collection
:param query: dictionary representing the mongo query
:param doc: dictionary representing the item to be updated
:return: UpdateResult
"""
if self.table is None:
self.build_ta... | python | def update_one(self, query, doc):
"""
Updates one element of the collection
:param query: dictionary representing the mongo query
:param doc: dictionary representing the item to be updated
:return: UpdateResult
"""
if self.table is None:
self.build_ta... | [
"def",
"update_one",
"(",
"self",
",",
"query",
",",
"doc",
")",
":",
"if",
"self",
".",
"table",
"is",
"None",
":",
"self",
".",
"build_table",
"(",
")",
"if",
"u\"$set\"",
"in",
"doc",
":",
"doc",
"=",
"doc",
"[",
"u\"$set\"",
"]",
"allcond",
"="... | Updates one element of the collection
:param query: dictionary representing the mongo query
:param doc: dictionary representing the item to be updated
:return: UpdateResult | [
"Updates",
"one",
"element",
"of",
"the",
"collection"
] | 993048059dc0aa789d879b69feb79a0f237a60b3 | https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L416-L439 | train |
schapman1974/tinymongo | tinymongo/tinymongo.py | TinyMongoCollection.find | def find(self, filter=None, sort=None, skip=None, limit=None,
*args, **kwargs):
"""
Finds all matching results
:param query: dictionary representing the mongo query
:return: cursor containing the search results
"""
if self.table is None:
self.bui... | python | def find(self, filter=None, sort=None, skip=None, limit=None,
*args, **kwargs):
"""
Finds all matching results
:param query: dictionary representing the mongo query
:return: cursor containing the search results
"""
if self.table is None:
self.bui... | [
"def",
"find",
"(",
"self",
",",
"filter",
"=",
"None",
",",
"sort",
"=",
"None",
",",
"skip",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"self",
".",
"table",
"is",
"None",
":",
"self",
".",
... | Finds all matching results
:param query: dictionary representing the mongo query
:return: cursor containing the search results | [
"Finds",
"all",
"matching",
"results"
] | 993048059dc0aa789d879b69feb79a0f237a60b3 | https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L441-L469 | train |
schapman1974/tinymongo | tinymongo/tinymongo.py | TinyMongoCollection.find_one | def find_one(self, filter=None):
"""
Finds one matching query element
:param query: dictionary representing the mongo query
:return: the resulting document (if found)
"""
if self.table is None:
self.build_table()
allcond = self.parse_query(filter)
... | python | def find_one(self, filter=None):
"""
Finds one matching query element
:param query: dictionary representing the mongo query
:return: the resulting document (if found)
"""
if self.table is None:
self.build_table()
allcond = self.parse_query(filter)
... | [
"def",
"find_one",
"(",
"self",
",",
"filter",
"=",
"None",
")",
":",
"if",
"self",
".",
"table",
"is",
"None",
":",
"self",
".",
"build_table",
"(",
")",
"allcond",
"=",
"self",
".",
"parse_query",
"(",
"filter",
")",
"return",
"self",
".",
"table",... | Finds one matching query element
:param query: dictionary representing the mongo query
:return: the resulting document (if found) | [
"Finds",
"one",
"matching",
"query",
"element"
] | 993048059dc0aa789d879b69feb79a0f237a60b3 | https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L471-L484 | train |
schapman1974/tinymongo | tinymongo/tinymongo.py | TinyMongoCollection.remove | def remove(self, spec_or_id, multi=True, *args, **kwargs):
"""Backwards compatibility with remove"""
if multi:
return self.delete_many(spec_or_id)
return self.delete_one(spec_or_id) | python | def remove(self, spec_or_id, multi=True, *args, **kwargs):
"""Backwards compatibility with remove"""
if multi:
return self.delete_many(spec_or_id)
return self.delete_one(spec_or_id) | [
"def",
"remove",
"(",
"self",
",",
"spec_or_id",
",",
"multi",
"=",
"True",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"multi",
":",
"return",
"self",
".",
"delete_many",
"(",
"spec_or_id",
")",
"return",
"self",
".",
"delete_one",
"(",
"... | Backwards compatibility with remove | [
"Backwards",
"compatibility",
"with",
"remove"
] | 993048059dc0aa789d879b69feb79a0f237a60b3 | https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L486-L490 | train |
schapman1974/tinymongo | tinymongo/tinymongo.py | TinyMongoCollection.delete_one | def delete_one(self, query):
"""
Deletes one document from the collection
:param query: dictionary representing the mongo query
:return: DeleteResult
"""
item = self.find_one(query)
result = self.table.remove(where(u'_id') == item[u'_id'])
return DeleteR... | python | def delete_one(self, query):
"""
Deletes one document from the collection
:param query: dictionary representing the mongo query
:return: DeleteResult
"""
item = self.find_one(query)
result = self.table.remove(where(u'_id') == item[u'_id'])
return DeleteR... | [
"def",
"delete_one",
"(",
"self",
",",
"query",
")",
":",
"item",
"=",
"self",
".",
"find_one",
"(",
"query",
")",
"result",
"=",
"self",
".",
"table",
".",
"remove",
"(",
"where",
"(",
"u'_id'",
")",
"==",
"item",
"[",
"u'_id'",
"]",
")",
"return"... | Deletes one document from the collection
:param query: dictionary representing the mongo query
:return: DeleteResult | [
"Deletes",
"one",
"document",
"from",
"the",
"collection"
] | 993048059dc0aa789d879b69feb79a0f237a60b3 | https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L492-L502 | train |
schapman1974/tinymongo | tinymongo/tinymongo.py | TinyMongoCollection.delete_many | def delete_many(self, query):
"""
Removes all items matching the mongo query
:param query: dictionary representing the mongo query
:return: DeleteResult
"""
items = self.find(query)
result = [
self.table.remove(where(u'_id') == item[u'_id'])
... | python | def delete_many(self, query):
"""
Removes all items matching the mongo query
:param query: dictionary representing the mongo query
:return: DeleteResult
"""
items = self.find(query)
result = [
self.table.remove(where(u'_id') == item[u'_id'])
... | [
"def",
"delete_many",
"(",
"self",
",",
"query",
")",
":",
"items",
"=",
"self",
".",
"find",
"(",
"query",
")",
"result",
"=",
"[",
"self",
".",
"table",
".",
"remove",
"(",
"where",
"(",
"u'_id'",
")",
"==",
"item",
"[",
"u'_id'",
"]",
")",
"fo... | Removes all items matching the mongo query
:param query: dictionary representing the mongo query
:return: DeleteResult | [
"Removes",
"all",
"items",
"matching",
"the",
"mongo",
"query"
] | 993048059dc0aa789d879b69feb79a0f237a60b3 | https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L504-L521 | train |
schapman1974/tinymongo | tinymongo/tinymongo.py | TinyMongoCursor.paginate | def paginate(self, skip, limit):
"""Paginate list of records"""
if not self.count() or not limit:
return
skip = skip or 0
pages = int(ceil(self.count() / float(limit)))
limits = {}
last = 0
for i in range(pages):
current = limit * i
... | python | def paginate(self, skip, limit):
"""Paginate list of records"""
if not self.count() or not limit:
return
skip = skip or 0
pages = int(ceil(self.count() / float(limit)))
limits = {}
last = 0
for i in range(pages):
current = limit * i
... | [
"def",
"paginate",
"(",
"self",
",",
"skip",
",",
"limit",
")",
":",
"if",
"not",
"self",
".",
"count",
"(",
")",
"or",
"not",
"limit",
":",
"return",
"skip",
"=",
"skip",
"or",
"0",
"pages",
"=",
"int",
"(",
"ceil",
"(",
"self",
".",
"count",
... | Paginate list of records | [
"Paginate",
"list",
"of",
"records"
] | 993048059dc0aa789d879b69feb79a0f237a60b3 | https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L548-L564 | train |
TracyWebTech/django-revproxy | revproxy/utils.py | should_stream | def should_stream(proxy_response):
"""Function to verify if the proxy_response must be converted into
a stream.This will be done by checking the proxy_response content-length
and verify if its length is bigger than one stipulated
by MIN_STREAMING_LENGTH.
:param proxy_response: An Instance of urllib... | python | def should_stream(proxy_response):
"""Function to verify if the proxy_response must be converted into
a stream.This will be done by checking the proxy_response content-length
and verify if its length is bigger than one stipulated
by MIN_STREAMING_LENGTH.
:param proxy_response: An Instance of urllib... | [
"def",
"should_stream",
"(",
"proxy_response",
")",
":",
"content_type",
"=",
"proxy_response",
".",
"headers",
".",
"get",
"(",
"'Content-Type'",
")",
"if",
"is_html_content_type",
"(",
"content_type",
")",
":",
"return",
"False",
"try",
":",
"content_length",
... | Function to verify if the proxy_response must be converted into
a stream.This will be done by checking the proxy_response content-length
and verify if its length is bigger than one stipulated
by MIN_STREAMING_LENGTH.
:param proxy_response: An Instance of urllib3.response.HTTPResponse
:returns: A bo... | [
"Function",
"to",
"verify",
"if",
"the",
"proxy_response",
"must",
"be",
"converted",
"into",
"a",
"stream",
".",
"This",
"will",
"be",
"done",
"by",
"checking",
"the",
"proxy_response",
"content",
"-",
"length",
"and",
"verify",
"if",
"its",
"length",
"is",... | b8d1d9e44eadbafbd16bc03f04d15560089d4472 | https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/utils.py#L60-L83 | train |
TracyWebTech/django-revproxy | revproxy/utils.py | get_charset | def get_charset(content_type):
"""Function used to retrieve the charset from a content-type.If there is no
charset in the content type then the charset defined on DEFAULT_CHARSET
will be returned
:param content_type: A string containing a Content-Type header
:returns: A string cont... | python | def get_charset(content_type):
"""Function used to retrieve the charset from a content-type.If there is no
charset in the content type then the charset defined on DEFAULT_CHARSET
will be returned
:param content_type: A string containing a Content-Type header
:returns: A string cont... | [
"def",
"get_charset",
"(",
"content_type",
")",
":",
"if",
"not",
"content_type",
":",
"return",
"DEFAULT_CHARSET",
"matched",
"=",
"_get_charset_re",
".",
"search",
"(",
"content_type",
")",
"if",
"matched",
":",
"return",
"matched",
".",
"group",
"(",
"'char... | Function used to retrieve the charset from a content-type.If there is no
charset in the content type then the charset defined on DEFAULT_CHARSET
will be returned
:param content_type: A string containing a Content-Type header
:returns: A string containing the charset | [
"Function",
"used",
"to",
"retrieve",
"the",
"charset",
"from",
"a",
"content",
"-",
"type",
".",
"If",
"there",
"is",
"no",
"charset",
"in",
"the",
"content",
"type",
"then",
"the",
"charset",
"defined",
"on",
"DEFAULT_CHARSET",
"will",
"be",
"returned"
] | b8d1d9e44eadbafbd16bc03f04d15560089d4472 | https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/utils.py#L86-L101 | train |
TracyWebTech/django-revproxy | revproxy/utils.py | required_header | def required_header(header):
"""Function that verify if the header parameter is a essential header
:param header: A string represented a header
:returns: A boolean value that represent if the header is required
"""
if header in IGNORE_HEADERS:
return False
if header.startswith('... | python | def required_header(header):
"""Function that verify if the header parameter is a essential header
:param header: A string represented a header
:returns: A boolean value that represent if the header is required
"""
if header in IGNORE_HEADERS:
return False
if header.startswith('... | [
"def",
"required_header",
"(",
"header",
")",
":",
"if",
"header",
"in",
"IGNORE_HEADERS",
":",
"return",
"False",
"if",
"header",
".",
"startswith",
"(",
"'HTTP_'",
")",
"or",
"header",
"==",
"'CONTENT_TYPE'",
":",
"return",
"True",
"return",
"False"
] | Function that verify if the header parameter is a essential header
:param header: A string represented a header
:returns: A boolean value that represent if the header is required | [
"Function",
"that",
"verify",
"if",
"the",
"header",
"parameter",
"is",
"a",
"essential",
"header"
] | b8d1d9e44eadbafbd16bc03f04d15560089d4472 | https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/utils.py#L104-L116 | train |
TracyWebTech/django-revproxy | revproxy/utils.py | normalize_request_headers | def normalize_request_headers(request):
r"""Function used to transform header, replacing 'HTTP\_' to ''
and replace '_' to '-'
:param request: A HttpRequest that will be transformed
:returns: A dictionary with the normalized headers
"""
norm_headers = {}
for header, value in request... | python | def normalize_request_headers(request):
r"""Function used to transform header, replacing 'HTTP\_' to ''
and replace '_' to '-'
:param request: A HttpRequest that will be transformed
:returns: A dictionary with the normalized headers
"""
norm_headers = {}
for header, value in request... | [
"def",
"normalize_request_headers",
"(",
"request",
")",
":",
"r",
"norm_headers",
"=",
"{",
"}",
"for",
"header",
",",
"value",
"in",
"request",
".",
"META",
".",
"items",
"(",
")",
":",
"if",
"required_header",
"(",
"header",
")",
":",
"norm_header",
"... | r"""Function used to transform header, replacing 'HTTP\_' to ''
and replace '_' to '-'
:param request: A HttpRequest that will be transformed
:returns: A dictionary with the normalized headers | [
"r",
"Function",
"used",
"to",
"transform",
"header",
"replacing",
"HTTP",
"\\",
"_",
"to",
"and",
"replace",
"_",
"to",
"-"
] | b8d1d9e44eadbafbd16bc03f04d15560089d4472 | https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/utils.py#L130-L143 | train |
TracyWebTech/django-revproxy | revproxy/utils.py | encode_items | def encode_items(items):
"""Function that encode all elements in the list of items passed as
a parameter
:param items: A list of tuple
:returns: A list of tuple with all items encoded in 'utf-8'
"""
encoded = []
for key, values in items:
for value in values:
encode... | python | def encode_items(items):
"""Function that encode all elements in the list of items passed as
a parameter
:param items: A list of tuple
:returns: A list of tuple with all items encoded in 'utf-8'
"""
encoded = []
for key, values in items:
for value in values:
encode... | [
"def",
"encode_items",
"(",
"items",
")",
":",
"encoded",
"=",
"[",
"]",
"for",
"key",
",",
"values",
"in",
"items",
":",
"for",
"value",
"in",
"values",
":",
"encoded",
".",
"append",
"(",
"(",
"key",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"valu... | Function that encode all elements in the list of items passed as
a parameter
:param items: A list of tuple
:returns: A list of tuple with all items encoded in 'utf-8' | [
"Function",
"that",
"encode",
"all",
"elements",
"in",
"the",
"list",
"of",
"items",
"passed",
"as",
"a",
"parameter"
] | b8d1d9e44eadbafbd16bc03f04d15560089d4472 | https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/utils.py#L146-L157 | train |
TracyWebTech/django-revproxy | revproxy/utils.py | cookie_from_string | def cookie_from_string(cookie_string, strict_cookies=False):
"""Parser for HTTP header set-cookie
The return from this function will be used as parameters for
django's response.set_cookie method. Because set_cookie doesn't
have parameter comment, this cookie attribute will be ignored.
:param cooki... | python | def cookie_from_string(cookie_string, strict_cookies=False):
"""Parser for HTTP header set-cookie
The return from this function will be used as parameters for
django's response.set_cookie method. Because set_cookie doesn't
have parameter comment, this cookie attribute will be ignored.
:param cooki... | [
"def",
"cookie_from_string",
"(",
"cookie_string",
",",
"strict_cookies",
"=",
"False",
")",
":",
"if",
"strict_cookies",
":",
"cookies",
"=",
"SimpleCookie",
"(",
"COOKIE_PREFIX",
"+",
"cookie_string",
")",
"if",
"not",
"cookies",
".",
"keys",
"(",
")",
":",
... | Parser for HTTP header set-cookie
The return from this function will be used as parameters for
django's response.set_cookie method. Because set_cookie doesn't
have parameter comment, this cookie attribute will be ignored.
:param cookie_string: A string representing a valid cookie
:param strict_co... | [
"Parser",
"for",
"HTTP",
"header",
"set",
"-",
"cookie",
"The",
"return",
"from",
"this",
"function",
"will",
"be",
"used",
"as",
"parameters",
"for",
"django",
"s",
"response",
".",
"set_cookie",
"method",
".",
"Because",
"set_cookie",
"doesn",
"t",
"have",... | b8d1d9e44eadbafbd16bc03f04d15560089d4472 | https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/utils.py#L163-L228 | train |
TracyWebTech/django-revproxy | revproxy/utils.py | unquote | def unquote(value):
"""Remove wrapping quotes from a string.
:param value: A string that might be wrapped in double quotes, such
as a HTTP cookie value.
:returns: Beginning and ending quotes removed and escaped quotes (``\"``)
unescaped
"""
if len(value) > 1 and valu... | python | def unquote(value):
"""Remove wrapping quotes from a string.
:param value: A string that might be wrapped in double quotes, such
as a HTTP cookie value.
:returns: Beginning and ending quotes removed and escaped quotes (``\"``)
unescaped
"""
if len(value) > 1 and valu... | [
"def",
"unquote",
"(",
"value",
")",
":",
"if",
"len",
"(",
"value",
")",
">",
"1",
"and",
"value",
"[",
"0",
"]",
"==",
"'\"'",
"and",
"value",
"[",
"-",
"1",
"]",
"==",
"'\"'",
":",
"value",
"=",
"value",
"[",
"1",
":",
"-",
"1",
"]",
"."... | Remove wrapping quotes from a string.
:param value: A string that might be wrapped in double quotes, such
as a HTTP cookie value.
:returns: Beginning and ending quotes removed and escaped quotes (``\"``)
unescaped | [
"Remove",
"wrapping",
"quotes",
"from",
"a",
"string",
"."
] | b8d1d9e44eadbafbd16bc03f04d15560089d4472 | https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/utils.py#L231-L241 | train |
TracyWebTech/django-revproxy | revproxy/transformer.py | asbool | def asbool(value):
"""Function used to convert certain string values into an appropriated
boolean value.If value is not a string the built-in python
bool function will be used to convert the passed parameter
:param value: an object to be converted to a boolean value
:returns: A boolean value... | python | def asbool(value):
"""Function used to convert certain string values into an appropriated
boolean value.If value is not a string the built-in python
bool function will be used to convert the passed parameter
:param value: an object to be converted to a boolean value
:returns: A boolean value... | [
"def",
"asbool",
"(",
"value",
")",
":",
"is_string",
"=",
"isinstance",
"(",
"value",
",",
"string_types",
")",
"if",
"is_string",
":",
"value",
"=",
"value",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"if",
"value",
"in",
"(",
"'true'",
",",
... | Function used to convert certain string values into an appropriated
boolean value.If value is not a string the built-in python
bool function will be used to convert the passed parameter
:param value: an object to be converted to a boolean value
:returns: A boolean value | [
"Function",
"used",
"to",
"convert",
"certain",
"string",
"values",
"into",
"an",
"appropriated",
"boolean",
"value",
".",
"If",
"value",
"is",
"not",
"a",
"string",
"the",
"built",
"-",
"in",
"python",
"bool",
"function",
"will",
"be",
"used",
"to",
"conv... | b8d1d9e44eadbafbd16bc03f04d15560089d4472 | https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/transformer.py#L30-L50 | train |
TracyWebTech/django-revproxy | revproxy/transformer.py | DiazoTransformer.should_transform | def should_transform(self):
"""Determine if we should transform the response
:returns: A boolean value
"""
if not HAS_DIAZO:
self.log.info("HAS_DIAZO: false")
return False
if asbool(self.request.META.get(DIAZO_OFF_REQUEST_HEADER)):
self.log... | python | def should_transform(self):
"""Determine if we should transform the response
:returns: A boolean value
"""
if not HAS_DIAZO:
self.log.info("HAS_DIAZO: false")
return False
if asbool(self.request.META.get(DIAZO_OFF_REQUEST_HEADER)):
self.log... | [
"def",
"should_transform",
"(",
"self",
")",
":",
"if",
"not",
"HAS_DIAZO",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"HAS_DIAZO: false\"",
")",
"return",
"False",
"if",
"asbool",
"(",
"self",
".",
"request",
".",
"META",
".",
"get",
"(",
"DIAZO_OFF_R... | Determine if we should transform the response
:returns: A boolean value | [
"Determine",
"if",
"we",
"should",
"transform",
"the",
"response"
] | b8d1d9e44eadbafbd16bc03f04d15560089d4472 | https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/transformer.py#L62-L110 | train |
TracyWebTech/django-revproxy | revproxy/transformer.py | DiazoTransformer.transform | def transform(self, rules, theme_template, is_html5, context_data=None):
"""Method used to make a transformation on the content of
the http response based on the rules and theme_templates
passed as paremters
:param rules: A file with a set of diazo rules to make a
... | python | def transform(self, rules, theme_template, is_html5, context_data=None):
"""Method used to make a transformation on the content of
the http response based on the rules and theme_templates
passed as paremters
:param rules: A file with a set of diazo rules to make a
... | [
"def",
"transform",
"(",
"self",
",",
"rules",
",",
"theme_template",
",",
"is_html5",
",",
"context_data",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"should_transform",
"(",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Don't need to be transf... | Method used to make a transformation on the content of
the http response based on the rules and theme_templates
passed as paremters
:param rules: A file with a set of diazo rules to make a
transformation over the original response content
:param theme_template: ... | [
"Method",
"used",
"to",
"make",
"a",
"transformation",
"on",
"the",
"content",
"of",
"the",
"http",
"response",
"based",
"on",
"the",
"rules",
"and",
"theme_templates",
"passed",
"as",
"paremters"
] | b8d1d9e44eadbafbd16bc03f04d15560089d4472 | https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/transformer.py#L112-L161 | train |
TracyWebTech/django-revproxy | revproxy/transformer.py | DiazoTransformer.set_html5_doctype | def set_html5_doctype(self):
"""Method used to transform a doctype in to a properly html5 doctype
"""
doctype = b'<!DOCTYPE html>\n'
content = doctype_re.subn(doctype, self.response.content, 1)[0]
self.response.content = content | python | def set_html5_doctype(self):
"""Method used to transform a doctype in to a properly html5 doctype
"""
doctype = b'<!DOCTYPE html>\n'
content = doctype_re.subn(doctype, self.response.content, 1)[0]
self.response.content = content | [
"def",
"set_html5_doctype",
"(",
"self",
")",
":",
"doctype",
"=",
"b'<!DOCTYPE html>\\n'",
"content",
"=",
"doctype_re",
".",
"subn",
"(",
"doctype",
",",
"self",
".",
"response",
".",
"content",
",",
"1",
")",
"[",
"0",
"]",
"self",
".",
"response",
".... | Method used to transform a doctype in to a properly html5 doctype | [
"Method",
"used",
"to",
"transform",
"a",
"doctype",
"in",
"to",
"a",
"properly",
"html5",
"doctype"
] | b8d1d9e44eadbafbd16bc03f04d15560089d4472 | https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/transformer.py#L170-L175 | train |
TracyWebTech/django-revproxy | revproxy/connection.py | _output | def _output(self, s):
"""Host header should always be first"""
if s.lower().startswith(b'host: '):
self._buffer.insert(1, s)
else:
self._buffer.append(s) | python | def _output(self, s):
"""Host header should always be first"""
if s.lower().startswith(b'host: '):
self._buffer.insert(1, s)
else:
self._buffer.append(s) | [
"def",
"_output",
"(",
"self",
",",
"s",
")",
":",
"if",
"s",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"b'host: '",
")",
":",
"self",
".",
"_buffer",
".",
"insert",
"(",
"1",
",",
"s",
")",
"else",
":",
"self",
".",
"_buffer",
".",
"appe... | Host header should always be first | [
"Host",
"header",
"should",
"always",
"be",
"first"
] | b8d1d9e44eadbafbd16bc03f04d15560089d4472 | https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/connection.py#L6-L12 | train |
TracyWebTech/django-revproxy | revproxy/response.py | get_django_response | def get_django_response(proxy_response, strict_cookies=False):
"""This method is used to create an appropriate response based on the
Content-Length of the proxy_response. If the content is bigger than
MIN_STREAMING_LENGTH, which is found on utils.py,
than django.http.StreamingHttpResponse will be create... | python | def get_django_response(proxy_response, strict_cookies=False):
"""This method is used to create an appropriate response based on the
Content-Length of the proxy_response. If the content is bigger than
MIN_STREAMING_LENGTH, which is found on utils.py,
than django.http.StreamingHttpResponse will be create... | [
"def",
"get_django_response",
"(",
"proxy_response",
",",
"strict_cookies",
"=",
"False",
")",
":",
"status",
"=",
"proxy_response",
".",
"status",
"headers",
"=",
"proxy_response",
".",
"headers",
"logger",
".",
"debug",
"(",
"'Proxy response headers: %s'",
",",
... | This method is used to create an appropriate response based on the
Content-Length of the proxy_response. If the content is bigger than
MIN_STREAMING_LENGTH, which is found on utils.py,
than django.http.StreamingHttpResponse will be created,
else a django.http.HTTPResponse will be created instead
:p... | [
"This",
"method",
"is",
"used",
"to",
"create",
"an",
"appropriate",
"response",
"based",
"on",
"the",
"Content",
"-",
"Length",
"of",
"the",
"proxy_response",
".",
"If",
"the",
"content",
"is",
"bigger",
"than",
"MIN_STREAMING_LENGTH",
"which",
"is",
"found",... | b8d1d9e44eadbafbd16bc03f04d15560089d4472 | https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/response.py#L13-L61 | train |
TracyWebTech/django-revproxy | revproxy/views.py | ProxyView.get_request_headers | def get_request_headers(self):
"""Return request headers that will be sent to upstream.
The header REMOTE_USER is set to the current user
if AuthenticationMiddleware is enabled and
the view's add_remote_user property is True.
.. versionadded:: 0.9.8
"""
request... | python | def get_request_headers(self):
"""Return request headers that will be sent to upstream.
The header REMOTE_USER is set to the current user
if AuthenticationMiddleware is enabled and
the view's add_remote_user property is True.
.. versionadded:: 0.9.8
"""
request... | [
"def",
"get_request_headers",
"(",
"self",
")",
":",
"request_headers",
"=",
"self",
".",
"get_proxy_request_headers",
"(",
"self",
".",
"request",
")",
"if",
"(",
"self",
".",
"add_remote_user",
"and",
"hasattr",
"(",
"self",
".",
"request",
",",
"'user'",
... | Return request headers that will be sent to upstream.
The header REMOTE_USER is set to the current user
if AuthenticationMiddleware is enabled and
the view's add_remote_user property is True.
.. versionadded:: 0.9.8 | [
"Return",
"request",
"headers",
"that",
"will",
"be",
"sent",
"to",
"upstream",
"."
] | b8d1d9e44eadbafbd16bc03f04d15560089d4472 | https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/views.py#L117-L134 | train |
TracyWebTech/django-revproxy | revproxy/views.py | ProxyView.get_encoded_query_params | def get_encoded_query_params(self):
"""Return encoded query params to be used in proxied request"""
get_data = encode_items(self.request.GET.lists())
return urlencode(get_data) | python | def get_encoded_query_params(self):
"""Return encoded query params to be used in proxied request"""
get_data = encode_items(self.request.GET.lists())
return urlencode(get_data) | [
"def",
"get_encoded_query_params",
"(",
"self",
")",
":",
"get_data",
"=",
"encode_items",
"(",
"self",
".",
"request",
".",
"GET",
".",
"lists",
"(",
")",
")",
"return",
"urlencode",
"(",
"get_data",
")"
] | Return encoded query params to be used in proxied request | [
"Return",
"encoded",
"query",
"params",
"to",
"be",
"used",
"in",
"proxied",
"request"
] | b8d1d9e44eadbafbd16bc03f04d15560089d4472 | https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/views.py#L140-L143 | train |
jsfenfen/990-xml-reader | irs_reader/file_utils.py | stream_download | def stream_download(url, target_path, verbose=False):
""" Download a large file without loading it into memory. """
response = requests.get(url, stream=True)
handle = open(target_path, "wb")
if verbose:
print("Beginning streaming download of %s" % url)
start = datetime.now()
try:... | python | def stream_download(url, target_path, verbose=False):
""" Download a large file without loading it into memory. """
response = requests.get(url, stream=True)
handle = open(target_path, "wb")
if verbose:
print("Beginning streaming download of %s" % url)
start = datetime.now()
try:... | [
"def",
"stream_download",
"(",
"url",
",",
"target_path",
",",
"verbose",
"=",
"False",
")",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"stream",
"=",
"True",
")",
"handle",
"=",
"open",
"(",
"target_path",
",",
"\"wb\"",
")",
"if",... | Download a large file without loading it into memory. | [
"Download",
"a",
"large",
"file",
"without",
"loading",
"it",
"into",
"memory",
"."
] | 00020529b789081329a31a2e30b5ee729ce7596a | https://github.com/jsfenfen/990-xml-reader/blob/00020529b789081329a31a2e30b5ee729ce7596a/irs_reader/file_utils.py#L20-L39 | train |
jsfenfen/990-xml-reader | irs_reader/file_utils.py | validate_object_id | def validate_object_id(object_id):
""" It's easy to make a mistake entering these, validate the format """
result = re.match(OBJECT_ID_RE, str(object_id))
if not result:
print("'%s' appears not to be a valid 990 object_id" % object_id)
raise RuntimeError(OBJECT_ID_MSG)
return object_id | python | def validate_object_id(object_id):
""" It's easy to make a mistake entering these, validate the format """
result = re.match(OBJECT_ID_RE, str(object_id))
if not result:
print("'%s' appears not to be a valid 990 object_id" % object_id)
raise RuntimeError(OBJECT_ID_MSG)
return object_id | [
"def",
"validate_object_id",
"(",
"object_id",
")",
":",
"result",
"=",
"re",
".",
"match",
"(",
"OBJECT_ID_RE",
",",
"str",
"(",
"object_id",
")",
")",
"if",
"not",
"result",
":",
"print",
"(",
"\"'%s' appears not to be a valid 990 object_id\"",
"%",
"object_id... | It's easy to make a mistake entering these, validate the format | [
"It",
"s",
"easy",
"to",
"make",
"a",
"mistake",
"entering",
"these",
"validate",
"the",
"format"
] | 00020529b789081329a31a2e30b5ee729ce7596a | https://github.com/jsfenfen/990-xml-reader/blob/00020529b789081329a31a2e30b5ee729ce7596a/irs_reader/file_utils.py#L42-L48 | train |
jsfenfen/990-xml-reader | irs_reader/sked_dict_reader.py | SkedDictReader._get_table_start | def _get_table_start(self):
""" prefill the columns we need for all tables """
if self.documentation:
standardized_table_start = {
'object_id': {
'value': self.object_id,
'ordering': -1,
'line_number': 'NA',
... | python | def _get_table_start(self):
""" prefill the columns we need for all tables """
if self.documentation:
standardized_table_start = {
'object_id': {
'value': self.object_id,
'ordering': -1,
'line_number': 'NA',
... | [
"def",
"_get_table_start",
"(",
"self",
")",
":",
"if",
"self",
".",
"documentation",
":",
"standardized_table_start",
"=",
"{",
"'object_id'",
":",
"{",
"'value'",
":",
"self",
".",
"object_id",
",",
"'ordering'",
":",
"-",
"1",
",",
"'line_number'",
":",
... | prefill the columns we need for all tables | [
"prefill",
"the",
"columns",
"we",
"need",
"for",
"all",
"tables"
] | 00020529b789081329a31a2e30b5ee729ce7596a | https://github.com/jsfenfen/990-xml-reader/blob/00020529b789081329a31a2e30b5ee729ce7596a/irs_reader/sked_dict_reader.py#L45-L78 | train |
jsfenfen/990-xml-reader | irs_reader/text_format_utils.py | debracket | def debracket(string):
""" Eliminate the bracketed var names in doc, line strings """
result = re.sub(BRACKET_RE, ';', str(string))
result = result.lstrip(';')
result = result.lstrip(' ')
result = result.replace('; ;',';')
return result | python | def debracket(string):
""" Eliminate the bracketed var names in doc, line strings """
result = re.sub(BRACKET_RE, ';', str(string))
result = result.lstrip(';')
result = result.lstrip(' ')
result = result.replace('; ;',';')
return result | [
"def",
"debracket",
"(",
"string",
")",
":",
"result",
"=",
"re",
".",
"sub",
"(",
"BRACKET_RE",
",",
"';'",
",",
"str",
"(",
"string",
")",
")",
"result",
"=",
"result",
".",
"lstrip",
"(",
"';'",
")",
"result",
"=",
"result",
".",
"lstrip",
"(",
... | Eliminate the bracketed var names in doc, line strings | [
"Eliminate",
"the",
"bracketed",
"var",
"names",
"in",
"doc",
"line",
"strings"
] | 00020529b789081329a31a2e30b5ee729ce7596a | https://github.com/jsfenfen/990-xml-reader/blob/00020529b789081329a31a2e30b5ee729ce7596a/irs_reader/text_format_utils.py#L15-L21 | train |
jsfenfen/990-xml-reader | irs_reader/filing.py | Filing._set_schedules | def _set_schedules(self):
""" Attach the known and unknown schedules """
self.schedules = ['ReturnHeader990x', ]
self.otherforms = []
for sked in self.raw_irs_dict['Return']['ReturnData'].keys():
if not sked.startswith("@"):
if sked in KNOWN_SCHEDULES:
... | python | def _set_schedules(self):
""" Attach the known and unknown schedules """
self.schedules = ['ReturnHeader990x', ]
self.otherforms = []
for sked in self.raw_irs_dict['Return']['ReturnData'].keys():
if not sked.startswith("@"):
if sked in KNOWN_SCHEDULES:
... | [
"def",
"_set_schedules",
"(",
"self",
")",
":",
"self",
".",
"schedules",
"=",
"[",
"'ReturnHeader990x'",
",",
"]",
"self",
".",
"otherforms",
"=",
"[",
"]",
"for",
"sked",
"in",
"self",
".",
"raw_irs_dict",
"[",
"'Return'",
"]",
"[",
"'ReturnData'",
"]"... | Attach the known and unknown schedules | [
"Attach",
"the",
"known",
"and",
"unknown",
"schedules"
] | 00020529b789081329a31a2e30b5ee729ce7596a | https://github.com/jsfenfen/990-xml-reader/blob/00020529b789081329a31a2e30b5ee729ce7596a/irs_reader/filing.py#L101-L110 | train |
jsfenfen/990-xml-reader | irs_reader/filing.py | Filing.get_parsed_sked | def get_parsed_sked(self, skedname):
""" Returns an array because multiple sked K's are allowed"""
if not self.processed:
raise Exception("Filing must be processed to return parsed sked")
if skedname in self.schedules:
matching_skeds = []
for sked in self.resu... | python | def get_parsed_sked(self, skedname):
""" Returns an array because multiple sked K's are allowed"""
if not self.processed:
raise Exception("Filing must be processed to return parsed sked")
if skedname in self.schedules:
matching_skeds = []
for sked in self.resu... | [
"def",
"get_parsed_sked",
"(",
"self",
",",
"skedname",
")",
":",
"if",
"not",
"self",
".",
"processed",
":",
"raise",
"Exception",
"(",
"\"Filing must be processed to return parsed sked\"",
")",
"if",
"skedname",
"in",
"self",
".",
"schedules",
":",
"matching_ske... | Returns an array because multiple sked K's are allowed | [
"Returns",
"an",
"array",
"because",
"multiple",
"sked",
"K",
"s",
"are",
"allowed"
] | 00020529b789081329a31a2e30b5ee729ce7596a | https://github.com/jsfenfen/990-xml-reader/blob/00020529b789081329a31a2e30b5ee729ce7596a/irs_reader/filing.py#L176-L187 | train |
tus/tus-py-client | tusclient/uploader.py | Uploader.headers | def headers(self):
"""
Return headers of the uploader instance. This would include the headers of the
client instance.
"""
client_headers = getattr(self.client, 'headers', {})
return dict(self.DEFAULT_HEADERS, **client_headers) | python | def headers(self):
"""
Return headers of the uploader instance. This would include the headers of the
client instance.
"""
client_headers = getattr(self.client, 'headers', {})
return dict(self.DEFAULT_HEADERS, **client_headers) | [
"def",
"headers",
"(",
"self",
")",
":",
"client_headers",
"=",
"getattr",
"(",
"self",
".",
"client",
",",
"'headers'",
",",
"{",
"}",
")",
"return",
"dict",
"(",
"self",
".",
"DEFAULT_HEADERS",
",",
"**",
"client_headers",
")"
] | Return headers of the uploader instance. This would include the headers of the
client instance. | [
"Return",
"headers",
"of",
"the",
"uploader",
"instance",
".",
"This",
"would",
"include",
"the",
"headers",
"of",
"the",
"client",
"instance",
"."
] | 0e5856efcfae6fc281171359ce38488a70468993 | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L139-L145 | train |
tus/tus-py-client | tusclient/uploader.py | Uploader.headers_as_list | def headers_as_list(self):
"""
Does the same as 'headers' except it is returned as a list.
"""
headers = self.headers
headers_list = ['{}: {}'.format(key, value) for key, value in iteritems(headers)]
return headers_list | python | def headers_as_list(self):
"""
Does the same as 'headers' except it is returned as a list.
"""
headers = self.headers
headers_list = ['{}: {}'.format(key, value) for key, value in iteritems(headers)]
return headers_list | [
"def",
"headers_as_list",
"(",
"self",
")",
":",
"headers",
"=",
"self",
".",
"headers",
"headers_list",
"=",
"[",
"'{}: {}'",
".",
"format",
"(",
"key",
",",
"value",
")",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"headers",
")",
"]",
"retur... | Does the same as 'headers' except it is returned as a list. | [
"Does",
"the",
"same",
"as",
"headers",
"except",
"it",
"is",
"returned",
"as",
"a",
"list",
"."
] | 0e5856efcfae6fc281171359ce38488a70468993 | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L148-L154 | train |
tus/tus-py-client | tusclient/uploader.py | Uploader.get_offset | def get_offset(self):
"""
Return offset from tus server.
This is different from the instance attribute 'offset' because this makes an
http request to the tus server to retrieve the offset.
"""
resp = requests.head(self.url, headers=self.headers)
offset = resp.hea... | python | def get_offset(self):
"""
Return offset from tus server.
This is different from the instance attribute 'offset' because this makes an
http request to the tus server to retrieve the offset.
"""
resp = requests.head(self.url, headers=self.headers)
offset = resp.hea... | [
"def",
"get_offset",
"(",
"self",
")",
":",
"resp",
"=",
"requests",
".",
"head",
"(",
"self",
".",
"url",
",",
"headers",
"=",
"self",
".",
"headers",
")",
"offset",
"=",
"resp",
".",
"headers",
".",
"get",
"(",
"'upload-offset'",
")",
"if",
"offset... | Return offset from tus server.
This is different from the instance attribute 'offset' because this makes an
http request to the tus server to retrieve the offset. | [
"Return",
"offset",
"from",
"tus",
"server",
"."
] | 0e5856efcfae6fc281171359ce38488a70468993 | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L170-L182 | train |
tus/tus-py-client | tusclient/uploader.py | Uploader.encode_metadata | def encode_metadata(self):
"""
Return list of encoded metadata as defined by the Tus protocol.
"""
encoded_list = []
for key, value in iteritems(self.metadata):
key_str = str(key) # dict keys may be of any object type.
# confirm that the key does not con... | python | def encode_metadata(self):
"""
Return list of encoded metadata as defined by the Tus protocol.
"""
encoded_list = []
for key, value in iteritems(self.metadata):
key_str = str(key) # dict keys may be of any object type.
# confirm that the key does not con... | [
"def",
"encode_metadata",
"(",
"self",
")",
":",
"encoded_list",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"self",
".",
"metadata",
")",
":",
"key_str",
"=",
"str",
"(",
"key",
")",
"if",
"re",
".",
"search",
"(",
"r'^$|[\\s,... | Return list of encoded metadata as defined by the Tus protocol. | [
"Return",
"list",
"of",
"encoded",
"metadata",
"as",
"defined",
"by",
"the",
"Tus",
"protocol",
"."
] | 0e5856efcfae6fc281171359ce38488a70468993 | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L184-L199 | train |
tus/tus-py-client | tusclient/uploader.py | Uploader.get_url | def get_url(self):
"""
Return the tus upload url.
If resumability is enabled, this would try to get the url from storage if available,
otherwise it would request a new upload url from the tus server.
"""
if self.store_url and self.url_storage:
key = self.fing... | python | def get_url(self):
"""
Return the tus upload url.
If resumability is enabled, this would try to get the url from storage if available,
otherwise it would request a new upload url from the tus server.
"""
if self.store_url and self.url_storage:
key = self.fing... | [
"def",
"get_url",
"(",
"self",
")",
":",
"if",
"self",
".",
"store_url",
"and",
"self",
".",
"url_storage",
":",
"key",
"=",
"self",
".",
"fingerprinter",
".",
"get_fingerprint",
"(",
"self",
".",
"get_file_stream",
"(",
")",
")",
"url",
"=",
"self",
"... | Return the tus upload url.
If resumability is enabled, this would try to get the url from storage if available,
otherwise it would request a new upload url from the tus server. | [
"Return",
"the",
"tus",
"upload",
"url",
"."
] | 0e5856efcfae6fc281171359ce38488a70468993 | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L201-L216 | train |
tus/tus-py-client | tusclient/uploader.py | Uploader.create_url | def create_url(self):
"""
Return upload url.
Makes request to tus server to create a new upload url for the required file upload.
"""
headers = self.headers
headers['upload-length'] = str(self.file_size)
headers['upload-metadata'] = ','.join(self.encode_metadata(... | python | def create_url(self):
"""
Return upload url.
Makes request to tus server to create a new upload url for the required file upload.
"""
headers = self.headers
headers['upload-length'] = str(self.file_size)
headers['upload-metadata'] = ','.join(self.encode_metadata(... | [
"def",
"create_url",
"(",
"self",
")",
":",
"headers",
"=",
"self",
".",
"headers",
"headers",
"[",
"'upload-length'",
"]",
"=",
"str",
"(",
"self",
".",
"file_size",
")",
"headers",
"[",
"'upload-metadata'",
"]",
"=",
"','",
".",
"join",
"(",
"self",
... | Return upload url.
Makes request to tus server to create a new upload url for the required file upload. | [
"Return",
"upload",
"url",
"."
] | 0e5856efcfae6fc281171359ce38488a70468993 | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L219-L233 | train |
tus/tus-py-client | tusclient/uploader.py | Uploader.request_length | def request_length(self):
"""
Return length of next chunk upload.
"""
remainder = self.stop_at - self.offset
return self.chunk_size if remainder > self.chunk_size else remainder | python | def request_length(self):
"""
Return length of next chunk upload.
"""
remainder = self.stop_at - self.offset
return self.chunk_size if remainder > self.chunk_size else remainder | [
"def",
"request_length",
"(",
"self",
")",
":",
"remainder",
"=",
"self",
".",
"stop_at",
"-",
"self",
".",
"offset",
"return",
"self",
".",
"chunk_size",
"if",
"remainder",
">",
"self",
".",
"chunk_size",
"else",
"remainder"
] | Return length of next chunk upload. | [
"Return",
"length",
"of",
"next",
"chunk",
"upload",
"."
] | 0e5856efcfae6fc281171359ce38488a70468993 | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L236-L241 | train |
tus/tus-py-client | tusclient/uploader.py | Uploader.verify_upload | def verify_upload(self):
"""
Confirm that the last upload was sucessful.
Raises TusUploadFailed exception if the upload was not sucessful.
"""
if self.request.status_code == 204:
return True
else:
raise TusUploadFailed('', self.request.status_code,... | python | def verify_upload(self):
"""
Confirm that the last upload was sucessful.
Raises TusUploadFailed exception if the upload was not sucessful.
"""
if self.request.status_code == 204:
return True
else:
raise TusUploadFailed('', self.request.status_code,... | [
"def",
"verify_upload",
"(",
"self",
")",
":",
"if",
"self",
".",
"request",
".",
"status_code",
"==",
"204",
":",
"return",
"True",
"else",
":",
"raise",
"TusUploadFailed",
"(",
"''",
",",
"self",
".",
"request",
".",
"status_code",
",",
"self",
".",
... | Confirm that the last upload was sucessful.
Raises TusUploadFailed exception if the upload was not sucessful. | [
"Confirm",
"that",
"the",
"last",
"upload",
"was",
"sucessful",
".",
"Raises",
"TusUploadFailed",
"exception",
"if",
"the",
"upload",
"was",
"not",
"sucessful",
"."
] | 0e5856efcfae6fc281171359ce38488a70468993 | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L243-L251 | train |
tus/tus-py-client | tusclient/uploader.py | Uploader.get_file_stream | def get_file_stream(self):
"""
Return a file stream instance of the upload.
"""
if self.file_stream:
self.file_stream.seek(0)
return self.file_stream
elif os.path.isfile(self.file_path):
return open(self.file_path, 'rb')
else:
... | python | def get_file_stream(self):
"""
Return a file stream instance of the upload.
"""
if self.file_stream:
self.file_stream.seek(0)
return self.file_stream
elif os.path.isfile(self.file_path):
return open(self.file_path, 'rb')
else:
... | [
"def",
"get_file_stream",
"(",
"self",
")",
":",
"if",
"self",
".",
"file_stream",
":",
"self",
".",
"file_stream",
".",
"seek",
"(",
"0",
")",
"return",
"self",
".",
"file_stream",
"elif",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"file_path... | Return a file stream instance of the upload. | [
"Return",
"a",
"file",
"stream",
"instance",
"of",
"the",
"upload",
"."
] | 0e5856efcfae6fc281171359ce38488a70468993 | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L253-L263 | train |
tus/tus-py-client | tusclient/uploader.py | Uploader.file_size | def file_size(self):
"""
Return size of the file.
"""
stream = self.get_file_stream()
stream.seek(0, os.SEEK_END)
return stream.tell() | python | def file_size(self):
"""
Return size of the file.
"""
stream = self.get_file_stream()
stream.seek(0, os.SEEK_END)
return stream.tell() | [
"def",
"file_size",
"(",
"self",
")",
":",
"stream",
"=",
"self",
".",
"get_file_stream",
"(",
")",
"stream",
".",
"seek",
"(",
"0",
",",
"os",
".",
"SEEK_END",
")",
"return",
"stream",
".",
"tell",
"(",
")"
] | Return size of the file. | [
"Return",
"size",
"of",
"the",
"file",
"."
] | 0e5856efcfae6fc281171359ce38488a70468993 | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L266-L272 | train |
tus/tus-py-client | tusclient/uploader.py | Uploader.upload | def upload(self, stop_at=None):
"""
Perform file upload.
Performs continous upload of chunks of the file. The size uploaded at each cycle is
the value of the attribute 'chunk_size'.
:Args:
- stop_at (Optional[int]):
Determines at what offset value th... | python | def upload(self, stop_at=None):
"""
Perform file upload.
Performs continous upload of chunks of the file. The size uploaded at each cycle is
the value of the attribute 'chunk_size'.
:Args:
- stop_at (Optional[int]):
Determines at what offset value th... | [
"def",
"upload",
"(",
"self",
",",
"stop_at",
"=",
"None",
")",
":",
"self",
".",
"stop_at",
"=",
"stop_at",
"or",
"self",
".",
"file_size",
"while",
"self",
".",
"offset",
"<",
"self",
".",
"stop_at",
":",
"self",
".",
"upload_chunk",
"(",
")",
"els... | Perform file upload.
Performs continous upload of chunks of the file. The size uploaded at each cycle is
the value of the attribute 'chunk_size'.
:Args:
- stop_at (Optional[int]):
Determines at what offset value the upload should stop. If not specified this
... | [
"Perform",
"file",
"upload",
"."
] | 0e5856efcfae6fc281171359ce38488a70468993 | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L274-L292 | train |
tus/tus-py-client | tusclient/uploader.py | Uploader.upload_chunk | def upload_chunk(self):
"""
Upload chunk of file.
"""
self._retried = 0
self._do_request()
self.offset = int(self.request.response_headers.get('upload-offset'))
if self.log_func:
msg = '{} bytes uploaded ...'.format(self.offset)
self.log_fu... | python | def upload_chunk(self):
"""
Upload chunk of file.
"""
self._retried = 0
self._do_request()
self.offset = int(self.request.response_headers.get('upload-offset'))
if self.log_func:
msg = '{} bytes uploaded ...'.format(self.offset)
self.log_fu... | [
"def",
"upload_chunk",
"(",
"self",
")",
":",
"self",
".",
"_retried",
"=",
"0",
"self",
".",
"_do_request",
"(",
")",
"self",
".",
"offset",
"=",
"int",
"(",
"self",
".",
"request",
".",
"response_headers",
".",
"get",
"(",
"'upload-offset'",
")",
")"... | Upload chunk of file. | [
"Upload",
"chunk",
"of",
"file",
"."
] | 0e5856efcfae6fc281171359ce38488a70468993 | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L294-L303 | train |
tus/tus-py-client | tusclient/storage/filestorage.py | FileStorage.get_item | def get_item(self, key):
"""
Return the tus url of a file, identified by the key specified.
:Args:
- key[str]: The unique id for the stored item (in this case, url)
:Returns: url[str]
"""
result = self._db.search(self._urls.key == key)
return result[0... | python | def get_item(self, key):
"""
Return the tus url of a file, identified by the key specified.
:Args:
- key[str]: The unique id for the stored item (in this case, url)
:Returns: url[str]
"""
result = self._db.search(self._urls.key == key)
return result[0... | [
"def",
"get_item",
"(",
"self",
",",
"key",
")",
":",
"result",
"=",
"self",
".",
"_db",
".",
"search",
"(",
"self",
".",
"_urls",
".",
"key",
"==",
"key",
")",
"return",
"result",
"[",
"0",
"]",
".",
"get",
"(",
"'url'",
")",
"if",
"result",
"... | Return the tus url of a file, identified by the key specified.
:Args:
- key[str]: The unique id for the stored item (in this case, url)
:Returns: url[str] | [
"Return",
"the",
"tus",
"url",
"of",
"a",
"file",
"identified",
"by",
"the",
"key",
"specified",
"."
] | 0e5856efcfae6fc281171359ce38488a70468993 | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/storage/filestorage.py#L14-L23 | train |
tus/tus-py-client | tusclient/storage/filestorage.py | FileStorage.set_item | def set_item(self, key, url):
"""
Store the url value under the unique key.
:Args:
- key[str]: The unique id to which the item (in this case, url) would be stored.
- value[str]: The actual url value to be stored.
"""
if self._db.search(self._urls.key == k... | python | def set_item(self, key, url):
"""
Store the url value under the unique key.
:Args:
- key[str]: The unique id to which the item (in this case, url) would be stored.
- value[str]: The actual url value to be stored.
"""
if self._db.search(self._urls.key == k... | [
"def",
"set_item",
"(",
"self",
",",
"key",
",",
"url",
")",
":",
"if",
"self",
".",
"_db",
".",
"search",
"(",
"self",
".",
"_urls",
".",
"key",
"==",
"key",
")",
":",
"self",
".",
"_db",
".",
"update",
"(",
"{",
"'url'",
":",
"url",
"}",
",... | Store the url value under the unique key.
:Args:
- key[str]: The unique id to which the item (in this case, url) would be stored.
- value[str]: The actual url value to be stored. | [
"Store",
"the",
"url",
"value",
"under",
"the",
"unique",
"key",
"."
] | 0e5856efcfae6fc281171359ce38488a70468993 | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/storage/filestorage.py#L25-L36 | train |
tus/tus-py-client | tusclient/request.py | TusRequest.perform | def perform(self):
"""
Perform actual request.
"""
try:
host = '{}://{}'.format(self._url.scheme, self._url.netloc)
path = self._url.geturl().replace(host, '', 1)
chunk = self.file.read(self._content_length)
if self._upload_checksum:
... | python | def perform(self):
"""
Perform actual request.
"""
try:
host = '{}://{}'.format(self._url.scheme, self._url.netloc)
path = self._url.geturl().replace(host, '', 1)
chunk = self.file.read(self._content_length)
if self._upload_checksum:
... | [
"def",
"perform",
"(",
"self",
")",
":",
"try",
":",
"host",
"=",
"'{}://{}'",
".",
"format",
"(",
"self",
".",
"_url",
".",
"scheme",
",",
"self",
".",
"_url",
".",
"netloc",
")",
"path",
"=",
"self",
".",
"_url",
".",
"geturl",
"(",
")",
".",
... | Perform actual request. | [
"Perform",
"actual",
"request",
"."
] | 0e5856efcfae6fc281171359ce38488a70468993 | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/request.py#L56-L84 | train |
tus/tus-py-client | tusclient/fingerprint/fingerprint.py | Fingerprint.get_fingerprint | def get_fingerprint(self, fs):
"""
Return a unique fingerprint string value based on the file stream recevied
:Args:
- fs[file]: The file stream instance of the file for which a fingerprint would be generated.
:Returns: fingerprint[str]
"""
hasher = hashlib.m... | python | def get_fingerprint(self, fs):
"""
Return a unique fingerprint string value based on the file stream recevied
:Args:
- fs[file]: The file stream instance of the file for which a fingerprint would be generated.
:Returns: fingerprint[str]
"""
hasher = hashlib.m... | [
"def",
"get_fingerprint",
"(",
"self",
",",
"fs",
")",
":",
"hasher",
"=",
"hashlib",
".",
"md5",
"(",
")",
"buf",
"=",
"self",
".",
"_encode_data",
"(",
"fs",
".",
"read",
"(",
"self",
".",
"BLOCK_SIZE",
")",
")",
"while",
"len",
"(",
"buf",
")",
... | Return a unique fingerprint string value based on the file stream recevied
:Args:
- fs[file]: The file stream instance of the file for which a fingerprint would be generated.
:Returns: fingerprint[str] | [
"Return",
"a",
"unique",
"fingerprint",
"string",
"value",
"based",
"on",
"the",
"file",
"stream",
"recevied"
] | 0e5856efcfae6fc281171359ce38488a70468993 | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/fingerprint/fingerprint.py#L15-L29 | train |
Yelp/threat_intel | threat_intel/util/http.py | SSLAdapter.init_poolmanager | def init_poolmanager(self, connections, maxsize, block=False, **pool_kwargs):
"""Called to initialize the HTTPAdapter when no proxy is used."""
try:
pool_kwargs['ssl_version'] = ssl.PROTOCOL_TLS
except AttributeError:
pool_kwargs['ssl_version'] = ssl.PROTOCOL_SSLv23
... | python | def init_poolmanager(self, connections, maxsize, block=False, **pool_kwargs):
"""Called to initialize the HTTPAdapter when no proxy is used."""
try:
pool_kwargs['ssl_version'] = ssl.PROTOCOL_TLS
except AttributeError:
pool_kwargs['ssl_version'] = ssl.PROTOCOL_SSLv23
... | [
"def",
"init_poolmanager",
"(",
"self",
",",
"connections",
",",
"maxsize",
",",
"block",
"=",
"False",
",",
"**",
"pool_kwargs",
")",
":",
"try",
":",
"pool_kwargs",
"[",
"'ssl_version'",
"]",
"=",
"ssl",
".",
"PROTOCOL_TLS",
"except",
"AttributeError",
":"... | Called to initialize the HTTPAdapter when no proxy is used. | [
"Called",
"to",
"initialize",
"the",
"HTTPAdapter",
"when",
"no",
"proxy",
"is",
"used",
"."
] | 60eef841d7cca115ec7857aeb9c553b72b694851 | https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/util/http.py#L51-L57 | train |
Yelp/threat_intel | threat_intel/util/http.py | SSLAdapter.proxy_manager_for | def proxy_manager_for(self, proxy, **proxy_kwargs):
"""Called to initialize the HTTPAdapter when a proxy is used."""
try:
proxy_kwargs['ssl_version'] = ssl.PROTOCOL_TLS
except AttributeError:
proxy_kwargs['ssl_version'] = ssl.PROTOCOL_SSLv23
return super(SSLAdapte... | python | def proxy_manager_for(self, proxy, **proxy_kwargs):
"""Called to initialize the HTTPAdapter when a proxy is used."""
try:
proxy_kwargs['ssl_version'] = ssl.PROTOCOL_TLS
except AttributeError:
proxy_kwargs['ssl_version'] = ssl.PROTOCOL_SSLv23
return super(SSLAdapte... | [
"def",
"proxy_manager_for",
"(",
"self",
",",
"proxy",
",",
"**",
"proxy_kwargs",
")",
":",
"try",
":",
"proxy_kwargs",
"[",
"'ssl_version'",
"]",
"=",
"ssl",
".",
"PROTOCOL_TLS",
"except",
"AttributeError",
":",
"proxy_kwargs",
"[",
"'ssl_version'",
"]",
"=",... | Called to initialize the HTTPAdapter when a proxy is used. | [
"Called",
"to",
"initialize",
"the",
"HTTPAdapter",
"when",
"a",
"proxy",
"is",
"used",
"."
] | 60eef841d7cca115ec7857aeb9c553b72b694851 | https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/util/http.py#L59-L65 | train |
Yelp/threat_intel | threat_intel/util/http.py | RateLimiter.make_calls | def make_calls(self, num_calls=1):
"""Adds appropriate sleep to avoid making too many calls.
Args:
num_calls: int the number of calls which will be made
"""
self._cull()
while self._outstanding_calls + num_calls > self._max_calls_per_second:
time.sleep(0)... | python | def make_calls(self, num_calls=1):
"""Adds appropriate sleep to avoid making too many calls.
Args:
num_calls: int the number of calls which will be made
"""
self._cull()
while self._outstanding_calls + num_calls > self._max_calls_per_second:
time.sleep(0)... | [
"def",
"make_calls",
"(",
"self",
",",
"num_calls",
"=",
"1",
")",
":",
"self",
".",
"_cull",
"(",
")",
"while",
"self",
".",
"_outstanding_calls",
"+",
"num_calls",
">",
"self",
".",
"_max_calls_per_second",
":",
"time",
".",
"sleep",
"(",
"0",
")",
"... | Adds appropriate sleep to avoid making too many calls.
Args:
num_calls: int the number of calls which will be made | [
"Adds",
"appropriate",
"sleep",
"to",
"avoid",
"making",
"too",
"many",
"calls",
"."
] | 60eef841d7cca115ec7857aeb9c553b72b694851 | https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/util/http.py#L79-L91 | train |
Yelp/threat_intel | threat_intel/util/http.py | RateLimiter._cull | def _cull(self):
"""Remove calls more than 1 second old from the queue."""
right_now = time.time()
cull_from = -1
for index in range(len(self._call_times)):
if right_now - self._call_times[index].time >= 1.0:
cull_from = index
self._outstandin... | python | def _cull(self):
"""Remove calls more than 1 second old from the queue."""
right_now = time.time()
cull_from = -1
for index in range(len(self._call_times)):
if right_now - self._call_times[index].time >= 1.0:
cull_from = index
self._outstandin... | [
"def",
"_cull",
"(",
"self",
")",
":",
"right_now",
"=",
"time",
".",
"time",
"(",
")",
"cull_from",
"=",
"-",
"1",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"_call_times",
")",
")",
":",
"if",
"right_now",
"-",
"self",
".",
"_... | Remove calls more than 1 second old from the queue. | [
"Remove",
"calls",
"more",
"than",
"1",
"second",
"old",
"from",
"the",
"queue",
"."
] | 60eef841d7cca115ec7857aeb9c553b72b694851 | https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/util/http.py#L93-L106 | train |
Yelp/threat_intel | threat_intel/util/http.py | AvailabilityLimiter.map_with_retries | def map_with_retries(self, requests, responses_for_requests):
"""Provides session-based retry functionality
:param requests: A collection of Request objects.
:param responses_for_requests: Dictionary mapping of requests to responses
:param max_retries: The maximum number of retries to p... | python | def map_with_retries(self, requests, responses_for_requests):
"""Provides session-based retry functionality
:param requests: A collection of Request objects.
:param responses_for_requests: Dictionary mapping of requests to responses
:param max_retries: The maximum number of retries to p... | [
"def",
"map_with_retries",
"(",
"self",
",",
"requests",
",",
"responses_for_requests",
")",
":",
"retries",
"=",
"[",
"]",
"response_futures",
"=",
"[",
"preq",
".",
"callable",
"(",
")",
"for",
"preq",
"in",
"requests",
"]",
"for",
"request",
",",
"respo... | Provides session-based retry functionality
:param requests: A collection of Request objects.
:param responses_for_requests: Dictionary mapping of requests to responses
:param max_retries: The maximum number of retries to perform per session
:param args: Additional arguments to pass into... | [
"Provides",
"session",
"-",
"based",
"retry",
"functionality"
] | 60eef841d7cca115ec7857aeb9c553b72b694851 | https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/util/http.py#L122-L151 | train |
Yelp/threat_intel | threat_intel/util/http.py | MultiRequest.multi_get | def multi_get(self, urls, query_params=None, to_json=True):
"""Issue multiple GET requests.
Args:
urls - A string URL or list of string URLs
query_params - None, a dict, or a list of dicts representing the query params
to_json - A boolean, should the responses be ret... | python | def multi_get(self, urls, query_params=None, to_json=True):
"""Issue multiple GET requests.
Args:
urls - A string URL or list of string URLs
query_params - None, a dict, or a list of dicts representing the query params
to_json - A boolean, should the responses be ret... | [
"def",
"multi_get",
"(",
"self",
",",
"urls",
",",
"query_params",
"=",
"None",
",",
"to_json",
"=",
"True",
")",
":",
"return",
"self",
".",
"_multi_request",
"(",
"MultiRequest",
".",
"_VERB_GET",
",",
"urls",
",",
"query_params",
",",
"data",
"=",
"No... | Issue multiple GET requests.
Args:
urls - A string URL or list of string URLs
query_params - None, a dict, or a list of dicts representing the query params
to_json - A boolean, should the responses be returned as JSON blobs
Returns:
a list of dicts if to_... | [
"Issue",
"multiple",
"GET",
"requests",
"."
] | 60eef841d7cca115ec7857aeb9c553b72b694851 | https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/util/http.py#L203-L218 | train |
Yelp/threat_intel | threat_intel/util/http.py | MultiRequest.multi_post | def multi_post(self, urls, query_params=None, data=None, to_json=True, send_as_file=False):
"""Issue multiple POST requests.
Args:
urls - A string URL or list of string URLs
query_params - None, a dict, or a list of dicts representing the query params
data - None, a ... | python | def multi_post(self, urls, query_params=None, data=None, to_json=True, send_as_file=False):
"""Issue multiple POST requests.
Args:
urls - A string URL or list of string URLs
query_params - None, a dict, or a list of dicts representing the query params
data - None, a ... | [
"def",
"multi_post",
"(",
"self",
",",
"urls",
",",
"query_params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"to_json",
"=",
"True",
",",
"send_as_file",
"=",
"False",
")",
":",
"return",
"self",
".",
"_multi_request",
"(",
"MultiRequest",
".",
"_VERB... | Issue multiple POST requests.
Args:
urls - A string URL or list of string URLs
query_params - None, a dict, or a list of dicts representing the query params
data - None, a dict or string, or a list of dicts and strings representing the data body.
to_json - A bool... | [
"Issue",
"multiple",
"POST",
"requests",
"."
] | 60eef841d7cca115ec7857aeb9c553b72b694851 | https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/util/http.py#L220-L237 | train |
Yelp/threat_intel | threat_intel/util/http.py | MultiRequest._zip_request_params | def _zip_request_params(self, urls, query_params, data):
"""Massages inputs and returns a list of 3-tuples zipping them up.
This is all the smarts behind deciding how many requests to issue.
It's fine for an input to have 0, 1, or a list of values.
If there are two inputs each with a li... | python | def _zip_request_params(self, urls, query_params, data):
"""Massages inputs and returns a list of 3-tuples zipping them up.
This is all the smarts behind deciding how many requests to issue.
It's fine for an input to have 0, 1, or a list of values.
If there are two inputs each with a li... | [
"def",
"_zip_request_params",
"(",
"self",
",",
"urls",
",",
"query_params",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"urls",
",",
"list",
")",
":",
"urls",
"=",
"[",
"urls",
"]",
"if",
"not",
"isinstance",
"(",
"query_params",
",",
"list... | Massages inputs and returns a list of 3-tuples zipping them up.
This is all the smarts behind deciding how many requests to issue.
It's fine for an input to have 0, 1, or a list of values.
If there are two inputs each with a list of values, the cardinality of those lists much match.
Ar... | [
"Massages",
"inputs",
"and",
"returns",
"a",
"list",
"of",
"3",
"-",
"tuples",
"zipping",
"them",
"up",
"."
] | 60eef841d7cca115ec7857aeb9c553b72b694851 | https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/util/http.py#L272-L322 | train |
Yelp/threat_intel | threat_intel/util/http.py | MultiRequest._wait_for_response | def _wait_for_response(self, requests):
"""Issues a batch of requests and waits for the responses.
If some of the requests fail it will retry the failed ones up to `_max_retry` times.
Args:
requests - A list of requests
Returns:
A list of `requests.models.Respons... | python | def _wait_for_response(self, requests):
"""Issues a batch of requests and waits for the responses.
If some of the requests fail it will retry the failed ones up to `_max_retry` times.
Args:
requests - A list of requests
Returns:
A list of `requests.models.Respons... | [
"def",
"_wait_for_response",
"(",
"self",
",",
"requests",
")",
":",
"failed_requests",
"=",
"[",
"]",
"responses_for_requests",
"=",
"OrderedDict",
".",
"fromkeys",
"(",
"requests",
")",
"for",
"retry",
"in",
"range",
"(",
"self",
".",
"_max_retry",
")",
":... | Issues a batch of requests and waits for the responses.
If some of the requests fail it will retry the failed ones up to `_max_retry` times.
Args:
requests - A list of requests
Returns:
A list of `requests.models.Response` objects
Raises:
InvalidReque... | [
"Issues",
"a",
"batch",
"of",
"requests",
"and",
"waits",
"for",
"the",
"responses",
".",
"If",
"some",
"of",
"the",
"requests",
"fail",
"it",
"will",
"retry",
"the",
"failed",
"ones",
"up",
"to",
"_max_retry",
"times",
"."
] | 60eef841d7cca115ec7857aeb9c553b72b694851 | https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/util/http.py#L324-L380 | train |
Yelp/threat_intel | threat_intel/util/http.py | MultiRequest._convert_to_json | def _convert_to_json(self, response):
"""Converts response to JSON.
If the response cannot be converted to JSON then `None` is returned.
Args:
response - An object of type `requests.models.Response`
Returns:
Response in JSON format if the response can be converte... | python | def _convert_to_json(self, response):
"""Converts response to JSON.
If the response cannot be converted to JSON then `None` is returned.
Args:
response - An object of type `requests.models.Response`
Returns:
Response in JSON format if the response can be converte... | [
"def",
"_convert_to_json",
"(",
"self",
",",
"response",
")",
":",
"try",
":",
"return",
"response",
".",
"json",
"(",
")",
"except",
"ValueError",
":",
"logging",
".",
"warning",
"(",
"'Expected response in JSON format from {0} but the actual response text is: {1}'",
... | Converts response to JSON.
If the response cannot be converted to JSON then `None` is returned.
Args:
response - An object of type `requests.models.Response`
Returns:
Response in JSON format if the response can be converted to JSON. `None` otherwise. | [
"Converts",
"response",
"to",
"JSON",
".",
"If",
"the",
"response",
"cannot",
"be",
"converted",
"to",
"JSON",
"then",
"None",
"is",
"returned",
"."
] | 60eef841d7cca115ec7857aeb9c553b72b694851 | https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/util/http.py#L382-L397 | train |
Yelp/threat_intel | threat_intel/util/http.py | MultiRequest._multi_request | def _multi_request(self, verb, urls, query_params, data, to_json=True, send_as_file=False):
"""Issues multiple batches of simultaneous HTTP requests and waits for responses.
Args:
verb - MultiRequest._VERB_POST or MultiRequest._VERB_GET
urls - A string URL or list of string URLs... | python | def _multi_request(self, verb, urls, query_params, data, to_json=True, send_as_file=False):
"""Issues multiple batches of simultaneous HTTP requests and waits for responses.
Args:
verb - MultiRequest._VERB_POST or MultiRequest._VERB_GET
urls - A string URL or list of string URLs... | [
"def",
"_multi_request",
"(",
"self",
",",
"verb",
",",
"urls",
",",
"query_params",
",",
"data",
",",
"to_json",
"=",
"True",
",",
"send_as_file",
"=",
"False",
")",
":",
"if",
"not",
"urls",
":",
"raise",
"InvalidRequestError",
"(",
"'No URL supplied'",
... | Issues multiple batches of simultaneous HTTP requests and waits for responses.
Args:
verb - MultiRequest._VERB_POST or MultiRequest._VERB_GET
urls - A string URL or list of string URLs
query_params - None, a dict, or a list of dicts representing the query params
... | [
"Issues",
"multiple",
"batches",
"of",
"simultaneous",
"HTTP",
"requests",
"and",
"waits",
"for",
"responses",
"."
] | 60eef841d7cca115ec7857aeb9c553b72b694851 | https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/util/http.py#L399-L443 | train |
Yelp/threat_intel | threat_intel/util/http.py | MultiRequest.error_handling | def error_handling(cls, fn):
"""Decorator to handle errors"""
def wrapper(*args, **kwargs):
try:
result = fn(*args, **kwargs)
return result
except InvalidRequestError as e:
write_exception(e)
if hasattr(e, 'request'... | python | def error_handling(cls, fn):
"""Decorator to handle errors"""
def wrapper(*args, **kwargs):
try:
result = fn(*args, **kwargs)
return result
except InvalidRequestError as e:
write_exception(e)
if hasattr(e, 'request'... | [
"def",
"error_handling",
"(",
"cls",
",",
"fn",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"try",
":",
"result",
"=",
"fn",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"return",
"result",
"except",
"InvalidRequestErr... | Decorator to handle errors | [
"Decorator",
"to",
"handle",
"errors"
] | 60eef841d7cca115ec7857aeb9c553b72b694851 | https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/util/http.py#L450-L465 | train |
glasslion/redlock | redlock/lock.py | RedLock.acquire_node | def acquire_node(self, node):
"""
acquire a single redis node
"""
try:
return node.set(self.resource, self.lock_key, nx=True, px=self.ttl)
except (redis.exceptions.ConnectionError, redis.exceptions.TimeoutError):
return False | python | def acquire_node(self, node):
"""
acquire a single redis node
"""
try:
return node.set(self.resource, self.lock_key, nx=True, px=self.ttl)
except (redis.exceptions.ConnectionError, redis.exceptions.TimeoutError):
return False | [
"def",
"acquire_node",
"(",
"self",
",",
"node",
")",
":",
"try",
":",
"return",
"node",
".",
"set",
"(",
"self",
".",
"resource",
",",
"self",
".",
"lock_key",
",",
"nx",
"=",
"True",
",",
"px",
"=",
"self",
".",
"ttl",
")",
"except",
"(",
"redi... | acquire a single redis node | [
"acquire",
"a",
"single",
"redis",
"node"
] | 7f873cc362eefa7f7adee8d4913e64f87c1fd1c9 | https://github.com/glasslion/redlock/blob/7f873cc362eefa7f7adee8d4913e64f87c1fd1c9/redlock/lock.py#L135-L142 | train |
glasslion/redlock | redlock/lock.py | RedLock.release_node | def release_node(self, node):
"""
release a single redis node
"""
# use the lua script to release the lock in a safe way
try:
node._release_script(keys=[self.resource], args=[self.lock_key])
except (redis.exceptions.ConnectionError, redis.exceptions.TimeoutErr... | python | def release_node(self, node):
"""
release a single redis node
"""
# use the lua script to release the lock in a safe way
try:
node._release_script(keys=[self.resource], args=[self.lock_key])
except (redis.exceptions.ConnectionError, redis.exceptions.TimeoutErr... | [
"def",
"release_node",
"(",
"self",
",",
"node",
")",
":",
"try",
":",
"node",
".",
"_release_script",
"(",
"keys",
"=",
"[",
"self",
".",
"resource",
"]",
",",
"args",
"=",
"[",
"self",
".",
"lock_key",
"]",
")",
"except",
"(",
"redis",
".",
"exce... | release a single redis node | [
"release",
"a",
"single",
"redis",
"node"
] | 7f873cc362eefa7f7adee8d4913e64f87c1fd1c9 | https://github.com/glasslion/redlock/blob/7f873cc362eefa7f7adee8d4913e64f87c1fd1c9/redlock/lock.py#L144-L152 | train |
Yelp/threat_intel | threat_intel/alexaranking.py | AlexaRankingApi._extract_response_xml | def _extract_response_xml(self, domain, response):
"""Extract XML content of an HTTP response into dictionary format.
Args:
response: HTML Response objects
Returns:
A dictionary: {alexa-ranking key : alexa-ranking value}.
"""
attributes = {}
alexa... | python | def _extract_response_xml(self, domain, response):
"""Extract XML content of an HTTP response into dictionary format.
Args:
response: HTML Response objects
Returns:
A dictionary: {alexa-ranking key : alexa-ranking value}.
"""
attributes = {}
alexa... | [
"def",
"_extract_response_xml",
"(",
"self",
",",
"domain",
",",
"response",
")",
":",
"attributes",
"=",
"{",
"}",
"alexa_keys",
"=",
"{",
"'POPULARITY'",
":",
"'TEXT'",
",",
"'REACH'",
":",
"'RANK'",
",",
"'RANK'",
":",
"'DELTA'",
"}",
"try",
":",
"xml... | Extract XML content of an HTTP response into dictionary format.
Args:
response: HTML Response objects
Returns:
A dictionary: {alexa-ranking key : alexa-ranking value}. | [
"Extract",
"XML",
"content",
"of",
"an",
"HTTP",
"response",
"into",
"dictionary",
"format",
"."
] | 60eef841d7cca115ec7857aeb9c553b72b694851 | https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/alexaranking.py#L74-L95 | train |
Yelp/threat_intel | threat_intel/alexaranking.py | AlexaRankingApi._bulk_cache_lookup | def _bulk_cache_lookup(self, api_name, keys):
"""Performes a bulk cache lookup and returns a tuple with the results
found and the keys missing in the cache. If cached is not configured
it will return an empty dictionary of found results and the initial
list of keys.
Args:
... | python | def _bulk_cache_lookup(self, api_name, keys):
"""Performes a bulk cache lookup and returns a tuple with the results
found and the keys missing in the cache. If cached is not configured
it will return an empty dictionary of found results and the initial
list of keys.
Args:
... | [
"def",
"_bulk_cache_lookup",
"(",
"self",
",",
"api_name",
",",
"keys",
")",
":",
"if",
"self",
".",
"_cache",
":",
"responses",
"=",
"self",
".",
"_cache",
".",
"bulk_lookup",
"(",
"api_name",
",",
"keys",
")",
"missing_keys",
"=",
"[",
"key",
"for",
... | Performes a bulk cache lookup and returns a tuple with the results
found and the keys missing in the cache. If cached is not configured
it will return an empty dictionary of found results and the initial
list of keys.
Args:
api_name: a string name of the API.
key... | [
"Performes",
"a",
"bulk",
"cache",
"lookup",
"and",
"returns",
"a",
"tuple",
"with",
"the",
"results",
"found",
"and",
"the",
"keys",
"missing",
"in",
"the",
"cache",
".",
"If",
"cached",
"is",
"not",
"configured",
"it",
"will",
"return",
"an",
"empty",
... | 60eef841d7cca115ec7857aeb9c553b72b694851 | https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/alexaranking.py#L97-L114 | train |
Yelp/threat_intel | threat_intel/util/api_cache.py | ApiCache._write_cache_to_file | def _write_cache_to_file(self):
"""Write the contents of the cache to a file on disk."""
with(open(self._cache_file_name, 'w')) as fp:
fp.write(simplejson.dumps(self._cache)) | python | def _write_cache_to_file(self):
"""Write the contents of the cache to a file on disk."""
with(open(self._cache_file_name, 'w')) as fp:
fp.write(simplejson.dumps(self._cache)) | [
"def",
"_write_cache_to_file",
"(",
"self",
")",
":",
"with",
"(",
"open",
"(",
"self",
".",
"_cache_file_name",
",",
"'w'",
")",
")",
"as",
"fp",
":",
"fp",
".",
"write",
"(",
"simplejson",
".",
"dumps",
"(",
"self",
".",
"_cache",
")",
")"
] | Write the contents of the cache to a file on disk. | [
"Write",
"the",
"contents",
"of",
"the",
"cache",
"to",
"a",
"file",
"on",
"disk",
"."
] | 60eef841d7cca115ec7857aeb9c553b72b694851 | https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/util/api_cache.py#L42-L45 | train |
Yelp/threat_intel | threat_intel/util/api_cache.py | ApiCache._read_cache_from_file | def _read_cache_from_file(self):
"""Read the contents of the cache from a file on disk."""
cache = {}
try:
with(open(self._cache_file_name, 'r')) as fp:
contents = fp.read()
cache = simplejson.loads(contents)
except (IOError, JSONDecodeError):
... | python | def _read_cache_from_file(self):
"""Read the contents of the cache from a file on disk."""
cache = {}
try:
with(open(self._cache_file_name, 'r')) as fp:
contents = fp.read()
cache = simplejson.loads(contents)
except (IOError, JSONDecodeError):
... | [
"def",
"_read_cache_from_file",
"(",
"self",
")",
":",
"cache",
"=",
"{",
"}",
"try",
":",
"with",
"(",
"open",
"(",
"self",
".",
"_cache_file_name",
",",
"'r'",
")",
")",
"as",
"fp",
":",
"contents",
"=",
"fp",
".",
"read",
"(",
")",
"cache",
"=",... | Read the contents of the cache from a file on disk. | [
"Read",
"the",
"contents",
"of",
"the",
"cache",
"from",
"a",
"file",
"on",
"disk",
"."
] | 60eef841d7cca115ec7857aeb9c553b72b694851 | https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/util/api_cache.py#L47-L58 | train |
Yelp/threat_intel | threat_intel/util/api_cache.py | ApiCache.bulk_lookup | def bulk_lookup(self, api_name, keys):
"""Perform lookup on an enumerable of keys.
Args:
api_name: a string name of the API. Keys and values are segmented by api_name.
keys: an enumerable of string keys.
"""
cached_data = {}
for key in keys:
... | python | def bulk_lookup(self, api_name, keys):
"""Perform lookup on an enumerable of keys.
Args:
api_name: a string name of the API. Keys and values are segmented by api_name.
keys: an enumerable of string keys.
"""
cached_data = {}
for key in keys:
... | [
"def",
"bulk_lookup",
"(",
"self",
",",
"api_name",
",",
"keys",
")",
":",
"cached_data",
"=",
"{",
"}",
"for",
"key",
"in",
"keys",
":",
"value",
"=",
"self",
".",
"lookup_value",
"(",
"api_name",
",",
"key",
")",
"if",
"value",
"is",
"not",
"None",... | Perform lookup on an enumerable of keys.
Args:
api_name: a string name of the API. Keys and values are segmented by api_name.
keys: an enumerable of string keys. | [
"Perform",
"lookup",
"on",
"an",
"enumerable",
"of",
"keys",
"."
] | 60eef841d7cca115ec7857aeb9c553b72b694851 | https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/util/api_cache.py#L82-L95 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.