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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
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 | 234,000 |
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",
"]",
"+",
"'-'",
"+",
"string",
"[",
"16",
":",
"20",
"]",
"+",
"'-'",
"+",
"string",
"[",
"20",
":",
"32",
"]"
] | 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 | 234,001 |
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::2])) | 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::2])) | [
"def",
"bt_addr_to_string",
"(",
"addr",
")",
":",
"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",
":",
":",
"2",
"]",
")",
")"
] | 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 | 234,002 |
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 | 234,003 |
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, \
EstimoteTelemetryFrameA, EstimoteTelemetryFrameB
return (cls in [EddystoneURLFrame, EddystoneUIDFrame, EddystoneEncryptedTLMFrame, \
EddystoneTLMFrame, EddystoneEIDFrame, IBeaconAdvertisement, \
EstimoteTelemetryFrameA, EstimoteTelemetryFrameB]) | python | def is_packet_type(cls):
"""Check if class is one the packet types."""
from .packet_types import EddystoneUIDFrame, EddystoneURLFrame, \
EddystoneEncryptedTLMFrame, EddystoneTLMFrame, \
EddystoneEIDFrame, IBeaconAdvertisement, \
EstimoteTelemetryFrameA, EstimoteTelemetryFrameB
return (cls in [EddystoneURLFrame, EddystoneUIDFrame, EddystoneEncryptedTLMFrame, \
EddystoneTLMFrame, EddystoneEIDFrame, IBeaconAdvertisement, \
EstimoteTelemetryFrameA, EstimoteTelemetryFrameB]) | [
"def",
"is_packet_type",
"(",
"cls",
")",
":",
"from",
".",
"packet_types",
"import",
"EddystoneUIDFrame",
",",
"EddystoneURLFrame",
",",
"EddystoneEncryptedTLMFrame",
",",
"EddystoneTLMFrame",
",",
"EddystoneEIDFrame",
",",
"IBeaconAdvertisement",
",",
"EstimoteTelemetryFrameA",
",",
"EstimoteTelemetryFrameB",
"return",
"(",
"cls",
"in",
"[",
"EddystoneURLFrame",
",",
"EddystoneUIDFrame",
",",
"EddystoneEncryptedTLMFrame",
",",
"EddystoneTLMFrame",
",",
"EddystoneEIDFrame",
",",
"IBeaconAdvertisement",
",",
"EstimoteTelemetryFrameA",
",",
"EstimoteTelemetryFrameB",
"]",
")"
] | 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 | 234,004 |
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\"",
",",
"bytes",
"(",
"[",
"string",
"]",
")",
")",
"[",
"0",
"]"
] | 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 | 234,005 |
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 filtr in device_filter:
if isinstance(filtr, IBeaconFilter):
mode |= ScannerMode.MODE_IBEACON
elif isinstance(filtr, EddystoneFilter):
mode |= ScannerMode.MODE_EDDYSTONE
elif isinstance(filtr, EstimoteFilter):
mode |= ScannerMode.MODE_ESTIMOTE
elif isinstance(filtr, BtAddrFilter):
mode |= ScannerMode.MODE_ALL
break
return mode | 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 filtr in device_filter:
if isinstance(filtr, IBeaconFilter):
mode |= ScannerMode.MODE_IBEACON
elif isinstance(filtr, EddystoneFilter):
mode |= ScannerMode.MODE_EDDYSTONE
elif isinstance(filtr, EstimoteFilter):
mode |= ScannerMode.MODE_ESTIMOTE
elif isinstance(filtr, BtAddrFilter):
mode |= ScannerMode.MODE_ALL
break
return mode | [
"def",
"get_mode",
"(",
"device_filter",
")",
":",
"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",
"filtr",
"in",
"device_filter",
":",
"if",
"isinstance",
"(",
"filtr",
",",
"IBeaconFilter",
")",
":",
"mode",
"|=",
"ScannerMode",
".",
"MODE_IBEACON",
"elif",
"isinstance",
"(",
"filtr",
",",
"EddystoneFilter",
")",
":",
"mode",
"|=",
"ScannerMode",
".",
"MODE_EDDYSTONE",
"elif",
"isinstance",
"(",
"filtr",
",",
"EstimoteFilter",
")",
":",
"mode",
"|=",
"ScannerMode",
".",
"MODE_ESTIMOTE",
"elif",
"isinstance",
"(",
"filtr",
",",
"BtAddrFilter",
")",
":",
"mode",
"|=",
"ScannerMode",
".",
"MODE_ALL",
"break",
"return",
"mode"
] | 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 | 234,006 |
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]:
return False
elif key in self.properties and value == self.properties[key]:
found_one = True
return found_one | 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]:
return False
elif key in self.properties and value == self.properties[key]:
found_one = True
return found_one | [
"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",
".",
"properties",
"and",
"value",
"!=",
"self",
".",
"properties",
"[",
"key",
"]",
":",
"return",
"False",
"elif",
"key",
"in",
"self",
".",
"properties",
"and",
"value",
"==",
"self",
".",
"properties",
"[",
"key",
"]",
":",
"found_one",
"=",
"True",
"return",
"found_one"
] | 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 | 234,007 |
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 | 234,008 |
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:
return parse_eddystone_service_data(data)
elif data["service_identifier"] == ESTIMOTE_UUID:
return parse_estimote_service_data(data)
except ConstructError:
return None
return None | 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:
return parse_eddystone_service_data(data)
elif data["service_identifier"] == ESTIMOTE_UUID:
return parse_estimote_service_data(data)
except ConstructError:
return None
return None | [
"def",
"parse_ltv_packet",
"(",
"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",
":",
"return",
"parse_eddystone_service_data",
"(",
"data",
")",
"elif",
"data",
"[",
"\"service_identifier\"",
"]",
"==",
"ESTIMOTE_UUID",
":",
"return",
"parse_estimote_service_data",
"(",
"data",
")",
"except",
"ConstructError",
":",
"return",
"None",
"return",
"None"
] | 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 | 234,009 |
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 EddystoneEncryptedTLMFrame(data['frame']['data'])
elif data['frame']['tlm_version'] == EDDYSTONE_TLM_UNENCRYPTED:
return EddystoneTLMFrame(data['frame']['data'])
elif data['frame_type'] == EDDYSTONE_URL_FRAME:
return EddystoneURLFrame(data['frame'])
elif data['frame_type'] == EDDYSTONE_EID_FRAME:
return EddystoneEIDFrame(data['frame'])
else:
return None | 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 EddystoneEncryptedTLMFrame(data['frame']['data'])
elif data['frame']['tlm_version'] == EDDYSTONE_TLM_UNENCRYPTED:
return EddystoneTLMFrame(data['frame']['data'])
elif data['frame_type'] == EDDYSTONE_URL_FRAME:
return EddystoneURLFrame(data['frame'])
elif data['frame_type'] == EDDYSTONE_EID_FRAME:
return EddystoneEIDFrame(data['frame'])
else:
return None | [
"def",
"parse_eddystone_service_data",
"(",
"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",
"EddystoneEncryptedTLMFrame",
"(",
"data",
"[",
"'frame'",
"]",
"[",
"'data'",
"]",
")",
"elif",
"data",
"[",
"'frame'",
"]",
"[",
"'tlm_version'",
"]",
"==",
"EDDYSTONE_TLM_UNENCRYPTED",
":",
"return",
"EddystoneTLMFrame",
"(",
"data",
"[",
"'frame'",
"]",
"[",
"'data'",
"]",
")",
"elif",
"data",
"[",
"'frame_type'",
"]",
"==",
"EDDYSTONE_URL_FRAME",
":",
"return",
"EddystoneURLFrame",
"(",
"data",
"[",
"'frame'",
"]",
")",
"elif",
"data",
"[",
"'frame_type'",
"]",
"==",
"EDDYSTONE_EID_FRAME",
":",
"return",
"EddystoneEIDFrame",
"(",
"data",
"[",
"'frame'",
"]",
")",
"else",
":",
"return",
"None"
] | Parse Eddystone service data. | [
"Parse",
"Eddystone",
"service",
"data",
"."
] | 15a83e9750d0a4393f8a36868e07f6d9458253fe | https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/parser.py#L40-L57 | train | 234,010 |
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(data['frame'], protocol_version)
elif data['frame']['subframe_type'] == ESTIMOTE_TELEMETRY_SUBFRAME_B:
return EstimoteTelemetryFrameB(data['frame'], protocol_version)
return None | 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(data['frame'], protocol_version)
elif data['frame']['subframe_type'] == ESTIMOTE_TELEMETRY_SUBFRAME_B:
return EstimoteTelemetryFrameB(data['frame'], protocol_version)
return None | [
"def",
"parse_estimote_service_data",
"(",
"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",
"(",
"data",
"[",
"'frame'",
"]",
",",
"protocol_version",
")",
"elif",
"data",
"[",
"'frame'",
"]",
"[",
"'subframe_type'",
"]",
"==",
"ESTIMOTE_TELEMETRY_SUBFRAME_B",
":",
"return",
"EstimoteTelemetryFrameB",
"(",
"data",
"[",
"'frame'",
"]",
",",
"protocol_version",
")",
"return",
"None"
] | Parse Estimote service data. | [
"Parse",
"Estimote",
"service",
"data",
"."
] | 15a83e9750d0a4393f8a36868e07f6d9458253fe | https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/parser.py#L59-L67 | train | 234,011 |
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:
number *= 60 * 60 * 24 # days
elif unit == 3:
number -= 32
number *= 60 * 60 * 24 * 7 # weeks
return number | 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:
number *= 60 * 60 * 24 # days
elif unit == 3:
number -= 32
number *= 60 * 60 * 24 * 7 # weeks
return number | [
"def",
"parse_motion_state",
"(",
"val",
")",
":",
"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",
":",
"number",
"*=",
"60",
"*",
"60",
"*",
"24",
"# days",
"elif",
"unit",
"==",
"3",
":",
"number",
"-=",
"32",
"number",
"*=",
"60",
"*",
"60",
"*",
"24",
"*",
"7",
"# weeks",
"return",
"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 | 234,012 |
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 | 234,013 |
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",
"]",
"=",
"(",
"framebuf",
".",
"buf",
"[",
"index",
"]",
"&",
"~",
"(",
"0x01",
"<<",
"offset",
")",
")",
"|",
"(",
"(",
"color",
"!=",
"0",
")",
"<<",
"offset",
")"
] | 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 | 234,014 |
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",
"]",
">>",
"offset",
")",
"&",
"0x01"
] | 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 | 234,015 |
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:
x = self.width - x - 1
y = self.height - y - 1
if self.rotation == 3:
x, y = y, x
y = self.height - y - 1
if x < 0 or x >= self.width or y < 0 or y >= self.height:
return None
if color is None:
return self.format.get_pixel(self, x, y)
self.format.set_pixel(self, x, y, color)
return None | 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:
x = self.width - x - 1
y = self.height - y - 1
if self.rotation == 3:
x, y = y, x
y = self.height - y - 1
if x < 0 or x >= self.width or y < 0 or y >= self.height:
return None
if color is None:
return self.format.get_pixel(self, x, y)
self.format.set_pixel(self, x, y, color)
return None | [
"def",
"pixel",
"(",
"self",
",",
"x",
",",
"y",
",",
"color",
"=",
"None",
")",
":",
"if",
"self",
".",
"rotation",
"==",
"1",
":",
"x",
",",
"y",
"=",
"y",
",",
"x",
"x",
"=",
"self",
".",
"width",
"-",
"x",
"-",
"1",
"if",
"self",
".",
"rotation",
"==",
"2",
":",
"x",
"=",
"self",
".",
"width",
"-",
"x",
"-",
"1",
"y",
"=",
"self",
".",
"height",
"-",
"y",
"-",
"1",
"if",
"self",
".",
"rotation",
"==",
"3",
":",
"x",
",",
"y",
"=",
"y",
",",
"x",
"y",
"=",
"self",
".",
"height",
"-",
"y",
"-",
"1",
"if",
"x",
"<",
"0",
"or",
"x",
">=",
"self",
".",
"width",
"or",
"y",
"<",
"0",
"or",
"y",
">=",
"self",
".",
"height",
":",
"return",
"None",
"if",
"color",
"is",
"None",
":",
"return",
"self",
".",
"format",
".",
"get_pixel",
"(",
"self",
",",
"x",
",",
"y",
")",
"self",
".",
"format",
".",
"set_pixel",
"(",
"self",
",",
"x",
",",
"y",
",",
"color",
")",
"return",
"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",
"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 | 234,016 |
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 | 234,017 |
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 | 234,018 |
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 = height, width
x = self.width - x - width
if self.rotation == 2:
x = self.width - x - width
y = self.height - y - height
if self.rotation == 3:
x, y = y, x
width, height = height, width
y = self.height - y - height
# pylint: disable=too-many-boolean-expressions
if width < 1 or height < 1 or (x + width) <= 0 or (y + height) <= 0 or \
y >= self.height or x >= self.width:
return
x_end = min(self.width-1, x + width-1)
y_end = min(self.height-1, y + height-1)
x = max(x, 0)
y = max(y, 0)
if fill:
self.format.fill_rect(self, x, y, x_end-x+1, y_end-y+1, color)
else:
self.format.fill_rect(self, x, y, x_end-x+1, 1, color)
self.format.fill_rect(self, x, y, 1, y_end-y+1, color)
self.format.fill_rect(self, x, y_end, x_end-x+1, 1, color)
self.format.fill_rect(self, x_end, y, 1, y_end-y+1, color) | 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 = height, width
x = self.width - x - width
if self.rotation == 2:
x = self.width - x - width
y = self.height - y - height
if self.rotation == 3:
x, y = y, x
width, height = height, width
y = self.height - y - height
# pylint: disable=too-many-boolean-expressions
if width < 1 or height < 1 or (x + width) <= 0 or (y + height) <= 0 or \
y >= self.height or x >= self.width:
return
x_end = min(self.width-1, x + width-1)
y_end = min(self.height-1, y + height-1)
x = max(x, 0)
y = max(y, 0)
if fill:
self.format.fill_rect(self, x, y, x_end-x+1, y_end-y+1, color)
else:
self.format.fill_rect(self, x, y, x_end-x+1, 1, color)
self.format.fill_rect(self, x, y, 1, y_end-y+1, color)
self.format.fill_rect(self, x, y_end, x_end-x+1, 1, color)
self.format.fill_rect(self, x_end, y, 1, y_end-y+1, color) | [
"def",
"rect",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"color",
",",
"*",
",",
"fill",
"=",
"False",
")",
":",
"# pylint: disable=too-many-arguments",
"if",
"self",
".",
"rotation",
"==",
"1",
":",
"x",
",",
"y",
"=",
"y",
",",
"x",
"width",
",",
"height",
"=",
"height",
",",
"width",
"x",
"=",
"self",
".",
"width",
"-",
"x",
"-",
"width",
"if",
"self",
".",
"rotation",
"==",
"2",
":",
"x",
"=",
"self",
".",
"width",
"-",
"x",
"-",
"width",
"y",
"=",
"self",
".",
"height",
"-",
"y",
"-",
"height",
"if",
"self",
".",
"rotation",
"==",
"3",
":",
"x",
",",
"y",
"=",
"y",
",",
"x",
"width",
",",
"height",
"=",
"height",
",",
"width",
"y",
"=",
"self",
".",
"height",
"-",
"y",
"-",
"height",
"# pylint: disable=too-many-boolean-expressions",
"if",
"width",
"<",
"1",
"or",
"height",
"<",
"1",
"or",
"(",
"x",
"+",
"width",
")",
"<=",
"0",
"or",
"(",
"y",
"+",
"height",
")",
"<=",
"0",
"or",
"y",
">=",
"self",
".",
"height",
"or",
"x",
">=",
"self",
".",
"width",
":",
"return",
"x_end",
"=",
"min",
"(",
"self",
".",
"width",
"-",
"1",
",",
"x",
"+",
"width",
"-",
"1",
")",
"y_end",
"=",
"min",
"(",
"self",
".",
"height",
"-",
"1",
",",
"y",
"+",
"height",
"-",
"1",
")",
"x",
"=",
"max",
"(",
"x",
",",
"0",
")",
"y",
"=",
"max",
"(",
"y",
",",
"0",
")",
"if",
"fill",
":",
"self",
".",
"format",
".",
"fill_rect",
"(",
"self",
",",
"x",
",",
"y",
",",
"x_end",
"-",
"x",
"+",
"1",
",",
"y_end",
"-",
"y",
"+",
"1",
",",
"color",
")",
"else",
":",
"self",
".",
"format",
".",
"fill_rect",
"(",
"self",
",",
"x",
",",
"y",
",",
"x_end",
"-",
"x",
"+",
"1",
",",
"1",
",",
"color",
")",
"self",
".",
"format",
".",
"fill_rect",
"(",
"self",
",",
"x",
",",
"y",
",",
"1",
",",
"y_end",
"-",
"y",
"+",
"1",
",",
"color",
")",
"self",
".",
"format",
".",
"fill_rect",
"(",
"self",
",",
"x",
",",
"y_end",
",",
"x_end",
"-",
"x",
"+",
"1",
",",
"1",
",",
"color",
")",
"self",
".",
"format",
".",
"fill_rect",
"(",
"self",
",",
"x_end",
",",
"y",
",",
"1",
",",
"y_end",
"-",
"y",
"+",
"1",
",",
"color",
")"
] | 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 | 234,019 |
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:
err = d_x / 2.0
while x != x_1:
self.pixel(x, y, color)
err -= d_y
if err < 0:
y += s_y
err += d_x
x += s_x
else:
err = d_y / 2.0
while y != y_1:
self.pixel(x, y, color)
err -= d_x
if err < 0:
x += s_x
err += d_y
y += s_y
self.pixel(x, y, color) | 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:
err = d_x / 2.0
while x != x_1:
self.pixel(x, y, color)
err -= d_y
if err < 0:
y += s_y
err += d_x
x += s_x
else:
err = d_y / 2.0
while y != y_1:
self.pixel(x, y, color)
err -= d_x
if err < 0:
x += s_x
err += d_y
y += s_y
self.pixel(x, y, color) | [
"def",
"line",
"(",
"self",
",",
"x_0",
",",
"y_0",
",",
"x_1",
",",
"y_1",
",",
"color",
")",
":",
"# pylint: disable=too-many-arguments",
"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",
":",
"err",
"=",
"d_x",
"/",
"2.0",
"while",
"x",
"!=",
"x_1",
":",
"self",
".",
"pixel",
"(",
"x",
",",
"y",
",",
"color",
")",
"err",
"-=",
"d_y",
"if",
"err",
"<",
"0",
":",
"y",
"+=",
"s_y",
"err",
"+=",
"d_x",
"x",
"+=",
"s_x",
"else",
":",
"err",
"=",
"d_y",
"/",
"2.0",
"while",
"y",
"!=",
"y_1",
":",
"self",
".",
"pixel",
"(",
"x",
",",
"y",
",",
"color",
")",
"err",
"-=",
"d_x",
"if",
"err",
"<",
"0",
":",
"x",
"+=",
"s_x",
"err",
"+=",
"d_y",
"y",
"+=",
"s_y",
"self",
".",
"pixel",
"(",
"x",
",",
"y",
",",
"color",
")"
] | Bresenham's line algorithm | [
"Bresenham",
"s",
"line",
"algorithm"
] | b9f62c4b71efa963150f9c5a0284b61c7add9d02 | https://github.com/adafruit/Adafruit_CircuitPython_framebuf/blob/b9f62c4b71efa963150f9c5a0284b61c7add9d02/adafruit_framebuf.py#L249-L275 | train | 234,020 |
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 < 0:
y = 0
yend = self.height + delta_y
dt_y = 1
else:
y = self.height - 1
yend = delta_y - 1
dt_y = -1
while y != yend:
x = shift_x
while x != xend:
self.format.set_pixel(
self, x, y, self.format.get_pixel(self, x - delta_x, y - delta_y))
x += dt_x
y += dt_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 < 0:
y = 0
yend = self.height + delta_y
dt_y = 1
else:
y = self.height - 1
yend = delta_y - 1
dt_y = -1
while y != yend:
x = shift_x
while x != xend:
self.format.set_pixel(
self, x, y, self.format.get_pixel(self, x - delta_x, y - delta_y))
x += dt_x
y += dt_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",
"-",
"1",
"xend",
"=",
"delta_x",
"-",
"1",
"dt_x",
"=",
"-",
"1",
"if",
"delta_y",
"<",
"0",
":",
"y",
"=",
"0",
"yend",
"=",
"self",
".",
"height",
"+",
"delta_y",
"dt_y",
"=",
"1",
"else",
":",
"y",
"=",
"self",
".",
"height",
"-",
"1",
"yend",
"=",
"delta_y",
"-",
"1",
"dt_y",
"=",
"-",
"1",
"while",
"y",
"!=",
"yend",
":",
"x",
"=",
"shift_x",
"while",
"x",
"!=",
"xend",
":",
"self",
".",
"format",
".",
"set_pixel",
"(",
"self",
",",
"x",
",",
"y",
",",
"self",
".",
"format",
".",
"get_pixel",
"(",
"self",
",",
"x",
"-",
"delta_x",
",",
"y",
"-",
"delta_y",
")",
")",
"x",
"+=",
"dt_x",
"y",
"+=",
"dt_y"
] | 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 | 234,021 |
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(string):
self._font.draw_char(char,
x + (i * (w + 1)),
y, self, color) | 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(string):
self._font.draw_char(char,
x + (i * (w + 1)),
y, self, color) | [
"def",
"text",
"(",
"self",
",",
"string",
",",
"x",
",",
"y",
",",
"color",
",",
"*",
",",
"font_name",
"=",
"\"font5x8.bin\"",
")",
":",
"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",
"(",
"string",
")",
":",
"self",
".",
"_font",
".",
"draw_char",
"(",
"char",
",",
"x",
"+",
"(",
"i",
"*",
"(",
"w",
"+",
"1",
")",
")",
",",
"y",
",",
"self",
",",
"color",
")"
] | 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 | 234,022 |
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='Missing Authorization Header')
parts = auth_header.split()
if parts[0].lower() != self.auth_header_prefix.lower():
raise falcon.HTTPUnauthorized(
description='Invalid Authorization Header: '
'Must start with {0}'.format(self.auth_header_prefix))
elif len(parts) == 1:
raise falcon.HTTPUnauthorized(
description='Invalid Authorization Header: Token Missing')
elif len(parts) > 2:
raise falcon.HTTPUnauthorized(
description='Invalid Authorization Header: Contains extra content')
return parts[1] | 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='Missing Authorization Header')
parts = auth_header.split()
if parts[0].lower() != self.auth_header_prefix.lower():
raise falcon.HTTPUnauthorized(
description='Invalid Authorization Header: '
'Must start with {0}'.format(self.auth_header_prefix))
elif len(parts) == 1:
raise falcon.HTTPUnauthorized(
description='Invalid Authorization Header: Token Missing')
elif len(parts) > 2:
raise falcon.HTTPUnauthorized(
description='Invalid Authorization Header: Contains extra content')
return parts[1] | [
"def",
"parse_auth_token_from_request",
"(",
"self",
",",
"auth_header",
")",
":",
"if",
"not",
"auth_header",
":",
"raise",
"falcon",
".",
"HTTPUnauthorized",
"(",
"description",
"=",
"'Missing Authorization Header'",
")",
"parts",
"=",
"auth_header",
".",
"split",
"(",
")",
"if",
"parts",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"!=",
"self",
".",
"auth_header_prefix",
".",
"lower",
"(",
")",
":",
"raise",
"falcon",
".",
"HTTPUnauthorized",
"(",
"description",
"=",
"'Invalid Authorization Header: '",
"'Must start with {0}'",
".",
"format",
"(",
"self",
".",
"auth_header_prefix",
")",
")",
"elif",
"len",
"(",
"parts",
")",
"==",
"1",
":",
"raise",
"falcon",
".",
"HTTPUnauthorized",
"(",
"description",
"=",
"'Invalid Authorization Header: Token Missing'",
")",
"elif",
"len",
"(",
"parts",
")",
">",
"2",
":",
"raise",
"falcon",
".",
"HTTPUnauthorized",
"(",
"description",
"=",
"'Invalid Authorization Header: Contains extra content'",
")",
"return",
"parts",
"[",
"1",
"]"
] | 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 | 234,023 |
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._decode_jwt_token(req)
user = self.user_loader(payload)
if not user:
raise falcon.HTTPUnauthorized(
description='Invalid JWT Credentials')
return user | 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._decode_jwt_token(req)
user = self.user_loader(payload)
if not user:
raise falcon.HTTPUnauthorized(
description='Invalid JWT Credentials')
return user | [
"def",
"authenticate",
"(",
"self",
",",
"req",
",",
"resp",
",",
"resource",
")",
":",
"payload",
"=",
"self",
".",
"_decode_jwt_token",
"(",
"req",
")",
"user",
"=",
"self",
".",
"user_loader",
"(",
"payload",
")",
"if",
"not",
"user",
":",
"raise",
"falcon",
".",
"HTTPUnauthorized",
"(",
"description",
"=",
"'Invalid JWT Credentials'",
")",
"return",
"user"
] | 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",
"exception"
] | b9063163fff8044a8579a6047a85f28f3b214fdf | https://github.com/loanzen/falcon-auth/blob/b9063163fff8044a8579a6047a85f28f3b214fdf/falcon_auth/backends.py#L213-L225 | train | 234,024 |
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 = {
'user': user_payload
}
if 'iat' in self.verify_claims:
payload['iat'] = now
if 'nbf' in self.verify_claims:
payload['nbf'] = now + self.leeway
if 'exp' in self.verify_claims:
payload['exp'] = now + self.expiration_delta
if self.audience is not None:
payload['aud'] = self.audience
if self.issuer is not None:
payload['iss'] = self.issuer
return jwt.encode(
payload,
self.secret_key,
algorithm=self.algorithm,
json_encoder=ExtendedJSONEncoder).decode('utf-8') | 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 = {
'user': user_payload
}
if 'iat' in self.verify_claims:
payload['iat'] = now
if 'nbf' in self.verify_claims:
payload['nbf'] = now + self.leeway
if 'exp' in self.verify_claims:
payload['exp'] = now + self.expiration_delta
if self.audience is not None:
payload['aud'] = self.audience
if self.issuer is not None:
payload['iss'] = self.issuer
return jwt.encode(
payload,
self.secret_key,
algorithm=self.algorithm,
json_encoder=ExtendedJSONEncoder).decode('utf-8') | [
"def",
"get_auth_token",
"(",
"self",
",",
"user_payload",
")",
":",
"now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"payload",
"=",
"{",
"'user'",
":",
"user_payload",
"}",
"if",
"'iat'",
"in",
"self",
".",
"verify_claims",
":",
"payload",
"[",
"'iat'",
"]",
"=",
"now",
"if",
"'nbf'",
"in",
"self",
".",
"verify_claims",
":",
"payload",
"[",
"'nbf'",
"]",
"=",
"now",
"+",
"self",
".",
"leeway",
"if",
"'exp'",
"in",
"self",
".",
"verify_claims",
":",
"payload",
"[",
"'exp'",
"]",
"=",
"now",
"+",
"self",
".",
"expiration_delta",
"if",
"self",
".",
"audience",
"is",
"not",
"None",
":",
"payload",
"[",
"'aud'",
"]",
"=",
"self",
".",
"audience",
"if",
"self",
".",
"issuer",
"is",
"not",
"None",
":",
"payload",
"[",
"'iss'",
"]",
"=",
"self",
".",
"issuer",
"return",
"jwt",
".",
"encode",
"(",
"payload",
",",
"self",
".",
"secret_key",
",",
"algorithm",
"=",
"self",
".",
"algorithm",
",",
"json_encoder",
"=",
"ExtendedJSONEncoder",
")",
".",
"decode",
"(",
"'utf-8'",
")"
] | 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 | 234,025 |
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(
auth_header_prefix=self.auth_header_prefix, token=token) | 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(
auth_header_prefix=self.auth_header_prefix, token=token) | [
"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",
"'{auth_header_prefix} {token}'",
".",
"format",
"(",
"auth_header_prefix",
"=",
"self",
".",
"auth_header_prefix",
",",
"token",
"=",
"token",
")"
] | 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 | 234,026 |
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(
description='Missing Authorization Header')
try:
auth_header_prefix, _ = auth_header.split(' ', 1)
except ValueError:
raise falcon.HTTPUnauthorized(
description='Invalid Authorization Header: Missing Scheme or Parameters')
if auth_header_prefix.lower() != self.auth_header_prefix.lower():
raise falcon.HTTPUnauthorized(
description='Invalid Authorization Header: '
'Must start with {0}'.format(self.auth_header_prefix))
return auth_header | 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(
description='Missing Authorization Header')
try:
auth_header_prefix, _ = auth_header.split(' ', 1)
except ValueError:
raise falcon.HTTPUnauthorized(
description='Invalid Authorization Header: Missing Scheme or Parameters')
if auth_header_prefix.lower() != self.auth_header_prefix.lower():
raise falcon.HTTPUnauthorized(
description='Invalid Authorization Header: '
'Must start with {0}'.format(self.auth_header_prefix))
return auth_header | [
"def",
"parse_auth_token_from_request",
"(",
"self",
",",
"auth_header",
")",
":",
"if",
"not",
"auth_header",
":",
"raise",
"falcon",
".",
"HTTPUnauthorized",
"(",
"description",
"=",
"'Missing Authorization Header'",
")",
"try",
":",
"auth_header_prefix",
",",
"_",
"=",
"auth_header",
".",
"split",
"(",
"' '",
",",
"1",
")",
"except",
"ValueError",
":",
"raise",
"falcon",
".",
"HTTPUnauthorized",
"(",
"description",
"=",
"'Invalid Authorization Header: Missing Scheme or Parameters'",
")",
"if",
"auth_header_prefix",
".",
"lower",
"(",
")",
"!=",
"self",
".",
"auth_header_prefix",
".",
"lower",
"(",
")",
":",
"raise",
"falcon",
".",
"HTTPUnauthorized",
"(",
"description",
"=",
"'Invalid Authorization Header: '",
"'Must start with {0}'",
".",
"format",
"(",
"self",
".",
"auth_header_prefix",
")",
")",
"return",
"auth_header"
] | 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 | 234,027 |
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.setStyleSheet(stylesheet.read()) | 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.setStyleSheet(stylesheet.read()) | [
"def",
"_apply_base_theme",
"(",
"app",
")",
":",
"if",
"QT_VERSION",
"<",
"(",
"5",
",",
")",
":",
"app",
".",
"setStyle",
"(",
"'plastique'",
")",
"else",
":",
"app",
".",
"setStyle",
"(",
"'Fusion'",
")",
"with",
"open",
"(",
"_STYLESHEET",
")",
"as",
"stylesheet",
":",
"app",
".",
"setStyleSheet",
"(",
"stylesheet",
".",
"read",
"(",
")",
")"
] | 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 | 234,028 |
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(QPalette.Button, QColor(53, 53, 53))
darkPalette.setColor(QPalette.Light, QColor(180, 180, 180))
darkPalette.setColor(QPalette.Midlight, QColor(90, 90, 90))
darkPalette.setColor(QPalette.Dark, QColor(35, 35, 35))
darkPalette.setColor(QPalette.Text, QColor(180, 180, 180))
darkPalette.setColor(QPalette.BrightText, QColor(180, 180, 180))
darkPalette.setColor(QPalette.ButtonText, QColor(180, 180, 180))
darkPalette.setColor(QPalette.Base, QColor(42, 42, 42))
darkPalette.setColor(QPalette.Window, QColor(53, 53, 53))
darkPalette.setColor(QPalette.Shadow, QColor(20, 20, 20))
darkPalette.setColor(QPalette.Highlight, QColor(42, 130, 218))
darkPalette.setColor(QPalette.HighlightedText, QColor(180, 180, 180))
darkPalette.setColor(QPalette.Link, QColor(56, 252, 196))
darkPalette.setColor(QPalette.AlternateBase, QColor(66, 66, 66))
darkPalette.setColor(QPalette.ToolTipBase, QColor(53, 53, 53))
darkPalette.setColor(QPalette.ToolTipText, QColor(180, 180, 180))
# disabled
darkPalette.setColor(QPalette.Disabled, QPalette.WindowText,
QColor(127, 127, 127))
darkPalette.setColor(QPalette.Disabled, QPalette.Text,
QColor(127, 127, 127))
darkPalette.setColor(QPalette.Disabled, QPalette.ButtonText,
QColor(127, 127, 127))
darkPalette.setColor(QPalette.Disabled, QPalette.Highlight,
QColor(80, 80, 80))
darkPalette.setColor(QPalette.Disabled, QPalette.HighlightedText,
QColor(127, 127, 127))
app.setPalette(darkPalette) | 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(QPalette.Button, QColor(53, 53, 53))
darkPalette.setColor(QPalette.Light, QColor(180, 180, 180))
darkPalette.setColor(QPalette.Midlight, QColor(90, 90, 90))
darkPalette.setColor(QPalette.Dark, QColor(35, 35, 35))
darkPalette.setColor(QPalette.Text, QColor(180, 180, 180))
darkPalette.setColor(QPalette.BrightText, QColor(180, 180, 180))
darkPalette.setColor(QPalette.ButtonText, QColor(180, 180, 180))
darkPalette.setColor(QPalette.Base, QColor(42, 42, 42))
darkPalette.setColor(QPalette.Window, QColor(53, 53, 53))
darkPalette.setColor(QPalette.Shadow, QColor(20, 20, 20))
darkPalette.setColor(QPalette.Highlight, QColor(42, 130, 218))
darkPalette.setColor(QPalette.HighlightedText, QColor(180, 180, 180))
darkPalette.setColor(QPalette.Link, QColor(56, 252, 196))
darkPalette.setColor(QPalette.AlternateBase, QColor(66, 66, 66))
darkPalette.setColor(QPalette.ToolTipBase, QColor(53, 53, 53))
darkPalette.setColor(QPalette.ToolTipText, QColor(180, 180, 180))
# disabled
darkPalette.setColor(QPalette.Disabled, QPalette.WindowText,
QColor(127, 127, 127))
darkPalette.setColor(QPalette.Disabled, QPalette.Text,
QColor(127, 127, 127))
darkPalette.setColor(QPalette.Disabled, QPalette.ButtonText,
QColor(127, 127, 127))
darkPalette.setColor(QPalette.Disabled, QPalette.Highlight,
QColor(80, 80, 80))
darkPalette.setColor(QPalette.Disabled, QPalette.HighlightedText,
QColor(127, 127, 127))
app.setPalette(darkPalette) | [
"def",
"dark",
"(",
"app",
")",
":",
"_apply_base_theme",
"(",
"app",
")",
"darkPalette",
"=",
"QPalette",
"(",
")",
"# base",
"darkPalette",
".",
"setColor",
"(",
"QPalette",
".",
"WindowText",
",",
"QColor",
"(",
"180",
",",
"180",
",",
"180",
")",
")",
"darkPalette",
".",
"setColor",
"(",
"QPalette",
".",
"Button",
",",
"QColor",
"(",
"53",
",",
"53",
",",
"53",
")",
")",
"darkPalette",
".",
"setColor",
"(",
"QPalette",
".",
"Light",
",",
"QColor",
"(",
"180",
",",
"180",
",",
"180",
")",
")",
"darkPalette",
".",
"setColor",
"(",
"QPalette",
".",
"Midlight",
",",
"QColor",
"(",
"90",
",",
"90",
",",
"90",
")",
")",
"darkPalette",
".",
"setColor",
"(",
"QPalette",
".",
"Dark",
",",
"QColor",
"(",
"35",
",",
"35",
",",
"35",
")",
")",
"darkPalette",
".",
"setColor",
"(",
"QPalette",
".",
"Text",
",",
"QColor",
"(",
"180",
",",
"180",
",",
"180",
")",
")",
"darkPalette",
".",
"setColor",
"(",
"QPalette",
".",
"BrightText",
",",
"QColor",
"(",
"180",
",",
"180",
",",
"180",
")",
")",
"darkPalette",
".",
"setColor",
"(",
"QPalette",
".",
"ButtonText",
",",
"QColor",
"(",
"180",
",",
"180",
",",
"180",
")",
")",
"darkPalette",
".",
"setColor",
"(",
"QPalette",
".",
"Base",
",",
"QColor",
"(",
"42",
",",
"42",
",",
"42",
")",
")",
"darkPalette",
".",
"setColor",
"(",
"QPalette",
".",
"Window",
",",
"QColor",
"(",
"53",
",",
"53",
",",
"53",
")",
")",
"darkPalette",
".",
"setColor",
"(",
"QPalette",
".",
"Shadow",
",",
"QColor",
"(",
"20",
",",
"20",
",",
"20",
")",
")",
"darkPalette",
".",
"setColor",
"(",
"QPalette",
".",
"Highlight",
",",
"QColor",
"(",
"42",
",",
"130",
",",
"218",
")",
")",
"darkPalette",
".",
"setColor",
"(",
"QPalette",
".",
"HighlightedText",
",",
"QColor",
"(",
"180",
",",
"180",
",",
"180",
")",
")",
"darkPalette",
".",
"setColor",
"(",
"QPalette",
".",
"Link",
",",
"QColor",
"(",
"56",
",",
"252",
",",
"196",
")",
")",
"darkPalette",
".",
"setColor",
"(",
"QPalette",
".",
"AlternateBase",
",",
"QColor",
"(",
"66",
",",
"66",
",",
"66",
")",
")",
"darkPalette",
".",
"setColor",
"(",
"QPalette",
".",
"ToolTipBase",
",",
"QColor",
"(",
"53",
",",
"53",
",",
"53",
")",
")",
"darkPalette",
".",
"setColor",
"(",
"QPalette",
".",
"ToolTipText",
",",
"QColor",
"(",
"180",
",",
"180",
",",
"180",
")",
")",
"# disabled",
"darkPalette",
".",
"setColor",
"(",
"QPalette",
".",
"Disabled",
",",
"QPalette",
".",
"WindowText",
",",
"QColor",
"(",
"127",
",",
"127",
",",
"127",
")",
")",
"darkPalette",
".",
"setColor",
"(",
"QPalette",
".",
"Disabled",
",",
"QPalette",
".",
"Text",
",",
"QColor",
"(",
"127",
",",
"127",
",",
"127",
")",
")",
"darkPalette",
".",
"setColor",
"(",
"QPalette",
".",
"Disabled",
",",
"QPalette",
".",
"ButtonText",
",",
"QColor",
"(",
"127",
",",
"127",
",",
"127",
")",
")",
"darkPalette",
".",
"setColor",
"(",
"QPalette",
".",
"Disabled",
",",
"QPalette",
".",
"Highlight",
",",
"QColor",
"(",
"80",
",",
"80",
",",
"80",
")",
")",
"darkPalette",
".",
"setColor",
"(",
"QPalette",
".",
"Disabled",
",",
"QPalette",
".",
"HighlightedText",
",",
"QColor",
"(",
"127",
",",
"127",
",",
"127",
")",
")",
"app",
".",
"setPalette",
"(",
"darkPalette",
")"
] | 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 | 234,029 |
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()
class_names = arguments
# Create a graph starting with the list of classes
graph = InheritanceGraph(class_names)
# Create xref nodes for each target of the graph's image map and
# add them to the doc tree so that Sphinx can resolve the
# references to real URLs later. These nodes will eventually be
# removed from the doctree after we're done with them.
for name in graph.get_all_class_names():
refnodes, x = xfileref_role(
'class', ':class:`%s`' % name, name, 0, state)
node.extend(refnodes)
# Store the graph object so we can use it to generate the
# dot file later
node['graph'] = graph
# Store the original content for use as a hash
node['parts'] = options.get('parts', 0)
node['content'] = " ".join(class_names)
return [node] | 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()
class_names = arguments
# Create a graph starting with the list of classes
graph = InheritanceGraph(class_names)
# Create xref nodes for each target of the graph's image map and
# add them to the doc tree so that Sphinx can resolve the
# references to real URLs later. These nodes will eventually be
# removed from the doctree after we're done with them.
for name in graph.get_all_class_names():
refnodes, x = xfileref_role(
'class', ':class:`%s`' % name, name, 0, state)
node.extend(refnodes)
# Store the graph object so we can use it to generate the
# dot file later
node['graph'] = graph
# Store the original content for use as a hash
node['parts'] = options.get('parts', 0)
node['content'] = " ".join(class_names)
return [node] | [
"def",
"inheritance_diagram_directive",
"(",
"name",
",",
"arguments",
",",
"options",
",",
"content",
",",
"lineno",
",",
"content_offset",
",",
"block_text",
",",
"state",
",",
"state_machine",
")",
":",
"node",
"=",
"inheritance_diagram",
"(",
")",
"class_names",
"=",
"arguments",
"# Create a graph starting with the list of classes",
"graph",
"=",
"InheritanceGraph",
"(",
"class_names",
")",
"# Create xref nodes for each target of the graph's image map and",
"# add them to the doc tree so that Sphinx can resolve the",
"# references to real URLs later. These nodes will eventually be",
"# removed from the doctree after we're done with them.",
"for",
"name",
"in",
"graph",
".",
"get_all_class_names",
"(",
")",
":",
"refnodes",
",",
"x",
"=",
"xfileref_role",
"(",
"'class'",
",",
"':class:`%s`'",
"%",
"name",
",",
"name",
",",
"0",
",",
"state",
")",
"node",
".",
"extend",
"(",
"refnodes",
")",
"# Store the graph object so we can use it to generate the",
"# dot file later",
"node",
"[",
"'graph'",
"]",
"=",
"graph",
"# Store the original content for use as a hash",
"node",
"[",
"'parts'",
"]",
"=",
"options",
".",
"get",
"(",
"'parts'",
",",
"0",
")",
"node",
"[",
"'content'",
"]",
"=",
"\" \"",
".",
"join",
"(",
"class_names",
")",
"return",
"[",
"node",
"]"
] | 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 | 234,030 |
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 the graph
*urls* is a dictionary mapping class names to http urls
Raises DotException for any of the many os and
installation-related errors that may occur.
"""
try:
dot = subprocess.Popen(['dot'] + list(args),
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
close_fds=True)
except OSError:
raise DotException("Could not execute 'dot'. Are you sure you have 'graphviz' installed?")
except ValueError:
raise DotException("'dot' called with invalid arguments")
except:
raise DotException("Unexpected error calling 'dot'")
self.generate_dot(dot.stdin, name, parts, urls, graph_options,
node_options, edge_options)
dot.stdin.close()
result = dot.stdout.read()
returncode = dot.wait()
if returncode != 0:
raise DotException("'dot' returned the errorcode %d" % returncode)
return result | 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 the graph
*urls* is a dictionary mapping class names to http urls
Raises DotException for any of the many os and
installation-related errors that may occur.
"""
try:
dot = subprocess.Popen(['dot'] + list(args),
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
close_fds=True)
except OSError:
raise DotException("Could not execute 'dot'. Are you sure you have 'graphviz' installed?")
except ValueError:
raise DotException("'dot' called with invalid arguments")
except:
raise DotException("Unexpected error calling 'dot'")
self.generate_dot(dot.stdin, name, parts, urls, graph_options,
node_options, edge_options)
dot.stdin.close()
result = dot.stdout.read()
returncode = dot.wait()
if returncode != 0:
raise DotException("'dot' returned the errorcode %d" % returncode)
return result | [
"def",
"run_dot",
"(",
"self",
",",
"args",
",",
"name",
",",
"parts",
"=",
"0",
",",
"urls",
"=",
"{",
"}",
",",
"graph_options",
"=",
"{",
"}",
",",
"node_options",
"=",
"{",
"}",
",",
"edge_options",
"=",
"{",
"}",
")",
":",
"try",
":",
"dot",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"'dot'",
"]",
"+",
"list",
"(",
"args",
")",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"close_fds",
"=",
"True",
")",
"except",
"OSError",
":",
"raise",
"DotException",
"(",
"\"Could not execute 'dot'. Are you sure you have 'graphviz' installed?\"",
")",
"except",
"ValueError",
":",
"raise",
"DotException",
"(",
"\"'dot' called with invalid arguments\"",
")",
"except",
":",
"raise",
"DotException",
"(",
"\"Unexpected error calling 'dot'\"",
")",
"self",
".",
"generate_dot",
"(",
"dot",
".",
"stdin",
",",
"name",
",",
"parts",
",",
"urls",
",",
"graph_options",
",",
"node_options",
",",
"edge_options",
")",
"dot",
".",
"stdin",
".",
"close",
"(",
")",
"result",
"=",
"dot",
".",
"stdout",
".",
"read",
"(",
")",
"returncode",
"=",
"dot",
".",
"wait",
"(",
")",
"if",
"returncode",
"!=",
"0",
":",
"raise",
"DotException",
"(",
"\"'dot' returned the errorcode %d\"",
"%",
"returncode",
")",
"return",
"result"
] | 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
installation-related errors that may occur. | [
"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 | 234,031 |
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 environment
return read(file) | 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 environment
return read(file) | [
"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",
":",
"# m2r may not be installed in user environment",
"return",
"read",
"(",
"file",
")"
] | 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 | 234,032 |
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 | 234,033 |
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",
"(",
")",
":",
"# TODO: Use six.string_type to Py3 compat",
"try",
":",
"return",
"unicode",
"(",
"uuid1",
"(",
")",
")",
".",
"replace",
"(",
"u\"-\"",
",",
"u\"\"",
")",
"except",
"NameError",
":",
"return",
"str",
"(",
"uuid1",
"(",
")",
")",
".",
"replace",
"(",
"u\"-\"",
",",
"u\"\"",
")"
] | Generate new UUID | [
"Generate",
"new",
"UUID"
] | 993048059dc0aa789d879b69feb79a0f237a60b3 | https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L806-L812 | train | 234,034 |
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",
")",
"else",
":",
"return",
"self",
".",
"insert_one",
"(",
"docs",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Backwards compatibility with insert | [
"Backwards",
"compatibility",
"with",
"insert"
] | 993048059dc0aa789d879b69feb79a0f237a60b3 | https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L170-L175 | train | 234,035 |
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, *args, **kwargs) | 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, *args, **kwargs) | [
"def",
"update",
"(",
"self",
",",
"query",
",",
"doc",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"doc",
",",
"list",
")",
":",
"return",
"[",
"self",
".",
"update_one",
"(",
"query",
",",
"item",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"for",
"item",
"in",
"doc",
"]",
"else",
":",
"return",
"self",
".",
"update_one",
"(",
"query",
",",
"doc",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | BAckwards compatibility with update | [
"BAckwards",
"compatibility",
"with",
"update"
] | 993048059dc0aa789d879b69feb79a0f237a60b3 | https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L406-L414 | train | 234,036 |
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_table()
if u"$set" in doc:
doc = doc[u"$set"]
allcond = self.parse_query(query)
try:
result = self.table.update(doc, allcond)
except:
# TODO: check table.update result
# check what pymongo does in that case
result = None
return UpdateResult(raw_result=result) | 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_table()
if u"$set" in doc:
doc = doc[u"$set"]
allcond = self.parse_query(query)
try:
result = self.table.update(doc, allcond)
except:
# TODO: check table.update result
# check what pymongo does in that case
result = None
return UpdateResult(raw_result=result) | [
"def",
"update_one",
"(",
"self",
",",
"query",
",",
"doc",
")",
":",
"if",
"self",
".",
"table",
"is",
"None",
":",
"self",
".",
"build_table",
"(",
")",
"if",
"u\"$set\"",
"in",
"doc",
":",
"doc",
"=",
"doc",
"[",
"u\"$set\"",
"]",
"allcond",
"=",
"self",
".",
"parse_query",
"(",
"query",
")",
"try",
":",
"result",
"=",
"self",
".",
"table",
".",
"update",
"(",
"doc",
",",
"allcond",
")",
"except",
":",
"# TODO: check table.update result",
"# check what pymongo does in that case",
"result",
"=",
"None",
"return",
"UpdateResult",
"(",
"raw_result",
"=",
"result",
")"
] | 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 | 234,037 |
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.build_table()
if filter is None:
result = self.table.all()
else:
allcond = self.parse_query(filter)
try:
result = self.table.search(allcond)
except (AttributeError, TypeError):
result = []
result = TinyMongoCursor(
result,
sort=sort,
skip=skip,
limit=limit
)
return result | 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.build_table()
if filter is None:
result = self.table.all()
else:
allcond = self.parse_query(filter)
try:
result = self.table.search(allcond)
except (AttributeError, TypeError):
result = []
result = TinyMongoCursor(
result,
sort=sort,
skip=skip,
limit=limit
)
return result | [
"def",
"find",
"(",
"self",
",",
"filter",
"=",
"None",
",",
"sort",
"=",
"None",
",",
"skip",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"table",
"is",
"None",
":",
"self",
".",
"build_table",
"(",
")",
"if",
"filter",
"is",
"None",
":",
"result",
"=",
"self",
".",
"table",
".",
"all",
"(",
")",
"else",
":",
"allcond",
"=",
"self",
".",
"parse_query",
"(",
"filter",
")",
"try",
":",
"result",
"=",
"self",
".",
"table",
".",
"search",
"(",
"allcond",
")",
"except",
"(",
"AttributeError",
",",
"TypeError",
")",
":",
"result",
"=",
"[",
"]",
"result",
"=",
"TinyMongoCursor",
"(",
"result",
",",
"sort",
"=",
"sort",
",",
"skip",
"=",
"skip",
",",
"limit",
"=",
"limit",
")",
"return",
"result"
] | 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 | 234,038 |
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)
return self.table.get(allcond) | 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)
return self.table.get(allcond) | [
"def",
"find_one",
"(",
"self",
",",
"filter",
"=",
"None",
")",
":",
"if",
"self",
".",
"table",
"is",
"None",
":",
"self",
".",
"build_table",
"(",
")",
"allcond",
"=",
"self",
".",
"parse_query",
"(",
"filter",
")",
"return",
"self",
".",
"table",
".",
"get",
"(",
"allcond",
")"
] | 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 | 234,039 |
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",
"(",
"spec_or_id",
")"
] | Backwards compatibility with remove | [
"Backwards",
"compatibility",
"with",
"remove"
] | 993048059dc0aa789d879b69feb79a0f237a60b3 | https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L486-L490 | train | 234,040 |
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 DeleteResult(raw_result=result) | 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 DeleteResult(raw_result=result) | [
"def",
"delete_one",
"(",
"self",
",",
"query",
")",
":",
"item",
"=",
"self",
".",
"find_one",
"(",
"query",
")",
"result",
"=",
"self",
".",
"table",
".",
"remove",
"(",
"where",
"(",
"u'_id'",
")",
"==",
"item",
"[",
"u'_id'",
"]",
")",
"return",
"DeleteResult",
"(",
"raw_result",
"=",
"result",
")"
] | 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 | 234,041 |
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'])
for item in items
]
if query == {}:
# need to reset TinyDB's index for docs order consistency
self.table._last_id = 0
return DeleteResult(raw_result=result) | 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'])
for item in items
]
if query == {}:
# need to reset TinyDB's index for docs order consistency
self.table._last_id = 0
return DeleteResult(raw_result=result) | [
"def",
"delete_many",
"(",
"self",
",",
"query",
")",
":",
"items",
"=",
"self",
".",
"find",
"(",
"query",
")",
"result",
"=",
"[",
"self",
".",
"table",
".",
"remove",
"(",
"where",
"(",
"u'_id'",
")",
"==",
"item",
"[",
"u'_id'",
"]",
")",
"for",
"item",
"in",
"items",
"]",
"if",
"query",
"==",
"{",
"}",
":",
"# need to reset TinyDB's index for docs order consistency",
"self",
".",
"table",
".",
"_last_id",
"=",
"0",
"return",
"DeleteResult",
"(",
"raw_result",
"=",
"result",
")"
] | 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 | 234,042 |
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
limits[last] = current
last = current
# example with count == 62
# {0: 20, 20: 40, 40: 60, 60: 62}
if limit and limit < self.count():
limit = limits.get(skip, self.count())
self.cursordat = self.cursordat[skip: limit] | 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
limits[last] = current
last = current
# example with count == 62
# {0: 20, 20: 40, 40: 60, 60: 62}
if limit and limit < self.count():
limit = limits.get(skip, self.count())
self.cursordat = self.cursordat[skip: limit] | [
"def",
"paginate",
"(",
"self",
",",
"skip",
",",
"limit",
")",
":",
"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",
"limits",
"[",
"last",
"]",
"=",
"current",
"last",
"=",
"current",
"# example with count == 62",
"# {0: 20, 20: 40, 40: 60, 60: 62}",
"if",
"limit",
"and",
"limit",
"<",
"self",
".",
"count",
"(",
")",
":",
"limit",
"=",
"limits",
".",
"get",
"(",
"skip",
",",
"self",
".",
"count",
"(",
")",
")",
"self",
".",
"cursordat",
"=",
"self",
".",
"cursordat",
"[",
"skip",
":",
"limit",
"]"
] | Paginate list of records | [
"Paginate",
"list",
"of",
"records"
] | 993048059dc0aa789d879b69feb79a0f237a60b3 | https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L548-L564 | train | 234,043 |
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 urllib3.response.HTTPResponse
:returns: A boolean stating if the proxy_response should
be treated as a stream
"""
content_type = proxy_response.headers.get('Content-Type')
if is_html_content_type(content_type):
return False
try:
content_length = int(proxy_response.headers.get('Content-Length', 0))
except ValueError:
content_length = 0
if not content_length or content_length > MIN_STREAMING_LENGTH:
return True
return False | 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 urllib3.response.HTTPResponse
:returns: A boolean stating if the proxy_response should
be treated as a stream
"""
content_type = proxy_response.headers.get('Content-Type')
if is_html_content_type(content_type):
return False
try:
content_length = int(proxy_response.headers.get('Content-Length', 0))
except ValueError:
content_length = 0
if not content_length or content_length > MIN_STREAMING_LENGTH:
return True
return False | [
"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",
"=",
"int",
"(",
"proxy_response",
".",
"headers",
".",
"get",
"(",
"'Content-Length'",
",",
"0",
")",
")",
"except",
"ValueError",
":",
"content_length",
"=",
"0",
"if",
"not",
"content_length",
"or",
"content_length",
">",
"MIN_STREAMING_LENGTH",
":",
"return",
"True",
"return",
"False"
] | 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 boolean stating if the proxy_response should
be treated as a stream | [
"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",
"."
] | b8d1d9e44eadbafbd16bc03f04d15560089d4472 | https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/utils.py#L60-L83 | train | 234,044 |
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 containing the charset
"""
if not content_type:
return DEFAULT_CHARSET
matched = _get_charset_re.search(content_type)
if matched:
# Extract the charset and strip its double quotes
return matched.group('charset').replace('"', '')
return DEFAULT_CHARSET | 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 containing the charset
"""
if not content_type:
return DEFAULT_CHARSET
matched = _get_charset_re.search(content_type)
if matched:
# Extract the charset and strip its double quotes
return matched.group('charset').replace('"', '')
return DEFAULT_CHARSET | [
"def",
"get_charset",
"(",
"content_type",
")",
":",
"if",
"not",
"content_type",
":",
"return",
"DEFAULT_CHARSET",
"matched",
"=",
"_get_charset_re",
".",
"search",
"(",
"content_type",
")",
"if",
"matched",
":",
"# Extract the charset and strip its double quotes",
"return",
"matched",
".",
"group",
"(",
"'charset'",
")",
".",
"replace",
"(",
"'\"'",
",",
"''",
")",
"return",
"DEFAULT_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
: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 | 234,045 |
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('HTTP_') or header == 'CONTENT_TYPE':
return True
return False | 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('HTTP_') or header == 'CONTENT_TYPE':
return True
return False | [
"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 | 234,046 |
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.META.items():
if required_header(header):
norm_header = header.replace('HTTP_', '').title().replace('_', '-')
norm_headers[norm_header] = value
return norm_headers | 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.META.items():
if required_header(header):
norm_header = header.replace('HTTP_', '').title().replace('_', '-')
norm_headers[norm_header] = value
return norm_headers | [
"def",
"normalize_request_headers",
"(",
"request",
")",
":",
"norm_headers",
"=",
"{",
"}",
"for",
"header",
",",
"value",
"in",
"request",
".",
"META",
".",
"items",
"(",
")",
":",
"if",
"required_header",
"(",
"header",
")",
":",
"norm_header",
"=",
"header",
".",
"replace",
"(",
"'HTTP_'",
",",
"''",
")",
".",
"title",
"(",
")",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
"norm_headers",
"[",
"norm_header",
"]",
"=",
"value",
"return",
"norm_headers"
] | 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 | 234,047 |
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:
encoded.append((key.encode('utf-8'), value.encode('utf-8')))
return encoded | 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:
encoded.append((key.encode('utf-8'), value.encode('utf-8')))
return encoded | [
"def",
"encode_items",
"(",
"items",
")",
":",
"encoded",
"=",
"[",
"]",
"for",
"key",
",",
"values",
"in",
"items",
":",
"for",
"value",
"in",
"values",
":",
"encoded",
".",
"append",
"(",
"(",
"key",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"value",
".",
"encode",
"(",
"'utf-8'",
")",
")",
")",
"return",
"encoded"
] | 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 | 234,048 |
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 cookie_string: A string representing a valid cookie
:param strict_cookies: Whether to only accept RFC-compliant cookies
:returns: A dictionary containing the cookie_string attributes
"""
if strict_cookies:
cookies = SimpleCookie(COOKIE_PREFIX + cookie_string)
if not cookies.keys():
return None
cookie_name, = cookies.keys()
cookie_dict = {k: v for k, v in cookies[cookie_name].items()
if v and k != 'comment'}
cookie_dict['key'] = cookie_name
cookie_dict['value'] = cookies[cookie_name].value
return cookie_dict
else:
valid_attrs = ('path', 'domain', 'comment', 'expires',
'max_age', 'httponly', 'secure')
cookie_dict = {}
cookie_parts = cookie_string.split(';')
try:
key, value = cookie_parts[0].split('=', 1)
cookie_dict['key'], cookie_dict['value'] = key, unquote(value)
except ValueError:
logger.warning('Invalid cookie: `%s`', cookie_string)
return None
if cookie_dict['value'].startswith('='):
logger.warning('Invalid cookie: `%s`', cookie_string)
return None
for part in cookie_parts[1:]:
if '=' in part:
attr, value = part.split('=', 1)
value = value.strip()
else:
attr = part
value = ''
attr = attr.strip().lower()
if not attr:
continue
if attr in valid_attrs:
if attr in ('httponly', 'secure'):
cookie_dict[attr] = True
elif attr in 'comment':
# ignoring comment attr as explained in the
# function docstring
continue
else:
cookie_dict[attr] = unquote(value)
else:
logger.warning('Unknown cookie attribute %s', attr)
return cookie_dict | 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 cookie_string: A string representing a valid cookie
:param strict_cookies: Whether to only accept RFC-compliant cookies
:returns: A dictionary containing the cookie_string attributes
"""
if strict_cookies:
cookies = SimpleCookie(COOKIE_PREFIX + cookie_string)
if not cookies.keys():
return None
cookie_name, = cookies.keys()
cookie_dict = {k: v for k, v in cookies[cookie_name].items()
if v and k != 'comment'}
cookie_dict['key'] = cookie_name
cookie_dict['value'] = cookies[cookie_name].value
return cookie_dict
else:
valid_attrs = ('path', 'domain', 'comment', 'expires',
'max_age', 'httponly', 'secure')
cookie_dict = {}
cookie_parts = cookie_string.split(';')
try:
key, value = cookie_parts[0].split('=', 1)
cookie_dict['key'], cookie_dict['value'] = key, unquote(value)
except ValueError:
logger.warning('Invalid cookie: `%s`', cookie_string)
return None
if cookie_dict['value'].startswith('='):
logger.warning('Invalid cookie: `%s`', cookie_string)
return None
for part in cookie_parts[1:]:
if '=' in part:
attr, value = part.split('=', 1)
value = value.strip()
else:
attr = part
value = ''
attr = attr.strip().lower()
if not attr:
continue
if attr in valid_attrs:
if attr in ('httponly', 'secure'):
cookie_dict[attr] = True
elif attr in 'comment':
# ignoring comment attr as explained in the
# function docstring
continue
else:
cookie_dict[attr] = unquote(value)
else:
logger.warning('Unknown cookie attribute %s', attr)
return cookie_dict | [
"def",
"cookie_from_string",
"(",
"cookie_string",
",",
"strict_cookies",
"=",
"False",
")",
":",
"if",
"strict_cookies",
":",
"cookies",
"=",
"SimpleCookie",
"(",
"COOKIE_PREFIX",
"+",
"cookie_string",
")",
"if",
"not",
"cookies",
".",
"keys",
"(",
")",
":",
"return",
"None",
"cookie_name",
",",
"=",
"cookies",
".",
"keys",
"(",
")",
"cookie_dict",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"cookies",
"[",
"cookie_name",
"]",
".",
"items",
"(",
")",
"if",
"v",
"and",
"k",
"!=",
"'comment'",
"}",
"cookie_dict",
"[",
"'key'",
"]",
"=",
"cookie_name",
"cookie_dict",
"[",
"'value'",
"]",
"=",
"cookies",
"[",
"cookie_name",
"]",
".",
"value",
"return",
"cookie_dict",
"else",
":",
"valid_attrs",
"=",
"(",
"'path'",
",",
"'domain'",
",",
"'comment'",
",",
"'expires'",
",",
"'max_age'",
",",
"'httponly'",
",",
"'secure'",
")",
"cookie_dict",
"=",
"{",
"}",
"cookie_parts",
"=",
"cookie_string",
".",
"split",
"(",
"';'",
")",
"try",
":",
"key",
",",
"value",
"=",
"cookie_parts",
"[",
"0",
"]",
".",
"split",
"(",
"'='",
",",
"1",
")",
"cookie_dict",
"[",
"'key'",
"]",
",",
"cookie_dict",
"[",
"'value'",
"]",
"=",
"key",
",",
"unquote",
"(",
"value",
")",
"except",
"ValueError",
":",
"logger",
".",
"warning",
"(",
"'Invalid cookie: `%s`'",
",",
"cookie_string",
")",
"return",
"None",
"if",
"cookie_dict",
"[",
"'value'",
"]",
".",
"startswith",
"(",
"'='",
")",
":",
"logger",
".",
"warning",
"(",
"'Invalid cookie: `%s`'",
",",
"cookie_string",
")",
"return",
"None",
"for",
"part",
"in",
"cookie_parts",
"[",
"1",
":",
"]",
":",
"if",
"'='",
"in",
"part",
":",
"attr",
",",
"value",
"=",
"part",
".",
"split",
"(",
"'='",
",",
"1",
")",
"value",
"=",
"value",
".",
"strip",
"(",
")",
"else",
":",
"attr",
"=",
"part",
"value",
"=",
"''",
"attr",
"=",
"attr",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"if",
"not",
"attr",
":",
"continue",
"if",
"attr",
"in",
"valid_attrs",
":",
"if",
"attr",
"in",
"(",
"'httponly'",
",",
"'secure'",
")",
":",
"cookie_dict",
"[",
"attr",
"]",
"=",
"True",
"elif",
"attr",
"in",
"'comment'",
":",
"# ignoring comment attr as explained in the",
"# function docstring",
"continue",
"else",
":",
"cookie_dict",
"[",
"attr",
"]",
"=",
"unquote",
"(",
"value",
")",
"else",
":",
"logger",
".",
"warning",
"(",
"'Unknown cookie attribute %s'",
",",
"attr",
")",
"return",
"cookie_dict"
] | 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_cookies: Whether to only accept RFC-compliant cookies
:returns: A dictionary containing the cookie_string attributes | [
"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",
"."
] | b8d1d9e44eadbafbd16bc03f04d15560089d4472 | https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/utils.py#L163-L228 | train | 234,049 |
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 value[0] == '"' and value[-1] == '"':
value = value[1:-1].replace(r'\"', '"')
return value | 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 value[0] == '"' and value[-1] == '"':
value = value[1:-1].replace(r'\"', '"')
return value | [
"def",
"unquote",
"(",
"value",
")",
":",
"if",
"len",
"(",
"value",
")",
">",
"1",
"and",
"value",
"[",
"0",
"]",
"==",
"'\"'",
"and",
"value",
"[",
"-",
"1",
"]",
"==",
"'\"'",
":",
"value",
"=",
"value",
"[",
"1",
":",
"-",
"1",
"]",
".",
"replace",
"(",
"r'\\\"'",
",",
"'\"'",
")",
"return",
"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 | [
"Remove",
"wrapping",
"quotes",
"from",
"a",
"string",
"."
] | b8d1d9e44eadbafbd16bc03f04d15560089d4472 | https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/utils.py#L231-L241 | train | 234,050 |
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
"""
is_string = isinstance(value, string_types)
if is_string:
value = value.strip().lower()
if value in ('true', 'yes', 'on', 'y', 't', '1',):
return True
elif value in ('false', 'no', 'off', 'n', 'f', '0'):
return False
else:
raise ValueError("String is not true/false: %r" % value)
else:
return bool(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
"""
is_string = isinstance(value, string_types)
if is_string:
value = value.strip().lower()
if value in ('true', 'yes', 'on', 'y', 't', '1',):
return True
elif value in ('false', 'no', 'off', 'n', 'f', '0'):
return False
else:
raise ValueError("String is not true/false: %r" % value)
else:
return bool(value) | [
"def",
"asbool",
"(",
"value",
")",
":",
"is_string",
"=",
"isinstance",
"(",
"value",
",",
"string_types",
")",
"if",
"is_string",
":",
"value",
"=",
"value",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"if",
"value",
"in",
"(",
"'true'",
",",
"'yes'",
",",
"'on'",
",",
"'y'",
",",
"'t'",
",",
"'1'",
",",
")",
":",
"return",
"True",
"elif",
"value",
"in",
"(",
"'false'",
",",
"'no'",
",",
"'off'",
",",
"'n'",
",",
"'f'",
",",
"'0'",
")",
":",
"return",
"False",
"else",
":",
"raise",
"ValueError",
"(",
"\"String is not true/false: %r\"",
"%",
"value",
")",
"else",
":",
"return",
"bool",
"(",
"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 | [
"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"
] | b8d1d9e44eadbafbd16bc03f04d15560089d4472 | https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/transformer.py#L30-L50 | train | 234,051 |
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.info("DIAZO_OFF_REQUEST_HEADER in request.META: off")
return False
if asbool(self.response.get(DIAZO_OFF_RESPONSE_HEADER)):
self.log.info("DIAZO_OFF_RESPONSE_HEADER in response.get: off")
return False
if self.request.is_ajax():
self.log.info("Request is AJAX")
return False
if self.response.streaming:
self.log.info("Response has streaming")
return False
content_type = self.response.get('Content-Type')
if not is_html_content_type(content_type):
self.log.info("Content-type: false")
return False
content_encoding = self.response.get('Content-Encoding')
if content_encoding in ('zip', 'compress'):
self.log.info("Content encode is %s", content_encoding)
return False
status_code = str(self.response.status_code)
if status_code.startswith('3') or \
status_code == '204' or \
status_code == '401':
self.log.info("Status code: %s", status_code)
return False
if len(self.response.content) == 0:
self.log.info("Response Content is EMPTY")
return False
self.log.info("Transform")
return True | 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.info("DIAZO_OFF_REQUEST_HEADER in request.META: off")
return False
if asbool(self.response.get(DIAZO_OFF_RESPONSE_HEADER)):
self.log.info("DIAZO_OFF_RESPONSE_HEADER in response.get: off")
return False
if self.request.is_ajax():
self.log.info("Request is AJAX")
return False
if self.response.streaming:
self.log.info("Response has streaming")
return False
content_type = self.response.get('Content-Type')
if not is_html_content_type(content_type):
self.log.info("Content-type: false")
return False
content_encoding = self.response.get('Content-Encoding')
if content_encoding in ('zip', 'compress'):
self.log.info("Content encode is %s", content_encoding)
return False
status_code = str(self.response.status_code)
if status_code.startswith('3') or \
status_code == '204' or \
status_code == '401':
self.log.info("Status code: %s", status_code)
return False
if len(self.response.content) == 0:
self.log.info("Response Content is EMPTY")
return False
self.log.info("Transform")
return True | [
"def",
"should_transform",
"(",
"self",
")",
":",
"if",
"not",
"HAS_DIAZO",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"HAS_DIAZO: false\"",
")",
"return",
"False",
"if",
"asbool",
"(",
"self",
".",
"request",
".",
"META",
".",
"get",
"(",
"DIAZO_OFF_REQUEST_HEADER",
")",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"DIAZO_OFF_REQUEST_HEADER in request.META: off\"",
")",
"return",
"False",
"if",
"asbool",
"(",
"self",
".",
"response",
".",
"get",
"(",
"DIAZO_OFF_RESPONSE_HEADER",
")",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"DIAZO_OFF_RESPONSE_HEADER in response.get: off\"",
")",
"return",
"False",
"if",
"self",
".",
"request",
".",
"is_ajax",
"(",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Request is AJAX\"",
")",
"return",
"False",
"if",
"self",
".",
"response",
".",
"streaming",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Response has streaming\"",
")",
"return",
"False",
"content_type",
"=",
"self",
".",
"response",
".",
"get",
"(",
"'Content-Type'",
")",
"if",
"not",
"is_html_content_type",
"(",
"content_type",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Content-type: false\"",
")",
"return",
"False",
"content_encoding",
"=",
"self",
".",
"response",
".",
"get",
"(",
"'Content-Encoding'",
")",
"if",
"content_encoding",
"in",
"(",
"'zip'",
",",
"'compress'",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Content encode is %s\"",
",",
"content_encoding",
")",
"return",
"False",
"status_code",
"=",
"str",
"(",
"self",
".",
"response",
".",
"status_code",
")",
"if",
"status_code",
".",
"startswith",
"(",
"'3'",
")",
"or",
"status_code",
"==",
"'204'",
"or",
"status_code",
"==",
"'401'",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Status code: %s\"",
",",
"status_code",
")",
"return",
"False",
"if",
"len",
"(",
"self",
".",
"response",
".",
"content",
")",
"==",
"0",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Response Content is EMPTY\"",
")",
"return",
"False",
"self",
".",
"log",
".",
"info",
"(",
"\"Transform\"",
")",
"return",
"True"
] | 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 | 234,052 |
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
transformation over the original response content
:param theme_template: A file containing the template used to format
the the original response content
:param is_html5: A boolean parameter to identify a html5 doctype
:returns: A response with a content transformed based on the rules and
theme_template
"""
if not self.should_transform():
self.log.info("Don't need to be transformed")
return self.response
theme = loader.render_to_string(theme_template, context=context_data,
request=self.request)
output_xslt = compile_theme(
rules=rules,
theme=StringIO(theme),
)
transform = etree.XSLT(output_xslt)
self.log.debug("Transform: %s", transform)
charset = get_charset(self.response.get('Content-Type'))
try:
decoded_response = self.response.content.decode(charset)
except UnicodeDecodeError:
decoded_response = self.response.content.decode(charset, 'ignore')
self.log.warning("Charset is {} and type of encode used in file is\
different. Some unknown characteres might be\
ignored.".format(charset))
content_doc = etree.fromstring(decoded_response,
parser=etree.HTMLParser())
self.response.content = transform(content_doc)
if is_html5:
self.set_html5_doctype()
self.reset_headers()
self.log.debug("Response transformer: %s", self.response)
return self.response | 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
transformation over the original response content
:param theme_template: A file containing the template used to format
the the original response content
:param is_html5: A boolean parameter to identify a html5 doctype
:returns: A response with a content transformed based on the rules and
theme_template
"""
if not self.should_transform():
self.log.info("Don't need to be transformed")
return self.response
theme = loader.render_to_string(theme_template, context=context_data,
request=self.request)
output_xslt = compile_theme(
rules=rules,
theme=StringIO(theme),
)
transform = etree.XSLT(output_xslt)
self.log.debug("Transform: %s", transform)
charset = get_charset(self.response.get('Content-Type'))
try:
decoded_response = self.response.content.decode(charset)
except UnicodeDecodeError:
decoded_response = self.response.content.decode(charset, 'ignore')
self.log.warning("Charset is {} and type of encode used in file is\
different. Some unknown characteres might be\
ignored.".format(charset))
content_doc = etree.fromstring(decoded_response,
parser=etree.HTMLParser())
self.response.content = transform(content_doc)
if is_html5:
self.set_html5_doctype()
self.reset_headers()
self.log.debug("Response transformer: %s", self.response)
return self.response | [
"def",
"transform",
"(",
"self",
",",
"rules",
",",
"theme_template",
",",
"is_html5",
",",
"context_data",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"should_transform",
"(",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Don't need to be transformed\"",
")",
"return",
"self",
".",
"response",
"theme",
"=",
"loader",
".",
"render_to_string",
"(",
"theme_template",
",",
"context",
"=",
"context_data",
",",
"request",
"=",
"self",
".",
"request",
")",
"output_xslt",
"=",
"compile_theme",
"(",
"rules",
"=",
"rules",
",",
"theme",
"=",
"StringIO",
"(",
"theme",
")",
",",
")",
"transform",
"=",
"etree",
".",
"XSLT",
"(",
"output_xslt",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"Transform: %s\"",
",",
"transform",
")",
"charset",
"=",
"get_charset",
"(",
"self",
".",
"response",
".",
"get",
"(",
"'Content-Type'",
")",
")",
"try",
":",
"decoded_response",
"=",
"self",
".",
"response",
".",
"content",
".",
"decode",
"(",
"charset",
")",
"except",
"UnicodeDecodeError",
":",
"decoded_response",
"=",
"self",
".",
"response",
".",
"content",
".",
"decode",
"(",
"charset",
",",
"'ignore'",
")",
"self",
".",
"log",
".",
"warning",
"(",
"\"Charset is {} and type of encode used in file is\\\n different. Some unknown characteres might be\\\n ignored.\"",
".",
"format",
"(",
"charset",
")",
")",
"content_doc",
"=",
"etree",
".",
"fromstring",
"(",
"decoded_response",
",",
"parser",
"=",
"etree",
".",
"HTMLParser",
"(",
")",
")",
"self",
".",
"response",
".",
"content",
"=",
"transform",
"(",
"content_doc",
")",
"if",
"is_html5",
":",
"self",
".",
"set_html5_doctype",
"(",
")",
"self",
".",
"reset_headers",
"(",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"Response transformer: %s\"",
",",
"self",
".",
"response",
")",
"return",
"self",
".",
"response"
] | 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: A file containing the template used to format
the the original response content
:param is_html5: A boolean parameter to identify a html5 doctype
:returns: A response with a content transformed based on the rules and
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 | 234,053 |
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",
".",
"content",
"=",
"content"
] | 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 | 234,054 |
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",
".",
"append",
"(",
"s",
")"
] | 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 | 234,055 |
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 created,
else a django.http.HTTPResponse will be created instead
:param proxy_response: An Instance of urllib3.response.HTTPResponse that
will create an appropriate response
:param strict_cookies: Whether to only accept RFC-compliant cookies
:returns: Returns an appropriate response based on the proxy_response
content-length
"""
status = proxy_response.status
headers = proxy_response.headers
logger.debug('Proxy response headers: %s', headers)
content_type = headers.get('Content-Type')
logger.debug('Content-Type: %s', content_type)
if should_stream(proxy_response):
logger.info('Content-Length is bigger than %s', DEFAULT_AMT)
response = StreamingHttpResponse(proxy_response.stream(DEFAULT_AMT),
status=status,
content_type=content_type)
else:
content = proxy_response.data or b''
response = HttpResponse(content, status=status,
content_type=content_type)
logger.info('Normalizing response headers')
set_response_headers(response, headers)
logger.debug('Response headers: %s', getattr(response, '_headers'))
cookies = proxy_response.headers.getlist('set-cookie')
logger.info('Checking for invalid cookies')
for cookie_string in cookies:
cookie_dict = cookie_from_string(cookie_string,
strict_cookies=strict_cookies)
# if cookie is invalid cookie_dict will be None
if cookie_dict:
response.set_cookie(**cookie_dict)
logger.debug('Response cookies: %s', response.cookies)
return response | 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 created,
else a django.http.HTTPResponse will be created instead
:param proxy_response: An Instance of urllib3.response.HTTPResponse that
will create an appropriate response
:param strict_cookies: Whether to only accept RFC-compliant cookies
:returns: Returns an appropriate response based on the proxy_response
content-length
"""
status = proxy_response.status
headers = proxy_response.headers
logger.debug('Proxy response headers: %s', headers)
content_type = headers.get('Content-Type')
logger.debug('Content-Type: %s', content_type)
if should_stream(proxy_response):
logger.info('Content-Length is bigger than %s', DEFAULT_AMT)
response = StreamingHttpResponse(proxy_response.stream(DEFAULT_AMT),
status=status,
content_type=content_type)
else:
content = proxy_response.data or b''
response = HttpResponse(content, status=status,
content_type=content_type)
logger.info('Normalizing response headers')
set_response_headers(response, headers)
logger.debug('Response headers: %s', getattr(response, '_headers'))
cookies = proxy_response.headers.getlist('set-cookie')
logger.info('Checking for invalid cookies')
for cookie_string in cookies:
cookie_dict = cookie_from_string(cookie_string,
strict_cookies=strict_cookies)
# if cookie is invalid cookie_dict will be None
if cookie_dict:
response.set_cookie(**cookie_dict)
logger.debug('Response cookies: %s', response.cookies)
return response | [
"def",
"get_django_response",
"(",
"proxy_response",
",",
"strict_cookies",
"=",
"False",
")",
":",
"status",
"=",
"proxy_response",
".",
"status",
"headers",
"=",
"proxy_response",
".",
"headers",
"logger",
".",
"debug",
"(",
"'Proxy response headers: %s'",
",",
"headers",
")",
"content_type",
"=",
"headers",
".",
"get",
"(",
"'Content-Type'",
")",
"logger",
".",
"debug",
"(",
"'Content-Type: %s'",
",",
"content_type",
")",
"if",
"should_stream",
"(",
"proxy_response",
")",
":",
"logger",
".",
"info",
"(",
"'Content-Length is bigger than %s'",
",",
"DEFAULT_AMT",
")",
"response",
"=",
"StreamingHttpResponse",
"(",
"proxy_response",
".",
"stream",
"(",
"DEFAULT_AMT",
")",
",",
"status",
"=",
"status",
",",
"content_type",
"=",
"content_type",
")",
"else",
":",
"content",
"=",
"proxy_response",
".",
"data",
"or",
"b''",
"response",
"=",
"HttpResponse",
"(",
"content",
",",
"status",
"=",
"status",
",",
"content_type",
"=",
"content_type",
")",
"logger",
".",
"info",
"(",
"'Normalizing response headers'",
")",
"set_response_headers",
"(",
"response",
",",
"headers",
")",
"logger",
".",
"debug",
"(",
"'Response headers: %s'",
",",
"getattr",
"(",
"response",
",",
"'_headers'",
")",
")",
"cookies",
"=",
"proxy_response",
".",
"headers",
".",
"getlist",
"(",
"'set-cookie'",
")",
"logger",
".",
"info",
"(",
"'Checking for invalid cookies'",
")",
"for",
"cookie_string",
"in",
"cookies",
":",
"cookie_dict",
"=",
"cookie_from_string",
"(",
"cookie_string",
",",
"strict_cookies",
"=",
"strict_cookies",
")",
"# if cookie is invalid cookie_dict will be None",
"if",
"cookie_dict",
":",
"response",
".",
"set_cookie",
"(",
"*",
"*",
"cookie_dict",
")",
"logger",
".",
"debug",
"(",
"'Response cookies: %s'",
",",
"response",
".",
"cookies",
")",
"return",
"response"
] | 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
:param proxy_response: An Instance of urllib3.response.HTTPResponse that
will create an appropriate response
:param strict_cookies: Whether to only accept RFC-compliant cookies
:returns: Returns an appropriate response based on the proxy_response
content-length | [
"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"
] | b8d1d9e44eadbafbd16bc03f04d15560089d4472 | https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/response.py#L13-L61 | train | 234,056 |
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_headers = self.get_proxy_request_headers(self.request)
if (self.add_remote_user and hasattr(self.request, 'user')
and self.request.user.is_active):
request_headers['REMOTE_USER'] = self.request.user.get_username()
self.log.info("REMOTE_USER set")
return request_headers | 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_headers = self.get_proxy_request_headers(self.request)
if (self.add_remote_user and hasattr(self.request, 'user')
and self.request.user.is_active):
request_headers['REMOTE_USER'] = self.request.user.get_username()
self.log.info("REMOTE_USER set")
return request_headers | [
"def",
"get_request_headers",
"(",
"self",
")",
":",
"request_headers",
"=",
"self",
".",
"get_proxy_request_headers",
"(",
"self",
".",
"request",
")",
"if",
"(",
"self",
".",
"add_remote_user",
"and",
"hasattr",
"(",
"self",
".",
"request",
",",
"'user'",
")",
"and",
"self",
".",
"request",
".",
"user",
".",
"is_active",
")",
":",
"request_headers",
"[",
"'REMOTE_USER'",
"]",
"=",
"self",
".",
"request",
".",
"user",
".",
"get_username",
"(",
")",
"self",
".",
"log",
".",
"info",
"(",
"\"REMOTE_USER set\"",
")",
"return",
"request_headers"
] | 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 | 234,057 |
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 | 234,058 |
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:
content_length = int(response.headers['Content-Length'])
content_MB = content_length/1048576.0
print("Total file size: %.2f MB" % content_MB)
except KeyError:
pass # allow Content-Length to be missing
for chunk in response.iter_content(chunk_size=512):
if chunk: # filter out keep-alive new chunks
handle.write(chunk)
if verbose:
print(
"Download completed to %s in %s" %
(target_path, datetime.now() - start)) | 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:
content_length = int(response.headers['Content-Length'])
content_MB = content_length/1048576.0
print("Total file size: %.2f MB" % content_MB)
except KeyError:
pass # allow Content-Length to be missing
for chunk in response.iter_content(chunk_size=512):
if chunk: # filter out keep-alive new chunks
handle.write(chunk)
if verbose:
print(
"Download completed to %s in %s" %
(target_path, datetime.now() - start)) | [
"def",
"stream_download",
"(",
"url",
",",
"target_path",
",",
"verbose",
"=",
"False",
")",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"stream",
"=",
"True",
")",
"handle",
"=",
"open",
"(",
"target_path",
",",
"\"wb\"",
")",
"if",
"verbose",
":",
"print",
"(",
"\"Beginning streaming download of %s\"",
"%",
"url",
")",
"start",
"=",
"datetime",
".",
"now",
"(",
")",
"try",
":",
"content_length",
"=",
"int",
"(",
"response",
".",
"headers",
"[",
"'Content-Length'",
"]",
")",
"content_MB",
"=",
"content_length",
"/",
"1048576.0",
"print",
"(",
"\"Total file size: %.2f MB\"",
"%",
"content_MB",
")",
"except",
"KeyError",
":",
"pass",
"# allow Content-Length to be missing",
"for",
"chunk",
"in",
"response",
".",
"iter_content",
"(",
"chunk_size",
"=",
"512",
")",
":",
"if",
"chunk",
":",
"# filter out keep-alive new chunks",
"handle",
".",
"write",
"(",
"chunk",
")",
"if",
"verbose",
":",
"print",
"(",
"\"Download completed to %s in %s\"",
"%",
"(",
"target_path",
",",
"datetime",
".",
"now",
"(",
")",
"-",
"start",
")",
")"
] | 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 | 234,059 |
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",
")",
"raise",
"RuntimeError",
"(",
"OBJECT_ID_MSG",
")",
"return",
"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 | 234,060 |
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',
'description': 'IRS-assigned object id',
'db_type': 'String(18)'
},
'ein': {
'value': self.ein,
'ordering': -2,
'line_number': 'NA',
'description': 'IRS employer id number',
'db_type': 'String(9)'
}
}
if self.documentId:
standardized_table_start['documentId'] = {
'value': self.documentId,
'description': 'Document ID',
'ordering': 0
}
else:
standardized_table_start = {
'object_id': self.object_id,
'ein': self.ein
}
if self.documentId:
standardized_table_start['documentId'] = self.documentId
return standardized_table_start | 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',
'description': 'IRS-assigned object id',
'db_type': 'String(18)'
},
'ein': {
'value': self.ein,
'ordering': -2,
'line_number': 'NA',
'description': 'IRS employer id number',
'db_type': 'String(9)'
}
}
if self.documentId:
standardized_table_start['documentId'] = {
'value': self.documentId,
'description': 'Document ID',
'ordering': 0
}
else:
standardized_table_start = {
'object_id': self.object_id,
'ein': self.ein
}
if self.documentId:
standardized_table_start['documentId'] = self.documentId
return standardized_table_start | [
"def",
"_get_table_start",
"(",
"self",
")",
":",
"if",
"self",
".",
"documentation",
":",
"standardized_table_start",
"=",
"{",
"'object_id'",
":",
"{",
"'value'",
":",
"self",
".",
"object_id",
",",
"'ordering'",
":",
"-",
"1",
",",
"'line_number'",
":",
"'NA'",
",",
"'description'",
":",
"'IRS-assigned object id'",
",",
"'db_type'",
":",
"'String(18)'",
"}",
",",
"'ein'",
":",
"{",
"'value'",
":",
"self",
".",
"ein",
",",
"'ordering'",
":",
"-",
"2",
",",
"'line_number'",
":",
"'NA'",
",",
"'description'",
":",
"'IRS employer id number'",
",",
"'db_type'",
":",
"'String(9)'",
"}",
"}",
"if",
"self",
".",
"documentId",
":",
"standardized_table_start",
"[",
"'documentId'",
"]",
"=",
"{",
"'value'",
":",
"self",
".",
"documentId",
",",
"'description'",
":",
"'Document ID'",
",",
"'ordering'",
":",
"0",
"}",
"else",
":",
"standardized_table_start",
"=",
"{",
"'object_id'",
":",
"self",
".",
"object_id",
",",
"'ein'",
":",
"self",
".",
"ein",
"}",
"if",
"self",
".",
"documentId",
":",
"standardized_table_start",
"[",
"'documentId'",
"]",
"=",
"self",
".",
"documentId",
"return",
"standardized_table_start"
] | 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 | 234,061 |
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",
"(",
"' '",
")",
"result",
"=",
"result",
".",
"replace",
"(",
"'; ;'",
",",
"';'",
")",
"return",
"result"
] | 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 | 234,062 |
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:
self.schedules.append(sked)
else:
self.otherforms.append(sked) | 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:
self.schedules.append(sked)
else:
self.otherforms.append(sked) | [
"def",
"_set_schedules",
"(",
"self",
")",
":",
"self",
".",
"schedules",
"=",
"[",
"'ReturnHeader990x'",
",",
"]",
"self",
".",
"otherforms",
"=",
"[",
"]",
"for",
"sked",
"in",
"self",
".",
"raw_irs_dict",
"[",
"'Return'",
"]",
"[",
"'ReturnData'",
"]",
".",
"keys",
"(",
")",
":",
"if",
"not",
"sked",
".",
"startswith",
"(",
"\"@\"",
")",
":",
"if",
"sked",
"in",
"KNOWN_SCHEDULES",
":",
"self",
".",
"schedules",
".",
"append",
"(",
"sked",
")",
"else",
":",
"self",
".",
"otherforms",
".",
"append",
"(",
"sked",
")"
] | 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 | 234,063 |
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.result:
if sked['schedule_name']==skedname:
matching_skeds.append(sked)
return matching_skeds
else:
return [] | 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.result:
if sked['schedule_name']==skedname:
matching_skeds.append(sked)
return matching_skeds
else:
return [] | [
"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_skeds",
"=",
"[",
"]",
"for",
"sked",
"in",
"self",
".",
"result",
":",
"if",
"sked",
"[",
"'schedule_name'",
"]",
"==",
"skedname",
":",
"matching_skeds",
".",
"append",
"(",
"sked",
")",
"return",
"matching_skeds",
"else",
":",
"return",
"[",
"]"
] | 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 | 234,064 |
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 | 234,065 |
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",
")",
"]",
"return",
"headers_list"
] | 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 | 234,066 |
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.headers.get('upload-offset')
if offset is None:
msg = 'Attempt to retrieve offset fails with status {}'.format(resp.status_code)
raise TusCommunicationError(msg, resp.status_code, resp.content)
return int(offset) | 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.headers.get('upload-offset')
if offset is None:
msg = 'Attempt to retrieve offset fails with status {}'.format(resp.status_code)
raise TusCommunicationError(msg, resp.status_code, resp.content)
return int(offset) | [
"def",
"get_offset",
"(",
"self",
")",
":",
"resp",
"=",
"requests",
".",
"head",
"(",
"self",
".",
"url",
",",
"headers",
"=",
"self",
".",
"headers",
")",
"offset",
"=",
"resp",
".",
"headers",
".",
"get",
"(",
"'upload-offset'",
")",
"if",
"offset",
"is",
"None",
":",
"msg",
"=",
"'Attempt to retrieve offset fails with status {}'",
".",
"format",
"(",
"resp",
".",
"status_code",
")",
"raise",
"TusCommunicationError",
"(",
"msg",
",",
"resp",
".",
"status_code",
",",
"resp",
".",
"content",
")",
"return",
"int",
"(",
"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 | 234,067 |
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 contain unwanted characters.
if re.search(r'^$|[\s,]+', key_str):
msg = 'Upload-metadata key "{}" cannot be empty nor contain spaces or commas.'
raise ValueError(msg.format(key_str))
value_bytes = b(value) # python 3 only encodes bytes
encoded_list.append('{} {}'.format(key_str, b64encode(value_bytes).decode('ascii')))
return encoded_list | 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 contain unwanted characters.
if re.search(r'^$|[\s,]+', key_str):
msg = 'Upload-metadata key "{}" cannot be empty nor contain spaces or commas.'
raise ValueError(msg.format(key_str))
value_bytes = b(value) # python 3 only encodes bytes
encoded_list.append('{} {}'.format(key_str, b64encode(value_bytes).decode('ascii')))
return encoded_list | [
"def",
"encode_metadata",
"(",
"self",
")",
":",
"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 contain unwanted characters.",
"if",
"re",
".",
"search",
"(",
"r'^$|[\\s,]+'",
",",
"key_str",
")",
":",
"msg",
"=",
"'Upload-metadata key \"{}\" cannot be empty nor contain spaces or commas.'",
"raise",
"ValueError",
"(",
"msg",
".",
"format",
"(",
"key_str",
")",
")",
"value_bytes",
"=",
"b",
"(",
"value",
")",
"# python 3 only encodes bytes",
"encoded_list",
".",
"append",
"(",
"'{} {}'",
".",
"format",
"(",
"key_str",
",",
"b64encode",
"(",
"value_bytes",
")",
".",
"decode",
"(",
"'ascii'",
")",
")",
")",
"return",
"encoded_list"
] | 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 | 234,068 |
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.fingerprinter.get_fingerprint(self.get_file_stream())
url = self.url_storage.get_item(key)
if not url:
url = self.create_url()
self.url_storage.set_item(key, url)
return url
else:
return self.create_url() | 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.fingerprinter.get_fingerprint(self.get_file_stream())
url = self.url_storage.get_item(key)
if not url:
url = self.create_url()
self.url_storage.set_item(key, url)
return url
else:
return self.create_url() | [
"def",
"get_url",
"(",
"self",
")",
":",
"if",
"self",
".",
"store_url",
"and",
"self",
".",
"url_storage",
":",
"key",
"=",
"self",
".",
"fingerprinter",
".",
"get_fingerprint",
"(",
"self",
".",
"get_file_stream",
"(",
")",
")",
"url",
"=",
"self",
".",
"url_storage",
".",
"get_item",
"(",
"key",
")",
"if",
"not",
"url",
":",
"url",
"=",
"self",
".",
"create_url",
"(",
")",
"self",
".",
"url_storage",
".",
"set_item",
"(",
"key",
",",
"url",
")",
"return",
"url",
"else",
":",
"return",
"self",
".",
"create_url",
"(",
")"
] | 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 | 234,069 |
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())
resp = requests.post(self.client.url, headers=headers)
url = resp.headers.get("location")
if url is None:
msg = 'Attempt to retrieve create file url with status {}'.format(resp.status_code)
raise TusCommunicationError(msg, resp.status_code, resp.content)
return urljoin(self.client.url, url) | 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())
resp = requests.post(self.client.url, headers=headers)
url = resp.headers.get("location")
if url is None:
msg = 'Attempt to retrieve create file url with status {}'.format(resp.status_code)
raise TusCommunicationError(msg, resp.status_code, resp.content)
return urljoin(self.client.url, url) | [
"def",
"create_url",
"(",
"self",
")",
":",
"headers",
"=",
"self",
".",
"headers",
"headers",
"[",
"'upload-length'",
"]",
"=",
"str",
"(",
"self",
".",
"file_size",
")",
"headers",
"[",
"'upload-metadata'",
"]",
"=",
"','",
".",
"join",
"(",
"self",
".",
"encode_metadata",
"(",
")",
")",
"resp",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"client",
".",
"url",
",",
"headers",
"=",
"headers",
")",
"url",
"=",
"resp",
".",
"headers",
".",
"get",
"(",
"\"location\"",
")",
"if",
"url",
"is",
"None",
":",
"msg",
"=",
"'Attempt to retrieve create file url with status {}'",
".",
"format",
"(",
"resp",
".",
"status_code",
")",
"raise",
"TusCommunicationError",
"(",
"msg",
",",
"resp",
".",
"status_code",
",",
"resp",
".",
"content",
")",
"return",
"urljoin",
"(",
"self",
".",
"client",
".",
"url",
",",
"url",
")"
] | 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 | 234,070 |
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 | 234,071 |
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, self.request.response_content) | 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, self.request.response_content) | [
"def",
"verify_upload",
"(",
"self",
")",
":",
"if",
"self",
".",
"request",
".",
"status_code",
"==",
"204",
":",
"return",
"True",
"else",
":",
"raise",
"TusUploadFailed",
"(",
"''",
",",
"self",
".",
"request",
".",
"status_code",
",",
"self",
".",
"request",
".",
"response_content",
")"
] | 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 | 234,072 |
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:
raise ValueError("invalid file {}".format(self.file_path)) | 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:
raise ValueError("invalid file {}".format(self.file_path)) | [
"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",
"open",
"(",
"self",
".",
"file_path",
",",
"'rb'",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"invalid file {}\"",
".",
"format",
"(",
"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 | 234,073 |
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 | 234,074 |
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 the upload should stop. If not specified this
defaults to the file size.
"""
self.stop_at = stop_at or self.file_size
while self.offset < self.stop_at:
self.upload_chunk()
else:
if self.log_func:
self.log_func("maximum upload specified({} bytes) has been reached".format(self.stop_at)) | 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 the upload should stop. If not specified this
defaults to the file size.
"""
self.stop_at = stop_at or self.file_size
while self.offset < self.stop_at:
self.upload_chunk()
else:
if self.log_func:
self.log_func("maximum upload specified({} bytes) has been reached".format(self.stop_at)) | [
"def",
"upload",
"(",
"self",
",",
"stop_at",
"=",
"None",
")",
":",
"self",
".",
"stop_at",
"=",
"stop_at",
"or",
"self",
".",
"file_size",
"while",
"self",
".",
"offset",
"<",
"self",
".",
"stop_at",
":",
"self",
".",
"upload_chunk",
"(",
")",
"else",
":",
"if",
"self",
".",
"log_func",
":",
"self",
".",
"log_func",
"(",
"\"maximum upload specified({} bytes) has been reached\"",
".",
"format",
"(",
"self",
".",
"stop_at",
")",
")"
] | 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
defaults to the file size. | [
"Perform",
"file",
"upload",
"."
] | 0e5856efcfae6fc281171359ce38488a70468993 | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L274-L292 | train | 234,075 |
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_func(msg) | 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_func(msg) | [
"def",
"upload_chunk",
"(",
"self",
")",
":",
"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_func",
"(",
"msg",
")"
] | Upload chunk of file. | [
"Upload",
"chunk",
"of",
"file",
"."
] | 0e5856efcfae6fc281171359ce38488a70468993 | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L294-L303 | train | 234,076 |
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].get('url') if result else None | 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].get('url') if result else None | [
"def",
"get_item",
"(",
"self",
",",
"key",
")",
":",
"result",
"=",
"self",
".",
"_db",
".",
"search",
"(",
"self",
".",
"_urls",
".",
"key",
"==",
"key",
")",
"return",
"result",
"[",
"0",
"]",
".",
"get",
"(",
"'url'",
")",
"if",
"result",
"else",
"None"
] | 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 | 234,077 |
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 == key):
self._db.update({'url': url}, self._urls.key == key)
else:
self._db.insert({'key': key, 'url': url}) | 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 == key):
self._db.update({'url': url}, self._urls.key == key)
else:
self._db.insert({'key': key, 'url': url}) | [
"def",
"set_item",
"(",
"self",
",",
"key",
",",
"url",
")",
":",
"if",
"self",
".",
"_db",
".",
"search",
"(",
"self",
".",
"_urls",
".",
"key",
"==",
"key",
")",
":",
"self",
".",
"_db",
".",
"update",
"(",
"{",
"'url'",
":",
"url",
"}",
",",
"self",
".",
"_urls",
".",
"key",
"==",
"key",
")",
"else",
":",
"self",
".",
"_db",
".",
"insert",
"(",
"{",
"'key'",
":",
"key",
",",
"'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 | 234,078 |
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:
self._request_headers["upload-checksum"] = \
" ".join((
self._checksum_algorithm_name,
base64.b64encode(
self._checksum_algorithm(chunk).digest()
).decode("ascii"),
))
self.handle.request("PATCH", path, chunk, self._request_headers)
self._response = self.handle.getresponse()
self.status_code = self._response.status
self.response_headers = {k.lower(): v for k, v in self._response.getheaders()}
except http.client.HTTPException as e:
raise TusUploadFailed(e)
# wrap connection related errors not raised by the http.client.HTTP(S)Connection
# as TusUploadFailed exceptions to enable retries
except OSError as e:
if e.errno in (errno.EPIPE, errno.ESHUTDOWN, errno.ECONNABORTED, errno.ECONNREFUSED, errno.ECONNRESET):
raise TusUploadFailed(e)
raise e | 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:
self._request_headers["upload-checksum"] = \
" ".join((
self._checksum_algorithm_name,
base64.b64encode(
self._checksum_algorithm(chunk).digest()
).decode("ascii"),
))
self.handle.request("PATCH", path, chunk, self._request_headers)
self._response = self.handle.getresponse()
self.status_code = self._response.status
self.response_headers = {k.lower(): v for k, v in self._response.getheaders()}
except http.client.HTTPException as e:
raise TusUploadFailed(e)
# wrap connection related errors not raised by the http.client.HTTP(S)Connection
# as TusUploadFailed exceptions to enable retries
except OSError as e:
if e.errno in (errno.EPIPE, errno.ESHUTDOWN, errno.ECONNABORTED, errno.ECONNREFUSED, errno.ECONNRESET):
raise TusUploadFailed(e)
raise e | [
"def",
"perform",
"(",
"self",
")",
":",
"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",
":",
"self",
".",
"_request_headers",
"[",
"\"upload-checksum\"",
"]",
"=",
"\" \"",
".",
"join",
"(",
"(",
"self",
".",
"_checksum_algorithm_name",
",",
"base64",
".",
"b64encode",
"(",
"self",
".",
"_checksum_algorithm",
"(",
"chunk",
")",
".",
"digest",
"(",
")",
")",
".",
"decode",
"(",
"\"ascii\"",
")",
",",
")",
")",
"self",
".",
"handle",
".",
"request",
"(",
"\"PATCH\"",
",",
"path",
",",
"chunk",
",",
"self",
".",
"_request_headers",
")",
"self",
".",
"_response",
"=",
"self",
".",
"handle",
".",
"getresponse",
"(",
")",
"self",
".",
"status_code",
"=",
"self",
".",
"_response",
".",
"status",
"self",
".",
"response_headers",
"=",
"{",
"k",
".",
"lower",
"(",
")",
":",
"v",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_response",
".",
"getheaders",
"(",
")",
"}",
"except",
"http",
".",
"client",
".",
"HTTPException",
"as",
"e",
":",
"raise",
"TusUploadFailed",
"(",
"e",
")",
"# wrap connection related errors not raised by the http.client.HTTP(S)Connection",
"# as TusUploadFailed exceptions to enable retries",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"in",
"(",
"errno",
".",
"EPIPE",
",",
"errno",
".",
"ESHUTDOWN",
",",
"errno",
".",
"ECONNABORTED",
",",
"errno",
".",
"ECONNREFUSED",
",",
"errno",
".",
"ECONNRESET",
")",
":",
"raise",
"TusUploadFailed",
"(",
"e",
")",
"raise",
"e"
] | Perform actual request. | [
"Perform",
"actual",
"request",
"."
] | 0e5856efcfae6fc281171359ce38488a70468993 | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/request.py#L56-L84 | train | 234,079 |
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.md5()
# we encode the content to avoid python 3 uncicode errors
buf = self._encode_data(fs.read(self.BLOCK_SIZE))
while len(buf) > 0:
hasher.update(buf)
buf = fs.read(self.BLOCK_SIZE)
return 'md5:' + hasher.hexdigest() | 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.md5()
# we encode the content to avoid python 3 uncicode errors
buf = self._encode_data(fs.read(self.BLOCK_SIZE))
while len(buf) > 0:
hasher.update(buf)
buf = fs.read(self.BLOCK_SIZE)
return 'md5:' + hasher.hexdigest() | [
"def",
"get_fingerprint",
"(",
"self",
",",
"fs",
")",
":",
"hasher",
"=",
"hashlib",
".",
"md5",
"(",
")",
"# we encode the content to avoid python 3 uncicode errors",
"buf",
"=",
"self",
".",
"_encode_data",
"(",
"fs",
".",
"read",
"(",
"self",
".",
"BLOCK_SIZE",
")",
")",
"while",
"len",
"(",
"buf",
")",
">",
"0",
":",
"hasher",
".",
"update",
"(",
"buf",
")",
"buf",
"=",
"fs",
".",
"read",
"(",
"self",
".",
"BLOCK_SIZE",
")",
"return",
"'md5:'",
"+",
"hasher",
".",
"hexdigest",
"(",
")"
] | 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 | 234,080 |
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
return super(SSLAdapter, self).init_poolmanager(connections, maxsize, block, **pool_kwargs) | 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
return super(SSLAdapter, self).init_poolmanager(connections, maxsize, block, **pool_kwargs) | [
"def",
"init_poolmanager",
"(",
"self",
",",
"connections",
",",
"maxsize",
",",
"block",
"=",
"False",
",",
"*",
"*",
"pool_kwargs",
")",
":",
"try",
":",
"pool_kwargs",
"[",
"'ssl_version'",
"]",
"=",
"ssl",
".",
"PROTOCOL_TLS",
"except",
"AttributeError",
":",
"pool_kwargs",
"[",
"'ssl_version'",
"]",
"=",
"ssl",
".",
"PROTOCOL_SSLv23",
"return",
"super",
"(",
"SSLAdapter",
",",
"self",
")",
".",
"init_poolmanager",
"(",
"connections",
",",
"maxsize",
",",
"block",
",",
"*",
"*",
"pool_kwargs",
")"
] | 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 | 234,081 |
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(SSLAdapter, self).proxy_manager_for(proxy, **proxy_kwargs) | 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(SSLAdapter, self).proxy_manager_for(proxy, **proxy_kwargs) | [
"def",
"proxy_manager_for",
"(",
"self",
",",
"proxy",
",",
"*",
"*",
"proxy_kwargs",
")",
":",
"try",
":",
"proxy_kwargs",
"[",
"'ssl_version'",
"]",
"=",
"ssl",
".",
"PROTOCOL_TLS",
"except",
"AttributeError",
":",
"proxy_kwargs",
"[",
"'ssl_version'",
"]",
"=",
"ssl",
".",
"PROTOCOL_SSLv23",
"return",
"super",
"(",
"SSLAdapter",
",",
"self",
")",
".",
"proxy_manager_for",
"(",
"proxy",
",",
"*",
"*",
"proxy_kwargs",
")"
] | 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 | 234,082 |
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) # yield
self._cull()
self._call_times.append(self.CallRecord(time=time.time(), num_calls=num_calls))
self._outstanding_calls += num_calls | 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) # yield
self._cull()
self._call_times.append(self.CallRecord(time=time.time(), num_calls=num_calls))
self._outstanding_calls += num_calls | [
"def",
"make_calls",
"(",
"self",
",",
"num_calls",
"=",
"1",
")",
":",
"self",
".",
"_cull",
"(",
")",
"while",
"self",
".",
"_outstanding_calls",
"+",
"num_calls",
">",
"self",
".",
"_max_calls_per_second",
":",
"time",
".",
"sleep",
"(",
"0",
")",
"# yield",
"self",
".",
"_cull",
"(",
")",
"self",
".",
"_call_times",
".",
"append",
"(",
"self",
".",
"CallRecord",
"(",
"time",
"=",
"time",
".",
"time",
"(",
")",
",",
"num_calls",
"=",
"num_calls",
")",
")",
"self",
".",
"_outstanding_calls",
"+=",
"num_calls"
] | 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 | 234,083 |
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._outstanding_calls -= self._call_times[index].num_calls
else:
break
if cull_from > -1:
self._call_times = self._call_times[cull_from + 1:] | 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._outstanding_calls -= self._call_times[index].num_calls
else:
break
if cull_from > -1:
self._call_times = self._call_times[cull_from + 1:] | [
"def",
"_cull",
"(",
"self",
")",
":",
"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",
".",
"_outstanding_calls",
"-=",
"self",
".",
"_call_times",
"[",
"index",
"]",
".",
"num_calls",
"else",
":",
"break",
"if",
"cull_from",
">",
"-",
"1",
":",
"self",
".",
"_call_times",
"=",
"self",
".",
"_call_times",
"[",
"cull_from",
"+",
"1",
":",
"]"
] | 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 | 234,084 |
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 perform per session
:param args: Additional arguments to pass into a retry mapping call
"""
retries = []
response_futures = [preq.callable() for preq in requests]
for request, response_future in zip(requests, response_futures):
try:
response = response_future.result()
if response is not None and response.status_code == 403:
logging.warning('Request to {} caused a 403 response status code.'.format(request.url))
raise InvalidRequestError('Access forbidden')
if response is not None:
responses_for_requests[request] = response
except RequestException as re:
logging.error('An exception was raised for {}: {}'.format(request.url, re))
if self.total_retries > 0:
self.total_retries -= 1
retries.append(request)
# Recursively retry failed requests with the modified total retry count
if retries:
self.map_with_retries(retries, responses_for_requests) | 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 perform per session
:param args: Additional arguments to pass into a retry mapping call
"""
retries = []
response_futures = [preq.callable() for preq in requests]
for request, response_future in zip(requests, response_futures):
try:
response = response_future.result()
if response is not None and response.status_code == 403:
logging.warning('Request to {} caused a 403 response status code.'.format(request.url))
raise InvalidRequestError('Access forbidden')
if response is not None:
responses_for_requests[request] = response
except RequestException as re:
logging.error('An exception was raised for {}: {}'.format(request.url, re))
if self.total_retries > 0:
self.total_retries -= 1
retries.append(request)
# Recursively retry failed requests with the modified total retry count
if retries:
self.map_with_retries(retries, responses_for_requests) | [
"def",
"map_with_retries",
"(",
"self",
",",
"requests",
",",
"responses_for_requests",
")",
":",
"retries",
"=",
"[",
"]",
"response_futures",
"=",
"[",
"preq",
".",
"callable",
"(",
")",
"for",
"preq",
"in",
"requests",
"]",
"for",
"request",
",",
"response_future",
"in",
"zip",
"(",
"requests",
",",
"response_futures",
")",
":",
"try",
":",
"response",
"=",
"response_future",
".",
"result",
"(",
")",
"if",
"response",
"is",
"not",
"None",
"and",
"response",
".",
"status_code",
"==",
"403",
":",
"logging",
".",
"warning",
"(",
"'Request to {} caused a 403 response status code.'",
".",
"format",
"(",
"request",
".",
"url",
")",
")",
"raise",
"InvalidRequestError",
"(",
"'Access forbidden'",
")",
"if",
"response",
"is",
"not",
"None",
":",
"responses_for_requests",
"[",
"request",
"]",
"=",
"response",
"except",
"RequestException",
"as",
"re",
":",
"logging",
".",
"error",
"(",
"'An exception was raised for {}: {}'",
".",
"format",
"(",
"request",
".",
"url",
",",
"re",
")",
")",
"if",
"self",
".",
"total_retries",
">",
"0",
":",
"self",
".",
"total_retries",
"-=",
"1",
"retries",
".",
"append",
"(",
"request",
")",
"# Recursively retry failed requests with the modified total retry count",
"if",
"retries",
":",
"self",
".",
"map_with_retries",
"(",
"retries",
",",
"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 perform per session
:param args: Additional arguments to pass into a retry mapping call | [
"Provides",
"session",
"-",
"based",
"retry",
"functionality"
] | 60eef841d7cca115ec7857aeb9c553b72b694851 | https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/util/http.py#L122-L151 | train | 234,085 |
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 returned as JSON blobs
Returns:
a list of dicts if to_json is set of requests.response otherwise.
Raises:
InvalidRequestError - Can not decide how many requests to issue.
"""
return self._multi_request(
MultiRequest._VERB_GET, urls, query_params,
data=None, to_json=to_json,
) | 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 returned as JSON blobs
Returns:
a list of dicts if to_json is set of requests.response otherwise.
Raises:
InvalidRequestError - Can not decide how many requests to issue.
"""
return self._multi_request(
MultiRequest._VERB_GET, urls, query_params,
data=None, to_json=to_json,
) | [
"def",
"multi_get",
"(",
"self",
",",
"urls",
",",
"query_params",
"=",
"None",
",",
"to_json",
"=",
"True",
")",
":",
"return",
"self",
".",
"_multi_request",
"(",
"MultiRequest",
".",
"_VERB_GET",
",",
"urls",
",",
"query_params",
",",
"data",
"=",
"None",
",",
"to_json",
"=",
"to_json",
",",
")"
] | 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_json is set of requests.response otherwise.
Raises:
InvalidRequestError - Can not decide how many requests to issue. | [
"Issue",
"multiple",
"GET",
"requests",
"."
] | 60eef841d7cca115ec7857aeb9c553b72b694851 | https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/util/http.py#L203-L218 | train | 234,086 |
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 dict or string, or a list of dicts and strings representing the data body.
to_json - A boolean, should the responses be returned as JSON blobs
send_as_file - A boolean, should the data be sent as a file.
Returns:
a list of dicts if to_json is set of requests.response otherwise.
Raises:
InvalidRequestError - Can not decide how many requests to issue.
"""
return self._multi_request(
MultiRequest._VERB_POST, urls, query_params,
data, to_json=to_json, send_as_file=send_as_file,
) | 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 dict or string, or a list of dicts and strings representing the data body.
to_json - A boolean, should the responses be returned as JSON blobs
send_as_file - A boolean, should the data be sent as a file.
Returns:
a list of dicts if to_json is set of requests.response otherwise.
Raises:
InvalidRequestError - Can not decide how many requests to issue.
"""
return self._multi_request(
MultiRequest._VERB_POST, urls, query_params,
data, to_json=to_json, send_as_file=send_as_file,
) | [
"def",
"multi_post",
"(",
"self",
",",
"urls",
",",
"query_params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"to_json",
"=",
"True",
",",
"send_as_file",
"=",
"False",
")",
":",
"return",
"self",
".",
"_multi_request",
"(",
"MultiRequest",
".",
"_VERB_POST",
",",
"urls",
",",
"query_params",
",",
"data",
",",
"to_json",
"=",
"to_json",
",",
"send_as_file",
"=",
"send_as_file",
",",
")"
] | 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 boolean, should the responses be returned as JSON blobs
send_as_file - A boolean, should the data be sent as a file.
Returns:
a list of dicts if to_json is set of requests.response otherwise.
Raises:
InvalidRequestError - Can not decide how many requests to issue. | [
"Issue",
"multiple",
"POST",
"requests",
"."
] | 60eef841d7cca115ec7857aeb9c553b72b694851 | https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/util/http.py#L220-L237 | train | 234,087 |
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 list of values, the cardinality of those lists much match.
Args:
urls - 1 string URL or a list of URLs
query_params - None, 1 dict, or a list of dicts
data - None, 1 dict or string, or a list of dicts or strings
Returns:
A list of 3-tuples (url, query_param, data)
Raises:
InvalidRequestError - if cardinality of lists does not match
"""
# Everybody gets to be a list
if not isinstance(urls, list):
urls = [urls]
if not isinstance(query_params, list):
query_params = [query_params]
if not isinstance(data, list):
data = [data]
# Counts must not mismatch
url_count = len(urls)
query_param_count = len(query_params)
data_count = len(data)
max_count = max(url_count, query_param_count, data_count)
if (
max_count > url_count > 1
or max_count > query_param_count > 1
or max_count > data_count > 1
):
raise InvalidRequestError(
'Mismatched parameter count url_count:{0} query_param_count:{1} data_count:{2} max_count:{3}',
url_count, query_param_count, data_count, max_count,
)
# Pad out lists
if url_count < max_count:
urls = urls * max_count
if query_param_count < max_count:
query_params = query_params * max_count
if data_count < max_count:
data = data * max_count
return list(zip(urls, query_params, data)) | 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 list of values, the cardinality of those lists much match.
Args:
urls - 1 string URL or a list of URLs
query_params - None, 1 dict, or a list of dicts
data - None, 1 dict or string, or a list of dicts or strings
Returns:
A list of 3-tuples (url, query_param, data)
Raises:
InvalidRequestError - if cardinality of lists does not match
"""
# Everybody gets to be a list
if not isinstance(urls, list):
urls = [urls]
if not isinstance(query_params, list):
query_params = [query_params]
if not isinstance(data, list):
data = [data]
# Counts must not mismatch
url_count = len(urls)
query_param_count = len(query_params)
data_count = len(data)
max_count = max(url_count, query_param_count, data_count)
if (
max_count > url_count > 1
or max_count > query_param_count > 1
or max_count > data_count > 1
):
raise InvalidRequestError(
'Mismatched parameter count url_count:{0} query_param_count:{1} data_count:{2} max_count:{3}',
url_count, query_param_count, data_count, max_count,
)
# Pad out lists
if url_count < max_count:
urls = urls * max_count
if query_param_count < max_count:
query_params = query_params * max_count
if data_count < max_count:
data = data * max_count
return list(zip(urls, query_params, data)) | [
"def",
"_zip_request_params",
"(",
"self",
",",
"urls",
",",
"query_params",
",",
"data",
")",
":",
"# Everybody gets to be a list",
"if",
"not",
"isinstance",
"(",
"urls",
",",
"list",
")",
":",
"urls",
"=",
"[",
"urls",
"]",
"if",
"not",
"isinstance",
"(",
"query_params",
",",
"list",
")",
":",
"query_params",
"=",
"[",
"query_params",
"]",
"if",
"not",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"data",
"=",
"[",
"data",
"]",
"# Counts must not mismatch",
"url_count",
"=",
"len",
"(",
"urls",
")",
"query_param_count",
"=",
"len",
"(",
"query_params",
")",
"data_count",
"=",
"len",
"(",
"data",
")",
"max_count",
"=",
"max",
"(",
"url_count",
",",
"query_param_count",
",",
"data_count",
")",
"if",
"(",
"max_count",
">",
"url_count",
">",
"1",
"or",
"max_count",
">",
"query_param_count",
">",
"1",
"or",
"max_count",
">",
"data_count",
">",
"1",
")",
":",
"raise",
"InvalidRequestError",
"(",
"'Mismatched parameter count url_count:{0} query_param_count:{1} data_count:{2} max_count:{3}'",
",",
"url_count",
",",
"query_param_count",
",",
"data_count",
",",
"max_count",
",",
")",
"# Pad out lists",
"if",
"url_count",
"<",
"max_count",
":",
"urls",
"=",
"urls",
"*",
"max_count",
"if",
"query_param_count",
"<",
"max_count",
":",
"query_params",
"=",
"query_params",
"*",
"max_count",
"if",
"data_count",
"<",
"max_count",
":",
"data",
"=",
"data",
"*",
"max_count",
"return",
"list",
"(",
"zip",
"(",
"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 list of values, the cardinality of those lists much match.
Args:
urls - 1 string URL or a list of URLs
query_params - None, 1 dict, or a list of dicts
data - None, 1 dict or string, or a list of dicts or strings
Returns:
A list of 3-tuples (url, query_param, data)
Raises:
InvalidRequestError - if cardinality of lists does not match | [
"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 | 234,088 |
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.Response` objects
Raises:
InvalidRequestError - if any of the requests returns "403 Forbidden" response
"""
failed_requests = []
responses_for_requests = OrderedDict.fromkeys(requests)
for retry in range(self._max_retry):
try:
logging.debug('Try #{0}'.format(retry + 1))
self._availability_limiter.map_with_retries(requests, responses_for_requests)
failed_requests = []
for request, response in responses_for_requests.items():
if self._drop_404s and response is not None and response.status_code == 404:
logging.warning('Request to {0} failed with status code 404, dropping.'.format(request.url))
elif not response:
failed_requests.append((request, response))
if not failed_requests:
break
logging.warning('Try #{0}. Expected {1} successful response(s) but only got {2}.'.format(
retry + 1, len(requests), len(requests) - len(failed_requests),
))
# retry only for the failed requests
requests = [fr[0] for fr in failed_requests]
except InvalidRequestError:
raise
except Exception as e:
# log the exception for the informative purposes and pass to the next iteration
logging.exception('Try #{0}. Exception occured: {1}. Retrying.'.format(retry + 1, e))
pass
if failed_requests:
logging.warning('Still {0} failed request(s) after {1} retries:'.format(
len(failed_requests), self._max_retry,
))
for failed_request, failed_response in failed_requests:
if failed_response is not None:
# in case response text does contain some non-ascii characters
failed_response_text = failed_response.text.encode('ascii', 'xmlcharrefreplace')
logging.warning('Request to {0} failed with status code {1}. Response text: {2}'.format(
failed_request.url, failed_response.status_code, failed_response_text,
))
else:
logging.warning('Request to {0} failed with None response.'.format(failed_request.url))
return list(responses_for_requests.values()) | 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.Response` objects
Raises:
InvalidRequestError - if any of the requests returns "403 Forbidden" response
"""
failed_requests = []
responses_for_requests = OrderedDict.fromkeys(requests)
for retry in range(self._max_retry):
try:
logging.debug('Try #{0}'.format(retry + 1))
self._availability_limiter.map_with_retries(requests, responses_for_requests)
failed_requests = []
for request, response in responses_for_requests.items():
if self._drop_404s and response is not None and response.status_code == 404:
logging.warning('Request to {0} failed with status code 404, dropping.'.format(request.url))
elif not response:
failed_requests.append((request, response))
if not failed_requests:
break
logging.warning('Try #{0}. Expected {1} successful response(s) but only got {2}.'.format(
retry + 1, len(requests), len(requests) - len(failed_requests),
))
# retry only for the failed requests
requests = [fr[0] for fr in failed_requests]
except InvalidRequestError:
raise
except Exception as e:
# log the exception for the informative purposes and pass to the next iteration
logging.exception('Try #{0}. Exception occured: {1}. Retrying.'.format(retry + 1, e))
pass
if failed_requests:
logging.warning('Still {0} failed request(s) after {1} retries:'.format(
len(failed_requests), self._max_retry,
))
for failed_request, failed_response in failed_requests:
if failed_response is not None:
# in case response text does contain some non-ascii characters
failed_response_text = failed_response.text.encode('ascii', 'xmlcharrefreplace')
logging.warning('Request to {0} failed with status code {1}. Response text: {2}'.format(
failed_request.url, failed_response.status_code, failed_response_text,
))
else:
logging.warning('Request to {0} failed with None response.'.format(failed_request.url))
return list(responses_for_requests.values()) | [
"def",
"_wait_for_response",
"(",
"self",
",",
"requests",
")",
":",
"failed_requests",
"=",
"[",
"]",
"responses_for_requests",
"=",
"OrderedDict",
".",
"fromkeys",
"(",
"requests",
")",
"for",
"retry",
"in",
"range",
"(",
"self",
".",
"_max_retry",
")",
":",
"try",
":",
"logging",
".",
"debug",
"(",
"'Try #{0}'",
".",
"format",
"(",
"retry",
"+",
"1",
")",
")",
"self",
".",
"_availability_limiter",
".",
"map_with_retries",
"(",
"requests",
",",
"responses_for_requests",
")",
"failed_requests",
"=",
"[",
"]",
"for",
"request",
",",
"response",
"in",
"responses_for_requests",
".",
"items",
"(",
")",
":",
"if",
"self",
".",
"_drop_404s",
"and",
"response",
"is",
"not",
"None",
"and",
"response",
".",
"status_code",
"==",
"404",
":",
"logging",
".",
"warning",
"(",
"'Request to {0} failed with status code 404, dropping.'",
".",
"format",
"(",
"request",
".",
"url",
")",
")",
"elif",
"not",
"response",
":",
"failed_requests",
".",
"append",
"(",
"(",
"request",
",",
"response",
")",
")",
"if",
"not",
"failed_requests",
":",
"break",
"logging",
".",
"warning",
"(",
"'Try #{0}. Expected {1} successful response(s) but only got {2}.'",
".",
"format",
"(",
"retry",
"+",
"1",
",",
"len",
"(",
"requests",
")",
",",
"len",
"(",
"requests",
")",
"-",
"len",
"(",
"failed_requests",
")",
",",
")",
")",
"# retry only for the failed requests",
"requests",
"=",
"[",
"fr",
"[",
"0",
"]",
"for",
"fr",
"in",
"failed_requests",
"]",
"except",
"InvalidRequestError",
":",
"raise",
"except",
"Exception",
"as",
"e",
":",
"# log the exception for the informative purposes and pass to the next iteration",
"logging",
".",
"exception",
"(",
"'Try #{0}. Exception occured: {1}. Retrying.'",
".",
"format",
"(",
"retry",
"+",
"1",
",",
"e",
")",
")",
"pass",
"if",
"failed_requests",
":",
"logging",
".",
"warning",
"(",
"'Still {0} failed request(s) after {1} retries:'",
".",
"format",
"(",
"len",
"(",
"failed_requests",
")",
",",
"self",
".",
"_max_retry",
",",
")",
")",
"for",
"failed_request",
",",
"failed_response",
"in",
"failed_requests",
":",
"if",
"failed_response",
"is",
"not",
"None",
":",
"# in case response text does contain some non-ascii characters",
"failed_response_text",
"=",
"failed_response",
".",
"text",
".",
"encode",
"(",
"'ascii'",
",",
"'xmlcharrefreplace'",
")",
"logging",
".",
"warning",
"(",
"'Request to {0} failed with status code {1}. Response text: {2}'",
".",
"format",
"(",
"failed_request",
".",
"url",
",",
"failed_response",
".",
"status_code",
",",
"failed_response_text",
",",
")",
")",
"else",
":",
"logging",
".",
"warning",
"(",
"'Request to {0} failed with None response.'",
".",
"format",
"(",
"failed_request",
".",
"url",
")",
")",
"return",
"list",
"(",
"responses_for_requests",
".",
"values",
"(",
")",
")"
] | 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:
InvalidRequestError - if any of the requests returns "403 Forbidden" response | [
"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 | 234,089 |
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 converted to JSON. `None` otherwise.
"""
try:
return response.json()
except ValueError:
logging.warning('Expected response in JSON format from {0} but the actual response text is: {1}'.format(
response.request.url, response.text,
))
return None | 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 converted to JSON. `None` otherwise.
"""
try:
return response.json()
except ValueError:
logging.warning('Expected response in JSON format from {0} but the actual response text is: {1}'.format(
response.request.url, response.text,
))
return None | [
"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}'",
".",
"format",
"(",
"response",
".",
"request",
".",
"url",
",",
"response",
".",
"text",
",",
")",
")",
"return",
"None"
] | 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 | 234,090 |
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
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 boolean, should the responses be returned as JSON blobs
Returns:
If multiple requests are made - a list of dicts if to_json, a list of requests responses otherwise
If a single request is made, the return is not a list
Raises:
InvalidRequestError - if no URL is supplied or if any of the requests returns 403 Access Forbidden response
"""
if not urls:
raise InvalidRequestError('No URL supplied')
# Break the params into batches of request_params
request_params = self._zip_request_params(urls, query_params, data)
batch_of_params = [
request_params[pos:pos + self._max_requests]
for pos in range(0, len(request_params), self._max_requests)
]
# Iteratively issue each batch, applying the rate limiter if necessary
all_responses = []
for param_batch in batch_of_params:
if self._rate_limiter:
self._rate_limiter.make_calls(num_calls=len(param_batch))
prepared_requests = [
self._create_request(
verb, url, query_params=query_param, data=datum, send_as_file=send_as_file,
) for url, query_param, datum in param_batch
]
responses = self._wait_for_response(prepared_requests)
for response in responses:
if response:
all_responses.append(self._convert_to_json(response) if to_json else response)
else:
all_responses.append(None)
return all_responses | 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
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 boolean, should the responses be returned as JSON blobs
Returns:
If multiple requests are made - a list of dicts if to_json, a list of requests responses otherwise
If a single request is made, the return is not a list
Raises:
InvalidRequestError - if no URL is supplied or if any of the requests returns 403 Access Forbidden response
"""
if not urls:
raise InvalidRequestError('No URL supplied')
# Break the params into batches of request_params
request_params = self._zip_request_params(urls, query_params, data)
batch_of_params = [
request_params[pos:pos + self._max_requests]
for pos in range(0, len(request_params), self._max_requests)
]
# Iteratively issue each batch, applying the rate limiter if necessary
all_responses = []
for param_batch in batch_of_params:
if self._rate_limiter:
self._rate_limiter.make_calls(num_calls=len(param_batch))
prepared_requests = [
self._create_request(
verb, url, query_params=query_param, data=datum, send_as_file=send_as_file,
) for url, query_param, datum in param_batch
]
responses = self._wait_for_response(prepared_requests)
for response in responses:
if response:
all_responses.append(self._convert_to_json(response) if to_json else response)
else:
all_responses.append(None)
return all_responses | [
"def",
"_multi_request",
"(",
"self",
",",
"verb",
",",
"urls",
",",
"query_params",
",",
"data",
",",
"to_json",
"=",
"True",
",",
"send_as_file",
"=",
"False",
")",
":",
"if",
"not",
"urls",
":",
"raise",
"InvalidRequestError",
"(",
"'No URL supplied'",
")",
"# Break the params into batches of request_params",
"request_params",
"=",
"self",
".",
"_zip_request_params",
"(",
"urls",
",",
"query_params",
",",
"data",
")",
"batch_of_params",
"=",
"[",
"request_params",
"[",
"pos",
":",
"pos",
"+",
"self",
".",
"_max_requests",
"]",
"for",
"pos",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"request_params",
")",
",",
"self",
".",
"_max_requests",
")",
"]",
"# Iteratively issue each batch, applying the rate limiter if necessary",
"all_responses",
"=",
"[",
"]",
"for",
"param_batch",
"in",
"batch_of_params",
":",
"if",
"self",
".",
"_rate_limiter",
":",
"self",
".",
"_rate_limiter",
".",
"make_calls",
"(",
"num_calls",
"=",
"len",
"(",
"param_batch",
")",
")",
"prepared_requests",
"=",
"[",
"self",
".",
"_create_request",
"(",
"verb",
",",
"url",
",",
"query_params",
"=",
"query_param",
",",
"data",
"=",
"datum",
",",
"send_as_file",
"=",
"send_as_file",
",",
")",
"for",
"url",
",",
"query_param",
",",
"datum",
"in",
"param_batch",
"]",
"responses",
"=",
"self",
".",
"_wait_for_response",
"(",
"prepared_requests",
")",
"for",
"response",
"in",
"responses",
":",
"if",
"response",
":",
"all_responses",
".",
"append",
"(",
"self",
".",
"_convert_to_json",
"(",
"response",
")",
"if",
"to_json",
"else",
"response",
")",
"else",
":",
"all_responses",
".",
"append",
"(",
"None",
")",
"return",
"all_responses"
] | 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
data - None, a dict or string, or a list of dicts and strings representing the data body.
to_json - A boolean, should the responses be returned as JSON blobs
Returns:
If multiple requests are made - a list of dicts if to_json, a list of requests responses otherwise
If a single request is made, the return is not a list
Raises:
InvalidRequestError - if no URL is supplied or if any of the requests returns 403 Access Forbidden response | [
"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 | 234,091 |
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'):
write_error_message('request {0}'.format(repr(e.request)))
if hasattr(e, 'response'):
write_error_message('response {0}'.format(repr(e.response)))
raise e
return wrapper | 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'):
write_error_message('request {0}'.format(repr(e.request)))
if hasattr(e, 'response'):
write_error_message('response {0}'.format(repr(e.response)))
raise e
return wrapper | [
"def",
"error_handling",
"(",
"cls",
",",
"fn",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"result",
"=",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"result",
"except",
"InvalidRequestError",
"as",
"e",
":",
"write_exception",
"(",
"e",
")",
"if",
"hasattr",
"(",
"e",
",",
"'request'",
")",
":",
"write_error_message",
"(",
"'request {0}'",
".",
"format",
"(",
"repr",
"(",
"e",
".",
"request",
")",
")",
")",
"if",
"hasattr",
"(",
"e",
",",
"'response'",
")",
":",
"write_error_message",
"(",
"'response {0}'",
".",
"format",
"(",
"repr",
"(",
"e",
".",
"response",
")",
")",
")",
"raise",
"e",
"return",
"wrapper"
] | 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 | 234,092 |
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",
"(",
"redis",
".",
"exceptions",
".",
"ConnectionError",
",",
"redis",
".",
"exceptions",
".",
"TimeoutError",
")",
":",
"return",
"False"
] | acquire a single redis node | [
"acquire",
"a",
"single",
"redis",
"node"
] | 7f873cc362eefa7f7adee8d4913e64f87c1fd1c9 | https://github.com/glasslion/redlock/blob/7f873cc362eefa7f7adee8d4913e64f87c1fd1c9/redlock/lock.py#L135-L142 | train | 234,093 |
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.TimeoutError):
pass | 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.TimeoutError):
pass | [
"def",
"release_node",
"(",
"self",
",",
"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",
".",
"TimeoutError",
")",
":",
"pass"
] | release a single redis node | [
"release",
"a",
"single",
"redis",
"node"
] | 7f873cc362eefa7f7adee8d4913e64f87c1fd1c9 | https://github.com/glasslion/redlock/blob/7f873cc362eefa7f7adee8d4913e64f87c1fd1c9/redlock/lock.py#L144-L152 | train | 234,094 |
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_keys = {'POPULARITY': 'TEXT', 'REACH': 'RANK', 'RANK': 'DELTA'}
try:
xml_root = ET.fromstring(response._content)
for xml_child in xml_root.findall('SD//'):
if xml_child.tag in alexa_keys and \
alexa_keys[xml_child.tag] in xml_child.attrib:
attributes[xml_child.tag.lower(
)] = xml_child.attrib[alexa_keys[xml_child.tag]]
except ParseError:
# Skip ill-formatted XML and return no Alexa attributes
pass
attributes['domain'] = domain
return {'attributes': attributes} | 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_keys = {'POPULARITY': 'TEXT', 'REACH': 'RANK', 'RANK': 'DELTA'}
try:
xml_root = ET.fromstring(response._content)
for xml_child in xml_root.findall('SD//'):
if xml_child.tag in alexa_keys and \
alexa_keys[xml_child.tag] in xml_child.attrib:
attributes[xml_child.tag.lower(
)] = xml_child.attrib[alexa_keys[xml_child.tag]]
except ParseError:
# Skip ill-formatted XML and return no Alexa attributes
pass
attributes['domain'] = domain
return {'attributes': attributes} | [
"def",
"_extract_response_xml",
"(",
"self",
",",
"domain",
",",
"response",
")",
":",
"attributes",
"=",
"{",
"}",
"alexa_keys",
"=",
"{",
"'POPULARITY'",
":",
"'TEXT'",
",",
"'REACH'",
":",
"'RANK'",
",",
"'RANK'",
":",
"'DELTA'",
"}",
"try",
":",
"xml_root",
"=",
"ET",
".",
"fromstring",
"(",
"response",
".",
"_content",
")",
"for",
"xml_child",
"in",
"xml_root",
".",
"findall",
"(",
"'SD//'",
")",
":",
"if",
"xml_child",
".",
"tag",
"in",
"alexa_keys",
"and",
"alexa_keys",
"[",
"xml_child",
".",
"tag",
"]",
"in",
"xml_child",
".",
"attrib",
":",
"attributes",
"[",
"xml_child",
".",
"tag",
".",
"lower",
"(",
")",
"]",
"=",
"xml_child",
".",
"attrib",
"[",
"alexa_keys",
"[",
"xml_child",
".",
"tag",
"]",
"]",
"except",
"ParseError",
":",
"# Skip ill-formatted XML and return no Alexa attributes",
"pass",
"attributes",
"[",
"'domain'",
"]",
"=",
"domain",
"return",
"{",
"'attributes'",
":",
"attributes",
"}"
] | 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 | 234,095 |
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:
api_name: a string name of the API.
keys: an enumerable of string keys.
Returns:
A tuple: (responses found, missing keys).
"""
if self._cache:
responses = self._cache.bulk_lookup(api_name, keys)
missing_keys = [key for key in keys if key not in responses.keys()]
return (responses, missing_keys)
return ({}, keys) | 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:
api_name: a string name of the API.
keys: an enumerable of string keys.
Returns:
A tuple: (responses found, missing keys).
"""
if self._cache:
responses = self._cache.bulk_lookup(api_name, keys)
missing_keys = [key for key in keys if key not in responses.keys()]
return (responses, missing_keys)
return ({}, keys) | [
"def",
"_bulk_cache_lookup",
"(",
"self",
",",
"api_name",
",",
"keys",
")",
":",
"if",
"self",
".",
"_cache",
":",
"responses",
"=",
"self",
".",
"_cache",
".",
"bulk_lookup",
"(",
"api_name",
",",
"keys",
")",
"missing_keys",
"=",
"[",
"key",
"for",
"key",
"in",
"keys",
"if",
"key",
"not",
"in",
"responses",
".",
"keys",
"(",
")",
"]",
"return",
"(",
"responses",
",",
"missing_keys",
")",
"return",
"(",
"{",
"}",
",",
"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:
api_name: a string name of the API.
keys: an enumerable of string keys.
Returns:
A tuple: (responses found, missing 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",
"."
] | 60eef841d7cca115ec7857aeb9c553b72b694851 | https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/alexaranking.py#L97-L114 | train | 234,096 |
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 | 234,097 |
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):
# The file could not be read. This is not a problem if the file does not exist.
pass
return cache | 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):
# The file could not be read. This is not a problem if the file does not exist.
pass
return cache | [
"def",
"_read_cache_from_file",
"(",
"self",
")",
":",
"cache",
"=",
"{",
"}",
"try",
":",
"with",
"(",
"open",
"(",
"self",
".",
"_cache_file_name",
",",
"'r'",
")",
")",
"as",
"fp",
":",
"contents",
"=",
"fp",
".",
"read",
"(",
")",
"cache",
"=",
"simplejson",
".",
"loads",
"(",
"contents",
")",
"except",
"(",
"IOError",
",",
"JSONDecodeError",
")",
":",
"# The file could not be read. This is not a problem if the file does not exist.",
"pass",
"return",
"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 | 234,098 |
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:
value = self.lookup_value(api_name, key)
if value is not None:
cached_data[key] = value
return cached_data | 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:
value = self.lookup_value(api_name, key)
if value is not None:
cached_data[key] = value
return cached_data | [
"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",
":",
"cached_data",
"[",
"key",
"]",
"=",
"value",
"return",
"cached_data"
] | 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 | 234,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.