repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_code_tokens
sequencelengths 15
672k
| func_documentation_string
stringlengths 1
47.2k
| func_documentation_tokens
sequencelengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|---|---|---|
nirum/tableprint | tableprint/printer.py | top | def top(n, width=WIDTH, style=STYLE):
"""Prints the top row of a table"""
return hrule(n, width, linestyle=STYLES[style].top) | python | def top(n, width=WIDTH, style=STYLE):
"""Prints the top row of a table"""
return hrule(n, width, linestyle=STYLES[style].top) | [
"def",
"top",
"(",
"n",
",",
"width",
"=",
"WIDTH",
",",
"style",
"=",
"STYLE",
")",
":",
"return",
"hrule",
"(",
"n",
",",
"width",
",",
"linestyle",
"=",
"STYLES",
"[",
"style",
"]",
".",
"top",
")"
] | Prints the top row of a table | [
"Prints",
"the",
"top",
"row",
"of",
"a",
"table"
] | train | https://github.com/nirum/tableprint/blob/50ab4b96706fce8ee035a4d48cb456e3271eab3d/tableprint/printer.py#L245-L247 |
nirum/tableprint | tableprint/printer.py | banner | def banner(message, width=30, style='banner', out=sys.stdout):
"""Prints a banner message
Parameters
----------
message : string
The message to print in the banner
width : int
The minimum width of the banner (Default: 30)
style : string
A line formatting style (Default: 'banner')
out : writer
An object that has write() and flush() methods (Default: sys.stdout)
"""
out.write(header([message], width=max(width, len(message)), style=style) + '\n')
out.flush() | python | def banner(message, width=30, style='banner', out=sys.stdout):
"""Prints a banner message
Parameters
----------
message : string
The message to print in the banner
width : int
The minimum width of the banner (Default: 30)
style : string
A line formatting style (Default: 'banner')
out : writer
An object that has write() and flush() methods (Default: sys.stdout)
"""
out.write(header([message], width=max(width, len(message)), style=style) + '\n')
out.flush() | [
"def",
"banner",
"(",
"message",
",",
"width",
"=",
"30",
",",
"style",
"=",
"'banner'",
",",
"out",
"=",
"sys",
".",
"stdout",
")",
":",
"out",
".",
"write",
"(",
"header",
"(",
"[",
"message",
"]",
",",
"width",
"=",
"max",
"(",
"width",
",",
"len",
"(",
"message",
")",
")",
",",
"style",
"=",
"style",
")",
"+",
"'\\n'",
")",
"out",
".",
"flush",
"(",
")"
] | Prints a banner message
Parameters
----------
message : string
The message to print in the banner
width : int
The minimum width of the banner (Default: 30)
style : string
A line formatting style (Default: 'banner')
out : writer
An object that has write() and flush() methods (Default: sys.stdout) | [
"Prints",
"a",
"banner",
"message"
] | train | https://github.com/nirum/tableprint/blob/50ab4b96706fce8ee035a4d48cb456e3271eab3d/tableprint/printer.py#L255-L273 |
nirum/tableprint | tableprint/printer.py | dataframe | def dataframe(df, **kwargs):
"""Print table with data from the given pandas DataFrame
Parameters
----------
df : DataFrame
A pandas DataFrame with the table to print
"""
table(df.values, list(df.columns), **kwargs) | python | def dataframe(df, **kwargs):
"""Print table with data from the given pandas DataFrame
Parameters
----------
df : DataFrame
A pandas DataFrame with the table to print
"""
table(df.values, list(df.columns), **kwargs) | [
"def",
"dataframe",
"(",
"df",
",",
"*",
"*",
"kwargs",
")",
":",
"table",
"(",
"df",
".",
"values",
",",
"list",
"(",
"df",
".",
"columns",
")",
",",
"*",
"*",
"kwargs",
")"
] | Print table with data from the given pandas DataFrame
Parameters
----------
df : DataFrame
A pandas DataFrame with the table to print | [
"Print",
"table",
"with",
"data",
"from",
"the",
"given",
"pandas",
"DataFrame"
] | train | https://github.com/nirum/tableprint/blob/50ab4b96706fce8ee035a4d48cb456e3271eab3d/tableprint/printer.py#L276-L284 |
AnthonyBloomer/daftlistings | daftlistings/daft.py | Daft.set_address | def set_address(self, address):
"""
Set the address.
:param address:
"""
self._query_params += str(QueryParam.ADVANCED) + str(QueryParam.ADDRESS) + address.replace(" ", "+").lower() | python | def set_address(self, address):
"""
Set the address.
:param address:
"""
self._query_params += str(QueryParam.ADVANCED) + str(QueryParam.ADDRESS) + address.replace(" ", "+").lower() | [
"def",
"set_address",
"(",
"self",
",",
"address",
")",
":",
"self",
".",
"_query_params",
"+=",
"str",
"(",
"QueryParam",
".",
"ADVANCED",
")",
"+",
"str",
"(",
"QueryParam",
".",
"ADDRESS",
")",
"+",
"address",
".",
"replace",
"(",
"\" \"",
",",
"\"+\"",
")",
".",
"lower",
"(",
")"
] | Set the address.
:param address: | [
"Set",
"the",
"address",
".",
":",
"param",
"address",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/daft.py#L42-L47 |
AnthonyBloomer/daftlistings | daftlistings/daft.py | Daft.set_min_lease | def set_min_lease(self, min_lease):
"""
Set the minimum lease period in months.
:param min_lease: int
"""
self._query_params += str(QueryParam.MIN_LEASE) + str(min_lease) | python | def set_min_lease(self, min_lease):
"""
Set the minimum lease period in months.
:param min_lease: int
"""
self._query_params += str(QueryParam.MIN_LEASE) + str(min_lease) | [
"def",
"set_min_lease",
"(",
"self",
",",
"min_lease",
")",
":",
"self",
".",
"_query_params",
"+=",
"str",
"(",
"QueryParam",
".",
"MIN_LEASE",
")",
"+",
"str",
"(",
"min_lease",
")"
] | Set the minimum lease period in months.
:param min_lease: int | [
"Set",
"the",
"minimum",
"lease",
"period",
"in",
"months",
".",
":",
"param",
"min_lease",
":",
"int"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/daft.py#L49-L54 |
AnthonyBloomer/daftlistings | daftlistings/daft.py | Daft.set_added_since | def set_added_since(self, added):
"""
Set this to retrieve ads that are a given number of days old.
For example to retrieve listings that have been been added a week ago: set_added_since(7)
:param added: int
"""
self._query_params += str(QueryParam.DAYS_OLD) + str(added) | python | def set_added_since(self, added):
"""
Set this to retrieve ads that are a given number of days old.
For example to retrieve listings that have been been added a week ago: set_added_since(7)
:param added: int
"""
self._query_params += str(QueryParam.DAYS_OLD) + str(added) | [
"def",
"set_added_since",
"(",
"self",
",",
"added",
")",
":",
"self",
".",
"_query_params",
"+=",
"str",
"(",
"QueryParam",
".",
"DAYS_OLD",
")",
"+",
"str",
"(",
"added",
")"
] | Set this to retrieve ads that are a given number of days old.
For example to retrieve listings that have been been added a week ago: set_added_since(7)
:param added: int | [
"Set",
"this",
"to",
"retrieve",
"ads",
"that",
"are",
"a",
"given",
"number",
"of",
"days",
"old",
".",
"For",
"example",
"to",
"retrieve",
"listings",
"that",
"have",
"been",
"been",
"added",
"a",
"week",
"ago",
":",
"set_added_since",
"(",
"7",
")",
":",
"param",
"added",
":",
"int"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/daft.py#L56-L62 |
AnthonyBloomer/daftlistings | daftlistings/daft.py | Daft.set_max_lease | def set_max_lease(self, max_lease):
"""
Set the maximum lease period in months.
:param max_lease: int
"""
self._query_params += str(QueryParam.MAX_LEASE) + str(max_lease) | python | def set_max_lease(self, max_lease):
"""
Set the maximum lease period in months.
:param max_lease: int
"""
self._query_params += str(QueryParam.MAX_LEASE) + str(max_lease) | [
"def",
"set_max_lease",
"(",
"self",
",",
"max_lease",
")",
":",
"self",
".",
"_query_params",
"+=",
"str",
"(",
"QueryParam",
".",
"MAX_LEASE",
")",
"+",
"str",
"(",
"max_lease",
")"
] | Set the maximum lease period in months.
:param max_lease: int | [
"Set",
"the",
"maximum",
"lease",
"period",
"in",
"months",
".",
":",
"param",
"max_lease",
":",
"int"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/daft.py#L64-L69 |
AnthonyBloomer/daftlistings | daftlistings/daft.py | Daft.set_availability | def set_availability(self, availability):
"""
Set the maximum lease period in months.
:param availability:
"""
if availability >= 5:
availability = '5%2B'
self._query_params += str(QueryParam.AVALIABILITY) + str(availability) | python | def set_availability(self, availability):
"""
Set the maximum lease period in months.
:param availability:
"""
if availability >= 5:
availability = '5%2B'
self._query_params += str(QueryParam.AVALIABILITY) + str(availability) | [
"def",
"set_availability",
"(",
"self",
",",
"availability",
")",
":",
"if",
"availability",
">=",
"5",
":",
"availability",
"=",
"'5%2B'",
"self",
".",
"_query_params",
"+=",
"str",
"(",
"QueryParam",
".",
"AVALIABILITY",
")",
"+",
"str",
"(",
"availability",
")"
] | Set the maximum lease period in months.
:param availability: | [
"Set",
"the",
"maximum",
"lease",
"period",
"in",
"months",
".",
":",
"param",
"availability",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/daft.py#L71-L78 |
AnthonyBloomer/daftlistings | daftlistings/daft.py | Daft.set_room_type | def set_room_type(self, room_type):
"""
Set the room type.
:param room_type:
"""
if not isinstance(room_type, RoomType):
raise DaftException("room_type should be an instance of RoomType.")
self._query_params += str(QueryParam.ROOM_TYPE) + str(room_type) | python | def set_room_type(self, room_type):
"""
Set the room type.
:param room_type:
"""
if not isinstance(room_type, RoomType):
raise DaftException("room_type should be an instance of RoomType.")
self._query_params += str(QueryParam.ROOM_TYPE) + str(room_type) | [
"def",
"set_room_type",
"(",
"self",
",",
"room_type",
")",
":",
"if",
"not",
"isinstance",
"(",
"room_type",
",",
"RoomType",
")",
":",
"raise",
"DaftException",
"(",
"\"room_type should be an instance of RoomType.\"",
")",
"self",
".",
"_query_params",
"+=",
"str",
"(",
"QueryParam",
".",
"ROOM_TYPE",
")",
"+",
"str",
"(",
"room_type",
")"
] | Set the room type.
:param room_type: | [
"Set",
"the",
"room",
"type",
".",
":",
"param",
"room_type",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/daft.py#L106-L113 |
AnthonyBloomer/daftlistings | daftlistings/daft.py | Daft.set_keywords | def set_keywords(self, keywords):
"""
Pass an array to filter the result by keywords.
:param keywords
"""
self._query_params += str(QueryParam.KEYWORDS) + '+'.join(keywords) | python | def set_keywords(self, keywords):
"""
Pass an array to filter the result by keywords.
:param keywords
"""
self._query_params += str(QueryParam.KEYWORDS) + '+'.join(keywords) | [
"def",
"set_keywords",
"(",
"self",
",",
"keywords",
")",
":",
"self",
".",
"_query_params",
"+=",
"str",
"(",
"QueryParam",
".",
"KEYWORDS",
")",
"+",
"'+'",
".",
"join",
"(",
"keywords",
")"
] | Pass an array to filter the result by keywords.
:param keywords | [
"Pass",
"an",
"array",
"to",
"filter",
"the",
"result",
"by",
"keywords",
".",
":",
"param",
"keywords"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/daft.py#L123-L128 |
AnthonyBloomer/daftlistings | daftlistings/daft.py | Daft.set_area | def set_area(self, area):
"""
The area to retrieve listings from. Use an array to search multiple areas.
:param area:
:return:
"""
self._area = area.replace(" ", "-").lower() if isinstance(area, str) else ','.join(
map(lambda x: x.lower().replace(' ', '-'), area)) | python | def set_area(self, area):
"""
The area to retrieve listings from. Use an array to search multiple areas.
:param area:
:return:
"""
self._area = area.replace(" ", "-").lower() if isinstance(area, str) else ','.join(
map(lambda x: x.lower().replace(' ', '-'), area)) | [
"def",
"set_area",
"(",
"self",
",",
"area",
")",
":",
"self",
".",
"_area",
"=",
"area",
".",
"replace",
"(",
"\" \"",
",",
"\"-\"",
")",
".",
"lower",
"(",
")",
"if",
"isinstance",
"(",
"area",
",",
"str",
")",
"else",
"','",
".",
"join",
"(",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"' '",
",",
"'-'",
")",
",",
"area",
")",
")"
] | The area to retrieve listings from. Use an array to search multiple areas.
:param area:
:return: | [
"The",
"area",
"to",
"retrieve",
"listings",
"from",
".",
"Use",
"an",
"array",
"to",
"search",
"multiple",
"areas",
".",
":",
"param",
"area",
":",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/daft.py#L139-L146 |
AnthonyBloomer/daftlistings | daftlistings/daft.py | Daft.set_open_viewing | def set_open_viewing(self, open_viewing):
"""
Set to True to only search for properties that have upcoming 'open for viewing' dates.
:param open_viewing:
:return:
"""
if open_viewing:
self._open_viewing = open_viewing
self._query_params += str(QueryParam.OPEN_VIEWING) | python | def set_open_viewing(self, open_viewing):
"""
Set to True to only search for properties that have upcoming 'open for viewing' dates.
:param open_viewing:
:return:
"""
if open_viewing:
self._open_viewing = open_viewing
self._query_params += str(QueryParam.OPEN_VIEWING) | [
"def",
"set_open_viewing",
"(",
"self",
",",
"open_viewing",
")",
":",
"if",
"open_viewing",
":",
"self",
".",
"_open_viewing",
"=",
"open_viewing",
"self",
".",
"_query_params",
"+=",
"str",
"(",
"QueryParam",
".",
"OPEN_VIEWING",
")"
] | Set to True to only search for properties that have upcoming 'open for viewing' dates.
:param open_viewing:
:return: | [
"Set",
"to",
"True",
"to",
"only",
"search",
"for",
"properties",
"that",
"have",
"upcoming",
"open",
"for",
"viewing",
"dates",
".",
":",
"param",
"open_viewing",
":",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/daft.py#L156-L164 |
AnthonyBloomer/daftlistings | daftlistings/daft.py | Daft.set_offset | def set_offset(self, offset):
"""
The page number which is in increments of 10. The default page number is 0.
:param offset:
:return:
"""
if not isinstance(offset, int) or offset < 0:
raise DaftException("Offset should be a positive integer.")
self._offset = str(offset) | python | def set_offset(self, offset):
"""
The page number which is in increments of 10. The default page number is 0.
:param offset:
:return:
"""
if not isinstance(offset, int) or offset < 0:
raise DaftException("Offset should be a positive integer.")
self._offset = str(offset) | [
"def",
"set_offset",
"(",
"self",
",",
"offset",
")",
":",
"if",
"not",
"isinstance",
"(",
"offset",
",",
"int",
")",
"or",
"offset",
"<",
"0",
":",
"raise",
"DaftException",
"(",
"\"Offset should be a positive integer.\"",
")",
"self",
".",
"_offset",
"=",
"str",
"(",
"offset",
")"
] | The page number which is in increments of 10. The default page number is 0.
:param offset:
:return: | [
"The",
"page",
"number",
"which",
"is",
"in",
"increments",
"of",
"10",
".",
"The",
"default",
"page",
"number",
"is",
"0",
".",
":",
"param",
"offset",
":",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/daft.py#L166-L176 |
AnthonyBloomer/daftlistings | daftlistings/daft.py | Daft.set_min_price | def set_min_price(self, min_price):
"""
The minimum price.
:param min_price:
:return:
"""
if not isinstance(min_price, int):
raise DaftException("Min price should be an integer.")
self._min_price = str(min_price)
self._price += str(QueryParam.MIN_PRICE) + self._min_price | python | def set_min_price(self, min_price):
"""
The minimum price.
:param min_price:
:return:
"""
if not isinstance(min_price, int):
raise DaftException("Min price should be an integer.")
self._min_price = str(min_price)
self._price += str(QueryParam.MIN_PRICE) + self._min_price | [
"def",
"set_min_price",
"(",
"self",
",",
"min_price",
")",
":",
"if",
"not",
"isinstance",
"(",
"min_price",
",",
"int",
")",
":",
"raise",
"DaftException",
"(",
"\"Min price should be an integer.\"",
")",
"self",
".",
"_min_price",
"=",
"str",
"(",
"min_price",
")",
"self",
".",
"_price",
"+=",
"str",
"(",
"QueryParam",
".",
"MIN_PRICE",
")",
"+",
"self",
".",
"_min_price"
] | The minimum price.
:param min_price:
:return: | [
"The",
"minimum",
"price",
".",
":",
"param",
"min_price",
":",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/daft.py#L178-L189 |
AnthonyBloomer/daftlistings | daftlistings/daft.py | Daft.set_max_price | def set_max_price(self, max_price):
"""
The maximum price.
:param max_price:
:return:
"""
if not isinstance(max_price, int):
raise DaftException("Max price should be an integer.")
self._max_price = str(max_price)
self._price += str(QueryParam.MAX_PRICE) + self._max_price | python | def set_max_price(self, max_price):
"""
The maximum price.
:param max_price:
:return:
"""
if not isinstance(max_price, int):
raise DaftException("Max price should be an integer.")
self._max_price = str(max_price)
self._price += str(QueryParam.MAX_PRICE) + self._max_price | [
"def",
"set_max_price",
"(",
"self",
",",
"max_price",
")",
":",
"if",
"not",
"isinstance",
"(",
"max_price",
",",
"int",
")",
":",
"raise",
"DaftException",
"(",
"\"Max price should be an integer.\"",
")",
"self",
".",
"_max_price",
"=",
"str",
"(",
"max_price",
")",
"self",
".",
"_price",
"+=",
"str",
"(",
"QueryParam",
".",
"MAX_PRICE",
")",
"+",
"self",
".",
"_max_price"
] | The maximum price.
:param max_price:
:return: | [
"The",
"maximum",
"price",
".",
":",
"param",
"max_price",
":",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/daft.py#L191-L202 |
AnthonyBloomer/daftlistings | daftlistings/daft.py | Daft.set_listing_type | def set_listing_type(self, listing_type):
"""
The listings you'd like to scrape i.e houses, properties, auction, commercial or apartments.
Use the SaleType or RentType enum to select the listing type.
i.e set_listing_type(SaleType.PROPERTIES)
:param listing_type:
:return:
"""
if not isinstance(listing_type, SaleType) and not isinstance(listing_type, RentType):
raise DaftException("listing_type should be an instance of SaleType or RentType.")
self._listing_type = listing_type | python | def set_listing_type(self, listing_type):
"""
The listings you'd like to scrape i.e houses, properties, auction, commercial or apartments.
Use the SaleType or RentType enum to select the listing type.
i.e set_listing_type(SaleType.PROPERTIES)
:param listing_type:
:return:
"""
if not isinstance(listing_type, SaleType) and not isinstance(listing_type, RentType):
raise DaftException("listing_type should be an instance of SaleType or RentType.")
self._listing_type = listing_type | [
"def",
"set_listing_type",
"(",
"self",
",",
"listing_type",
")",
":",
"if",
"not",
"isinstance",
"(",
"listing_type",
",",
"SaleType",
")",
"and",
"not",
"isinstance",
"(",
"listing_type",
",",
"RentType",
")",
":",
"raise",
"DaftException",
"(",
"\"listing_type should be an instance of SaleType or RentType.\"",
")",
"self",
".",
"_listing_type",
"=",
"listing_type"
] | The listings you'd like to scrape i.e houses, properties, auction, commercial or apartments.
Use the SaleType or RentType enum to select the listing type.
i.e set_listing_type(SaleType.PROPERTIES)
:param listing_type:
:return: | [
"The",
"listings",
"you",
"d",
"like",
"to",
"scrape",
"i",
".",
"e",
"houses",
"properties",
"auction",
"commercial",
"or",
"apartments",
".",
"Use",
"the",
"SaleType",
"or",
"RentType",
"enum",
"to",
"select",
"the",
"listing",
"type",
".",
"i",
".",
"e",
"set_listing_type",
"(",
"SaleType",
".",
"PROPERTIES",
")",
":",
"param",
"listing_type",
":",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/daft.py#L204-L216 |
AnthonyBloomer/daftlistings | daftlistings/daft.py | Daft.set_min_beds | def set_min_beds(self, min_beds):
"""
The minimum number of beds.
:param min_beds:
:return:
"""
if not isinstance(min_beds, int):
raise DaftException("Minimum number of beds should be an integer.")
self._min_beds = str(min_beds)
self._query_params += str(QueryParam.MIN_BEDS) + self._min_beds | python | def set_min_beds(self, min_beds):
"""
The minimum number of beds.
:param min_beds:
:return:
"""
if not isinstance(min_beds, int):
raise DaftException("Minimum number of beds should be an integer.")
self._min_beds = str(min_beds)
self._query_params += str(QueryParam.MIN_BEDS) + self._min_beds | [
"def",
"set_min_beds",
"(",
"self",
",",
"min_beds",
")",
":",
"if",
"not",
"isinstance",
"(",
"min_beds",
",",
"int",
")",
":",
"raise",
"DaftException",
"(",
"\"Minimum number of beds should be an integer.\"",
")",
"self",
".",
"_min_beds",
"=",
"str",
"(",
"min_beds",
")",
"self",
".",
"_query_params",
"+=",
"str",
"(",
"QueryParam",
".",
"MIN_BEDS",
")",
"+",
"self",
".",
"_min_beds"
] | The minimum number of beds.
:param min_beds:
:return: | [
"The",
"minimum",
"number",
"of",
"beds",
".",
":",
"param",
"min_beds",
":",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/daft.py#L226-L237 |
AnthonyBloomer/daftlistings | daftlistings/daft.py | Daft.set_max_beds | def set_max_beds(self, max_beds):
"""
The maximum number of beds.
:param max_beds:
:return:
"""
if not isinstance(max_beds, int):
raise DaftException("Maximum number of beds should be an integer.")
self._max_beds = str(max_beds)
self._query_params += str(QueryParam.MAX_BEDS) + self._max_beds | python | def set_max_beds(self, max_beds):
"""
The maximum number of beds.
:param max_beds:
:return:
"""
if not isinstance(max_beds, int):
raise DaftException("Maximum number of beds should be an integer.")
self._max_beds = str(max_beds)
self._query_params += str(QueryParam.MAX_BEDS) + self._max_beds | [
"def",
"set_max_beds",
"(",
"self",
",",
"max_beds",
")",
":",
"if",
"not",
"isinstance",
"(",
"max_beds",
",",
"int",
")",
":",
"raise",
"DaftException",
"(",
"\"Maximum number of beds should be an integer.\"",
")",
"self",
".",
"_max_beds",
"=",
"str",
"(",
"max_beds",
")",
"self",
".",
"_query_params",
"+=",
"str",
"(",
"QueryParam",
".",
"MAX_BEDS",
")",
"+",
"self",
".",
"_max_beds"
] | The maximum number of beds.
:param max_beds:
:return: | [
"The",
"maximum",
"number",
"of",
"beds",
".",
":",
"param",
"max_beds",
":",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/daft.py#L239-L249 |
AnthonyBloomer/daftlistings | daftlistings/daft.py | Daft.set_sort_by | def set_sort_by(self, sort_by):
"""
Use this method to sort by price, distance, upcoming viewing or date using the SortType object.
:param sort_by:
:return:
"""
if not isinstance(sort_by, SortType):
raise DaftException("sort_by should be an instance of SortType.")
self._sort_by = str(sort_by) | python | def set_sort_by(self, sort_by):
"""
Use this method to sort by price, distance, upcoming viewing or date using the SortType object.
:param sort_by:
:return:
"""
if not isinstance(sort_by, SortType):
raise DaftException("sort_by should be an instance of SortType.")
self._sort_by = str(sort_by) | [
"def",
"set_sort_by",
"(",
"self",
",",
"sort_by",
")",
":",
"if",
"not",
"isinstance",
"(",
"sort_by",
",",
"SortType",
")",
":",
"raise",
"DaftException",
"(",
"\"sort_by should be an instance of SortType.\"",
")",
"self",
".",
"_sort_by",
"=",
"str",
"(",
"sort_by",
")"
] | Use this method to sort by price, distance, upcoming viewing or date using the SortType object.
:param sort_by:
:return: | [
"Use",
"this",
"method",
"to",
"sort",
"by",
"price",
"distance",
"upcoming",
"viewing",
"or",
"date",
"using",
"the",
"SortType",
"object",
".",
":",
"param",
"sort_by",
":",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/daft.py#L251-L260 |
AnthonyBloomer/daftlistings | daftlistings/daft.py | Daft.set_sort_order | def set_sort_order(self, sort_order):
"""
Use the SortOrder object to sort the listings descending or ascending.
:param sort_order:
:return:
"""
if not isinstance(sort_order, SortOrder):
raise DaftException("sort_order should be an instance of SortOrder.")
self._sort_order = str(sort_order) | python | def set_sort_order(self, sort_order):
"""
Use the SortOrder object to sort the listings descending or ascending.
:param sort_order:
:return:
"""
if not isinstance(sort_order, SortOrder):
raise DaftException("sort_order should be an instance of SortOrder.")
self._sort_order = str(sort_order) | [
"def",
"set_sort_order",
"(",
"self",
",",
"sort_order",
")",
":",
"if",
"not",
"isinstance",
"(",
"sort_order",
",",
"SortOrder",
")",
":",
"raise",
"DaftException",
"(",
"\"sort_order should be an instance of SortOrder.\"",
")",
"self",
".",
"_sort_order",
"=",
"str",
"(",
"sort_order",
")"
] | Use the SortOrder object to sort the listings descending or ascending.
:param sort_order:
:return: | [
"Use",
"the",
"SortOrder",
"object",
"to",
"sort",
"the",
"listings",
"descending",
"or",
"ascending",
".",
":",
"param",
"sort_order",
":",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/daft.py#L262-L272 |
AnthonyBloomer/daftlistings | daftlistings/daft.py | Daft.set_commercial_property_type | def set_commercial_property_type(self, commercial_property_type):
"""
Use the CommercialType object to set the commercial property type.
:param commercial_property_type:
:return:
"""
if not isinstance(commercial_property_type, CommercialType):
raise DaftException("commercial_property_type should be an instance of CommercialType.")
self._commercial_property_type = str(commercial_property_type) | python | def set_commercial_property_type(self, commercial_property_type):
"""
Use the CommercialType object to set the commercial property type.
:param commercial_property_type:
:return:
"""
if not isinstance(commercial_property_type, CommercialType):
raise DaftException("commercial_property_type should be an instance of CommercialType.")
self._commercial_property_type = str(commercial_property_type) | [
"def",
"set_commercial_property_type",
"(",
"self",
",",
"commercial_property_type",
")",
":",
"if",
"not",
"isinstance",
"(",
"commercial_property_type",
",",
"CommercialType",
")",
":",
"raise",
"DaftException",
"(",
"\"commercial_property_type should be an instance of CommercialType.\"",
")",
"self",
".",
"_commercial_property_type",
"=",
"str",
"(",
"commercial_property_type",
")"
] | Use the CommercialType object to set the commercial property type.
:param commercial_property_type:
:return: | [
"Use",
"the",
"CommercialType",
"object",
"to",
"set",
"the",
"commercial",
"property",
"type",
".",
":",
"param",
"commercial_property_type",
":",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/daft.py#L274-L284 |
AnthonyBloomer/daftlistings | daftlistings/daft.py | Daft.set_commercial_min_size | def set_commercial_min_size(self, commercial_min_size):
"""
The minimum size in sq ft.
:param commercial_min_size:
:return:
"""
if not isinstance(commercial_min_size, int):
raise DaftException("commercial_min_size should be an integer.")
self._commercial_min_size = str(commercial_min_size)
self._query_params += str(QueryParam.COMMERCIAL_MIN) + self._commercial_min_size | python | def set_commercial_min_size(self, commercial_min_size):
"""
The minimum size in sq ft.
:param commercial_min_size:
:return:
"""
if not isinstance(commercial_min_size, int):
raise DaftException("commercial_min_size should be an integer.")
self._commercial_min_size = str(commercial_min_size)
self._query_params += str(QueryParam.COMMERCIAL_MIN) + self._commercial_min_size | [
"def",
"set_commercial_min_size",
"(",
"self",
",",
"commercial_min_size",
")",
":",
"if",
"not",
"isinstance",
"(",
"commercial_min_size",
",",
"int",
")",
":",
"raise",
"DaftException",
"(",
"\"commercial_min_size should be an integer.\"",
")",
"self",
".",
"_commercial_min_size",
"=",
"str",
"(",
"commercial_min_size",
")",
"self",
".",
"_query_params",
"+=",
"str",
"(",
"QueryParam",
".",
"COMMERCIAL_MIN",
")",
"+",
"self",
".",
"_commercial_min_size"
] | The minimum size in sq ft.
:param commercial_min_size:
:return: | [
"The",
"minimum",
"size",
"in",
"sq",
"ft",
".",
":",
"param",
"commercial_min_size",
":",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/daft.py#L286-L296 |
AnthonyBloomer/daftlistings | daftlistings/daft.py | Daft.set_commercial_max_size | def set_commercial_max_size(self, commercial_max_size):
"""
The maximum size in sq ft.
:param commercial_max_size:
:return:
"""
if not isinstance(commercial_max_size, int):
raise DaftException("commercial_max_size should be an integer.")
self._commercial_max_size = str(commercial_max_size)
self._query_params += str(QueryParam.COMMERCIAL_MAX) + self._commercial_max_size | python | def set_commercial_max_size(self, commercial_max_size):
"""
The maximum size in sq ft.
:param commercial_max_size:
:return:
"""
if not isinstance(commercial_max_size, int):
raise DaftException("commercial_max_size should be an integer.")
self._commercial_max_size = str(commercial_max_size)
self._query_params += str(QueryParam.COMMERCIAL_MAX) + self._commercial_max_size | [
"def",
"set_commercial_max_size",
"(",
"self",
",",
"commercial_max_size",
")",
":",
"if",
"not",
"isinstance",
"(",
"commercial_max_size",
",",
"int",
")",
":",
"raise",
"DaftException",
"(",
"\"commercial_max_size should be an integer.\"",
")",
"self",
".",
"_commercial_max_size",
"=",
"str",
"(",
"commercial_max_size",
")",
"self",
".",
"_query_params",
"+=",
"str",
"(",
"QueryParam",
".",
"COMMERCIAL_MAX",
")",
"+",
"self",
".",
"_commercial_max_size"
] | The maximum size in sq ft.
:param commercial_max_size:
:return: | [
"The",
"maximum",
"size",
"in",
"sq",
"ft",
".",
":",
"param",
"commercial_max_size",
":",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/daft.py#L298-L308 |
AnthonyBloomer/daftlistings | daftlistings/daft.py | Daft.set_student_accommodation_type | def set_student_accommodation_type(self, student_accommodation_type):
"""
Set the student accomodation type.
:param student_accommodation_type: StudentAccomodationType
"""
if not isinstance(student_accommodation_type, StudentAccommodationType):
raise DaftException("student_accommodation_type should be an instance of StudentAccommodationType.")
self._student_accommodation_type = str(student_accommodation_type) | python | def set_student_accommodation_type(self, student_accommodation_type):
"""
Set the student accomodation type.
:param student_accommodation_type: StudentAccomodationType
"""
if not isinstance(student_accommodation_type, StudentAccommodationType):
raise DaftException("student_accommodation_type should be an instance of StudentAccommodationType.")
self._student_accommodation_type = str(student_accommodation_type) | [
"def",
"set_student_accommodation_type",
"(",
"self",
",",
"student_accommodation_type",
")",
":",
"if",
"not",
"isinstance",
"(",
"student_accommodation_type",
",",
"StudentAccommodationType",
")",
":",
"raise",
"DaftException",
"(",
"\"student_accommodation_type should be an instance of StudentAccommodationType.\"",
")",
"self",
".",
"_student_accommodation_type",
"=",
"str",
"(",
"student_accommodation_type",
")"
] | Set the student accomodation type.
:param student_accommodation_type: StudentAccomodationType | [
"Set",
"the",
"student",
"accomodation",
"type",
".",
":",
"param",
"student_accommodation_type",
":",
"StudentAccomodationType"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/daft.py#L318-L326 |
AnthonyBloomer/daftlistings | daftlistings/daft.py | Daft.set_num_occupants | def set_num_occupants(self, num_occupants):
"""
Set the max number of occupants living in the property for rent.
:param num_occupants: int
"""
self._query_params += str(QueryParam.NUM_OCCUPANTS) + str(num_occupants) | python | def set_num_occupants(self, num_occupants):
"""
Set the max number of occupants living in the property for rent.
:param num_occupants: int
"""
self._query_params += str(QueryParam.NUM_OCCUPANTS) + str(num_occupants) | [
"def",
"set_num_occupants",
"(",
"self",
",",
"num_occupants",
")",
":",
"self",
".",
"_query_params",
"+=",
"str",
"(",
"QueryParam",
".",
"NUM_OCCUPANTS",
")",
"+",
"str",
"(",
"num_occupants",
")"
] | Set the max number of occupants living in the property for rent.
:param num_occupants: int | [
"Set",
"the",
"max",
"number",
"of",
"occupants",
"living",
"in",
"the",
"property",
"for",
"rent",
".",
":",
"param",
"num_occupants",
":",
"int"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/daft.py#L328-L333 |
AnthonyBloomer/daftlistings | daftlistings/daft.py | Daft.set_public_transport_route | def set_public_transport_route(self, public_transport_route):
"""
Set the public transport route.
:param public_transport_route: TransportRoute
"""
self._query_params += str(QueryParam.ROUTE_ID) + str(public_transport_route) | python | def set_public_transport_route(self, public_transport_route):
"""
Set the public transport route.
:param public_transport_route: TransportRoute
"""
self._query_params += str(QueryParam.ROUTE_ID) + str(public_transport_route) | [
"def",
"set_public_transport_route",
"(",
"self",
",",
"public_transport_route",
")",
":",
"self",
".",
"_query_params",
"+=",
"str",
"(",
"QueryParam",
".",
"ROUTE_ID",
")",
"+",
"str",
"(",
"public_transport_route",
")"
] | Set the public transport route.
:param public_transport_route: TransportRoute | [
"Set",
"the",
"public",
"transport",
"route",
".",
":",
"param",
"public_transport_route",
":",
"TransportRoute"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/daft.py#L342-L347 |
AnthonyBloomer/daftlistings | daftlistings/daft.py | Daft.set_property_type | def set_property_type(self, property_types):
"""
Set the property type for rents.
:param property_types: Array of Enum PropertyType
"""
query_add = ''
for property_type in property_types:
if not isinstance(property_type, PropertyType):
raise DaftException("property_types should be an instance of PropertyType.")
query_add += str(property_type)
self._query_params += query_add | python | def set_property_type(self, property_types):
"""
Set the property type for rents.
:param property_types: Array of Enum PropertyType
"""
query_add = ''
for property_type in property_types:
if not isinstance(property_type, PropertyType):
raise DaftException("property_types should be an instance of PropertyType.")
query_add += str(property_type)
self._query_params += query_add | [
"def",
"set_property_type",
"(",
"self",
",",
"property_types",
")",
":",
"query_add",
"=",
"''",
"for",
"property_type",
"in",
"property_types",
":",
"if",
"not",
"isinstance",
"(",
"property_type",
",",
"PropertyType",
")",
":",
"raise",
"DaftException",
"(",
"\"property_types should be an instance of PropertyType.\"",
")",
"query_add",
"+=",
"str",
"(",
"property_type",
")",
"self",
".",
"_query_params",
"+=",
"query_add"
] | Set the property type for rents.
:param property_types: Array of Enum PropertyType | [
"Set",
"the",
"property",
"type",
"for",
"rents",
".",
":",
"param",
"property_types",
":",
"Array",
"of",
"Enum",
"PropertyType"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/daft.py#L357-L368 |
AnthonyBloomer/daftlistings | daftlistings/daft.py | Daft.search | def search(self):
"""
The search function returns an array of Listing objects.
:return: Listing object
"""
self.set_url()
listings = []
request = Request(debug=self._debug)
url = self.get_url()
soup = request.get(url)
divs = soup.find_all("div", {"class": "box"})
[listings.append(Listing(div, debug=self._debug)) for div in divs]
return listings | python | def search(self):
"""
The search function returns an array of Listing objects.
:return: Listing object
"""
self.set_url()
listings = []
request = Request(debug=self._debug)
url = self.get_url()
soup = request.get(url)
divs = soup.find_all("div", {"class": "box"})
[listings.append(Listing(div, debug=self._debug)) for div in divs]
return listings | [
"def",
"search",
"(",
"self",
")",
":",
"self",
".",
"set_url",
"(",
")",
"listings",
"=",
"[",
"]",
"request",
"=",
"Request",
"(",
"debug",
"=",
"self",
".",
"_debug",
")",
"url",
"=",
"self",
".",
"get_url",
"(",
")",
"soup",
"=",
"request",
".",
"get",
"(",
"url",
")",
"divs",
"=",
"soup",
".",
"find_all",
"(",
"\"div\"",
",",
"{",
"\"class\"",
":",
"\"box\"",
"}",
")",
"[",
"listings",
".",
"append",
"(",
"Listing",
"(",
"div",
",",
"debug",
"=",
"self",
".",
"_debug",
")",
")",
"for",
"div",
"in",
"divs",
"]",
"return",
"listings"
] | The search function returns an array of Listing objects.
:return: Listing object | [
"The",
"search",
"function",
"returns",
"an",
"array",
"of",
"Listing",
"objects",
".",
":",
"return",
":",
"Listing",
"object"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/daft.py#L424-L436 |
AnthonyBloomer/daftlistings | daftlistings/listing.py | Listing.price_change | def price_change(self):
"""
This method returns any price change.
:return:
"""
try:
if self._data_from_search:
return self._data_from_search.find('div', {'class': 'price-changes-sr'}).text
else:
return self._ad_page_content.find('div', {'class': 'price-changes-sr'}).text
except Exception as e:
if self._debug:
logging.error(
"Error getting price_change. Error message: " + e.args[0])
return | python | def price_change(self):
"""
This method returns any price change.
:return:
"""
try:
if self._data_from_search:
return self._data_from_search.find('div', {'class': 'price-changes-sr'}).text
else:
return self._ad_page_content.find('div', {'class': 'price-changes-sr'}).text
except Exception as e:
if self._debug:
logging.error(
"Error getting price_change. Error message: " + e.args[0])
return | [
"def",
"price_change",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"_data_from_search",
":",
"return",
"self",
".",
"_data_from_search",
".",
"find",
"(",
"'div'",
",",
"{",
"'class'",
":",
"'price-changes-sr'",
"}",
")",
".",
"text",
"else",
":",
"return",
"self",
".",
"_ad_page_content",
".",
"find",
"(",
"'div'",
",",
"{",
"'class'",
":",
"'price-changes-sr'",
"}",
")",
".",
"text",
"except",
"Exception",
"as",
"e",
":",
"if",
"self",
".",
"_debug",
":",
"logging",
".",
"error",
"(",
"\"Error getting price_change. Error message: \"",
"+",
"e",
".",
"args",
"[",
"0",
"]",
")",
"return"
] | This method returns any price change.
:return: | [
"This",
"method",
"returns",
"any",
"price",
"change",
".",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L104-L118 |
AnthonyBloomer/daftlistings | daftlistings/listing.py | Listing.upcoming_viewings | def upcoming_viewings(self):
"""
Returns an array of upcoming viewings for a property.
:return:
"""
upcoming_viewings = []
try:
if self._data_from_search:
viewings = self._data_from_search.find_all(
'div', {'class': 'smi-onview-text'})
else:
viewings = []
except Exception as e:
if self._debug:
logging.error(
"Error getting upcoming_viewings. Error message: " + e.args[0])
return
for viewing in viewings:
upcoming_viewings.append(viewing.text.strip())
return upcoming_viewings | python | def upcoming_viewings(self):
"""
Returns an array of upcoming viewings for a property.
:return:
"""
upcoming_viewings = []
try:
if self._data_from_search:
viewings = self._data_from_search.find_all(
'div', {'class': 'smi-onview-text'})
else:
viewings = []
except Exception as e:
if self._debug:
logging.error(
"Error getting upcoming_viewings. Error message: " + e.args[0])
return
for viewing in viewings:
upcoming_viewings.append(viewing.text.strip())
return upcoming_viewings | [
"def",
"upcoming_viewings",
"(",
"self",
")",
":",
"upcoming_viewings",
"=",
"[",
"]",
"try",
":",
"if",
"self",
".",
"_data_from_search",
":",
"viewings",
"=",
"self",
".",
"_data_from_search",
".",
"find_all",
"(",
"'div'",
",",
"{",
"'class'",
":",
"'smi-onview-text'",
"}",
")",
"else",
":",
"viewings",
"=",
"[",
"]",
"except",
"Exception",
"as",
"e",
":",
"if",
"self",
".",
"_debug",
":",
"logging",
".",
"error",
"(",
"\"Error getting upcoming_viewings. Error message: \"",
"+",
"e",
".",
"args",
"[",
"0",
"]",
")",
"return",
"for",
"viewing",
"in",
"viewings",
":",
"upcoming_viewings",
".",
"append",
"(",
"viewing",
".",
"text",
".",
"strip",
"(",
")",
")",
"return",
"upcoming_viewings"
] | Returns an array of upcoming viewings for a property.
:return: | [
"Returns",
"an",
"array",
"of",
"upcoming",
"viewings",
"for",
"a",
"property",
".",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L121-L140 |
AnthonyBloomer/daftlistings | daftlistings/listing.py | Listing.facilities | def facilities(self):
"""
This method returns the properties facilities.
:return:
"""
facilities = []
try:
list_items = self._ad_page_content.select("#facilities li")
except Exception as e:
if self._debug:
logging.error(
"Error getting facilities. Error message: " + e.args[0])
return
for li in list_items:
facilities.append(li.text)
return facilities | python | def facilities(self):
"""
This method returns the properties facilities.
:return:
"""
facilities = []
try:
list_items = self._ad_page_content.select("#facilities li")
except Exception as e:
if self._debug:
logging.error(
"Error getting facilities. Error message: " + e.args[0])
return
for li in list_items:
facilities.append(li.text)
return facilities | [
"def",
"facilities",
"(",
"self",
")",
":",
"facilities",
"=",
"[",
"]",
"try",
":",
"list_items",
"=",
"self",
".",
"_ad_page_content",
".",
"select",
"(",
"\"#facilities li\"",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
"self",
".",
"_debug",
":",
"logging",
".",
"error",
"(",
"\"Error getting facilities. Error message: \"",
"+",
"e",
".",
"args",
"[",
"0",
"]",
")",
"return",
"for",
"li",
"in",
"list_items",
":",
"facilities",
".",
"append",
"(",
"li",
".",
"text",
")",
"return",
"facilities"
] | This method returns the properties facilities.
:return: | [
"This",
"method",
"returns",
"the",
"properties",
"facilities",
".",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L143-L159 |
AnthonyBloomer/daftlistings | daftlistings/listing.py | Listing.overviews | def overviews(self):
"""
This method returns the properties overviews.
:return:
"""
overviews = []
try:
list_items = self._ad_page_content.select("#overview li")
except Exception as e:
if self._debug:
logging.error(
"Error getting overviews. Error message: " + e.args[0])
return
for li in list_items:
overviews.append(li.text)
return overviews | python | def overviews(self):
"""
This method returns the properties overviews.
:return:
"""
overviews = []
try:
list_items = self._ad_page_content.select("#overview li")
except Exception as e:
if self._debug:
logging.error(
"Error getting overviews. Error message: " + e.args[0])
return
for li in list_items:
overviews.append(li.text)
return overviews | [
"def",
"overviews",
"(",
"self",
")",
":",
"overviews",
"=",
"[",
"]",
"try",
":",
"list_items",
"=",
"self",
".",
"_ad_page_content",
".",
"select",
"(",
"\"#overview li\"",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
"self",
".",
"_debug",
":",
"logging",
".",
"error",
"(",
"\"Error getting overviews. Error message: \"",
"+",
"e",
".",
"args",
"[",
"0",
"]",
")",
"return",
"for",
"li",
"in",
"list_items",
":",
"overviews",
".",
"append",
"(",
"li",
".",
"text",
")",
"return",
"overviews"
] | This method returns the properties overviews.
:return: | [
"This",
"method",
"returns",
"the",
"properties",
"overviews",
".",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L162-L178 |
AnthonyBloomer/daftlistings | daftlistings/listing.py | Listing.features | def features(self):
"""
This method returns the properties features.
:return:
"""
features = []
try:
list_items = self._ad_page_content.select("#features li")
except Exception as e:
if self._debug:
logging.error(
"Error getting features. Error message: " + e.args[0])
return
for li in list_items:
features.append(li.text)
return features | python | def features(self):
"""
This method returns the properties features.
:return:
"""
features = []
try:
list_items = self._ad_page_content.select("#features li")
except Exception as e:
if self._debug:
logging.error(
"Error getting features. Error message: " + e.args[0])
return
for li in list_items:
features.append(li.text)
return features | [
"def",
"features",
"(",
"self",
")",
":",
"features",
"=",
"[",
"]",
"try",
":",
"list_items",
"=",
"self",
".",
"_ad_page_content",
".",
"select",
"(",
"\"#features li\"",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
"self",
".",
"_debug",
":",
"logging",
".",
"error",
"(",
"\"Error getting features. Error message: \"",
"+",
"e",
".",
"args",
"[",
"0",
"]",
")",
"return",
"for",
"li",
"in",
"list_items",
":",
"features",
".",
"append",
"(",
"li",
".",
"text",
")",
"return",
"features"
] | This method returns the properties features.
:return: | [
"This",
"method",
"returns",
"the",
"properties",
"features",
".",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L181-L197 |
AnthonyBloomer/daftlistings | daftlistings/listing.py | Listing.formalised_address | def formalised_address(self):
"""
This method returns the formalised address.
:return:
"""
try:
if self._data_from_search:
t = self._data_from_search.find('a').contents[0]
else:
t = self._ad_page_content.find(
'div', {'class': 'smi-object-header'}).find(
'h1').text.strip()
except Exception as e:
if self._debug:
logging.error(
"Error getting formalised_address. Error message: " + e.args[0])
return
s = t.split('-')
a = s[0].strip()
if 'SALE AGREED' in a:
a = a.split()
a = a[3:]
a = ' '.join([str(x) for x in a])
return a.lower().title().strip() | python | def formalised_address(self):
"""
This method returns the formalised address.
:return:
"""
try:
if self._data_from_search:
t = self._data_from_search.find('a').contents[0]
else:
t = self._ad_page_content.find(
'div', {'class': 'smi-object-header'}).find(
'h1').text.strip()
except Exception as e:
if self._debug:
logging.error(
"Error getting formalised_address. Error message: " + e.args[0])
return
s = t.split('-')
a = s[0].strip()
if 'SALE AGREED' in a:
a = a.split()
a = a[3:]
a = ' '.join([str(x) for x in a])
return a.lower().title().strip() | [
"def",
"formalised_address",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"_data_from_search",
":",
"t",
"=",
"self",
".",
"_data_from_search",
".",
"find",
"(",
"'a'",
")",
".",
"contents",
"[",
"0",
"]",
"else",
":",
"t",
"=",
"self",
".",
"_ad_page_content",
".",
"find",
"(",
"'div'",
",",
"{",
"'class'",
":",
"'smi-object-header'",
"}",
")",
".",
"find",
"(",
"'h1'",
")",
".",
"text",
".",
"strip",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
"self",
".",
"_debug",
":",
"logging",
".",
"error",
"(",
"\"Error getting formalised_address. Error message: \"",
"+",
"e",
".",
"args",
"[",
"0",
"]",
")",
"return",
"s",
"=",
"t",
".",
"split",
"(",
"'-'",
")",
"a",
"=",
"s",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"if",
"'SALE AGREED'",
"in",
"a",
":",
"a",
"=",
"a",
".",
"split",
"(",
")",
"a",
"=",
"a",
"[",
"3",
":",
"]",
"a",
"=",
"' '",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"a",
"]",
")",
"return",
"a",
".",
"lower",
"(",
")",
".",
"title",
"(",
")",
".",
"strip",
"(",
")"
] | This method returns the formalised address.
:return: | [
"This",
"method",
"returns",
"the",
"formalised",
"address",
".",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L200-L224 |
AnthonyBloomer/daftlistings | daftlistings/listing.py | Listing.address_line_1 | def address_line_1(self):
"""
This method returns the first line of the address.
:return:
"""
formalised_address = self.formalised_address
if formalised_address is None:
return
try:
address = formalised_address.split(',')
except Exception as e:
if self._debug:
logging.error(
"Error getting address_line_1. Error message: " + e.args[0])
return
return address[0].strip() | python | def address_line_1(self):
"""
This method returns the first line of the address.
:return:
"""
formalised_address = self.formalised_address
if formalised_address is None:
return
try:
address = formalised_address.split(',')
except Exception as e:
if self._debug:
logging.error(
"Error getting address_line_1. Error message: " + e.args[0])
return
return address[0].strip() | [
"def",
"address_line_1",
"(",
"self",
")",
":",
"formalised_address",
"=",
"self",
".",
"formalised_address",
"if",
"formalised_address",
"is",
"None",
":",
"return",
"try",
":",
"address",
"=",
"formalised_address",
".",
"split",
"(",
"','",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
"self",
".",
"_debug",
":",
"logging",
".",
"error",
"(",
"\"Error getting address_line_1. Error message: \"",
"+",
"e",
".",
"args",
"[",
"0",
"]",
")",
"return",
"return",
"address",
"[",
"0",
"]",
".",
"strip",
"(",
")"
] | This method returns the first line of the address.
:return: | [
"This",
"method",
"returns",
"the",
"first",
"line",
"of",
"the",
"address",
".",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L227-L243 |
AnthonyBloomer/daftlistings | daftlistings/listing.py | Listing.images | def images(self):
"""
This method returns the listing image.
:return:
"""
try:
uls = self._ad_page_content.find(
"ul", {"class": "smi-gallery-list"})
except Exception as e:
if self._debug:
logging.error(
"Error getting images. Error message: " + e.args[0])
return
images = []
if uls is None:
return
for li in uls.find_all('li'):
if li.find('img')['src']:
images.append(li.find('img')['src'])
return images | python | def images(self):
"""
This method returns the listing image.
:return:
"""
try:
uls = self._ad_page_content.find(
"ul", {"class": "smi-gallery-list"})
except Exception as e:
if self._debug:
logging.error(
"Error getting images. Error message: " + e.args[0])
return
images = []
if uls is None:
return
for li in uls.find_all('li'):
if li.find('img')['src']:
images.append(li.find('img')['src'])
return images | [
"def",
"images",
"(",
"self",
")",
":",
"try",
":",
"uls",
"=",
"self",
".",
"_ad_page_content",
".",
"find",
"(",
"\"ul\"",
",",
"{",
"\"class\"",
":",
"\"smi-gallery-list\"",
"}",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
"self",
".",
"_debug",
":",
"logging",
".",
"error",
"(",
"\"Error getting images. Error message: \"",
"+",
"e",
".",
"args",
"[",
"0",
"]",
")",
"return",
"images",
"=",
"[",
"]",
"if",
"uls",
"is",
"None",
":",
"return",
"for",
"li",
"in",
"uls",
".",
"find_all",
"(",
"'li'",
")",
":",
"if",
"li",
".",
"find",
"(",
"'img'",
")",
"[",
"'src'",
"]",
":",
"images",
".",
"append",
"(",
"li",
".",
"find",
"(",
"'img'",
")",
"[",
"'src'",
"]",
")",
"return",
"images"
] | This method returns the listing image.
:return: | [
"This",
"method",
"returns",
"the",
"listing",
"image",
".",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L266-L286 |
AnthonyBloomer/daftlistings | daftlistings/listing.py | Listing.agent | def agent(self):
"""
This method returns the agent name.
:return:
"""
try:
if self._data_from_search:
agent = self._data_from_search.find(
'ul', {'class': 'links'}).text
return agent.split(':')[1].strip()
else:
return self._ad_page_content.find('a', {'id': 'smi-link-branded'}).text.strip()
except Exception as e:
if self._debug:
logging.error(
"Error getting agent. Error message: " + e.args[0])
return | python | def agent(self):
"""
This method returns the agent name.
:return:
"""
try:
if self._data_from_search:
agent = self._data_from_search.find(
'ul', {'class': 'links'}).text
return agent.split(':')[1].strip()
else:
return self._ad_page_content.find('a', {'id': 'smi-link-branded'}).text.strip()
except Exception as e:
if self._debug:
logging.error(
"Error getting agent. Error message: " + e.args[0])
return | [
"def",
"agent",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"_data_from_search",
":",
"agent",
"=",
"self",
".",
"_data_from_search",
".",
"find",
"(",
"'ul'",
",",
"{",
"'class'",
":",
"'links'",
"}",
")",
".",
"text",
"return",
"agent",
".",
"split",
"(",
"':'",
")",
"[",
"1",
"]",
".",
"strip",
"(",
")",
"else",
":",
"return",
"self",
".",
"_ad_page_content",
".",
"find",
"(",
"'a'",
",",
"{",
"'id'",
":",
"'smi-link-branded'",
"}",
")",
".",
"text",
".",
"strip",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
"self",
".",
"_debug",
":",
"logging",
".",
"error",
"(",
"\"Error getting agent. Error message: \"",
"+",
"e",
".",
"args",
"[",
"0",
"]",
")",
"return"
] | This method returns the agent name.
:return: | [
"This",
"method",
"returns",
"the",
"agent",
"name",
".",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L311-L327 |
AnthonyBloomer/daftlistings | daftlistings/listing.py | Listing.agent_url | def agent_url(self):
"""
This method returns the agent's url.
:return:
"""
try:
if self._data_from_search:
agent = self._data_from_search.find('ul', {'class': 'links'})
links = agent.find_all('a')
return links[1]['href']
else:
return self._ad_page_content.find('a', {'id': 'smi-link-branded'})['href']
except Exception as e:
if self._debug:
logging.error(
"Error getting agent_url. Error message: " + e.args[0])
return | python | def agent_url(self):
"""
This method returns the agent's url.
:return:
"""
try:
if self._data_from_search:
agent = self._data_from_search.find('ul', {'class': 'links'})
links = agent.find_all('a')
return links[1]['href']
else:
return self._ad_page_content.find('a', {'id': 'smi-link-branded'})['href']
except Exception as e:
if self._debug:
logging.error(
"Error getting agent_url. Error message: " + e.args[0])
return | [
"def",
"agent_url",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"_data_from_search",
":",
"agent",
"=",
"self",
".",
"_data_from_search",
".",
"find",
"(",
"'ul'",
",",
"{",
"'class'",
":",
"'links'",
"}",
")",
"links",
"=",
"agent",
".",
"find_all",
"(",
"'a'",
")",
"return",
"links",
"[",
"1",
"]",
"[",
"'href'",
"]",
"else",
":",
"return",
"self",
".",
"_ad_page_content",
".",
"find",
"(",
"'a'",
",",
"{",
"'id'",
":",
"'smi-link-branded'",
"}",
")",
"[",
"'href'",
"]",
"except",
"Exception",
"as",
"e",
":",
"if",
"self",
".",
"_debug",
":",
"logging",
".",
"error",
"(",
"\"Error getting agent_url. Error message: \"",
"+",
"e",
".",
"args",
"[",
"0",
"]",
")",
"return"
] | This method returns the agent's url.
:return: | [
"This",
"method",
"returns",
"the",
"agent",
"s",
"url",
".",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L330-L346 |
AnthonyBloomer/daftlistings | daftlistings/listing.py | Listing.contact_number | def contact_number(self):
"""
This method returns the contact phone number.
:return:
"""
try:
number = self._ad_page_content.find(
'button', {'class': 'phone-number'})
return (base64.b64decode(number.attrs['data-p'])).decode('ascii')
except Exception as e:
if self._debug:
logging.error(
"Error getting contact_number. Error message: " + e.args[0])
return 'N/A' | python | def contact_number(self):
"""
This method returns the contact phone number.
:return:
"""
try:
number = self._ad_page_content.find(
'button', {'class': 'phone-number'})
return (base64.b64decode(number.attrs['data-p'])).decode('ascii')
except Exception as e:
if self._debug:
logging.error(
"Error getting contact_number. Error message: " + e.args[0])
return 'N/A' | [
"def",
"contact_number",
"(",
"self",
")",
":",
"try",
":",
"number",
"=",
"self",
".",
"_ad_page_content",
".",
"find",
"(",
"'button'",
",",
"{",
"'class'",
":",
"'phone-number'",
"}",
")",
"return",
"(",
"base64",
".",
"b64decode",
"(",
"number",
".",
"attrs",
"[",
"'data-p'",
"]",
")",
")",
".",
"decode",
"(",
"'ascii'",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
"self",
".",
"_debug",
":",
"logging",
".",
"error",
"(",
"\"Error getting contact_number. Error message: \"",
"+",
"e",
".",
"args",
"[",
"0",
"]",
")",
"return",
"'N/A'"
] | This method returns the contact phone number.
:return: | [
"This",
"method",
"returns",
"the",
"contact",
"phone",
"number",
".",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L349-L362 |
AnthonyBloomer/daftlistings | daftlistings/listing.py | Listing.daft_link | def daft_link(self):
"""
This method returns the url of the listing.
:return:
"""
try:
if self._data_from_search:
link = self._data_from_search.find('a', href=True)
return 'http://www.daft.ie' + link['href']
else:
return self._ad_page_content.find('link', {'rel': 'canonical'})['href']
except Exception as e:
if self._debug:
logging.error(
"Error getting daft_link. Error message: " + e.args[0])
return | python | def daft_link(self):
"""
This method returns the url of the listing.
:return:
"""
try:
if self._data_from_search:
link = self._data_from_search.find('a', href=True)
return 'http://www.daft.ie' + link['href']
else:
return self._ad_page_content.find('link', {'rel': 'canonical'})['href']
except Exception as e:
if self._debug:
logging.error(
"Error getting daft_link. Error message: " + e.args[0])
return | [
"def",
"daft_link",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"_data_from_search",
":",
"link",
"=",
"self",
".",
"_data_from_search",
".",
"find",
"(",
"'a'",
",",
"href",
"=",
"True",
")",
"return",
"'http://www.daft.ie'",
"+",
"link",
"[",
"'href'",
"]",
"else",
":",
"return",
"self",
".",
"_ad_page_content",
".",
"find",
"(",
"'link'",
",",
"{",
"'rel'",
":",
"'canonical'",
"}",
")",
"[",
"'href'",
"]",
"except",
"Exception",
"as",
"e",
":",
"if",
"self",
".",
"_debug",
":",
"logging",
".",
"error",
"(",
"\"Error getting daft_link. Error message: \"",
"+",
"e",
".",
"args",
"[",
"0",
"]",
")",
"return"
] | This method returns the url of the listing.
:return: | [
"This",
"method",
"returns",
"the",
"url",
"of",
"the",
"listing",
".",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L365-L380 |
AnthonyBloomer/daftlistings | daftlistings/listing.py | Listing.shortcode | def shortcode(self):
"""
This method returns the shortcode url of the listing.
:return:
"""
try:
div = self._ad_page_content.find(
'div', {'class': 'description_extras'})
index = [i for i, s in enumerate(
div.contents) if 'Shortcode' in str(s)][0] + 1
return div.contents[index]['href']
except Exception as e:
if self._debug:
logging.error(
"Error getting shortcode. Error message: " + e.args[0])
return 'N/A' | python | def shortcode(self):
"""
This method returns the shortcode url of the listing.
:return:
"""
try:
div = self._ad_page_content.find(
'div', {'class': 'description_extras'})
index = [i for i, s in enumerate(
div.contents) if 'Shortcode' in str(s)][0] + 1
return div.contents[index]['href']
except Exception as e:
if self._debug:
logging.error(
"Error getting shortcode. Error message: " + e.args[0])
return 'N/A' | [
"def",
"shortcode",
"(",
"self",
")",
":",
"try",
":",
"div",
"=",
"self",
".",
"_ad_page_content",
".",
"find",
"(",
"'div'",
",",
"{",
"'class'",
":",
"'description_extras'",
"}",
")",
"index",
"=",
"[",
"i",
"for",
"i",
",",
"s",
"in",
"enumerate",
"(",
"div",
".",
"contents",
")",
"if",
"'Shortcode'",
"in",
"str",
"(",
"s",
")",
"]",
"[",
"0",
"]",
"+",
"1",
"return",
"div",
".",
"contents",
"[",
"index",
"]",
"[",
"'href'",
"]",
"except",
"Exception",
"as",
"e",
":",
"if",
"self",
".",
"_debug",
":",
"logging",
".",
"error",
"(",
"\"Error getting shortcode. Error message: \"",
"+",
"e",
".",
"args",
"[",
"0",
"]",
")",
"return",
"'N/A'"
] | This method returns the shortcode url of the listing.
:return: | [
"This",
"method",
"returns",
"the",
"shortcode",
"url",
"of",
"the",
"listing",
".",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L383-L398 |
AnthonyBloomer/daftlistings | daftlistings/listing.py | Listing.views | def views(self):
"""
This method returns the "Property Views" from listing.
:return:
"""
try:
div = self._ad_page_content.find(
'div', {'class': 'description_extras'})
index = [i for i, s in enumerate(
div.contents) if 'Property Views' in str(s)][0] + 1
return int(''.join(list(filter(str.isdigit, div.contents[index]))))
except Exception as e:
if self._debug:
logging.error(
"Error getting views. Error message: " + e.args[0])
return 'N/A' | python | def views(self):
"""
This method returns the "Property Views" from listing.
:return:
"""
try:
div = self._ad_page_content.find(
'div', {'class': 'description_extras'})
index = [i for i, s in enumerate(
div.contents) if 'Property Views' in str(s)][0] + 1
return int(''.join(list(filter(str.isdigit, div.contents[index]))))
except Exception as e:
if self._debug:
logging.error(
"Error getting views. Error message: " + e.args[0])
return 'N/A' | [
"def",
"views",
"(",
"self",
")",
":",
"try",
":",
"div",
"=",
"self",
".",
"_ad_page_content",
".",
"find",
"(",
"'div'",
",",
"{",
"'class'",
":",
"'description_extras'",
"}",
")",
"index",
"=",
"[",
"i",
"for",
"i",
",",
"s",
"in",
"enumerate",
"(",
"div",
".",
"contents",
")",
"if",
"'Property Views'",
"in",
"str",
"(",
"s",
")",
"]",
"[",
"0",
"]",
"+",
"1",
"return",
"int",
"(",
"''",
".",
"join",
"(",
"list",
"(",
"filter",
"(",
"str",
".",
"isdigit",
",",
"div",
".",
"contents",
"[",
"index",
"]",
")",
")",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
"self",
".",
"_debug",
":",
"logging",
".",
"error",
"(",
"\"Error getting views. Error message: \"",
"+",
"e",
".",
"args",
"[",
"0",
"]",
")",
"return",
"'N/A'"
] | This method returns the "Property Views" from listing.
:return: | [
"This",
"method",
"returns",
"the",
"Property",
"Views",
"from",
"listing",
".",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L419-L434 |
AnthonyBloomer/daftlistings | daftlistings/listing.py | Listing.dwelling_type | def dwelling_type(self):
"""
This method returns the dwelling type.
:return:
"""
try:
if self._data_from_search:
info = self._data_from_search.find(
'ul', {"class": "info"}).text
s = info.split('|')
return s[0].strip()
else:
return self._ad_page_content.find(
'div', {'id': 'smi-summary-items'}
).find('span', {'class': 'header_text'}).text
except Exception as e:
if self._debug:
logging.error(
"Error getting dwelling_type. Error message: " + e.args[0])
return | python | def dwelling_type(self):
"""
This method returns the dwelling type.
:return:
"""
try:
if self._data_from_search:
info = self._data_from_search.find(
'ul', {"class": "info"}).text
s = info.split('|')
return s[0].strip()
else:
return self._ad_page_content.find(
'div', {'id': 'smi-summary-items'}
).find('span', {'class': 'header_text'}).text
except Exception as e:
if self._debug:
logging.error(
"Error getting dwelling_type. Error message: " + e.args[0])
return | [
"def",
"dwelling_type",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"_data_from_search",
":",
"info",
"=",
"self",
".",
"_data_from_search",
".",
"find",
"(",
"'ul'",
",",
"{",
"\"class\"",
":",
"\"info\"",
"}",
")",
".",
"text",
"s",
"=",
"info",
".",
"split",
"(",
"'|'",
")",
"return",
"s",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"else",
":",
"return",
"self",
".",
"_ad_page_content",
".",
"find",
"(",
"'div'",
",",
"{",
"'id'",
":",
"'smi-summary-items'",
"}",
")",
".",
"find",
"(",
"'span'",
",",
"{",
"'class'",
":",
"'header_text'",
"}",
")",
".",
"text",
"except",
"Exception",
"as",
"e",
":",
"if",
"self",
".",
"_debug",
":",
"logging",
".",
"error",
"(",
"\"Error getting dwelling_type. Error message: \"",
"+",
"e",
".",
"args",
"[",
"0",
"]",
")",
"return"
] | This method returns the dwelling type.
:return: | [
"This",
"method",
"returns",
"the",
"dwelling",
"type",
".",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L437-L457 |
AnthonyBloomer/daftlistings | daftlistings/listing.py | Listing.posted_since | def posted_since(self):
"""
This method returns the date the listing was entered.
:return:
"""
try:
if self._data_from_search:
info = self._data_from_search.find(
'div', {"class": "date_entered"}).text
s = info.split(':')
return s[-1].strip()
else:
div = self._ad_page_content.find(
'div', {'class': 'description_extras'})
index = [i for i, s in enumerate(
div.contents) if 'Entered/Renewed' in str(s)][0] + 1
return re.search("([0-9]{1,2}/[0-9]{1,2}/[0-9]{4})", str(div.contents[index]))[0]
except Exception as e:
if self._debug:
logging.error(
"Error getting posted_since. Error message: " + e.args[0])
return | python | def posted_since(self):
"""
This method returns the date the listing was entered.
:return:
"""
try:
if self._data_from_search:
info = self._data_from_search.find(
'div', {"class": "date_entered"}).text
s = info.split(':')
return s[-1].strip()
else:
div = self._ad_page_content.find(
'div', {'class': 'description_extras'})
index = [i for i, s in enumerate(
div.contents) if 'Entered/Renewed' in str(s)][0] + 1
return re.search("([0-9]{1,2}/[0-9]{1,2}/[0-9]{4})", str(div.contents[index]))[0]
except Exception as e:
if self._debug:
logging.error(
"Error getting posted_since. Error message: " + e.args[0])
return | [
"def",
"posted_since",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"_data_from_search",
":",
"info",
"=",
"self",
".",
"_data_from_search",
".",
"find",
"(",
"'div'",
",",
"{",
"\"class\"",
":",
"\"date_entered\"",
"}",
")",
".",
"text",
"s",
"=",
"info",
".",
"split",
"(",
"':'",
")",
"return",
"s",
"[",
"-",
"1",
"]",
".",
"strip",
"(",
")",
"else",
":",
"div",
"=",
"self",
".",
"_ad_page_content",
".",
"find",
"(",
"'div'",
",",
"{",
"'class'",
":",
"'description_extras'",
"}",
")",
"index",
"=",
"[",
"i",
"for",
"i",
",",
"s",
"in",
"enumerate",
"(",
"div",
".",
"contents",
")",
"if",
"'Entered/Renewed'",
"in",
"str",
"(",
"s",
")",
"]",
"[",
"0",
"]",
"+",
"1",
"return",
"re",
".",
"search",
"(",
"\"([0-9]{1,2}/[0-9]{1,2}/[0-9]{4})\"",
",",
"str",
"(",
"div",
".",
"contents",
"[",
"index",
"]",
")",
")",
"[",
"0",
"]",
"except",
"Exception",
"as",
"e",
":",
"if",
"self",
".",
"_debug",
":",
"logging",
".",
"error",
"(",
"\"Error getting posted_since. Error message: \"",
"+",
"e",
".",
"args",
"[",
"0",
"]",
")",
"return"
] | This method returns the date the listing was entered.
:return: | [
"This",
"method",
"returns",
"the",
"date",
"the",
"listing",
"was",
"entered",
".",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L460-L481 |
AnthonyBloomer/daftlistings | daftlistings/listing.py | Listing.bedrooms | def bedrooms(self):
"""
This method gets the number of bedrooms.
:return:
"""
try:
if self._data_from_search:
info = self._data_from_search.find(
'ul', {"class": "info"}).text
s = info.split('|')
nb = s[1].strip()
return int(nb.split()[0])
else:
div = self._ad_page_content.find(
'div', {'id': 'smi-summary-items'})
spans = div.find_all('span', {'class': 'header_text'})
for span in spans:
# print(span.text)
if 'bed' in span.text.lower():
return int(''.join([n for n in span.text if n.isdigit()]))
return
except Exception as e:
if self._debug:
logging.error(
"Error getting bedrooms. Error message: " + e.args[0])
return 'N/A' | python | def bedrooms(self):
"""
This method gets the number of bedrooms.
:return:
"""
try:
if self._data_from_search:
info = self._data_from_search.find(
'ul', {"class": "info"}).text
s = info.split('|')
nb = s[1].strip()
return int(nb.split()[0])
else:
div = self._ad_page_content.find(
'div', {'id': 'smi-summary-items'})
spans = div.find_all('span', {'class': 'header_text'})
for span in spans:
# print(span.text)
if 'bed' in span.text.lower():
return int(''.join([n for n in span.text if n.isdigit()]))
return
except Exception as e:
if self._debug:
logging.error(
"Error getting bedrooms. Error message: " + e.args[0])
return 'N/A' | [
"def",
"bedrooms",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"_data_from_search",
":",
"info",
"=",
"self",
".",
"_data_from_search",
".",
"find",
"(",
"'ul'",
",",
"{",
"\"class\"",
":",
"\"info\"",
"}",
")",
".",
"text",
"s",
"=",
"info",
".",
"split",
"(",
"'|'",
")",
"nb",
"=",
"s",
"[",
"1",
"]",
".",
"strip",
"(",
")",
"return",
"int",
"(",
"nb",
".",
"split",
"(",
")",
"[",
"0",
"]",
")",
"else",
":",
"div",
"=",
"self",
".",
"_ad_page_content",
".",
"find",
"(",
"'div'",
",",
"{",
"'id'",
":",
"'smi-summary-items'",
"}",
")",
"spans",
"=",
"div",
".",
"find_all",
"(",
"'span'",
",",
"{",
"'class'",
":",
"'header_text'",
"}",
")",
"for",
"span",
"in",
"spans",
":",
"# print(span.text)",
"if",
"'bed'",
"in",
"span",
".",
"text",
".",
"lower",
"(",
")",
":",
"return",
"int",
"(",
"''",
".",
"join",
"(",
"[",
"n",
"for",
"n",
"in",
"span",
".",
"text",
"if",
"n",
".",
"isdigit",
"(",
")",
"]",
")",
")",
"return",
"except",
"Exception",
"as",
"e",
":",
"if",
"self",
".",
"_debug",
":",
"logging",
".",
"error",
"(",
"\"Error getting bedrooms. Error message: \"",
"+",
"e",
".",
"args",
"[",
"0",
"]",
")",
"return",
"'N/A'"
] | This method gets the number of bedrooms.
:return: | [
"This",
"method",
"gets",
"the",
"number",
"of",
"bedrooms",
".",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L484-L509 |
AnthonyBloomer/daftlistings | daftlistings/listing.py | Listing.city_center_distance | def city_center_distance(self):
"""
This method gets the distance to city center, in km.
:return:
"""
try:
infos = self._ad_page_content.find_all(
'div', {"class": "map_info_box"})
for info in infos:
if 'Distance to City Centre' in info.text:
distance_list = re.findall(
'Distance to City Centre: (.*) km', info.text)
return distance_list[0]
return None
except Exception as e:
if self._debug:
logging.error(e.args[0])
print(e)
return 'N/A' | python | def city_center_distance(self):
"""
This method gets the distance to city center, in km.
:return:
"""
try:
infos = self._ad_page_content.find_all(
'div', {"class": "map_info_box"})
for info in infos:
if 'Distance to City Centre' in info.text:
distance_list = re.findall(
'Distance to City Centre: (.*) km', info.text)
return distance_list[0]
return None
except Exception as e:
if self._debug:
logging.error(e.args[0])
print(e)
return 'N/A' | [
"def",
"city_center_distance",
"(",
"self",
")",
":",
"try",
":",
"infos",
"=",
"self",
".",
"_ad_page_content",
".",
"find_all",
"(",
"'div'",
",",
"{",
"\"class\"",
":",
"\"map_info_box\"",
"}",
")",
"for",
"info",
"in",
"infos",
":",
"if",
"'Distance to City Centre'",
"in",
"info",
".",
"text",
":",
"distance_list",
"=",
"re",
".",
"findall",
"(",
"'Distance to City Centre: (.*) km'",
",",
"info",
".",
"text",
")",
"return",
"distance_list",
"[",
"0",
"]",
"return",
"None",
"except",
"Exception",
"as",
"e",
":",
"if",
"self",
".",
"_debug",
":",
"logging",
".",
"error",
"(",
"e",
".",
"args",
"[",
"0",
"]",
")",
"print",
"(",
"e",
")",
"return",
"'N/A'"
] | This method gets the distance to city center, in km.
:return: | [
"This",
"method",
"gets",
"the",
"distance",
"to",
"city",
"center",
"in",
"km",
".",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L541-L559 |
AnthonyBloomer/daftlistings | daftlistings/listing.py | Listing.transport_routes | def transport_routes(self):
"""
This method gets a dict of routes listed in Daft.
:return:
"""
routes = {}
try:
big_div = self._ad_page_content.find(
'div', {"class": "half_area_box_right"})
uls = big_div.find("ul")
if uls is None:
return None
for li in uls.find_all('li'):
route_li = li.text.split(':')
routes[route_li[0]] = [x.strip()
for x in route_li[1].split(',')]
return routes
except Exception as e:
if self._debug:
logging.error(e.args[0])
return 'N/A' | python | def transport_routes(self):
"""
This method gets a dict of routes listed in Daft.
:return:
"""
routes = {}
try:
big_div = self._ad_page_content.find(
'div', {"class": "half_area_box_right"})
uls = big_div.find("ul")
if uls is None:
return None
for li in uls.find_all('li'):
route_li = li.text.split(':')
routes[route_li[0]] = [x.strip()
for x in route_li[1].split(',')]
return routes
except Exception as e:
if self._debug:
logging.error(e.args[0])
return 'N/A' | [
"def",
"transport_routes",
"(",
"self",
")",
":",
"routes",
"=",
"{",
"}",
"try",
":",
"big_div",
"=",
"self",
".",
"_ad_page_content",
".",
"find",
"(",
"'div'",
",",
"{",
"\"class\"",
":",
"\"half_area_box_right\"",
"}",
")",
"uls",
"=",
"big_div",
".",
"find",
"(",
"\"ul\"",
")",
"if",
"uls",
"is",
"None",
":",
"return",
"None",
"for",
"li",
"in",
"uls",
".",
"find_all",
"(",
"'li'",
")",
":",
"route_li",
"=",
"li",
".",
"text",
".",
"split",
"(",
"':'",
")",
"routes",
"[",
"route_li",
"[",
"0",
"]",
"]",
"=",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"route_li",
"[",
"1",
"]",
".",
"split",
"(",
"','",
")",
"]",
"return",
"routes",
"except",
"Exception",
"as",
"e",
":",
"if",
"self",
".",
"_debug",
":",
"logging",
".",
"error",
"(",
"e",
".",
"args",
"[",
"0",
"]",
")",
"return",
"'N/A'"
] | This method gets a dict of routes listed in Daft.
:return: | [
"This",
"method",
"gets",
"a",
"dict",
"of",
"routes",
"listed",
"in",
"Daft",
".",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L562-L582 |
AnthonyBloomer/daftlistings | daftlistings/listing.py | Listing.longitude | def longitude(self):
"""
This method gets a dict of routes listed in Daft.
:return:
"""
try:
scripts = self._ad_page_content.find_all('script')
for script in scripts:
if 'longitude' in script.text:
find_list = re.findall(
r'"longitude":"([\-]?[0-9.]*[0-9]+)"', script.text)
if len(find_list) >= 1:
return find_list[0]
return None
except Exception as e:
if self._debug:
logging.error(
"Error getting longitude. Error message: " + e.args[0])
return None | python | def longitude(self):
"""
This method gets a dict of routes listed in Daft.
:return:
"""
try:
scripts = self._ad_page_content.find_all('script')
for script in scripts:
if 'longitude' in script.text:
find_list = re.findall(
r'"longitude":"([\-]?[0-9.]*[0-9]+)"', script.text)
if len(find_list) >= 1:
return find_list[0]
return None
except Exception as e:
if self._debug:
logging.error(
"Error getting longitude. Error message: " + e.args[0])
return None | [
"def",
"longitude",
"(",
"self",
")",
":",
"try",
":",
"scripts",
"=",
"self",
".",
"_ad_page_content",
".",
"find_all",
"(",
"'script'",
")",
"for",
"script",
"in",
"scripts",
":",
"if",
"'longitude'",
"in",
"script",
".",
"text",
":",
"find_list",
"=",
"re",
".",
"findall",
"(",
"r'\"longitude\":\"([\\-]?[0-9.]*[0-9]+)\"'",
",",
"script",
".",
"text",
")",
"if",
"len",
"(",
"find_list",
")",
">=",
"1",
":",
"return",
"find_list",
"[",
"0",
"]",
"return",
"None",
"except",
"Exception",
"as",
"e",
":",
"if",
"self",
".",
"_debug",
":",
"logging",
".",
"error",
"(",
"\"Error getting longitude. Error message: \"",
"+",
"e",
".",
"args",
"[",
"0",
"]",
")",
"return",
"None"
] | This method gets a dict of routes listed in Daft.
:return: | [
"This",
"method",
"gets",
"a",
"dict",
"of",
"routes",
"listed",
"in",
"Daft",
".",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L606-L624 |
AnthonyBloomer/daftlistings | daftlistings/listing.py | Listing.ber_code | def ber_code(self):
"""
This method gets ber code listed in Daft.
:return:
"""
try:
alt_text = self._ad_page_content.find(
'span', {'class': 'ber-hover'}
).find('img')['alt']
if ('exempt' in alt_text):
return 'exempt'
else:
alt_arr = alt_text.split()
if 'ber' in alt_arr[0].lower():
return alt_arr[1].lower()
else:
return None
except Exception as e:
if self._debug:
logging.error(
"Error getting the Ber Code. Error message: " + e.args[0])
return None | python | def ber_code(self):
"""
This method gets ber code listed in Daft.
:return:
"""
try:
alt_text = self._ad_page_content.find(
'span', {'class': 'ber-hover'}
).find('img')['alt']
if ('exempt' in alt_text):
return 'exempt'
else:
alt_arr = alt_text.split()
if 'ber' in alt_arr[0].lower():
return alt_arr[1].lower()
else:
return None
except Exception as e:
if self._debug:
logging.error(
"Error getting the Ber Code. Error message: " + e.args[0])
return None | [
"def",
"ber_code",
"(",
"self",
")",
":",
"try",
":",
"alt_text",
"=",
"self",
".",
"_ad_page_content",
".",
"find",
"(",
"'span'",
",",
"{",
"'class'",
":",
"'ber-hover'",
"}",
")",
".",
"find",
"(",
"'img'",
")",
"[",
"'alt'",
"]",
"if",
"(",
"'exempt'",
"in",
"alt_text",
")",
":",
"return",
"'exempt'",
"else",
":",
"alt_arr",
"=",
"alt_text",
".",
"split",
"(",
")",
"if",
"'ber'",
"in",
"alt_arr",
"[",
"0",
"]",
".",
"lower",
"(",
")",
":",
"return",
"alt_arr",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"else",
":",
"return",
"None",
"except",
"Exception",
"as",
"e",
":",
"if",
"self",
".",
"_debug",
":",
"logging",
".",
"error",
"(",
"\"Error getting the Ber Code. Error message: \"",
"+",
"e",
".",
"args",
"[",
"0",
"]",
")",
"return",
"None"
] | This method gets ber code listed in Daft.
:return: | [
"This",
"method",
"gets",
"ber",
"code",
"listed",
"in",
"Daft",
".",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L627-L649 |
AnthonyBloomer/daftlistings | daftlistings/listing.py | Listing.contact_advertiser | def contact_advertiser(self, name, email, contact_number, message):
"""
This method allows you to contact the advertiser of a listing.
:param name: Your name
:param email: Your email address.
:param contact_number: Your contact number.
:param message: Your message.
:return:
"""
req = Request(debug=self._debug)
ad_search_type = self.search_type
agent_id = self.agent_id
ad_id = self.id
response = req.post('https://www.daft.ie/ajax_endpoint.php?', params={
'action': 'daft_contact_advertiser',
'from': name,
'email': email,
'message': message,
'contact_number': contact_number,
'type': ad_search_type,
'agent_id': agent_id,
'id': ad_id
})
if self._debug:
logging.info("Status code: %d" % response.status_code)
logging.info("Response: %s" % response.content)
if response.status_code != 200:
logging.error("Status code: %d" % response.status_code)
logging.error("Response: %s" % response.content)
return response.status_code == 200 | python | def contact_advertiser(self, name, email, contact_number, message):
"""
This method allows you to contact the advertiser of a listing.
:param name: Your name
:param email: Your email address.
:param contact_number: Your contact number.
:param message: Your message.
:return:
"""
req = Request(debug=self._debug)
ad_search_type = self.search_type
agent_id = self.agent_id
ad_id = self.id
response = req.post('https://www.daft.ie/ajax_endpoint.php?', params={
'action': 'daft_contact_advertiser',
'from': name,
'email': email,
'message': message,
'contact_number': contact_number,
'type': ad_search_type,
'agent_id': agent_id,
'id': ad_id
})
if self._debug:
logging.info("Status code: %d" % response.status_code)
logging.info("Response: %s" % response.content)
if response.status_code != 200:
logging.error("Status code: %d" % response.status_code)
logging.error("Response: %s" % response.content)
return response.status_code == 200 | [
"def",
"contact_advertiser",
"(",
"self",
",",
"name",
",",
"email",
",",
"contact_number",
",",
"message",
")",
":",
"req",
"=",
"Request",
"(",
"debug",
"=",
"self",
".",
"_debug",
")",
"ad_search_type",
"=",
"self",
".",
"search_type",
"agent_id",
"=",
"self",
".",
"agent_id",
"ad_id",
"=",
"self",
".",
"id",
"response",
"=",
"req",
".",
"post",
"(",
"'https://www.daft.ie/ajax_endpoint.php?'",
",",
"params",
"=",
"{",
"'action'",
":",
"'daft_contact_advertiser'",
",",
"'from'",
":",
"name",
",",
"'email'",
":",
"email",
",",
"'message'",
":",
"message",
",",
"'contact_number'",
":",
"contact_number",
",",
"'type'",
":",
"ad_search_type",
",",
"'agent_id'",
":",
"agent_id",
",",
"'id'",
":",
"ad_id",
"}",
")",
"if",
"self",
".",
"_debug",
":",
"logging",
".",
"info",
"(",
"\"Status code: %d\"",
"%",
"response",
".",
"status_code",
")",
"logging",
".",
"info",
"(",
"\"Response: %s\"",
"%",
"response",
".",
"content",
")",
"if",
"response",
".",
"status_code",
"!=",
"200",
":",
"logging",
".",
"error",
"(",
"\"Status code: %d\"",
"%",
"response",
".",
"status_code",
")",
"logging",
".",
"error",
"(",
"\"Response: %s\"",
"%",
"response",
".",
"content",
")",
"return",
"response",
".",
"status_code",
"==",
"200"
] | This method allows you to contact the advertiser of a listing.
:param name: Your name
:param email: Your email address.
:param contact_number: Your contact number.
:param message: Your message.
:return: | [
"This",
"method",
"allows",
"you",
"to",
"contact",
"the",
"advertiser",
"of",
"a",
"listing",
".",
":",
"param",
"name",
":",
"Your",
"name",
":",
"param",
"email",
":",
"Your",
"email",
"address",
".",
":",
"param",
"contact_number",
":",
"Your",
"contact",
"number",
".",
":",
"param",
"message",
":",
"Your",
"message",
".",
":",
"return",
":"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L671-L704 |
AnthonyBloomer/daftlistings | daftlistings/listing.py | Listing.as_dict | def as_dict(self):
"""
Return a Listing object as Dictionary
:return: dict
"""
return {
'search_type': self.search_type,
'agent_id': self.agent_id,
'id': self.id,
'price': self.price,
'price_change': self.price_change,
'viewings': self.upcoming_viewings,
'facilities': self.facilities,
'overviews': self.overviews,
'formalised_address': self.formalised_address,
'address_line_1': self.address_line_1,
'county': self.county,
'listing_image': self.images,
'listing_hires_image': self.hires_images,
'agent': self.agent,
'agent_url': self.agent_url,
'contact_number': self.contact_number,
'daft_link': self.daft_link,
'shortcode': self.shortcode,
'date_insert_update': self.date_insert_update,
'views': self.views,
'description': self.description,
'dwelling_type': self.dwelling_type,
'posted_since': self.posted_since,
'num_bedrooms': self.bedrooms,
'num_bathrooms': self.bathrooms,
'city_center_distance': self.city_center_distance,
'transport_routes': self.transport_routes,
'latitude': self.latitude,
'longitude': self.longitude,
'ber_code': self.ber_code,
'commercial_area_size': self.commercial_area_size
} | python | def as_dict(self):
"""
Return a Listing object as Dictionary
:return: dict
"""
return {
'search_type': self.search_type,
'agent_id': self.agent_id,
'id': self.id,
'price': self.price,
'price_change': self.price_change,
'viewings': self.upcoming_viewings,
'facilities': self.facilities,
'overviews': self.overviews,
'formalised_address': self.formalised_address,
'address_line_1': self.address_line_1,
'county': self.county,
'listing_image': self.images,
'listing_hires_image': self.hires_images,
'agent': self.agent,
'agent_url': self.agent_url,
'contact_number': self.contact_number,
'daft_link': self.daft_link,
'shortcode': self.shortcode,
'date_insert_update': self.date_insert_update,
'views': self.views,
'description': self.description,
'dwelling_type': self.dwelling_type,
'posted_since': self.posted_since,
'num_bedrooms': self.bedrooms,
'num_bathrooms': self.bathrooms,
'city_center_distance': self.city_center_distance,
'transport_routes': self.transport_routes,
'latitude': self.latitude,
'longitude': self.longitude,
'ber_code': self.ber_code,
'commercial_area_size': self.commercial_area_size
} | [
"def",
"as_dict",
"(",
"self",
")",
":",
"return",
"{",
"'search_type'",
":",
"self",
".",
"search_type",
",",
"'agent_id'",
":",
"self",
".",
"agent_id",
",",
"'id'",
":",
"self",
".",
"id",
",",
"'price'",
":",
"self",
".",
"price",
",",
"'price_change'",
":",
"self",
".",
"price_change",
",",
"'viewings'",
":",
"self",
".",
"upcoming_viewings",
",",
"'facilities'",
":",
"self",
".",
"facilities",
",",
"'overviews'",
":",
"self",
".",
"overviews",
",",
"'formalised_address'",
":",
"self",
".",
"formalised_address",
",",
"'address_line_1'",
":",
"self",
".",
"address_line_1",
",",
"'county'",
":",
"self",
".",
"county",
",",
"'listing_image'",
":",
"self",
".",
"images",
",",
"'listing_hires_image'",
":",
"self",
".",
"hires_images",
",",
"'agent'",
":",
"self",
".",
"agent",
",",
"'agent_url'",
":",
"self",
".",
"agent_url",
",",
"'contact_number'",
":",
"self",
".",
"contact_number",
",",
"'daft_link'",
":",
"self",
".",
"daft_link",
",",
"'shortcode'",
":",
"self",
".",
"shortcode",
",",
"'date_insert_update'",
":",
"self",
".",
"date_insert_update",
",",
"'views'",
":",
"self",
".",
"views",
",",
"'description'",
":",
"self",
".",
"description",
",",
"'dwelling_type'",
":",
"self",
".",
"dwelling_type",
",",
"'posted_since'",
":",
"self",
".",
"posted_since",
",",
"'num_bedrooms'",
":",
"self",
".",
"bedrooms",
",",
"'num_bathrooms'",
":",
"self",
".",
"bathrooms",
",",
"'city_center_distance'",
":",
"self",
".",
"city_center_distance",
",",
"'transport_routes'",
":",
"self",
".",
"transport_routes",
",",
"'latitude'",
":",
"self",
".",
"latitude",
",",
"'longitude'",
":",
"self",
".",
"longitude",
",",
"'ber_code'",
":",
"self",
".",
"ber_code",
",",
"'commercial_area_size'",
":",
"self",
".",
"commercial_area_size",
"}"
] | Return a Listing object as Dictionary
:return: dict | [
"Return",
"a",
"Listing",
"object",
"as",
"Dictionary",
":",
"return",
":",
"dict"
] | train | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L706-L743 |
fralau/mkdocs_macros_plugin | macros/plugin.py | MacrosPlugin.on_config | def on_config(self, config):
"Fetch the variables and functions"
#print("Here is the config:", config)
# fetch variables from YAML file:
self._variables = config.get(YAML_SUBSET)
# add variables and functions from the module:
module_reader.load_variables(self._variables, config)
print("Variables:", self.variables) | python | def on_config(self, config):
"Fetch the variables and functions"
#print("Here is the config:", config)
# fetch variables from YAML file:
self._variables = config.get(YAML_SUBSET)
# add variables and functions from the module:
module_reader.load_variables(self._variables, config)
print("Variables:", self.variables) | [
"def",
"on_config",
"(",
"self",
",",
"config",
")",
":",
"#print(\"Here is the config:\", config)",
"# fetch variables from YAML file:",
"self",
".",
"_variables",
"=",
"config",
".",
"get",
"(",
"YAML_SUBSET",
")",
"# add variables and functions from the module:",
"module_reader",
".",
"load_variables",
"(",
"self",
".",
"_variables",
",",
"config",
")",
"print",
"(",
"\"Variables:\"",
",",
"self",
".",
"variables",
")"
] | Fetch the variables and functions | [
"Fetch",
"the",
"variables",
"and",
"functions"
] | train | https://github.com/fralau/mkdocs_macros_plugin/blob/8a02189395adae3acd2d18d9edcf0790ff7b4904/macros/plugin.py#L41-L51 |
fralau/mkdocs_macros_plugin | macros/plugin.py | MacrosPlugin.on_page_markdown | def on_page_markdown(self, markdown, page, config,
site_navigation=None, **kwargs):
"Provide a hook for defining functions from an external module"
# the site_navigation argument has been made optional
# (deleted in post 1.0 mkdocs, but maintained here
# for backward compatibility)
if not self.variables:
return markdown
else:
# Create templae and get the variables
md_template = Template(markdown)
# Execute the jinja2 template and return
return md_template.render(**self.variables) | python | def on_page_markdown(self, markdown, page, config,
site_navigation=None, **kwargs):
"Provide a hook for defining functions from an external module"
# the site_navigation argument has been made optional
# (deleted in post 1.0 mkdocs, but maintained here
# for backward compatibility)
if not self.variables:
return markdown
else:
# Create templae and get the variables
md_template = Template(markdown)
# Execute the jinja2 template and return
return md_template.render(**self.variables) | [
"def",
"on_page_markdown",
"(",
"self",
",",
"markdown",
",",
"page",
",",
"config",
",",
"site_navigation",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# the site_navigation argument has been made optional",
"# (deleted in post 1.0 mkdocs, but maintained here",
"# for backward compatibility)",
"if",
"not",
"self",
".",
"variables",
":",
"return",
"markdown",
"else",
":",
"# Create templae and get the variables",
"md_template",
"=",
"Template",
"(",
"markdown",
")",
"# Execute the jinja2 template and return",
"return",
"md_template",
".",
"render",
"(",
"*",
"*",
"self",
".",
"variables",
")"
] | Provide a hook for defining functions from an external module | [
"Provide",
"a",
"hook",
"for",
"defining",
"functions",
"from",
"an",
"external",
"module"
] | train | https://github.com/fralau/mkdocs_macros_plugin/blob/8a02189395adae3acd2d18d9edcf0790ff7b4904/macros/plugin.py#L54-L71 |
fralau/mkdocs_macros_plugin | macros/module_reader.py | load_variables | def load_variables(variables, config):
"""
Add the template functions, via the python module
located in the same directory as the Yaml config file.
The python module must contain the following hook:
declare_variables(variables, macro):
variables['a'] = 5
@macro
def bar(x):
....
@macro
def baz(x):
....
"""
def macro(v, name=''):
"""
Registers a variable as a macro in the template,
i.e. in the variables dictionary:
macro(myfunc)
Optionally, you can assign a different name:
macro(myfunc, 'funcname')
You can also use it as a decorator:
@macro
def foo(a):
return a ** 2
More info:
https://stackoverflow.com/questions/6036082/call-a-python-function-from-jinja2
"""
name = name or v.__name__
variables[name] = v
return v
# determine the package name, from the filename:
python_module = config.get('python_module') or DEFAULT_MODULE_NAME
# get the directory of the yaml file:
config_file = config['config_file_path']
yaml_dir = os.path.dirname(config_file)
# print("Found yaml directory: %s" % yaml_dir)
# that's the directory of the package:
repackage.add(yaml_dir)
try:
module = importlib.import_module(python_module)
print("Found module '%s'" % python_module)
# execute the hook, passing the template decorator function
module.declare_variables(variables, macro)
except ModuleNotFoundError:
print("No module found.") | python | def load_variables(variables, config):
"""
Add the template functions, via the python module
located in the same directory as the Yaml config file.
The python module must contain the following hook:
declare_variables(variables, macro):
variables['a'] = 5
@macro
def bar(x):
....
@macro
def baz(x):
....
"""
def macro(v, name=''):
"""
Registers a variable as a macro in the template,
i.e. in the variables dictionary:
macro(myfunc)
Optionally, you can assign a different name:
macro(myfunc, 'funcname')
You can also use it as a decorator:
@macro
def foo(a):
return a ** 2
More info:
https://stackoverflow.com/questions/6036082/call-a-python-function-from-jinja2
"""
name = name or v.__name__
variables[name] = v
return v
# determine the package name, from the filename:
python_module = config.get('python_module') or DEFAULT_MODULE_NAME
# get the directory of the yaml file:
config_file = config['config_file_path']
yaml_dir = os.path.dirname(config_file)
# print("Found yaml directory: %s" % yaml_dir)
# that's the directory of the package:
repackage.add(yaml_dir)
try:
module = importlib.import_module(python_module)
print("Found module '%s'" % python_module)
# execute the hook, passing the template decorator function
module.declare_variables(variables, macro)
except ModuleNotFoundError:
print("No module found.") | [
"def",
"load_variables",
"(",
"variables",
",",
"config",
")",
":",
"def",
"macro",
"(",
"v",
",",
"name",
"=",
"''",
")",
":",
"\"\"\"\n Registers a variable as a macro in the template,\n i.e. in the variables dictionary:\n\n macro(myfunc)\n\n Optionally, you can assign a different name:\n\n macro(myfunc, 'funcname')\n\n\n You can also use it as a decorator:\n\n @macro\n def foo(a):\n return a ** 2\n\n More info:\n https://stackoverflow.com/questions/6036082/call-a-python-function-from-jinja2\n \"\"\"",
"name",
"=",
"name",
"or",
"v",
".",
"__name__",
"variables",
"[",
"name",
"]",
"=",
"v",
"return",
"v",
"# determine the package name, from the filename:",
"python_module",
"=",
"config",
".",
"get",
"(",
"'python_module'",
")",
"or",
"DEFAULT_MODULE_NAME",
"# get the directory of the yaml file:",
"config_file",
"=",
"config",
"[",
"'config_file_path'",
"]",
"yaml_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"config_file",
")",
"# print(\"Found yaml directory: %s\" % yaml_dir)",
"# that's the directory of the package:",
"repackage",
".",
"add",
"(",
"yaml_dir",
")",
"try",
":",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"python_module",
")",
"print",
"(",
"\"Found module '%s'\"",
"%",
"python_module",
")",
"# execute the hook, passing the template decorator function",
"module",
".",
"declare_variables",
"(",
"variables",
",",
"macro",
")",
"except",
"ModuleNotFoundError",
":",
"print",
"(",
"\"No module found.\"",
")"
] | Add the template functions, via the python module
located in the same directory as the Yaml config file.
The python module must contain the following hook:
declare_variables(variables, macro):
variables['a'] = 5
@macro
def bar(x):
....
@macro
def baz(x):
.... | [
"Add",
"the",
"template",
"functions",
"via",
"the",
"python",
"module",
"located",
"in",
"the",
"same",
"directory",
"as",
"the",
"Yaml",
"config",
"file",
"."
] | train | https://github.com/fralau/mkdocs_macros_plugin/blob/8a02189395adae3acd2d18d9edcf0790ff7b4904/macros/module_reader.py#L18-L84 |
mayeut/pybase64 | pybase64/_fallback.py | b64decode | def b64decode(s, altchars=None, validate=False):
"""Decode bytes encoded with the standard Base64 alphabet.
Argument ``s`` is a :term:`bytes-like object` or ASCII string to
decode.
Optional ``altchars`` must be a :term:`bytes-like object` or ASCII
string of length 2 which specifies the alternative alphabet used instead
of the '+' and '/' characters.
If ``validate`` is ``False`` (the default), characters that are neither in
the normal base-64 alphabet nor the alternative alphabet are discarded
prior to the padding check.
If ``validate`` is ``True``, these non-alphabet characters in the input
result in a :exc:`binascii.Error`.
The result is returned as a :class:`bytes` object.
A :exc:`binascii.Error` is raised if ``s`` is incorrectly padded.
"""
if version_info < (3, 0) or validate:
if validate and len(s) % 4 != 0:
raise BinAsciiError('Incorrect padding')
s = _get_bytes(s)
if altchars is not None:
altchars = _get_bytes(altchars)
assert len(altchars) == 2, repr(altchars)
if version_info < (3, 0):
map = maketrans(altchars, b'+/')
else:
map = bytes.maketrans(altchars, b'+/')
s = s.translate(map)
try:
result = builtin_decode(s, altchars)
except TypeError as e:
raise BinAsciiError(str(e))
if validate:
# check length of result vs length of input
padding = 0
if len(s) > 1 and s[-2] in (b'=', 61):
padding = padding + 1
if len(s) > 0 and s[-1] in (b'=', 61):
padding = padding + 1
if 3 * (len(s) / 4) - padding != len(result):
raise BinAsciiError('Non-base64 digit found')
return result
return builtin_decode(s, altchars) | python | def b64decode(s, altchars=None, validate=False):
"""Decode bytes encoded with the standard Base64 alphabet.
Argument ``s`` is a :term:`bytes-like object` or ASCII string to
decode.
Optional ``altchars`` must be a :term:`bytes-like object` or ASCII
string of length 2 which specifies the alternative alphabet used instead
of the '+' and '/' characters.
If ``validate`` is ``False`` (the default), characters that are neither in
the normal base-64 alphabet nor the alternative alphabet are discarded
prior to the padding check.
If ``validate`` is ``True``, these non-alphabet characters in the input
result in a :exc:`binascii.Error`.
The result is returned as a :class:`bytes` object.
A :exc:`binascii.Error` is raised if ``s`` is incorrectly padded.
"""
if version_info < (3, 0) or validate:
if validate and len(s) % 4 != 0:
raise BinAsciiError('Incorrect padding')
s = _get_bytes(s)
if altchars is not None:
altchars = _get_bytes(altchars)
assert len(altchars) == 2, repr(altchars)
if version_info < (3, 0):
map = maketrans(altchars, b'+/')
else:
map = bytes.maketrans(altchars, b'+/')
s = s.translate(map)
try:
result = builtin_decode(s, altchars)
except TypeError as e:
raise BinAsciiError(str(e))
if validate:
# check length of result vs length of input
padding = 0
if len(s) > 1 and s[-2] in (b'=', 61):
padding = padding + 1
if len(s) > 0 and s[-1] in (b'=', 61):
padding = padding + 1
if 3 * (len(s) / 4) - padding != len(result):
raise BinAsciiError('Non-base64 digit found')
return result
return builtin_decode(s, altchars) | [
"def",
"b64decode",
"(",
"s",
",",
"altchars",
"=",
"None",
",",
"validate",
"=",
"False",
")",
":",
"if",
"version_info",
"<",
"(",
"3",
",",
"0",
")",
"or",
"validate",
":",
"if",
"validate",
"and",
"len",
"(",
"s",
")",
"%",
"4",
"!=",
"0",
":",
"raise",
"BinAsciiError",
"(",
"'Incorrect padding'",
")",
"s",
"=",
"_get_bytes",
"(",
"s",
")",
"if",
"altchars",
"is",
"not",
"None",
":",
"altchars",
"=",
"_get_bytes",
"(",
"altchars",
")",
"assert",
"len",
"(",
"altchars",
")",
"==",
"2",
",",
"repr",
"(",
"altchars",
")",
"if",
"version_info",
"<",
"(",
"3",
",",
"0",
")",
":",
"map",
"=",
"maketrans",
"(",
"altchars",
",",
"b'+/'",
")",
"else",
":",
"map",
"=",
"bytes",
".",
"maketrans",
"(",
"altchars",
",",
"b'+/'",
")",
"s",
"=",
"s",
".",
"translate",
"(",
"map",
")",
"try",
":",
"result",
"=",
"builtin_decode",
"(",
"s",
",",
"altchars",
")",
"except",
"TypeError",
"as",
"e",
":",
"raise",
"BinAsciiError",
"(",
"str",
"(",
"e",
")",
")",
"if",
"validate",
":",
"# check length of result vs length of input",
"padding",
"=",
"0",
"if",
"len",
"(",
"s",
")",
">",
"1",
"and",
"s",
"[",
"-",
"2",
"]",
"in",
"(",
"b'='",
",",
"61",
")",
":",
"padding",
"=",
"padding",
"+",
"1",
"if",
"len",
"(",
"s",
")",
">",
"0",
"and",
"s",
"[",
"-",
"1",
"]",
"in",
"(",
"b'='",
",",
"61",
")",
":",
"padding",
"=",
"padding",
"+",
"1",
"if",
"3",
"*",
"(",
"len",
"(",
"s",
")",
"/",
"4",
")",
"-",
"padding",
"!=",
"len",
"(",
"result",
")",
":",
"raise",
"BinAsciiError",
"(",
"'Non-base64 digit found'",
")",
"return",
"result",
"return",
"builtin_decode",
"(",
"s",
",",
"altchars",
")"
] | Decode bytes encoded with the standard Base64 alphabet.
Argument ``s`` is a :term:`bytes-like object` or ASCII string to
decode.
Optional ``altchars`` must be a :term:`bytes-like object` or ASCII
string of length 2 which specifies the alternative alphabet used instead
of the '+' and '/' characters.
If ``validate`` is ``False`` (the default), characters that are neither in
the normal base-64 alphabet nor the alternative alphabet are discarded
prior to the padding check.
If ``validate`` is ``True``, these non-alphabet characters in the input
result in a :exc:`binascii.Error`.
The result is returned as a :class:`bytes` object.
A :exc:`binascii.Error` is raised if ``s`` is incorrectly padded. | [
"Decode",
"bytes",
"encoded",
"with",
"the",
"standard",
"Base64",
"alphabet",
"."
] | train | https://github.com/mayeut/pybase64/blob/861c48675fd6e37c129e1d7a1233074f8d54449e/pybase64/_fallback.py#L40-L86 |
mayeut/pybase64 | pybase64/_fallback.py | b64encode | def b64encode(s, altchars=None):
"""Encode bytes using the standard Base64 alphabet.
Argument ``s`` is a :term:`bytes-like object` to encode.
Optional ``altchars`` must be a byte string of length 2 which specifies
an alternative alphabet for the '+' and '/' characters. This allows an
application to e.g. generate url or filesystem safe Base64 strings.
The result is returned as a :class:`bytes` object.
"""
if altchars is not None:
altchars = _get_bytes(altchars)
assert len(altchars) == 2, repr(altchars)
if version_info < (3, 0):
if isinstance(s, text_type):
raise TypeError('a bytes-like object is required, not \''
+ type(s).__name__ + '\'')
return builtin_encode(s, altchars) | python | def b64encode(s, altchars=None):
"""Encode bytes using the standard Base64 alphabet.
Argument ``s`` is a :term:`bytes-like object` to encode.
Optional ``altchars`` must be a byte string of length 2 which specifies
an alternative alphabet for the '+' and '/' characters. This allows an
application to e.g. generate url or filesystem safe Base64 strings.
The result is returned as a :class:`bytes` object.
"""
if altchars is not None:
altchars = _get_bytes(altchars)
assert len(altchars) == 2, repr(altchars)
if version_info < (3, 0):
if isinstance(s, text_type):
raise TypeError('a bytes-like object is required, not \''
+ type(s).__name__ + '\'')
return builtin_encode(s, altchars) | [
"def",
"b64encode",
"(",
"s",
",",
"altchars",
"=",
"None",
")",
":",
"if",
"altchars",
"is",
"not",
"None",
":",
"altchars",
"=",
"_get_bytes",
"(",
"altchars",
")",
"assert",
"len",
"(",
"altchars",
")",
"==",
"2",
",",
"repr",
"(",
"altchars",
")",
"if",
"version_info",
"<",
"(",
"3",
",",
"0",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"text_type",
")",
":",
"raise",
"TypeError",
"(",
"'a bytes-like object is required, not \\''",
"+",
"type",
"(",
"s",
")",
".",
"__name__",
"+",
"'\\''",
")",
"return",
"builtin_encode",
"(",
"s",
",",
"altchars",
")"
] | Encode bytes using the standard Base64 alphabet.
Argument ``s`` is a :term:`bytes-like object` to encode.
Optional ``altchars`` must be a byte string of length 2 which specifies
an alternative alphabet for the '+' and '/' characters. This allows an
application to e.g. generate url or filesystem safe Base64 strings.
The result is returned as a :class:`bytes` object. | [
"Encode",
"bytes",
"using",
"the",
"standard",
"Base64",
"alphabet",
"."
] | train | https://github.com/mayeut/pybase64/blob/861c48675fd6e37c129e1d7a1233074f8d54449e/pybase64/_fallback.py#L89-L107 |
mayeut/pybase64 | setup.py | CleanExtensionCommand.run | def run(self):
"""Run command."""
for ext in ['*.so', '*.pyd']:
for file in glob.glob('./pybase64/' + ext):
log.info("removing '%s'", file)
if self.dry_run:
continue
os.remove(file) | python | def run(self):
"""Run command."""
for ext in ['*.so', '*.pyd']:
for file in glob.glob('./pybase64/' + ext):
log.info("removing '%s'", file)
if self.dry_run:
continue
os.remove(file) | [
"def",
"run",
"(",
"self",
")",
":",
"for",
"ext",
"in",
"[",
"'*.so'",
",",
"'*.pyd'",
"]",
":",
"for",
"file",
"in",
"glob",
".",
"glob",
"(",
"'./pybase64/'",
"+",
"ext",
")",
":",
"log",
".",
"info",
"(",
"\"removing '%s'\"",
",",
"file",
")",
"if",
"self",
".",
"dry_run",
":",
"continue",
"os",
".",
"remove",
"(",
"file",
")"
] | Run command. | [
"Run",
"command",
"."
] | train | https://github.com/mayeut/pybase64/blob/861c48675fd6e37c129e1d7a1233074f8d54449e/setup.py#L204-L211 |
kalbhor/MusicTools | musictools/musictools.py | improve_name | def improve_name(song_name):
"""
Improves file name by removing words such as HD, Official,etc
eg : Hey Jude (Official HD) lyrics -> Hey Jude
This helps in better searching of metadata since a spotify search of
'Hey Jude (Official HD) lyrics' fetches 0 results
"""
try:
song_name = os.path.splitext(song_name)[0]
except IndexError:
pass
song_name = song_name.partition('ft')[0]
# Replace characters to filter with spaces
song_name = ''.join(
map(lambda c: " " if c in chars_filter else c, song_name))
# Remove crap words
song_name = re.sub('|'.join(re.escape(key) for key in words_filter),
"", song_name, flags=re.IGNORECASE)
# Remove duplicate spaces
song_name = re.sub(' +', ' ', song_name)
return song_name.strip() | python | def improve_name(song_name):
"""
Improves file name by removing words such as HD, Official,etc
eg : Hey Jude (Official HD) lyrics -> Hey Jude
This helps in better searching of metadata since a spotify search of
'Hey Jude (Official HD) lyrics' fetches 0 results
"""
try:
song_name = os.path.splitext(song_name)[0]
except IndexError:
pass
song_name = song_name.partition('ft')[0]
# Replace characters to filter with spaces
song_name = ''.join(
map(lambda c: " " if c in chars_filter else c, song_name))
# Remove crap words
song_name = re.sub('|'.join(re.escape(key) for key in words_filter),
"", song_name, flags=re.IGNORECASE)
# Remove duplicate spaces
song_name = re.sub(' +', ' ', song_name)
return song_name.strip() | [
"def",
"improve_name",
"(",
"song_name",
")",
":",
"try",
":",
"song_name",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"song_name",
")",
"[",
"0",
"]",
"except",
"IndexError",
":",
"pass",
"song_name",
"=",
"song_name",
".",
"partition",
"(",
"'ft'",
")",
"[",
"0",
"]",
"# Replace characters to filter with spaces",
"song_name",
"=",
"''",
".",
"join",
"(",
"map",
"(",
"lambda",
"c",
":",
"\" \"",
"if",
"c",
"in",
"chars_filter",
"else",
"c",
",",
"song_name",
")",
")",
"# Remove crap words",
"song_name",
"=",
"re",
".",
"sub",
"(",
"'|'",
".",
"join",
"(",
"re",
".",
"escape",
"(",
"key",
")",
"for",
"key",
"in",
"words_filter",
")",
",",
"\"\"",
",",
"song_name",
",",
"flags",
"=",
"re",
".",
"IGNORECASE",
")",
"# Remove duplicate spaces",
"song_name",
"=",
"re",
".",
"sub",
"(",
"' +'",
",",
"' '",
",",
"song_name",
")",
"return",
"song_name",
".",
"strip",
"(",
")"
] | Improves file name by removing words such as HD, Official,etc
eg : Hey Jude (Official HD) lyrics -> Hey Jude
This helps in better searching of metadata since a spotify search of
'Hey Jude (Official HD) lyrics' fetches 0 results | [
"Improves",
"file",
"name",
"by",
"removing",
"words",
"such",
"as",
"HD",
"Official",
"etc",
"eg",
":",
"Hey",
"Jude",
"(",
"Official",
"HD",
")",
"lyrics",
"-",
">",
"Hey",
"Jude",
"This",
"helps",
"in",
"better",
"searching",
"of",
"metadata",
"since",
"a",
"spotify",
"search",
"of",
"Hey",
"Jude",
"(",
"Official",
"HD",
")",
"lyrics",
"fetches",
"0",
"results"
] | train | https://github.com/kalbhor/MusicTools/blob/324159448553033173bb050458c6a56e3cfa2738/musictools/musictools.py#L18-L44 |
kalbhor/MusicTools | musictools/musictools.py | get_song_urls | def get_song_urls(song_input):
"""
Gather all urls, titles for a search query
from youtube
"""
YOUTUBECLASS = 'spf-prefetch'
html = requests.get("https://www.youtube.com/results",
params={'search_query': song_input})
soup = BeautifulSoup(html.text, 'html.parser')
soup_section = soup.findAll('a', {'rel': YOUTUBECLASS})
# Use generator over list, since storage isn't important
song_urls = ('https://www.youtube.com' + i.get('href')
for i in soup_section)
song_titles = (i.get('title') for i in soup_section)
youtube_list = list(zip(song_urls, song_titles))
del song_urls
del song_titles
return youtube_list | python | def get_song_urls(song_input):
"""
Gather all urls, titles for a search query
from youtube
"""
YOUTUBECLASS = 'spf-prefetch'
html = requests.get("https://www.youtube.com/results",
params={'search_query': song_input})
soup = BeautifulSoup(html.text, 'html.parser')
soup_section = soup.findAll('a', {'rel': YOUTUBECLASS})
# Use generator over list, since storage isn't important
song_urls = ('https://www.youtube.com' + i.get('href')
for i in soup_section)
song_titles = (i.get('title') for i in soup_section)
youtube_list = list(zip(song_urls, song_titles))
del song_urls
del song_titles
return youtube_list | [
"def",
"get_song_urls",
"(",
"song_input",
")",
":",
"YOUTUBECLASS",
"=",
"'spf-prefetch'",
"html",
"=",
"requests",
".",
"get",
"(",
"\"https://www.youtube.com/results\"",
",",
"params",
"=",
"{",
"'search_query'",
":",
"song_input",
"}",
")",
"soup",
"=",
"BeautifulSoup",
"(",
"html",
".",
"text",
",",
"'html.parser'",
")",
"soup_section",
"=",
"soup",
".",
"findAll",
"(",
"'a'",
",",
"{",
"'rel'",
":",
"YOUTUBECLASS",
"}",
")",
"# Use generator over list, since storage isn't important",
"song_urls",
"=",
"(",
"'https://www.youtube.com'",
"+",
"i",
".",
"get",
"(",
"'href'",
")",
"for",
"i",
"in",
"soup_section",
")",
"song_titles",
"=",
"(",
"i",
".",
"get",
"(",
"'title'",
")",
"for",
"i",
"in",
"soup_section",
")",
"youtube_list",
"=",
"list",
"(",
"zip",
"(",
"song_urls",
",",
"song_titles",
")",
")",
"del",
"song_urls",
"del",
"song_titles",
"return",
"youtube_list"
] | Gather all urls, titles for a search query
from youtube | [
"Gather",
"all",
"urls",
"titles",
"for",
"a",
"search",
"query",
"from",
"youtube"
] | train | https://github.com/kalbhor/MusicTools/blob/324159448553033173bb050458c6a56e3cfa2738/musictools/musictools.py#L46-L69 |
kalbhor/MusicTools | musictools/musictools.py | download_song | def download_song(song_url, song_title):
"""
Download a song using youtube url and song title
"""
outtmpl = song_title + '.%(ext)s'
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': outtmpl,
'postprocessors': [
{'key': 'FFmpegExtractAudio','preferredcodec': 'mp3',
'preferredquality': '192',
},
{'key': 'FFmpegMetadata'},
],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
info_dict = ydl.extract_info(song_url, download=True) | python | def download_song(song_url, song_title):
"""
Download a song using youtube url and song title
"""
outtmpl = song_title + '.%(ext)s'
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': outtmpl,
'postprocessors': [
{'key': 'FFmpegExtractAudio','preferredcodec': 'mp3',
'preferredquality': '192',
},
{'key': 'FFmpegMetadata'},
],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
info_dict = ydl.extract_info(song_url, download=True) | [
"def",
"download_song",
"(",
"song_url",
",",
"song_title",
")",
":",
"outtmpl",
"=",
"song_title",
"+",
"'.%(ext)s'",
"ydl_opts",
"=",
"{",
"'format'",
":",
"'bestaudio/best'",
",",
"'outtmpl'",
":",
"outtmpl",
",",
"'postprocessors'",
":",
"[",
"{",
"'key'",
":",
"'FFmpegExtractAudio'",
",",
"'preferredcodec'",
":",
"'mp3'",
",",
"'preferredquality'",
":",
"'192'",
",",
"}",
",",
"{",
"'key'",
":",
"'FFmpegMetadata'",
"}",
",",
"]",
",",
"}",
"with",
"youtube_dl",
".",
"YoutubeDL",
"(",
"ydl_opts",
")",
"as",
"ydl",
":",
"info_dict",
"=",
"ydl",
".",
"extract_info",
"(",
"song_url",
",",
"download",
"=",
"True",
")"
] | Download a song using youtube url and song title | [
"Download",
"a",
"song",
"using",
"youtube",
"url",
"and",
"song",
"title"
] | train | https://github.com/kalbhor/MusicTools/blob/324159448553033173bb050458c6a56e3cfa2738/musictools/musictools.py#L72-L90 |
kalbhor/MusicTools | musictools/musictools.py | get_metadata | def get_metadata(file_name, client_id, client_secret):
"""
Tries finding metadata through Spotify
"""
song_name = improve_name(file_name) # Remove useless words from title
client_credentials_manager = SpotifyClientCredentials(client_id, client_secret)
spotify = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
results = spotify.search(song_name, limit=1)
results = results['tracks']['items'][0] # Find top result
album = results['album']['name'] # Parse json dictionary
artist = results['album']['artists'][0]['name']
song_title = results['name']
album_art = results['album']['images'][0]['url']
return artist, album, song_title, album_art | python | def get_metadata(file_name, client_id, client_secret):
"""
Tries finding metadata through Spotify
"""
song_name = improve_name(file_name) # Remove useless words from title
client_credentials_manager = SpotifyClientCredentials(client_id, client_secret)
spotify = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
results = spotify.search(song_name, limit=1)
results = results['tracks']['items'][0] # Find top result
album = results['album']['name'] # Parse json dictionary
artist = results['album']['artists'][0]['name']
song_title = results['name']
album_art = results['album']['images'][0]['url']
return artist, album, song_title, album_art | [
"def",
"get_metadata",
"(",
"file_name",
",",
"client_id",
",",
"client_secret",
")",
":",
"song_name",
"=",
"improve_name",
"(",
"file_name",
")",
"# Remove useless words from title",
"client_credentials_manager",
"=",
"SpotifyClientCredentials",
"(",
"client_id",
",",
"client_secret",
")",
"spotify",
"=",
"spotipy",
".",
"Spotify",
"(",
"client_credentials_manager",
"=",
"client_credentials_manager",
")",
"results",
"=",
"spotify",
".",
"search",
"(",
"song_name",
",",
"limit",
"=",
"1",
")",
"results",
"=",
"results",
"[",
"'tracks'",
"]",
"[",
"'items'",
"]",
"[",
"0",
"]",
"# Find top result",
"album",
"=",
"results",
"[",
"'album'",
"]",
"[",
"'name'",
"]",
"# Parse json dictionary",
"artist",
"=",
"results",
"[",
"'album'",
"]",
"[",
"'artists'",
"]",
"[",
"0",
"]",
"[",
"'name'",
"]",
"song_title",
"=",
"results",
"[",
"'name'",
"]",
"album_art",
"=",
"results",
"[",
"'album'",
"]",
"[",
"'images'",
"]",
"[",
"0",
"]",
"[",
"'url'",
"]",
"return",
"artist",
",",
"album",
",",
"song_title",
",",
"album_art"
] | Tries finding metadata through Spotify | [
"Tries",
"finding",
"metadata",
"through",
"Spotify"
] | train | https://github.com/kalbhor/MusicTools/blob/324159448553033173bb050458c6a56e3cfa2738/musictools/musictools.py#L93-L110 |
kalbhor/MusicTools | musictools/musictools.py | add_album_art | def add_album_art(file_name, album_art):
"""
Add album_art in .mp3's tags
"""
img = requests.get(album_art, stream=True) # Gets album art from url
img = img.raw
audio = EasyMP3(file_name, ID3=ID3)
try:
audio.add_tags()
except _util.error:
pass
audio.tags.add(
APIC(
encoding=3, # UTF-8
mime='image/png',
type=3, # 3 is for album art
desc='Cover',
data=img.read() # Reads and adds album art
)
)
audio.save()
return album_art | python | def add_album_art(file_name, album_art):
"""
Add album_art in .mp3's tags
"""
img = requests.get(album_art, stream=True) # Gets album art from url
img = img.raw
audio = EasyMP3(file_name, ID3=ID3)
try:
audio.add_tags()
except _util.error:
pass
audio.tags.add(
APIC(
encoding=3, # UTF-8
mime='image/png',
type=3, # 3 is for album art
desc='Cover',
data=img.read() # Reads and adds album art
)
)
audio.save()
return album_art | [
"def",
"add_album_art",
"(",
"file_name",
",",
"album_art",
")",
":",
"img",
"=",
"requests",
".",
"get",
"(",
"album_art",
",",
"stream",
"=",
"True",
")",
"# Gets album art from url",
"img",
"=",
"img",
".",
"raw",
"audio",
"=",
"EasyMP3",
"(",
"file_name",
",",
"ID3",
"=",
"ID3",
")",
"try",
":",
"audio",
".",
"add_tags",
"(",
")",
"except",
"_util",
".",
"error",
":",
"pass",
"audio",
".",
"tags",
".",
"add",
"(",
"APIC",
"(",
"encoding",
"=",
"3",
",",
"# UTF-8",
"mime",
"=",
"'image/png'",
",",
"type",
"=",
"3",
",",
"# 3 is for album art",
"desc",
"=",
"'Cover'",
",",
"data",
"=",
"img",
".",
"read",
"(",
")",
"# Reads and adds album art",
")",
")",
"audio",
".",
"save",
"(",
")",
"return",
"album_art"
] | Add album_art in .mp3's tags | [
"Add",
"album_art",
"in",
".",
"mp3",
"s",
"tags"
] | train | https://github.com/kalbhor/MusicTools/blob/324159448553033173bb050458c6a56e3cfa2738/musictools/musictools.py#L113-L139 |
kalbhor/MusicTools | musictools/musictools.py | add_metadata | def add_metadata(file_name, title, artist, album):
"""
As the method name suggests
"""
tags = EasyMP3(file_name)
if title:
tags["title"] = title
if artist:
tags["artist"] = artist
if album:
tags["album"] = album
tags.save()
return file_name | python | def add_metadata(file_name, title, artist, album):
"""
As the method name suggests
"""
tags = EasyMP3(file_name)
if title:
tags["title"] = title
if artist:
tags["artist"] = artist
if album:
tags["album"] = album
tags.save()
return file_name | [
"def",
"add_metadata",
"(",
"file_name",
",",
"title",
",",
"artist",
",",
"album",
")",
":",
"tags",
"=",
"EasyMP3",
"(",
"file_name",
")",
"if",
"title",
":",
"tags",
"[",
"\"title\"",
"]",
"=",
"title",
"if",
"artist",
":",
"tags",
"[",
"\"artist\"",
"]",
"=",
"artist",
"if",
"album",
":",
"tags",
"[",
"\"album\"",
"]",
"=",
"album",
"tags",
".",
"save",
"(",
")",
"return",
"file_name"
] | As the method name suggests | [
"As",
"the",
"method",
"name",
"suggests"
] | train | https://github.com/kalbhor/MusicTools/blob/324159448553033173bb050458c6a56e3cfa2738/musictools/musictools.py#L142-L156 |
kalbhor/MusicTools | musictools/musictools.py | revert_metadata | def revert_metadata(files):
"""
Removes all tags from a mp3 file
"""
for file_path in files:
tags = EasyMP3(file_path)
tags.delete()
tags.save() | python | def revert_metadata(files):
"""
Removes all tags from a mp3 file
"""
for file_path in files:
tags = EasyMP3(file_path)
tags.delete()
tags.save() | [
"def",
"revert_metadata",
"(",
"files",
")",
":",
"for",
"file_path",
"in",
"files",
":",
"tags",
"=",
"EasyMP3",
"(",
"file_path",
")",
"tags",
".",
"delete",
"(",
")",
"tags",
".",
"save",
"(",
")"
] | Removes all tags from a mp3 file | [
"Removes",
"all",
"tags",
"from",
"a",
"mp3",
"file"
] | train | https://github.com/kalbhor/MusicTools/blob/324159448553033173bb050458c6a56e3cfa2738/musictools/musictools.py#L166-L173 |
Tivix/django-braintree | django_braintree/models.py | UserVaultManager.get_user_vault_instance_or_none | def get_user_vault_instance_or_none(self, user):
"""Returns a vault_id string or None"""
qset = self.filter(user=user)
if not qset:
return None
if qset.count() > 1:
raise Exception('This app does not currently support multiple vault ids')
return qset.get() | python | def get_user_vault_instance_or_none(self, user):
"""Returns a vault_id string or None"""
qset = self.filter(user=user)
if not qset:
return None
if qset.count() > 1:
raise Exception('This app does not currently support multiple vault ids')
return qset.get() | [
"def",
"get_user_vault_instance_or_none",
"(",
"self",
",",
"user",
")",
":",
"qset",
"=",
"self",
".",
"filter",
"(",
"user",
"=",
"user",
")",
"if",
"not",
"qset",
":",
"return",
"None",
"if",
"qset",
".",
"count",
"(",
")",
">",
"1",
":",
"raise",
"Exception",
"(",
"'This app does not currently support multiple vault ids'",
")",
"return",
"qset",
".",
"get",
"(",
")"
] | Returns a vault_id string or None | [
"Returns",
"a",
"vault_id",
"string",
"or",
"None"
] | train | https://github.com/Tivix/django-braintree/blob/7beb2c8392c2a454c36b353818f3e1db20511ef9/django_braintree/models.py#L11-L20 |
Tivix/django-braintree | django_braintree/models.py | UserVaultManager.charge | def charge(self, user, vault_id=None):
"""If vault_id is not passed this will assume that there is only one instane of user and vault_id in the db."""
assert self.is_in_vault(user)
if vault_id:
user_vault = self.get(user=user, vault_id=vault_id)
else:
user_vault = self.get(user=user) | python | def charge(self, user, vault_id=None):
"""If vault_id is not passed this will assume that there is only one instane of user and vault_id in the db."""
assert self.is_in_vault(user)
if vault_id:
user_vault = self.get(user=user, vault_id=vault_id)
else:
user_vault = self.get(user=user) | [
"def",
"charge",
"(",
"self",
",",
"user",
",",
"vault_id",
"=",
"None",
")",
":",
"assert",
"self",
".",
"is_in_vault",
"(",
"user",
")",
"if",
"vault_id",
":",
"user_vault",
"=",
"self",
".",
"get",
"(",
"user",
"=",
"user",
",",
"vault_id",
"=",
"vault_id",
")",
"else",
":",
"user_vault",
"=",
"self",
".",
"get",
"(",
"user",
"=",
"user",
")"
] | If vault_id is not passed this will assume that there is only one instane of user and vault_id in the db. | [
"If",
"vault_id",
"is",
"not",
"passed",
"this",
"will",
"assume",
"that",
"there",
"is",
"only",
"one",
"instane",
"of",
"user",
"and",
"vault_id",
"in",
"the",
"db",
"."
] | train | https://github.com/Tivix/django-braintree/blob/7beb2c8392c2a454c36b353818f3e1db20511ef9/django_braintree/models.py#L25-L31 |
Tivix/django-braintree | django_braintree/models.py | UserVault.charge | def charge(self, amount):
"""
Charges the users credit card, with he passed $amount, if they are in the vault. Returns the payment_log instance
or None (if charge fails etc.)
"""
try:
result = Transaction.sale(
{
'amount': amount.quantize(Decimal('.01')),
'customer_id': self.vault_id,
"options": {
"submit_for_settlement": True
}
}
)
if result.is_success:
# create a payment log
payment_log = PaymentLog.objects.create(user=self.user, amount=amount, transaction_id=result.transaction.id)
return payment_log
else:
raise Exception('Logical error in CC transaction')
except Exception:
logging.error('Failed to charge $%s to user: %s with vault_id: %s' % (amount, self.user, self.vault_id))
return None | python | def charge(self, amount):
"""
Charges the users credit card, with he passed $amount, if they are in the vault. Returns the payment_log instance
or None (if charge fails etc.)
"""
try:
result = Transaction.sale(
{
'amount': amount.quantize(Decimal('.01')),
'customer_id': self.vault_id,
"options": {
"submit_for_settlement": True
}
}
)
if result.is_success:
# create a payment log
payment_log = PaymentLog.objects.create(user=self.user, amount=amount, transaction_id=result.transaction.id)
return payment_log
else:
raise Exception('Logical error in CC transaction')
except Exception:
logging.error('Failed to charge $%s to user: %s with vault_id: %s' % (amount, self.user, self.vault_id))
return None | [
"def",
"charge",
"(",
"self",
",",
"amount",
")",
":",
"try",
":",
"result",
"=",
"Transaction",
".",
"sale",
"(",
"{",
"'amount'",
":",
"amount",
".",
"quantize",
"(",
"Decimal",
"(",
"'.01'",
")",
")",
",",
"'customer_id'",
":",
"self",
".",
"vault_id",
",",
"\"options\"",
":",
"{",
"\"submit_for_settlement\"",
":",
"True",
"}",
"}",
")",
"if",
"result",
".",
"is_success",
":",
"# create a payment log",
"payment_log",
"=",
"PaymentLog",
".",
"objects",
".",
"create",
"(",
"user",
"=",
"self",
".",
"user",
",",
"amount",
"=",
"amount",
",",
"transaction_id",
"=",
"result",
".",
"transaction",
".",
"id",
")",
"return",
"payment_log",
"else",
":",
"raise",
"Exception",
"(",
"'Logical error in CC transaction'",
")",
"except",
"Exception",
":",
"logging",
".",
"error",
"(",
"'Failed to charge $%s to user: %s with vault_id: %s'",
"%",
"(",
"amount",
",",
"self",
".",
"user",
",",
"self",
".",
"vault_id",
")",
")",
"return",
"None"
] | Charges the users credit card, with he passed $amount, if they are in the vault. Returns the payment_log instance
or None (if charge fails etc.) | [
"Charges",
"the",
"users",
"credit",
"card",
"with",
"he",
"passed",
"$amount",
"if",
"they",
"are",
"in",
"the",
"vault",
".",
"Returns",
"the",
"payment_log",
"instance",
"or",
"None",
"(",
"if",
"charge",
"fails",
"etc",
".",
")"
] | train | https://github.com/Tivix/django-braintree/blob/7beb2c8392c2a454c36b353818f3e1db20511ef9/django_braintree/models.py#L43-L67 |
Tivix/django-braintree | django_braintree/forms.py | UserCCDetailsForm.save | def save(self, prepend_vault_id=''):
"""
Adds or updates a users CC to the vault.
@prepend_vault_id: any string to prepend all vault id's with in case the same braintree account is used by
multiple projects/apps.
"""
assert self.is_valid()
cc_details_map = { # cc details
'number': self.cleaned_data['cc_number'],
'cardholder_name': self.cleaned_data['name'],
'expiration_date': '%s/%s' %\
(self.cleaned_data['expiration_month'], self.cleaned_data['expiration_year']),
'cvv': self.cleaned_data['cvv'],
'billing_address': {
'postal_code': self.cleaned_data['zip_code'],
}
}
if self.__user_vault:
try:
# get customer info, its credit card and then update that credit card
response = Customer.find(self.__user_vault.vault_id)
cc_info = response.credit_cards[0]
return CreditCard.update(cc_info.token, params=cc_details_map)
except Exception, e:
logging.error('Was not able to get customer from vault. %s' % e)
self.__user_vault.delete() # delete the stale instance from our db
# in case the above updating fails or user was never in the vault
new_customer_vault_id = '%s%s' % (prepend_vault_id, md5_hash()[:24])
respone = Customer.create({ # creating a customer, but we really just want to store their CC details
'id': new_customer_vault_id, # vault id, uniquely identifies customer. We're not caring about tokens (used for storing multiple CC's per user)
'credit_card': cc_details_map
})
if respone.is_success: # save a new UserVault instance
UserVault.objects.create(user=self.__user, vault_id=new_customer_vault_id)
return respone | python | def save(self, prepend_vault_id=''):
"""
Adds or updates a users CC to the vault.
@prepend_vault_id: any string to prepend all vault id's with in case the same braintree account is used by
multiple projects/apps.
"""
assert self.is_valid()
cc_details_map = { # cc details
'number': self.cleaned_data['cc_number'],
'cardholder_name': self.cleaned_data['name'],
'expiration_date': '%s/%s' %\
(self.cleaned_data['expiration_month'], self.cleaned_data['expiration_year']),
'cvv': self.cleaned_data['cvv'],
'billing_address': {
'postal_code': self.cleaned_data['zip_code'],
}
}
if self.__user_vault:
try:
# get customer info, its credit card and then update that credit card
response = Customer.find(self.__user_vault.vault_id)
cc_info = response.credit_cards[0]
return CreditCard.update(cc_info.token, params=cc_details_map)
except Exception, e:
logging.error('Was not able to get customer from vault. %s' % e)
self.__user_vault.delete() # delete the stale instance from our db
# in case the above updating fails or user was never in the vault
new_customer_vault_id = '%s%s' % (prepend_vault_id, md5_hash()[:24])
respone = Customer.create({ # creating a customer, but we really just want to store their CC details
'id': new_customer_vault_id, # vault id, uniquely identifies customer. We're not caring about tokens (used for storing multiple CC's per user)
'credit_card': cc_details_map
})
if respone.is_success: # save a new UserVault instance
UserVault.objects.create(user=self.__user, vault_id=new_customer_vault_id)
return respone | [
"def",
"save",
"(",
"self",
",",
"prepend_vault_id",
"=",
"''",
")",
":",
"assert",
"self",
".",
"is_valid",
"(",
")",
"cc_details_map",
"=",
"{",
"# cc details",
"'number'",
":",
"self",
".",
"cleaned_data",
"[",
"'cc_number'",
"]",
",",
"'cardholder_name'",
":",
"self",
".",
"cleaned_data",
"[",
"'name'",
"]",
",",
"'expiration_date'",
":",
"'%s/%s'",
"%",
"(",
"self",
".",
"cleaned_data",
"[",
"'expiration_month'",
"]",
",",
"self",
".",
"cleaned_data",
"[",
"'expiration_year'",
"]",
")",
",",
"'cvv'",
":",
"self",
".",
"cleaned_data",
"[",
"'cvv'",
"]",
",",
"'billing_address'",
":",
"{",
"'postal_code'",
":",
"self",
".",
"cleaned_data",
"[",
"'zip_code'",
"]",
",",
"}",
"}",
"if",
"self",
".",
"__user_vault",
":",
"try",
":",
"# get customer info, its credit card and then update that credit card",
"response",
"=",
"Customer",
".",
"find",
"(",
"self",
".",
"__user_vault",
".",
"vault_id",
")",
"cc_info",
"=",
"response",
".",
"credit_cards",
"[",
"0",
"]",
"return",
"CreditCard",
".",
"update",
"(",
"cc_info",
".",
"token",
",",
"params",
"=",
"cc_details_map",
")",
"except",
"Exception",
",",
"e",
":",
"logging",
".",
"error",
"(",
"'Was not able to get customer from vault. %s'",
"%",
"e",
")",
"self",
".",
"__user_vault",
".",
"delete",
"(",
")",
"# delete the stale instance from our db",
"# in case the above updating fails or user was never in the vault",
"new_customer_vault_id",
"=",
"'%s%s'",
"%",
"(",
"prepend_vault_id",
",",
"md5_hash",
"(",
")",
"[",
":",
"24",
"]",
")",
"respone",
"=",
"Customer",
".",
"create",
"(",
"{",
"# creating a customer, but we really just want to store their CC details",
"'id'",
":",
"new_customer_vault_id",
",",
"# vault id, uniquely identifies customer. We're not caring about tokens (used for storing multiple CC's per user)",
"'credit_card'",
":",
"cc_details_map",
"}",
")",
"if",
"respone",
".",
"is_success",
":",
"# save a new UserVault instance",
"UserVault",
".",
"objects",
".",
"create",
"(",
"user",
"=",
"self",
".",
"__user",
",",
"vault_id",
"=",
"new_customer_vault_id",
")",
"return",
"respone"
] | Adds or updates a users CC to the vault.
@prepend_vault_id: any string to prepend all vault id's with in case the same braintree account is used by
multiple projects/apps. | [
"Adds",
"or",
"updates",
"a",
"users",
"CC",
"to",
"the",
"vault",
"."
] | train | https://github.com/Tivix/django-braintree/blob/7beb2c8392c2a454c36b353818f3e1db20511ef9/django_braintree/forms.py#L93-L133 |
Tivix/django-braintree | django_braintree/views.py | payments_billing | def payments_billing(request, template='django_braintree/payments_billing.html'):
"""
Renders both the past payments that have occurred on the users credit card, but also their CC information on file
(if any)
"""
d = {}
if request.method == 'POST':
# Credit Card is being changed/updated by the user
form = UserCCDetailsForm(request.user, True, request.POST)
if form.is_valid():
response = form.save()
if response.is_success:
messages.add_message(request, messages.SUCCESS, 'Your credit card information has been securely saved.')
return JsonResponse()
else:
return JsonResponse(success=False, errors=[BAD_CC_ERROR_MSG])
return JsonResponse(success=False, data={'form': form_errors_serialize(form)})
else:
if UserVault.objects.is_in_vault(request.user):
try:
response = Customer.find(UserVault.objects.get_user_vault_instance_or_none(request.user).vault_id)
d['current_cc_info'] = response.credit_cards[0]
except Exception, e:
logging.error('Unable to get vault information for user from braintree. %s' % e)
d['cc_form'] = UserCCDetailsForm(request.user)
return render(request, template, d) | python | def payments_billing(request, template='django_braintree/payments_billing.html'):
"""
Renders both the past payments that have occurred on the users credit card, but also their CC information on file
(if any)
"""
d = {}
if request.method == 'POST':
# Credit Card is being changed/updated by the user
form = UserCCDetailsForm(request.user, True, request.POST)
if form.is_valid():
response = form.save()
if response.is_success:
messages.add_message(request, messages.SUCCESS, 'Your credit card information has been securely saved.')
return JsonResponse()
else:
return JsonResponse(success=False, errors=[BAD_CC_ERROR_MSG])
return JsonResponse(success=False, data={'form': form_errors_serialize(form)})
else:
if UserVault.objects.is_in_vault(request.user):
try:
response = Customer.find(UserVault.objects.get_user_vault_instance_or_none(request.user).vault_id)
d['current_cc_info'] = response.credit_cards[0]
except Exception, e:
logging.error('Unable to get vault information for user from braintree. %s' % e)
d['cc_form'] = UserCCDetailsForm(request.user)
return render(request, template, d) | [
"def",
"payments_billing",
"(",
"request",
",",
"template",
"=",
"'django_braintree/payments_billing.html'",
")",
":",
"d",
"=",
"{",
"}",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"# Credit Card is being changed/updated by the user",
"form",
"=",
"UserCCDetailsForm",
"(",
"request",
".",
"user",
",",
"True",
",",
"request",
".",
"POST",
")",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"response",
"=",
"form",
".",
"save",
"(",
")",
"if",
"response",
".",
"is_success",
":",
"messages",
".",
"add_message",
"(",
"request",
",",
"messages",
".",
"SUCCESS",
",",
"'Your credit card information has been securely saved.'",
")",
"return",
"JsonResponse",
"(",
")",
"else",
":",
"return",
"JsonResponse",
"(",
"success",
"=",
"False",
",",
"errors",
"=",
"[",
"BAD_CC_ERROR_MSG",
"]",
")",
"return",
"JsonResponse",
"(",
"success",
"=",
"False",
",",
"data",
"=",
"{",
"'form'",
":",
"form_errors_serialize",
"(",
"form",
")",
"}",
")",
"else",
":",
"if",
"UserVault",
".",
"objects",
".",
"is_in_vault",
"(",
"request",
".",
"user",
")",
":",
"try",
":",
"response",
"=",
"Customer",
".",
"find",
"(",
"UserVault",
".",
"objects",
".",
"get_user_vault_instance_or_none",
"(",
"request",
".",
"user",
")",
".",
"vault_id",
")",
"d",
"[",
"'current_cc_info'",
"]",
"=",
"response",
".",
"credit_cards",
"[",
"0",
"]",
"except",
"Exception",
",",
"e",
":",
"logging",
".",
"error",
"(",
"'Unable to get vault information for user from braintree. %s'",
"%",
"e",
")",
"d",
"[",
"'cc_form'",
"]",
"=",
"UserCCDetailsForm",
"(",
"request",
".",
"user",
")",
"return",
"render",
"(",
"request",
",",
"template",
",",
"d",
")"
] | Renders both the past payments that have occurred on the users credit card, but also their CC information on file
(if any) | [
"Renders",
"both",
"the",
"past",
"payments",
"that",
"have",
"occurred",
"on",
"the",
"users",
"credit",
"card",
"but",
"also",
"their",
"CC",
"information",
"on",
"file",
"(",
"if",
"any",
")"
] | train | https://github.com/Tivix/django-braintree/blob/7beb2c8392c2a454c36b353818f3e1db20511ef9/django_braintree/views.py#L20-L48 |
dropbox/pygerduty | pygerduty/v2.py | Incident.snooze | def snooze(self, requester, duration):
"""Snooze incident.
:param requester: The email address of the individual requesting snooze.
"""
path = '{0}/{1}/{2}'.format(self.collection.name, self.id, 'snooze')
data = {"duration": duration}
extra_headers = {"From": requester}
return self.pagerduty.request('POST', path, data=_json_dumper(data), extra_headers=extra_headers) | python | def snooze(self, requester, duration):
"""Snooze incident.
:param requester: The email address of the individual requesting snooze.
"""
path = '{0}/{1}/{2}'.format(self.collection.name, self.id, 'snooze')
data = {"duration": duration}
extra_headers = {"From": requester}
return self.pagerduty.request('POST', path, data=_json_dumper(data), extra_headers=extra_headers) | [
"def",
"snooze",
"(",
"self",
",",
"requester",
",",
"duration",
")",
":",
"path",
"=",
"'{0}/{1}/{2}'",
".",
"format",
"(",
"self",
".",
"collection",
".",
"name",
",",
"self",
".",
"id",
",",
"'snooze'",
")",
"data",
"=",
"{",
"\"duration\"",
":",
"duration",
"}",
"extra_headers",
"=",
"{",
"\"From\"",
":",
"requester",
"}",
"return",
"self",
".",
"pagerduty",
".",
"request",
"(",
"'POST'",
",",
"path",
",",
"data",
"=",
"_json_dumper",
"(",
"data",
")",
",",
"extra_headers",
"=",
"extra_headers",
")"
] | Snooze incident.
:param requester: The email address of the individual requesting snooze. | [
"Snooze",
"incident",
".",
":",
"param",
"requester",
":",
"The",
"email",
"address",
"of",
"the",
"individual",
"requesting",
"snooze",
"."
] | train | https://github.com/dropbox/pygerduty/blob/11b28bfb66306aa7fc2b95ab9df65eb97ea831cf/pygerduty/v2.py#L465-L472 |
dropbox/pygerduty | pygerduty/v2.py | Incident.reassign | def reassign(self, user_ids, requester):
"""Reassign this incident to a user or list of users
:param user_ids: A non-empty list of user ids
:param requester: The email address of individual requesting reassign
"""
path = '{0}'.format(self.collection.name)
assignments = []
if not user_ids:
raise Error('Must pass at least one user id')
for user_id in user_ids:
ref = {
"assignee": {
"id": user_id,
"type": "user_reference"
}
}
assignments.append(ref)
data = {
"incidents": [
{
"id": self.id,
"type": "incident_reference",
"assignments": assignments
}
]
}
extra_headers = {"From": requester}
return self.pagerduty.request('PUT', path, data=_json_dumper(data), extra_headers=extra_headers) | python | def reassign(self, user_ids, requester):
"""Reassign this incident to a user or list of users
:param user_ids: A non-empty list of user ids
:param requester: The email address of individual requesting reassign
"""
path = '{0}'.format(self.collection.name)
assignments = []
if not user_ids:
raise Error('Must pass at least one user id')
for user_id in user_ids:
ref = {
"assignee": {
"id": user_id,
"type": "user_reference"
}
}
assignments.append(ref)
data = {
"incidents": [
{
"id": self.id,
"type": "incident_reference",
"assignments": assignments
}
]
}
extra_headers = {"From": requester}
return self.pagerduty.request('PUT', path, data=_json_dumper(data), extra_headers=extra_headers) | [
"def",
"reassign",
"(",
"self",
",",
"user_ids",
",",
"requester",
")",
":",
"path",
"=",
"'{0}'",
".",
"format",
"(",
"self",
".",
"collection",
".",
"name",
")",
"assignments",
"=",
"[",
"]",
"if",
"not",
"user_ids",
":",
"raise",
"Error",
"(",
"'Must pass at least one user id'",
")",
"for",
"user_id",
"in",
"user_ids",
":",
"ref",
"=",
"{",
"\"assignee\"",
":",
"{",
"\"id\"",
":",
"user_id",
",",
"\"type\"",
":",
"\"user_reference\"",
"}",
"}",
"assignments",
".",
"append",
"(",
"ref",
")",
"data",
"=",
"{",
"\"incidents\"",
":",
"[",
"{",
"\"id\"",
":",
"self",
".",
"id",
",",
"\"type\"",
":",
"\"incident_reference\"",
",",
"\"assignments\"",
":",
"assignments",
"}",
"]",
"}",
"extra_headers",
"=",
"{",
"\"From\"",
":",
"requester",
"}",
"return",
"self",
".",
"pagerduty",
".",
"request",
"(",
"'PUT'",
",",
"path",
",",
"data",
"=",
"_json_dumper",
"(",
"data",
")",
",",
"extra_headers",
"=",
"extra_headers",
")"
] | Reassign this incident to a user or list of users
:param user_ids: A non-empty list of user ids
:param requester: The email address of individual requesting reassign | [
"Reassign",
"this",
"incident",
"to",
"a",
"user",
"or",
"list",
"of",
"users"
] | train | https://github.com/dropbox/pygerduty/blob/11b28bfb66306aa7fc2b95ab9df65eb97ea831cf/pygerduty/v2.py#L478-L506 |
dropbox/pygerduty | pygerduty/events.py | Events.resolve_incident | def resolve_incident(self, incident_key,
description=None, details=None):
""" Causes the referenced incident to enter resolved state.
Send a resolve event when the problem that caused the initial
trigger has been fixed.
"""
return self.create_event(description, "resolve",
details, incident_key) | python | def resolve_incident(self, incident_key,
description=None, details=None):
""" Causes the referenced incident to enter resolved state.
Send a resolve event when the problem that caused the initial
trigger has been fixed.
"""
return self.create_event(description, "resolve",
details, incident_key) | [
"def",
"resolve_incident",
"(",
"self",
",",
"incident_key",
",",
"description",
"=",
"None",
",",
"details",
"=",
"None",
")",
":",
"return",
"self",
".",
"create_event",
"(",
"description",
",",
"\"resolve\"",
",",
"details",
",",
"incident_key",
")"
] | Causes the referenced incident to enter resolved state.
Send a resolve event when the problem that caused the initial
trigger has been fixed. | [
"Causes",
"the",
"referenced",
"incident",
"to",
"enter",
"resolved",
"state",
".",
"Send",
"a",
"resolve",
"event",
"when",
"the",
"problem",
"that",
"caused",
"the",
"initial",
"trigger",
"has",
"been",
"fixed",
"."
] | train | https://github.com/dropbox/pygerduty/blob/11b28bfb66306aa7fc2b95ab9df65eb97ea831cf/pygerduty/events.py#L57-L65 |
dropbox/pygerduty | pygerduty/common.py | clean_response | def clean_response(response):
'''Recurse through dictionary and replace any keys "self" with
"self_"'''
if type(response) is list:
for elem in response:
clean_response(elem)
elif type(response) is dict:
for key, val in response.items():
if key == 'self':
val = response.pop('self')
response['self_'] = val
clean_response(val)
else:
clean_response(response[key])
return response | python | def clean_response(response):
'''Recurse through dictionary and replace any keys "self" with
"self_"'''
if type(response) is list:
for elem in response:
clean_response(elem)
elif type(response) is dict:
for key, val in response.items():
if key == 'self':
val = response.pop('self')
response['self_'] = val
clean_response(val)
else:
clean_response(response[key])
return response | [
"def",
"clean_response",
"(",
"response",
")",
":",
"if",
"type",
"(",
"response",
")",
"is",
"list",
":",
"for",
"elem",
"in",
"response",
":",
"clean_response",
"(",
"elem",
")",
"elif",
"type",
"(",
"response",
")",
"is",
"dict",
":",
"for",
"key",
",",
"val",
"in",
"response",
".",
"items",
"(",
")",
":",
"if",
"key",
"==",
"'self'",
":",
"val",
"=",
"response",
".",
"pop",
"(",
"'self'",
")",
"response",
"[",
"'self_'",
"]",
"=",
"val",
"clean_response",
"(",
"val",
")",
"else",
":",
"clean_response",
"(",
"response",
"[",
"key",
"]",
")",
"return",
"response"
] | Recurse through dictionary and replace any keys "self" with
"self_" | [
"Recurse",
"through",
"dictionary",
"and",
"replace",
"any",
"keys",
"self",
"with",
"self_"
] | train | https://github.com/dropbox/pygerduty/blob/11b28bfb66306aa7fc2b95ab9df65eb97ea831cf/pygerduty/common.py#L55-L69 |
dropbox/pygerduty | pygerduty/common.py | _lower | def _lower(string):
"""Custom lower string function.
Examples:
FooBar -> foo_bar
"""
if not string:
return ""
new_string = [string[0].lower()]
for char in string[1:]:
if char.isupper():
new_string.append("_")
new_string.append(char.lower())
return "".join(new_string) | python | def _lower(string):
"""Custom lower string function.
Examples:
FooBar -> foo_bar
"""
if not string:
return ""
new_string = [string[0].lower()]
for char in string[1:]:
if char.isupper():
new_string.append("_")
new_string.append(char.lower())
return "".join(new_string) | [
"def",
"_lower",
"(",
"string",
")",
":",
"if",
"not",
"string",
":",
"return",
"\"\"",
"new_string",
"=",
"[",
"string",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"]",
"for",
"char",
"in",
"string",
"[",
"1",
":",
"]",
":",
"if",
"char",
".",
"isupper",
"(",
")",
":",
"new_string",
".",
"append",
"(",
"\"_\"",
")",
"new_string",
".",
"append",
"(",
"char",
".",
"lower",
"(",
")",
")",
"return",
"\"\"",
".",
"join",
"(",
"new_string",
")"
] | Custom lower string function.
Examples:
FooBar -> foo_bar | [
"Custom",
"lower",
"string",
"function",
".",
"Examples",
":",
"FooBar",
"-",
">",
"foo_bar"
] | train | https://github.com/dropbox/pygerduty/blob/11b28bfb66306aa7fc2b95ab9df65eb97ea831cf/pygerduty/common.py#L72-L86 |
dropbox/pygerduty | pygerduty/__init__.py | Incident.reassign | def reassign(self, user_ids, requester_id):
"""Reassign this incident to a user or list of users
:param user_ids: A non-empty list of user ids
"""
if not user_ids:
raise Error('Must pass at least one user id')
self._do_action('reassign', requester_id=requester_id, assigned_to_user=','.join(user_ids)) | python | def reassign(self, user_ids, requester_id):
"""Reassign this incident to a user or list of users
:param user_ids: A non-empty list of user ids
"""
if not user_ids:
raise Error('Must pass at least one user id')
self._do_action('reassign', requester_id=requester_id, assigned_to_user=','.join(user_ids)) | [
"def",
"reassign",
"(",
"self",
",",
"user_ids",
",",
"requester_id",
")",
":",
"if",
"not",
"user_ids",
":",
"raise",
"Error",
"(",
"'Must pass at least one user id'",
")",
"self",
".",
"_do_action",
"(",
"'reassign'",
",",
"requester_id",
"=",
"requester_id",
",",
"assigned_to_user",
"=",
"','",
".",
"join",
"(",
"user_ids",
")",
")"
] | Reassign this incident to a user or list of users
:param user_ids: A non-empty list of user ids | [
"Reassign",
"this",
"incident",
"to",
"a",
"user",
"or",
"list",
"of",
"users"
] | train | https://github.com/dropbox/pygerduty/blob/11b28bfb66306aa7fc2b95ab9df65eb97ea831cf/pygerduty/__init__.py#L391-L398 |
dropbox/pygerduty | pygerduty/__init__.py | PagerDuty.acknowledge_incident | def acknowledge_incident(self, service_key, incident_key,
description=None, details=None):
""" Causes the referenced incident to enter the acknowledged state.
Send an acknowledge event when someone is presently working on the
incident.
"""
return self.create_event(service_key, description, "acknowledge",
details, incident_key) | python | def acknowledge_incident(self, service_key, incident_key,
description=None, details=None):
""" Causes the referenced incident to enter the acknowledged state.
Send an acknowledge event when someone is presently working on the
incident.
"""
return self.create_event(service_key, description, "acknowledge",
details, incident_key) | [
"def",
"acknowledge_incident",
"(",
"self",
",",
"service_key",
",",
"incident_key",
",",
"description",
"=",
"None",
",",
"details",
"=",
"None",
")",
":",
"return",
"self",
".",
"create_event",
"(",
"service_key",
",",
"description",
",",
"\"acknowledge\"",
",",
"details",
",",
"incident_key",
")"
] | Causes the referenced incident to enter the acknowledged state.
Send an acknowledge event when someone is presently working on the
incident. | [
"Causes",
"the",
"referenced",
"incident",
"to",
"enter",
"the",
"acknowledged",
"state",
".",
"Send",
"an",
"acknowledge",
"event",
"when",
"someone",
"is",
"presently",
"working",
"on",
"the",
"incident",
"."
] | train | https://github.com/dropbox/pygerduty/blob/11b28bfb66306aa7fc2b95ab9df65eb97ea831cf/pygerduty/__init__.py#L573-L581 |
dropbox/pygerduty | pygerduty/__init__.py | PagerDuty.trigger_incident | def trigger_incident(self, service_key, description,
incident_key=None, details=None,
client=None, client_url=None, contexts=None):
""" Report a new or ongoing problem. When PagerDuty receives a trigger,
it will either open a new incident, or add a new log entry to an
existing incident.
"""
return self.create_event(service_key, description, "trigger",
details, incident_key,
client=client, client_url=client_url, contexts=contexts) | python | def trigger_incident(self, service_key, description,
incident_key=None, details=None,
client=None, client_url=None, contexts=None):
""" Report a new or ongoing problem. When PagerDuty receives a trigger,
it will either open a new incident, or add a new log entry to an
existing incident.
"""
return self.create_event(service_key, description, "trigger",
details, incident_key,
client=client, client_url=client_url, contexts=contexts) | [
"def",
"trigger_incident",
"(",
"self",
",",
"service_key",
",",
"description",
",",
"incident_key",
"=",
"None",
",",
"details",
"=",
"None",
",",
"client",
"=",
"None",
",",
"client_url",
"=",
"None",
",",
"contexts",
"=",
"None",
")",
":",
"return",
"self",
".",
"create_event",
"(",
"service_key",
",",
"description",
",",
"\"trigger\"",
",",
"details",
",",
"incident_key",
",",
"client",
"=",
"client",
",",
"client_url",
"=",
"client_url",
",",
"contexts",
"=",
"contexts",
")"
] | Report a new or ongoing problem. When PagerDuty receives a trigger,
it will either open a new incident, or add a new log entry to an
existing incident. | [
"Report",
"a",
"new",
"or",
"ongoing",
"problem",
".",
"When",
"PagerDuty",
"receives",
"a",
"trigger",
"it",
"will",
"either",
"open",
"a",
"new",
"incident",
"or",
"add",
"a",
"new",
"log",
"entry",
"to",
"an",
"existing",
"incident",
"."
] | train | https://github.com/dropbox/pygerduty/blob/11b28bfb66306aa7fc2b95ab9df65eb97ea831cf/pygerduty/__init__.py#L583-L593 |
tanyaschlusser/array2gif | array2gif/core.py | check_dataset | def check_dataset(dataset):
"""Confirm shape (3 colors x rows x cols) and values [0 to 255] are OK."""
if isinstance(dataset, numpy.ndarray) and not len(dataset.shape) == 4:
check_dataset_shape(dataset)
check_dataset_range(dataset)
else: # must be a list of arrays or a 4D NumPy array
for i, d in enumerate(dataset):
if not isinstance(d, numpy.ndarray):
raise ValueError(
'Requires a NumPy array (rgb x rows x cols) '
'with integer values in the range [0, 255].'
)
try:
check_dataset_shape(d)
check_dataset_range(d)
except ValueError as err:
raise ValueError(
'{}\nAt position {} in the list of arrays.'
.format(err, i)
) | python | def check_dataset(dataset):
"""Confirm shape (3 colors x rows x cols) and values [0 to 255] are OK."""
if isinstance(dataset, numpy.ndarray) and not len(dataset.shape) == 4:
check_dataset_shape(dataset)
check_dataset_range(dataset)
else: # must be a list of arrays or a 4D NumPy array
for i, d in enumerate(dataset):
if not isinstance(d, numpy.ndarray):
raise ValueError(
'Requires a NumPy array (rgb x rows x cols) '
'with integer values in the range [0, 255].'
)
try:
check_dataset_shape(d)
check_dataset_range(d)
except ValueError as err:
raise ValueError(
'{}\nAt position {} in the list of arrays.'
.format(err, i)
) | [
"def",
"check_dataset",
"(",
"dataset",
")",
":",
"if",
"isinstance",
"(",
"dataset",
",",
"numpy",
".",
"ndarray",
")",
"and",
"not",
"len",
"(",
"dataset",
".",
"shape",
")",
"==",
"4",
":",
"check_dataset_shape",
"(",
"dataset",
")",
"check_dataset_range",
"(",
"dataset",
")",
"else",
":",
"# must be a list of arrays or a 4D NumPy array",
"for",
"i",
",",
"d",
"in",
"enumerate",
"(",
"dataset",
")",
":",
"if",
"not",
"isinstance",
"(",
"d",
",",
"numpy",
".",
"ndarray",
")",
":",
"raise",
"ValueError",
"(",
"'Requires a NumPy array (rgb x rows x cols) '",
"'with integer values in the range [0, 255].'",
")",
"try",
":",
"check_dataset_shape",
"(",
"d",
")",
"check_dataset_range",
"(",
"d",
")",
"except",
"ValueError",
"as",
"err",
":",
"raise",
"ValueError",
"(",
"'{}\\nAt position {} in the list of arrays.'",
".",
"format",
"(",
"err",
",",
"i",
")",
")"
] | Confirm shape (3 colors x rows x cols) and values [0 to 255] are OK. | [
"Confirm",
"shape",
"(",
"3",
"colors",
"x",
"rows",
"x",
"cols",
")",
"and",
"values",
"[",
"0",
"to",
"255",
"]",
"are",
"OK",
"."
] | train | https://github.com/tanyaschlusser/array2gif/blob/b229da6c8e979314810f59ed0a15ea0f16f71243/array2gif/core.py#L55-L74 |
tanyaschlusser/array2gif | array2gif/core.py | try_fix_dataset | def try_fix_dataset(dataset):
"""Transpose the image data if it's in PIL format."""
if isinstance(dataset, numpy.ndarray):
if len(dataset.shape) == 3: # NumPy 3D
if dataset.shape[-1] == 3:
return dataset.transpose((2, 0, 1))
elif len(dataset.shape) == 4: # NumPy 4D
if dataset.shape[-1] == 3:
return dataset.transpose((0, 3, 1, 2))
# Otherwise couldn't fix it.
return dataset
# List of Numpy 3D arrays.
for i, d in enumerate(dataset):
if not isinstance(d, numpy.ndarray):
return dataset
if not (len(d.shape) == 3 and d.shape[-1] == 3):
return dataset
dataset[i] = d.transpose()
return dataset | python | def try_fix_dataset(dataset):
"""Transpose the image data if it's in PIL format."""
if isinstance(dataset, numpy.ndarray):
if len(dataset.shape) == 3: # NumPy 3D
if dataset.shape[-1] == 3:
return dataset.transpose((2, 0, 1))
elif len(dataset.shape) == 4: # NumPy 4D
if dataset.shape[-1] == 3:
return dataset.transpose((0, 3, 1, 2))
# Otherwise couldn't fix it.
return dataset
# List of Numpy 3D arrays.
for i, d in enumerate(dataset):
if not isinstance(d, numpy.ndarray):
return dataset
if not (len(d.shape) == 3 and d.shape[-1] == 3):
return dataset
dataset[i] = d.transpose()
return dataset | [
"def",
"try_fix_dataset",
"(",
"dataset",
")",
":",
"if",
"isinstance",
"(",
"dataset",
",",
"numpy",
".",
"ndarray",
")",
":",
"if",
"len",
"(",
"dataset",
".",
"shape",
")",
"==",
"3",
":",
"# NumPy 3D",
"if",
"dataset",
".",
"shape",
"[",
"-",
"1",
"]",
"==",
"3",
":",
"return",
"dataset",
".",
"transpose",
"(",
"(",
"2",
",",
"0",
",",
"1",
")",
")",
"elif",
"len",
"(",
"dataset",
".",
"shape",
")",
"==",
"4",
":",
"# NumPy 4D",
"if",
"dataset",
".",
"shape",
"[",
"-",
"1",
"]",
"==",
"3",
":",
"return",
"dataset",
".",
"transpose",
"(",
"(",
"0",
",",
"3",
",",
"1",
",",
"2",
")",
")",
"# Otherwise couldn't fix it.",
"return",
"dataset",
"# List of Numpy 3D arrays.",
"for",
"i",
",",
"d",
"in",
"enumerate",
"(",
"dataset",
")",
":",
"if",
"not",
"isinstance",
"(",
"d",
",",
"numpy",
".",
"ndarray",
")",
":",
"return",
"dataset",
"if",
"not",
"(",
"len",
"(",
"d",
".",
"shape",
")",
"==",
"3",
"and",
"d",
".",
"shape",
"[",
"-",
"1",
"]",
"==",
"3",
")",
":",
"return",
"dataset",
"dataset",
"[",
"i",
"]",
"=",
"d",
".",
"transpose",
"(",
")",
"return",
"dataset"
] | Transpose the image data if it's in PIL format. | [
"Transpose",
"the",
"image",
"data",
"if",
"it",
"s",
"in",
"PIL",
"format",
"."
] | train | https://github.com/tanyaschlusser/array2gif/blob/b229da6c8e979314810f59ed0a15ea0f16f71243/array2gif/core.py#L77-L95 |
tanyaschlusser/array2gif | array2gif/core.py | get_image | def get_image(dataset):
"""Convert the NumPy array to two nested lists with r,g,b tuples."""
dim, nrow, ncol = dataset.shape
uint8_dataset = dataset.astype('uint8')
if not (uint8_dataset == dataset).all():
message = (
"\nYour image was cast to a `uint8` (`<img>.astype(uint8)`), "
"but some information was lost.\nPlease check your gif and "
"convert to uint8 beforehand if the gif looks wrong."
)
warnings.warn(message)
image = [[
struct.pack(
'BBB',
uint8_dataset[0, i, j],
uint8_dataset[1, i, j],
uint8_dataset[2, i, j]
)
for j in range(ncol)]
for i in range(nrow)]
return image | python | def get_image(dataset):
"""Convert the NumPy array to two nested lists with r,g,b tuples."""
dim, nrow, ncol = dataset.shape
uint8_dataset = dataset.astype('uint8')
if not (uint8_dataset == dataset).all():
message = (
"\nYour image was cast to a `uint8` (`<img>.astype(uint8)`), "
"but some information was lost.\nPlease check your gif and "
"convert to uint8 beforehand if the gif looks wrong."
)
warnings.warn(message)
image = [[
struct.pack(
'BBB',
uint8_dataset[0, i, j],
uint8_dataset[1, i, j],
uint8_dataset[2, i, j]
)
for j in range(ncol)]
for i in range(nrow)]
return image | [
"def",
"get_image",
"(",
"dataset",
")",
":",
"dim",
",",
"nrow",
",",
"ncol",
"=",
"dataset",
".",
"shape",
"uint8_dataset",
"=",
"dataset",
".",
"astype",
"(",
"'uint8'",
")",
"if",
"not",
"(",
"uint8_dataset",
"==",
"dataset",
")",
".",
"all",
"(",
")",
":",
"message",
"=",
"(",
"\"\\nYour image was cast to a `uint8` (`<img>.astype(uint8)`), \"",
"\"but some information was lost.\\nPlease check your gif and \"",
"\"convert to uint8 beforehand if the gif looks wrong.\"",
")",
"warnings",
".",
"warn",
"(",
"message",
")",
"image",
"=",
"[",
"[",
"struct",
".",
"pack",
"(",
"'BBB'",
",",
"uint8_dataset",
"[",
"0",
",",
"i",
",",
"j",
"]",
",",
"uint8_dataset",
"[",
"1",
",",
"i",
",",
"j",
"]",
",",
"uint8_dataset",
"[",
"2",
",",
"i",
",",
"j",
"]",
")",
"for",
"j",
"in",
"range",
"(",
"ncol",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"nrow",
")",
"]",
"return",
"image"
] | Convert the NumPy array to two nested lists with r,g,b tuples. | [
"Convert",
"the",
"NumPy",
"array",
"to",
"two",
"nested",
"lists",
"with",
"r",
"g",
"b",
"tuples",
"."
] | train | https://github.com/tanyaschlusser/array2gif/blob/b229da6c8e979314810f59ed0a15ea0f16f71243/array2gif/core.py#L98-L118 |
tanyaschlusser/array2gif | array2gif/core.py | get_color_table_size | def get_color_table_size(num_colors):
"""Total values in the color table is 2**(1 + int(result, base=2)).
The result is a three-bit value (represented as a string with
ones or zeros) that will become part of a packed byte encoding
various details about the color table, used in the Logical
Screen Descriptor block.
"""
nbits = max(math.ceil(math.log(num_colors, 2)), 2)
return '{:03b}'.format(int(nbits - 1)) | python | def get_color_table_size(num_colors):
"""Total values in the color table is 2**(1 + int(result, base=2)).
The result is a three-bit value (represented as a string with
ones or zeros) that will become part of a packed byte encoding
various details about the color table, used in the Logical
Screen Descriptor block.
"""
nbits = max(math.ceil(math.log(num_colors, 2)), 2)
return '{:03b}'.format(int(nbits - 1)) | [
"def",
"get_color_table_size",
"(",
"num_colors",
")",
":",
"nbits",
"=",
"max",
"(",
"math",
".",
"ceil",
"(",
"math",
".",
"log",
"(",
"num_colors",
",",
"2",
")",
")",
",",
"2",
")",
"return",
"'{:03b}'",
".",
"format",
"(",
"int",
"(",
"nbits",
"-",
"1",
")",
")"
] | Total values in the color table is 2**(1 + int(result, base=2)).
The result is a three-bit value (represented as a string with
ones or zeros) that will become part of a packed byte encoding
various details about the color table, used in the Logical
Screen Descriptor block. | [
"Total",
"values",
"in",
"the",
"color",
"table",
"is",
"2",
"**",
"(",
"1",
"+",
"int",
"(",
"result",
"base",
"=",
"2",
"))",
"."
] | train | https://github.com/tanyaschlusser/array2gif/blob/b229da6c8e979314810f59ed0a15ea0f16f71243/array2gif/core.py#L122-L131 |
tanyaschlusser/array2gif | array2gif/core.py | get_colors | def get_colors(image):
"""Return a Counter containing each color and how often it appears.
"""
colors = Counter(pixel for row in image for pixel in row)
if len(colors) > 256:
msg = (
"The maximum number of distinct colors in a GIF is 256 but "
"this image has {} colors and can't be encoded properly."
)
raise RuntimeError(msg.format(len(colors)))
return colors | python | def get_colors(image):
"""Return a Counter containing each color and how often it appears.
"""
colors = Counter(pixel for row in image for pixel in row)
if len(colors) > 256:
msg = (
"The maximum number of distinct colors in a GIF is 256 but "
"this image has {} colors and can't be encoded properly."
)
raise RuntimeError(msg.format(len(colors)))
return colors | [
"def",
"get_colors",
"(",
"image",
")",
":",
"colors",
"=",
"Counter",
"(",
"pixel",
"for",
"row",
"in",
"image",
"for",
"pixel",
"in",
"row",
")",
"if",
"len",
"(",
"colors",
")",
">",
"256",
":",
"msg",
"=",
"(",
"\"The maximum number of distinct colors in a GIF is 256 but \"",
"\"this image has {} colors and can't be encoded properly.\"",
")",
"raise",
"RuntimeError",
"(",
"msg",
".",
"format",
"(",
"len",
"(",
"colors",
")",
")",
")",
"return",
"colors"
] | Return a Counter containing each color and how often it appears. | [
"Return",
"a",
"Counter",
"containing",
"each",
"color",
"and",
"how",
"often",
"it",
"appears",
"."
] | train | https://github.com/tanyaschlusser/array2gif/blob/b229da6c8e979314810f59ed0a15ea0f16f71243/array2gif/core.py#L167-L177 |
tanyaschlusser/array2gif | array2gif/core.py | _get_global_color_table | def _get_global_color_table(colors):
"""Return a color table sorted in descending order of count.
"""
global_color_table = b''.join(c[0] for c in colors.most_common())
full_table_size = 2**(1+int(get_color_table_size(len(colors)), 2))
repeats = 3 * (full_table_size - len(colors))
zeros = struct.pack('<{}x'.format(repeats))
return global_color_table + zeros | python | def _get_global_color_table(colors):
"""Return a color table sorted in descending order of count.
"""
global_color_table = b''.join(c[0] for c in colors.most_common())
full_table_size = 2**(1+int(get_color_table_size(len(colors)), 2))
repeats = 3 * (full_table_size - len(colors))
zeros = struct.pack('<{}x'.format(repeats))
return global_color_table + zeros | [
"def",
"_get_global_color_table",
"(",
"colors",
")",
":",
"global_color_table",
"=",
"b''",
".",
"join",
"(",
"c",
"[",
"0",
"]",
"for",
"c",
"in",
"colors",
".",
"most_common",
"(",
")",
")",
"full_table_size",
"=",
"2",
"**",
"(",
"1",
"+",
"int",
"(",
"get_color_table_size",
"(",
"len",
"(",
"colors",
")",
")",
",",
"2",
")",
")",
"repeats",
"=",
"3",
"*",
"(",
"full_table_size",
"-",
"len",
"(",
"colors",
")",
")",
"zeros",
"=",
"struct",
".",
"pack",
"(",
"'<{}x'",
".",
"format",
"(",
"repeats",
")",
")",
"return",
"global_color_table",
"+",
"zeros"
] | Return a color table sorted in descending order of count. | [
"Return",
"a",
"color",
"table",
"sorted",
"in",
"descending",
"order",
"of",
"count",
"."
] | train | https://github.com/tanyaschlusser/array2gif/blob/b229da6c8e979314810f59ed0a15ea0f16f71243/array2gif/core.py#L180-L187 |
tanyaschlusser/array2gif | array2gif/core.py | _get_image_data | def _get_image_data(image, colors):
"""Performs the LZW compression as described by Matthew Flickinger.
This isn't fast, but it works.
http://www.matthewflickinger.com/lab/whatsinagif/lzw_image_data.asp
"""
lzw_code_size, coded_bits = _lzw_encode(image, colors)
coded_bytes = ''.join(
'{{:0{}b}}'.format(nbits).format(val) for val, nbits in coded_bits)
coded_bytes = '0' * ((8 - len(coded_bytes)) % 8) + coded_bytes
coded_data = list(
reversed([
int(coded_bytes[8*i:8*(i+1)], 2)
for i in range(len(coded_bytes) // 8)
])
)
output = [struct.pack('<B', lzw_code_size)]
# Must output the data in blocks of length 255
block_length = min(255, len(coded_data))
while block_length > 0:
block = struct.pack(
'<{}B'.format(block_length + 1),
block_length,
*coded_data[:block_length]
)
output.append(block)
coded_data = coded_data[block_length:]
block_length = min(255, len(coded_data))
return b''.join(output) | python | def _get_image_data(image, colors):
"""Performs the LZW compression as described by Matthew Flickinger.
This isn't fast, but it works.
http://www.matthewflickinger.com/lab/whatsinagif/lzw_image_data.asp
"""
lzw_code_size, coded_bits = _lzw_encode(image, colors)
coded_bytes = ''.join(
'{{:0{}b}}'.format(nbits).format(val) for val, nbits in coded_bits)
coded_bytes = '0' * ((8 - len(coded_bytes)) % 8) + coded_bytes
coded_data = list(
reversed([
int(coded_bytes[8*i:8*(i+1)], 2)
for i in range(len(coded_bytes) // 8)
])
)
output = [struct.pack('<B', lzw_code_size)]
# Must output the data in blocks of length 255
block_length = min(255, len(coded_data))
while block_length > 0:
block = struct.pack(
'<{}B'.format(block_length + 1),
block_length,
*coded_data[:block_length]
)
output.append(block)
coded_data = coded_data[block_length:]
block_length = min(255, len(coded_data))
return b''.join(output) | [
"def",
"_get_image_data",
"(",
"image",
",",
"colors",
")",
":",
"lzw_code_size",
",",
"coded_bits",
"=",
"_lzw_encode",
"(",
"image",
",",
"colors",
")",
"coded_bytes",
"=",
"''",
".",
"join",
"(",
"'{{:0{}b}}'",
".",
"format",
"(",
"nbits",
")",
".",
"format",
"(",
"val",
")",
"for",
"val",
",",
"nbits",
"in",
"coded_bits",
")",
"coded_bytes",
"=",
"'0'",
"*",
"(",
"(",
"8",
"-",
"len",
"(",
"coded_bytes",
")",
")",
"%",
"8",
")",
"+",
"coded_bytes",
"coded_data",
"=",
"list",
"(",
"reversed",
"(",
"[",
"int",
"(",
"coded_bytes",
"[",
"8",
"*",
"i",
":",
"8",
"*",
"(",
"i",
"+",
"1",
")",
"]",
",",
"2",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"coded_bytes",
")",
"//",
"8",
")",
"]",
")",
")",
"output",
"=",
"[",
"struct",
".",
"pack",
"(",
"'<B'",
",",
"lzw_code_size",
")",
"]",
"# Must output the data in blocks of length 255",
"block_length",
"=",
"min",
"(",
"255",
",",
"len",
"(",
"coded_data",
")",
")",
"while",
"block_length",
">",
"0",
":",
"block",
"=",
"struct",
".",
"pack",
"(",
"'<{}B'",
".",
"format",
"(",
"block_length",
"+",
"1",
")",
",",
"block_length",
",",
"*",
"coded_data",
"[",
":",
"block_length",
"]",
")",
"output",
".",
"append",
"(",
"block",
")",
"coded_data",
"=",
"coded_data",
"[",
"block_length",
":",
"]",
"block_length",
"=",
"min",
"(",
"255",
",",
"len",
"(",
"coded_data",
")",
")",
"return",
"b''",
".",
"join",
"(",
"output",
")"
] | Performs the LZW compression as described by Matthew Flickinger.
This isn't fast, but it works.
http://www.matthewflickinger.com/lab/whatsinagif/lzw_image_data.asp | [
"Performs",
"the",
"LZW",
"compression",
"as",
"described",
"by",
"Matthew",
"Flickinger",
"."
] | train | https://github.com/tanyaschlusser/array2gif/blob/b229da6c8e979314810f59ed0a15ea0f16f71243/array2gif/core.py#L311-L339 |
tanyaschlusser/array2gif | array2gif/core.py | write_gif | def write_gif(dataset, filename, fps=10):
"""Write a NumPy array to GIF 89a format.
Or write a list of NumPy arrays to an animation (GIF 89a format).
- Positional arguments::
:param dataset: A NumPy arrayor list of arrays with shape
rgb x rows x cols and integer values in [0, 255].
:param filename: The output file that will contain the GIF image.
:param fps: The (integer) frames/second of the animation (default 10).
:type dataset: a NumPy array or list of NumPy arrays.
:return: None
- Example: a minimal array, with one red pixel, would look like this::
import numpy as np
one_red_pixel = np.array([[[255]], [[0]], [[0]]])
write_gif(one_red_pixel, 'red_pixel.gif')
..raises:: ValueError
"""
try:
check_dataset(dataset)
except ValueError as e:
dataset = try_fix_dataset(dataset)
check_dataset(dataset)
delay_time = 100 // int(fps)
def encode(d):
four_d = isinstance(dataset, numpy.ndarray) and len(dataset.shape) == 4
if four_d or not isinstance(dataset, numpy.ndarray):
return _make_animated_gif(d, delay_time=delay_time)
else:
return _make_gif(d)
with open(filename, 'wb') as outfile:
outfile.write(HEADER)
for block in encode(dataset):
outfile.write(block)
outfile.write(TRAILER) | python | def write_gif(dataset, filename, fps=10):
"""Write a NumPy array to GIF 89a format.
Or write a list of NumPy arrays to an animation (GIF 89a format).
- Positional arguments::
:param dataset: A NumPy arrayor list of arrays with shape
rgb x rows x cols and integer values in [0, 255].
:param filename: The output file that will contain the GIF image.
:param fps: The (integer) frames/second of the animation (default 10).
:type dataset: a NumPy array or list of NumPy arrays.
:return: None
- Example: a minimal array, with one red pixel, would look like this::
import numpy as np
one_red_pixel = np.array([[[255]], [[0]], [[0]]])
write_gif(one_red_pixel, 'red_pixel.gif')
..raises:: ValueError
"""
try:
check_dataset(dataset)
except ValueError as e:
dataset = try_fix_dataset(dataset)
check_dataset(dataset)
delay_time = 100 // int(fps)
def encode(d):
four_d = isinstance(dataset, numpy.ndarray) and len(dataset.shape) == 4
if four_d or not isinstance(dataset, numpy.ndarray):
return _make_animated_gif(d, delay_time=delay_time)
else:
return _make_gif(d)
with open(filename, 'wb') as outfile:
outfile.write(HEADER)
for block in encode(dataset):
outfile.write(block)
outfile.write(TRAILER) | [
"def",
"write_gif",
"(",
"dataset",
",",
"filename",
",",
"fps",
"=",
"10",
")",
":",
"try",
":",
"check_dataset",
"(",
"dataset",
")",
"except",
"ValueError",
"as",
"e",
":",
"dataset",
"=",
"try_fix_dataset",
"(",
"dataset",
")",
"check_dataset",
"(",
"dataset",
")",
"delay_time",
"=",
"100",
"//",
"int",
"(",
"fps",
")",
"def",
"encode",
"(",
"d",
")",
":",
"four_d",
"=",
"isinstance",
"(",
"dataset",
",",
"numpy",
".",
"ndarray",
")",
"and",
"len",
"(",
"dataset",
".",
"shape",
")",
"==",
"4",
"if",
"four_d",
"or",
"not",
"isinstance",
"(",
"dataset",
",",
"numpy",
".",
"ndarray",
")",
":",
"return",
"_make_animated_gif",
"(",
"d",
",",
"delay_time",
"=",
"delay_time",
")",
"else",
":",
"return",
"_make_gif",
"(",
"d",
")",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"outfile",
":",
"outfile",
".",
"write",
"(",
"HEADER",
")",
"for",
"block",
"in",
"encode",
"(",
"dataset",
")",
":",
"outfile",
".",
"write",
"(",
"block",
")",
"outfile",
".",
"write",
"(",
"TRAILER",
")"
] | Write a NumPy array to GIF 89a format.
Or write a list of NumPy arrays to an animation (GIF 89a format).
- Positional arguments::
:param dataset: A NumPy arrayor list of arrays with shape
rgb x rows x cols and integer values in [0, 255].
:param filename: The output file that will contain the GIF image.
:param fps: The (integer) frames/second of the animation (default 10).
:type dataset: a NumPy array or list of NumPy arrays.
:return: None
- Example: a minimal array, with one red pixel, would look like this::
import numpy as np
one_red_pixel = np.array([[[255]], [[0]], [[0]]])
write_gif(one_red_pixel, 'red_pixel.gif')
..raises:: ValueError | [
"Write",
"a",
"NumPy",
"array",
"to",
"GIF",
"89a",
"format",
"."
] | train | https://github.com/tanyaschlusser/array2gif/blob/b229da6c8e979314810f59ed0a15ea0f16f71243/array2gif/core.py#L386-L426 |
mstuttgart/qdarkgraystyle | example/example_pyqt5.py | main | def main():
"""
Application entry point
"""
logging.basicConfig(level=logging.DEBUG)
# create the application and the main window
app = QtWidgets.QApplication(sys.argv)
window = QtWidgets.QMainWindow()
# setup ui
ui = example_ui.Ui_MainWindow()
ui.setupUi(window)
ui.bt_delay_popup.addActions([
ui.actionAction,
ui.actionAction_C
])
ui.bt_instant_popup.addActions([
ui.actionAction,
ui.actionAction_C
])
ui.bt_menu_button_popup.addActions([
ui.actionAction,
ui.actionAction_C
])
window.setWindowTitle('QDarkGrayStyle example')
# tabify dock widgets to show bug #6
window.tabifyDockWidget(ui.dockWidget1, ui.dockWidget2)
# setup stylesheet
app.setStyleSheet(qdarkgraystyle.load_stylesheet())
# auto quit after 2s when testing on travis-ci
if '--travis' in sys.argv:
QtCore.QTimer.singleShot(2000, app.exit)
# run
window.show()
app.exec_() | python | def main():
"""
Application entry point
"""
logging.basicConfig(level=logging.DEBUG)
# create the application and the main window
app = QtWidgets.QApplication(sys.argv)
window = QtWidgets.QMainWindow()
# setup ui
ui = example_ui.Ui_MainWindow()
ui.setupUi(window)
ui.bt_delay_popup.addActions([
ui.actionAction,
ui.actionAction_C
])
ui.bt_instant_popup.addActions([
ui.actionAction,
ui.actionAction_C
])
ui.bt_menu_button_popup.addActions([
ui.actionAction,
ui.actionAction_C
])
window.setWindowTitle('QDarkGrayStyle example')
# tabify dock widgets to show bug #6
window.tabifyDockWidget(ui.dockWidget1, ui.dockWidget2)
# setup stylesheet
app.setStyleSheet(qdarkgraystyle.load_stylesheet())
# auto quit after 2s when testing on travis-ci
if '--travis' in sys.argv:
QtCore.QTimer.singleShot(2000, app.exit)
# run
window.show()
app.exec_() | [
"def",
"main",
"(",
")",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
")",
"# create the application and the main window",
"app",
"=",
"QtWidgets",
".",
"QApplication",
"(",
"sys",
".",
"argv",
")",
"window",
"=",
"QtWidgets",
".",
"QMainWindow",
"(",
")",
"# setup ui",
"ui",
"=",
"example_ui",
".",
"Ui_MainWindow",
"(",
")",
"ui",
".",
"setupUi",
"(",
"window",
")",
"ui",
".",
"bt_delay_popup",
".",
"addActions",
"(",
"[",
"ui",
".",
"actionAction",
",",
"ui",
".",
"actionAction_C",
"]",
")",
"ui",
".",
"bt_instant_popup",
".",
"addActions",
"(",
"[",
"ui",
".",
"actionAction",
",",
"ui",
".",
"actionAction_C",
"]",
")",
"ui",
".",
"bt_menu_button_popup",
".",
"addActions",
"(",
"[",
"ui",
".",
"actionAction",
",",
"ui",
".",
"actionAction_C",
"]",
")",
"window",
".",
"setWindowTitle",
"(",
"'QDarkGrayStyle example'",
")",
"# tabify dock widgets to show bug #6",
"window",
".",
"tabifyDockWidget",
"(",
"ui",
".",
"dockWidget1",
",",
"ui",
".",
"dockWidget2",
")",
"# setup stylesheet",
"app",
".",
"setStyleSheet",
"(",
"qdarkgraystyle",
".",
"load_stylesheet",
"(",
")",
")",
"# auto quit after 2s when testing on travis-ci",
"if",
"'--travis'",
"in",
"sys",
".",
"argv",
":",
"QtCore",
".",
"QTimer",
".",
"singleShot",
"(",
"2000",
",",
"app",
".",
"exit",
")",
"# run",
"window",
".",
"show",
"(",
")",
"app",
".",
"exec_",
"(",
")"
] | Application entry point | [
"Application",
"entry",
"point"
] | train | https://github.com/mstuttgart/qdarkgraystyle/blob/d65182cfe4510fc507e80bfe974dd7faa5429cf0/example/example_pyqt5.py#L51-L89 |
mstuttgart/qdarkgraystyle | qdarkgraystyle/__init__.py | load_stylesheet | def load_stylesheet():
"""
Loads the stylesheet for use in a pyqt5 application.
:return the stylesheet string
"""
# Smart import of the rc file
f = QtCore.QFile(':qdarkgraystyle/style.qss')
if not f.exists():
_logger().error('Unable to load stylesheet, file not found in '
'resources')
return ''
else:
f.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text)
ts = QtCore.QTextStream(f)
stylesheet = ts.readAll()
if platform.system().lower() == 'darwin': # see issue #12 on github
mac_fix = '''
QDockWidget::title
{
background-color: #31363b;
text-align: center;
height: 12px;
}
'''
stylesheet += mac_fix
return stylesheet | python | def load_stylesheet():
"""
Loads the stylesheet for use in a pyqt5 application.
:return the stylesheet string
"""
# Smart import of the rc file
f = QtCore.QFile(':qdarkgraystyle/style.qss')
if not f.exists():
_logger().error('Unable to load stylesheet, file not found in '
'resources')
return ''
else:
f.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text)
ts = QtCore.QTextStream(f)
stylesheet = ts.readAll()
if platform.system().lower() == 'darwin': # see issue #12 on github
mac_fix = '''
QDockWidget::title
{
background-color: #31363b;
text-align: center;
height: 12px;
}
'''
stylesheet += mac_fix
return stylesheet | [
"def",
"load_stylesheet",
"(",
")",
":",
"# Smart import of the rc file",
"f",
"=",
"QtCore",
".",
"QFile",
"(",
"':qdarkgraystyle/style.qss'",
")",
"if",
"not",
"f",
".",
"exists",
"(",
")",
":",
"_logger",
"(",
")",
".",
"error",
"(",
"'Unable to load stylesheet, file not found in '",
"'resources'",
")",
"return",
"''",
"else",
":",
"f",
".",
"open",
"(",
"QtCore",
".",
"QFile",
".",
"ReadOnly",
"|",
"QtCore",
".",
"QFile",
".",
"Text",
")",
"ts",
"=",
"QtCore",
".",
"QTextStream",
"(",
"f",
")",
"stylesheet",
"=",
"ts",
".",
"readAll",
"(",
")",
"if",
"platform",
".",
"system",
"(",
")",
".",
"lower",
"(",
")",
"==",
"'darwin'",
":",
"# see issue #12 on github",
"mac_fix",
"=",
"'''\n QDockWidget::title\n {\n background-color: #31363b;\n text-align: center;\n height: 12px;\n }\n '''",
"stylesheet",
"+=",
"mac_fix",
"return",
"stylesheet"
] | Loads the stylesheet for use in a pyqt5 application.
:return the stylesheet string | [
"Loads",
"the",
"stylesheet",
"for",
"use",
"in",
"a",
"pyqt5",
"application",
".",
":",
"return",
"the",
"stylesheet",
"string"
] | train | https://github.com/mstuttgart/qdarkgraystyle/blob/d65182cfe4510fc507e80bfe974dd7faa5429cf0/qdarkgraystyle/__init__.py#L48-L74 |
hovren/crisp | crisp/timesync.py | sync_camera_gyro | def sync_camera_gyro(image_sequence_or_flow, image_timestamps, gyro_data, gyro_timestamps, levels=6, full_output=False):
"""Get time offset that aligns image timestamps with gyro timestamps.
Given an image sequence, and gyroscope data, with their respective timestamps,
calculate the offset that aligns the image data with the gyro data.
The timestamps must only differ by an offset, not a scale factor.
This function finds an approximation of the offset *d* that makes this transformation
t_gyro = t_camera + d
i.e. your new image timestamps should be
image_timestamps_aligned = image_timestamps + d
The offset is calculated using zero-mean cross correlation of the gyroscope data magnitude
and the optical flow magnitude, calculated from the image sequence.
ZNCC is performed using pyramids to make it quick.
The offset is accurate up to about +/- 2 frames, so you should run
*refine_time_offset* if you need better accuracy.
Parameters
---------------
image_sequence_or_flow : sequence of image data, or ndarray
This must be either a list or generator that provides a stream of
images that are used for optical flow calculations.
image_timestamps : ndarray
Timestamps of the images in image_sequence
gyro_data : (3, N) ndarray
Gyroscope measurements (angular velocity)
gyro_timestamps : ndarray
Timestamps of data in gyro_data
levels : int
Number of pyramid levels
full_output : bool
If False, only return the offset, otherwise return extra data
Returns
--------------
time_offset : float
The time offset to add to image_timestamps to align the image data
with the gyroscope data
flow : ndarray
(Only if full_output=True)
The calculated optical flow magnitude
"""
# If input is not flow, then create from iamge sequence
try:
assert image_sequence_or_flow.ndim == 1
flow_org = image_sequence_or_flow
except AssertionError:
flow_org = tracking.optical_flow_magnitude(image_sequence_or_flow)
# Gyro from gyro data
gyro_mag = np.sum(gyro_data**2, axis=0)
flow_timestamps = image_timestamps[:-2]
# Resample to match highest
rate = lambda ts: len(ts) / (ts[-1] - ts[0])
freq_gyro = rate(gyro_timestamps)
freq_image = rate(flow_timestamps)
if freq_gyro > freq_image:
rel_rate = freq_gyro / freq_image
flow_mag = znccpyr.upsample(flow_org, rel_rate)
else:
flow_mag = flow_org
rel_rate = freq_image / freq_gyro
gyro_mag = znccpyr.upsample(gyro_mag, rel_rate)
ishift = znccpyr.find_shift_pyr(flow_mag, gyro_mag, levels)
if freq_gyro > freq_image:
flow_shift = int(-ishift / rel_rate)
else:
flow_shift = int(-ishift)
time_offset = flow_timestamps[flow_shift]
if full_output:
return time_offset, flow_org # Return the orginal flow, not the upsampled version
else:
return time_offset | python | def sync_camera_gyro(image_sequence_or_flow, image_timestamps, gyro_data, gyro_timestamps, levels=6, full_output=False):
"""Get time offset that aligns image timestamps with gyro timestamps.
Given an image sequence, and gyroscope data, with their respective timestamps,
calculate the offset that aligns the image data with the gyro data.
The timestamps must only differ by an offset, not a scale factor.
This function finds an approximation of the offset *d* that makes this transformation
t_gyro = t_camera + d
i.e. your new image timestamps should be
image_timestamps_aligned = image_timestamps + d
The offset is calculated using zero-mean cross correlation of the gyroscope data magnitude
and the optical flow magnitude, calculated from the image sequence.
ZNCC is performed using pyramids to make it quick.
The offset is accurate up to about +/- 2 frames, so you should run
*refine_time_offset* if you need better accuracy.
Parameters
---------------
image_sequence_or_flow : sequence of image data, or ndarray
This must be either a list or generator that provides a stream of
images that are used for optical flow calculations.
image_timestamps : ndarray
Timestamps of the images in image_sequence
gyro_data : (3, N) ndarray
Gyroscope measurements (angular velocity)
gyro_timestamps : ndarray
Timestamps of data in gyro_data
levels : int
Number of pyramid levels
full_output : bool
If False, only return the offset, otherwise return extra data
Returns
--------------
time_offset : float
The time offset to add to image_timestamps to align the image data
with the gyroscope data
flow : ndarray
(Only if full_output=True)
The calculated optical flow magnitude
"""
# If input is not flow, then create from iamge sequence
try:
assert image_sequence_or_flow.ndim == 1
flow_org = image_sequence_or_flow
except AssertionError:
flow_org = tracking.optical_flow_magnitude(image_sequence_or_flow)
# Gyro from gyro data
gyro_mag = np.sum(gyro_data**2, axis=0)
flow_timestamps = image_timestamps[:-2]
# Resample to match highest
rate = lambda ts: len(ts) / (ts[-1] - ts[0])
freq_gyro = rate(gyro_timestamps)
freq_image = rate(flow_timestamps)
if freq_gyro > freq_image:
rel_rate = freq_gyro / freq_image
flow_mag = znccpyr.upsample(flow_org, rel_rate)
else:
flow_mag = flow_org
rel_rate = freq_image / freq_gyro
gyro_mag = znccpyr.upsample(gyro_mag, rel_rate)
ishift = znccpyr.find_shift_pyr(flow_mag, gyro_mag, levels)
if freq_gyro > freq_image:
flow_shift = int(-ishift / rel_rate)
else:
flow_shift = int(-ishift)
time_offset = flow_timestamps[flow_shift]
if full_output:
return time_offset, flow_org # Return the orginal flow, not the upsampled version
else:
return time_offset | [
"def",
"sync_camera_gyro",
"(",
"image_sequence_or_flow",
",",
"image_timestamps",
",",
"gyro_data",
",",
"gyro_timestamps",
",",
"levels",
"=",
"6",
",",
"full_output",
"=",
"False",
")",
":",
"# If input is not flow, then create from iamge sequence",
"try",
":",
"assert",
"image_sequence_or_flow",
".",
"ndim",
"==",
"1",
"flow_org",
"=",
"image_sequence_or_flow",
"except",
"AssertionError",
":",
"flow_org",
"=",
"tracking",
".",
"optical_flow_magnitude",
"(",
"image_sequence_or_flow",
")",
"# Gyro from gyro data",
"gyro_mag",
"=",
"np",
".",
"sum",
"(",
"gyro_data",
"**",
"2",
",",
"axis",
"=",
"0",
")",
"flow_timestamps",
"=",
"image_timestamps",
"[",
":",
"-",
"2",
"]",
"# Resample to match highest",
"rate",
"=",
"lambda",
"ts",
":",
"len",
"(",
"ts",
")",
"/",
"(",
"ts",
"[",
"-",
"1",
"]",
"-",
"ts",
"[",
"0",
"]",
")",
"freq_gyro",
"=",
"rate",
"(",
"gyro_timestamps",
")",
"freq_image",
"=",
"rate",
"(",
"flow_timestamps",
")",
"if",
"freq_gyro",
">",
"freq_image",
":",
"rel_rate",
"=",
"freq_gyro",
"/",
"freq_image",
"flow_mag",
"=",
"znccpyr",
".",
"upsample",
"(",
"flow_org",
",",
"rel_rate",
")",
"else",
":",
"flow_mag",
"=",
"flow_org",
"rel_rate",
"=",
"freq_image",
"/",
"freq_gyro",
"gyro_mag",
"=",
"znccpyr",
".",
"upsample",
"(",
"gyro_mag",
",",
"rel_rate",
")",
"ishift",
"=",
"znccpyr",
".",
"find_shift_pyr",
"(",
"flow_mag",
",",
"gyro_mag",
",",
"levels",
")",
"if",
"freq_gyro",
">",
"freq_image",
":",
"flow_shift",
"=",
"int",
"(",
"-",
"ishift",
"/",
"rel_rate",
")",
"else",
":",
"flow_shift",
"=",
"int",
"(",
"-",
"ishift",
")",
"time_offset",
"=",
"flow_timestamps",
"[",
"flow_shift",
"]",
"if",
"full_output",
":",
"return",
"time_offset",
",",
"flow_org",
"# Return the orginal flow, not the upsampled version",
"else",
":",
"return",
"time_offset"
] | Get time offset that aligns image timestamps with gyro timestamps.
Given an image sequence, and gyroscope data, with their respective timestamps,
calculate the offset that aligns the image data with the gyro data.
The timestamps must only differ by an offset, not a scale factor.
This function finds an approximation of the offset *d* that makes this transformation
t_gyro = t_camera + d
i.e. your new image timestamps should be
image_timestamps_aligned = image_timestamps + d
The offset is calculated using zero-mean cross correlation of the gyroscope data magnitude
and the optical flow magnitude, calculated from the image sequence.
ZNCC is performed using pyramids to make it quick.
The offset is accurate up to about +/- 2 frames, so you should run
*refine_time_offset* if you need better accuracy.
Parameters
---------------
image_sequence_or_flow : sequence of image data, or ndarray
This must be either a list or generator that provides a stream of
images that are used for optical flow calculations.
image_timestamps : ndarray
Timestamps of the images in image_sequence
gyro_data : (3, N) ndarray
Gyroscope measurements (angular velocity)
gyro_timestamps : ndarray
Timestamps of data in gyro_data
levels : int
Number of pyramid levels
full_output : bool
If False, only return the offset, otherwise return extra data
Returns
--------------
time_offset : float
The time offset to add to image_timestamps to align the image data
with the gyroscope data
flow : ndarray
(Only if full_output=True)
The calculated optical flow magnitude | [
"Get",
"time",
"offset",
"that",
"aligns",
"image",
"timestamps",
"with",
"gyro",
"timestamps",
".",
"Given",
"an",
"image",
"sequence",
"and",
"gyroscope",
"data",
"with",
"their",
"respective",
"timestamps",
"calculate",
"the",
"offset",
"that",
"aligns",
"the",
"image",
"data",
"with",
"the",
"gyro",
"data",
".",
"The",
"timestamps",
"must",
"only",
"differ",
"by",
"an",
"offset",
"not",
"a",
"scale",
"factor",
"."
] | train | https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/timesync.py#L36-L120 |
hovren/crisp | crisp/timesync.py | sync_camera_gyro_manual | def sync_camera_gyro_manual(image_sequence, image_timestamps, gyro_data, gyro_timestamps, full_output=False):
"""Get time offset that aligns image timestamps with gyro timestamps.
Given an image sequence, and gyroscope data, with their respective timestamps,
calculate the offset that aligns the image data with the gyro data.
The timestamps must only differ by an offset, not a scale factor.
This function finds an approximation of the offset *d* that makes this transformation
t_gyro = t_camera + d
i.e. your new image timestamps should be
image_timestamps_aligned = image_timestamps + d
The offset is calculated using correlation. The parts of the signals to use are
chosen by the user by picking points in a plot window.
The offset is accurate up to about +/- 2 frames, so you should run
*refine_time_offset* if you need better accuracy.
Parameters
---------------
image_sequence : sequence of image data
This must be either a list or generator that provides a stream of
images that are used for optical flow calculations.
image_timestamps : ndarray
Timestamps of the images in image_sequence
gyro_data : (3, N) ndarray
Gyroscope measurements (angular velocity)
gyro_timestamps : ndarray
Timestamps of data in gyro_data
full_output : bool
If False, only return the offset, otherwise return extra data
Returns
--------------
time_offset : float
The time offset to add to image_timestamps to align the image data
with the gyroscope data
flow : ndarray
(Only if full_output=True)
The calculated optical flow magnitude
frame_pair : (int, int)
The frame pair that was picked for synchronization
"""
flow = tracking.optical_flow_magnitude(image_sequence)
flow_timestamps = image_timestamps[:-2]
# Let user select points in both pieces of data
(frame_pair, gyro_idx) = manual_sync_pick(flow, gyro_timestamps, gyro_data)
# Normalize data
gyro_abs_max = np.max(np.abs(gyro_data), axis=0)
gyro_normalized = (gyro_abs_max / np.max(gyro_abs_max)).flatten()
flow_normalized = (flow / np.max(flow)).flatten()
rate = lambda ts: len(ts) / (ts[-1] - ts[0])
# Resample to match highest
freq_gyro = rate(gyro_timestamps)
freq_image = rate(flow_timestamps)
logger.debug("Gyro sampling frequency: %.2f Hz, Image sampling frequency: %.2f Hz", freq_gyro, freq_image)
gyro_part = gyro_normalized[gyro_idx[0]:gyro_idx[1]+1] # only largest
flow_part = flow_normalized[frame_pair[0]:frame_pair[1]+1]
N = flow_part.size * freq_gyro / freq_image
flow_part_resampled = ssig.resample(flow_part, N).flatten()
# ) Cross correlate the two signals and find time diff
corr = ssig.correlate(gyro_part, flow_part_resampled, 'full') # Find the flow in gyro data
i = np.argmax(corr)
t_0_f = flow_timestamps[frame_pair[0]]
t_1_f = flow_timestamps[frame_pair[1]]
t_off_g = gyro_timestamps[gyro_idx[0] + i]
t_off_f = t_1_f
time_offset = t_off_g - t_off_f
if full_output:
return time_offset, flow, frame_pair
else:
return time_offset | python | def sync_camera_gyro_manual(image_sequence, image_timestamps, gyro_data, gyro_timestamps, full_output=False):
"""Get time offset that aligns image timestamps with gyro timestamps.
Given an image sequence, and gyroscope data, with their respective timestamps,
calculate the offset that aligns the image data with the gyro data.
The timestamps must only differ by an offset, not a scale factor.
This function finds an approximation of the offset *d* that makes this transformation
t_gyro = t_camera + d
i.e. your new image timestamps should be
image_timestamps_aligned = image_timestamps + d
The offset is calculated using correlation. The parts of the signals to use are
chosen by the user by picking points in a plot window.
The offset is accurate up to about +/- 2 frames, so you should run
*refine_time_offset* if you need better accuracy.
Parameters
---------------
image_sequence : sequence of image data
This must be either a list or generator that provides a stream of
images that are used for optical flow calculations.
image_timestamps : ndarray
Timestamps of the images in image_sequence
gyro_data : (3, N) ndarray
Gyroscope measurements (angular velocity)
gyro_timestamps : ndarray
Timestamps of data in gyro_data
full_output : bool
If False, only return the offset, otherwise return extra data
Returns
--------------
time_offset : float
The time offset to add to image_timestamps to align the image data
with the gyroscope data
flow : ndarray
(Only if full_output=True)
The calculated optical flow magnitude
frame_pair : (int, int)
The frame pair that was picked for synchronization
"""
flow = tracking.optical_flow_magnitude(image_sequence)
flow_timestamps = image_timestamps[:-2]
# Let user select points in both pieces of data
(frame_pair, gyro_idx) = manual_sync_pick(flow, gyro_timestamps, gyro_data)
# Normalize data
gyro_abs_max = np.max(np.abs(gyro_data), axis=0)
gyro_normalized = (gyro_abs_max / np.max(gyro_abs_max)).flatten()
flow_normalized = (flow / np.max(flow)).flatten()
rate = lambda ts: len(ts) / (ts[-1] - ts[0])
# Resample to match highest
freq_gyro = rate(gyro_timestamps)
freq_image = rate(flow_timestamps)
logger.debug("Gyro sampling frequency: %.2f Hz, Image sampling frequency: %.2f Hz", freq_gyro, freq_image)
gyro_part = gyro_normalized[gyro_idx[0]:gyro_idx[1]+1] # only largest
flow_part = flow_normalized[frame_pair[0]:frame_pair[1]+1]
N = flow_part.size * freq_gyro / freq_image
flow_part_resampled = ssig.resample(flow_part, N).flatten()
# ) Cross correlate the two signals and find time diff
corr = ssig.correlate(gyro_part, flow_part_resampled, 'full') # Find the flow in gyro data
i = np.argmax(corr)
t_0_f = flow_timestamps[frame_pair[0]]
t_1_f = flow_timestamps[frame_pair[1]]
t_off_g = gyro_timestamps[gyro_idx[0] + i]
t_off_f = t_1_f
time_offset = t_off_g - t_off_f
if full_output:
return time_offset, flow, frame_pair
else:
return time_offset | [
"def",
"sync_camera_gyro_manual",
"(",
"image_sequence",
",",
"image_timestamps",
",",
"gyro_data",
",",
"gyro_timestamps",
",",
"full_output",
"=",
"False",
")",
":",
"flow",
"=",
"tracking",
".",
"optical_flow_magnitude",
"(",
"image_sequence",
")",
"flow_timestamps",
"=",
"image_timestamps",
"[",
":",
"-",
"2",
"]",
"# Let user select points in both pieces of data",
"(",
"frame_pair",
",",
"gyro_idx",
")",
"=",
"manual_sync_pick",
"(",
"flow",
",",
"gyro_timestamps",
",",
"gyro_data",
")",
"# Normalize data",
"gyro_abs_max",
"=",
"np",
".",
"max",
"(",
"np",
".",
"abs",
"(",
"gyro_data",
")",
",",
"axis",
"=",
"0",
")",
"gyro_normalized",
"=",
"(",
"gyro_abs_max",
"/",
"np",
".",
"max",
"(",
"gyro_abs_max",
")",
")",
".",
"flatten",
"(",
")",
"flow_normalized",
"=",
"(",
"flow",
"/",
"np",
".",
"max",
"(",
"flow",
")",
")",
".",
"flatten",
"(",
")",
"rate",
"=",
"lambda",
"ts",
":",
"len",
"(",
"ts",
")",
"/",
"(",
"ts",
"[",
"-",
"1",
"]",
"-",
"ts",
"[",
"0",
"]",
")",
"# Resample to match highest",
"freq_gyro",
"=",
"rate",
"(",
"gyro_timestamps",
")",
"freq_image",
"=",
"rate",
"(",
"flow_timestamps",
")",
"logger",
".",
"debug",
"(",
"\"Gyro sampling frequency: %.2f Hz, Image sampling frequency: %.2f Hz\"",
",",
"freq_gyro",
",",
"freq_image",
")",
"gyro_part",
"=",
"gyro_normalized",
"[",
"gyro_idx",
"[",
"0",
"]",
":",
"gyro_idx",
"[",
"1",
"]",
"+",
"1",
"]",
"# only largest",
"flow_part",
"=",
"flow_normalized",
"[",
"frame_pair",
"[",
"0",
"]",
":",
"frame_pair",
"[",
"1",
"]",
"+",
"1",
"]",
"N",
"=",
"flow_part",
".",
"size",
"*",
"freq_gyro",
"/",
"freq_image",
"flow_part_resampled",
"=",
"ssig",
".",
"resample",
"(",
"flow_part",
",",
"N",
")",
".",
"flatten",
"(",
")",
"# ) Cross correlate the two signals and find time diff",
"corr",
"=",
"ssig",
".",
"correlate",
"(",
"gyro_part",
",",
"flow_part_resampled",
",",
"'full'",
")",
"# Find the flow in gyro data",
"i",
"=",
"np",
".",
"argmax",
"(",
"corr",
")",
"t_0_f",
"=",
"flow_timestamps",
"[",
"frame_pair",
"[",
"0",
"]",
"]",
"t_1_f",
"=",
"flow_timestamps",
"[",
"frame_pair",
"[",
"1",
"]",
"]",
"t_off_g",
"=",
"gyro_timestamps",
"[",
"gyro_idx",
"[",
"0",
"]",
"+",
"i",
"]",
"t_off_f",
"=",
"t_1_f",
"time_offset",
"=",
"t_off_g",
"-",
"t_off_f",
"if",
"full_output",
":",
"return",
"time_offset",
",",
"flow",
",",
"frame_pair",
"else",
":",
"return",
"time_offset"
] | Get time offset that aligns image timestamps with gyro timestamps.
Given an image sequence, and gyroscope data, with their respective timestamps,
calculate the offset that aligns the image data with the gyro data.
The timestamps must only differ by an offset, not a scale factor.
This function finds an approximation of the offset *d* that makes this transformation
t_gyro = t_camera + d
i.e. your new image timestamps should be
image_timestamps_aligned = image_timestamps + d
The offset is calculated using correlation. The parts of the signals to use are
chosen by the user by picking points in a plot window.
The offset is accurate up to about +/- 2 frames, so you should run
*refine_time_offset* if you need better accuracy.
Parameters
---------------
image_sequence : sequence of image data
This must be either a list or generator that provides a stream of
images that are used for optical flow calculations.
image_timestamps : ndarray
Timestamps of the images in image_sequence
gyro_data : (3, N) ndarray
Gyroscope measurements (angular velocity)
gyro_timestamps : ndarray
Timestamps of data in gyro_data
full_output : bool
If False, only return the offset, otherwise return extra data
Returns
--------------
time_offset : float
The time offset to add to image_timestamps to align the image data
with the gyroscope data
flow : ndarray
(Only if full_output=True)
The calculated optical flow magnitude
frame_pair : (int, int)
The frame pair that was picked for synchronization | [
"Get",
"time",
"offset",
"that",
"aligns",
"image",
"timestamps",
"with",
"gyro",
"timestamps",
".",
"Given",
"an",
"image",
"sequence",
"and",
"gyroscope",
"data",
"with",
"their",
"respective",
"timestamps",
"calculate",
"the",
"offset",
"that",
"aligns",
"the",
"image",
"data",
"with",
"the",
"gyro",
"data",
".",
"The",
"timestamps",
"must",
"only",
"differ",
"by",
"an",
"offset",
"not",
"a",
"scale",
"factor",
"."
] | train | https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/timesync.py#L124-L210 |
hovren/crisp | crisp/timesync.py | refine_time_offset | def refine_time_offset(image_list, frame_timestamps, rotation_sequence, rotation_timestamps, camera_matrix, readout_time):
"""Refine a time offset between camera and IMU using rolling shutter aware optimization.
To refine the time offset using this function, you must meet the following constraints
1) The data must already be roughly aligned. Only a few image frames of error
is allowed.
2) The images *must* have been captured by a *rolling shutter* camera.
This function finds a refined offset using optimization.
Points are first tracked from the start to the end of the provided images.
Then an optimization function looks at the reprojection error of the tracked points
given the IMU-data and the refined offset.
The found offset *d* is such that you want to perform the following time update
new_frame_timestamps = frame_timestamps + d
Parameters
------------
image_list : list of ndarray
A list of images to perform tracking on. High quality tracks are required,
so make sure the sequence you choose is easy to track in.
frame_timestamps : ndarray
Timestamps of image_list
rotation_sequence : (4, N) ndarray
Absolute rotations as a sequence of unit quaternions (first element is scalar).
rotation_timestamps : ndarray
Timestamps of rotation_sequence
camera_matrix : (3,3) ndarray
The internal camera calibration matrix of the camera.
readout_time : float
The readout time of the camera.
Returns
------------
offset : float
A refined offset that aligns the image data with the rotation data.
"""
# ) Track points
max_corners = 200
quality_level = 0.07
min_distance = 5
max_tracks = 20
initial_points = cv2.goodFeaturesToTrack(image_list[0], max_corners, quality_level, min_distance)
(points, status) = tracking.track_retrack(image_list, initial_points)
# Prune to at most max_tracks number of tracks, choose randomly
track_id_list = np.random.permutation(points.shape[0])[:max_tracks]
rows, cols = image_list[0].shape[:2]
row_delta_time = readout_time / rows
num_tracks, num_frames, _ = points.shape
K = np.matrix(camera_matrix)
def func_to_optimize(td, *args):
res = 0.0
N = 0
for frame_idx in range(num_frames-1):
for track_id in track_id_list:
p1 = points[track_id, frame_idx, :].reshape((-1,1))
p2 = points[track_id, frame_idx + 1, :].reshape((-1,1))
t1 = frame_timestamps[frame_idx] + (p1[1] - 1) * row_delta_time + td
t2 = frame_timestamps[frame_idx + 1] + (p2[1] - 1) * row_delta_time +td
t1 = float(t1)
t2 = float(t2)
q1 = IMU.rotation_at_time(t1, rotation_timestamps, rotation_sequence)
q2 = IMU.rotation_at_time(t2, rotation_timestamps, rotation_sequence)
R1 = rotations.quat_to_rotation_matrix(q1)
R2 = rotations.quat_to_rotation_matrix(q2)
p1_rec = K.dot(R1.T).dot(R2).dot(K.I).dot(np.vstack((p2, 1)))
if p1_rec[2] == 0:
continue
else:
p1_rec /= p1_rec[2]
res += np.sum((p1 - np.array(p1_rec[0:2]))**2)
N += 1
return res / N
# Bounded Brent optimizer
t0 = time.time()
tolerance = 1e-4 # one tenth millisecond
(refined_offset, fval, ierr, numfunc) = scipy.optimize.fminbound(func_to_optimize, -0.12, 0.12, xtol=tolerance, full_output=True)
t1 = time.time()
if ierr == 0:
logger.info("Time offset found by brent optimizer: %.4f. Elapsed: %.2f seconds (%d function calls)", refined_offset, t1-t0, numfunc)
else:
logger.error("Brent optimizer did not converge. Aborting!")
raise Exception("Brent optimizer did not converge, when trying to refine offset.")
return refined_offset | python | def refine_time_offset(image_list, frame_timestamps, rotation_sequence, rotation_timestamps, camera_matrix, readout_time):
"""Refine a time offset between camera and IMU using rolling shutter aware optimization.
To refine the time offset using this function, you must meet the following constraints
1) The data must already be roughly aligned. Only a few image frames of error
is allowed.
2) The images *must* have been captured by a *rolling shutter* camera.
This function finds a refined offset using optimization.
Points are first tracked from the start to the end of the provided images.
Then an optimization function looks at the reprojection error of the tracked points
given the IMU-data and the refined offset.
The found offset *d* is such that you want to perform the following time update
new_frame_timestamps = frame_timestamps + d
Parameters
------------
image_list : list of ndarray
A list of images to perform tracking on. High quality tracks are required,
so make sure the sequence you choose is easy to track in.
frame_timestamps : ndarray
Timestamps of image_list
rotation_sequence : (4, N) ndarray
Absolute rotations as a sequence of unit quaternions (first element is scalar).
rotation_timestamps : ndarray
Timestamps of rotation_sequence
camera_matrix : (3,3) ndarray
The internal camera calibration matrix of the camera.
readout_time : float
The readout time of the camera.
Returns
------------
offset : float
A refined offset that aligns the image data with the rotation data.
"""
# ) Track points
max_corners = 200
quality_level = 0.07
min_distance = 5
max_tracks = 20
initial_points = cv2.goodFeaturesToTrack(image_list[0], max_corners, quality_level, min_distance)
(points, status) = tracking.track_retrack(image_list, initial_points)
# Prune to at most max_tracks number of tracks, choose randomly
track_id_list = np.random.permutation(points.shape[0])[:max_tracks]
rows, cols = image_list[0].shape[:2]
row_delta_time = readout_time / rows
num_tracks, num_frames, _ = points.shape
K = np.matrix(camera_matrix)
def func_to_optimize(td, *args):
res = 0.0
N = 0
for frame_idx in range(num_frames-1):
for track_id in track_id_list:
p1 = points[track_id, frame_idx, :].reshape((-1,1))
p2 = points[track_id, frame_idx + 1, :].reshape((-1,1))
t1 = frame_timestamps[frame_idx] + (p1[1] - 1) * row_delta_time + td
t2 = frame_timestamps[frame_idx + 1] + (p2[1] - 1) * row_delta_time +td
t1 = float(t1)
t2 = float(t2)
q1 = IMU.rotation_at_time(t1, rotation_timestamps, rotation_sequence)
q2 = IMU.rotation_at_time(t2, rotation_timestamps, rotation_sequence)
R1 = rotations.quat_to_rotation_matrix(q1)
R2 = rotations.quat_to_rotation_matrix(q2)
p1_rec = K.dot(R1.T).dot(R2).dot(K.I).dot(np.vstack((p2, 1)))
if p1_rec[2] == 0:
continue
else:
p1_rec /= p1_rec[2]
res += np.sum((p1 - np.array(p1_rec[0:2]))**2)
N += 1
return res / N
# Bounded Brent optimizer
t0 = time.time()
tolerance = 1e-4 # one tenth millisecond
(refined_offset, fval, ierr, numfunc) = scipy.optimize.fminbound(func_to_optimize, -0.12, 0.12, xtol=tolerance, full_output=True)
t1 = time.time()
if ierr == 0:
logger.info("Time offset found by brent optimizer: %.4f. Elapsed: %.2f seconds (%d function calls)", refined_offset, t1-t0, numfunc)
else:
logger.error("Brent optimizer did not converge. Aborting!")
raise Exception("Brent optimizer did not converge, when trying to refine offset.")
return refined_offset | [
"def",
"refine_time_offset",
"(",
"image_list",
",",
"frame_timestamps",
",",
"rotation_sequence",
",",
"rotation_timestamps",
",",
"camera_matrix",
",",
"readout_time",
")",
":",
"# ) Track points",
"max_corners",
"=",
"200",
"quality_level",
"=",
"0.07",
"min_distance",
"=",
"5",
"max_tracks",
"=",
"20",
"initial_points",
"=",
"cv2",
".",
"goodFeaturesToTrack",
"(",
"image_list",
"[",
"0",
"]",
",",
"max_corners",
",",
"quality_level",
",",
"min_distance",
")",
"(",
"points",
",",
"status",
")",
"=",
"tracking",
".",
"track_retrack",
"(",
"image_list",
",",
"initial_points",
")",
"# Prune to at most max_tracks number of tracks, choose randomly ",
"track_id_list",
"=",
"np",
".",
"random",
".",
"permutation",
"(",
"points",
".",
"shape",
"[",
"0",
"]",
")",
"[",
":",
"max_tracks",
"]",
"rows",
",",
"cols",
"=",
"image_list",
"[",
"0",
"]",
".",
"shape",
"[",
":",
"2",
"]",
"row_delta_time",
"=",
"readout_time",
"/",
"rows",
"num_tracks",
",",
"num_frames",
",",
"_",
"=",
"points",
".",
"shape",
"K",
"=",
"np",
".",
"matrix",
"(",
"camera_matrix",
")",
"def",
"func_to_optimize",
"(",
"td",
",",
"*",
"args",
")",
":",
"res",
"=",
"0.0",
"N",
"=",
"0",
"for",
"frame_idx",
"in",
"range",
"(",
"num_frames",
"-",
"1",
")",
":",
"for",
"track_id",
"in",
"track_id_list",
":",
"p1",
"=",
"points",
"[",
"track_id",
",",
"frame_idx",
",",
":",
"]",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"1",
")",
")",
"p2",
"=",
"points",
"[",
"track_id",
",",
"frame_idx",
"+",
"1",
",",
":",
"]",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"1",
")",
")",
"t1",
"=",
"frame_timestamps",
"[",
"frame_idx",
"]",
"+",
"(",
"p1",
"[",
"1",
"]",
"-",
"1",
")",
"*",
"row_delta_time",
"+",
"td",
"t2",
"=",
"frame_timestamps",
"[",
"frame_idx",
"+",
"1",
"]",
"+",
"(",
"p2",
"[",
"1",
"]",
"-",
"1",
")",
"*",
"row_delta_time",
"+",
"td",
"t1",
"=",
"float",
"(",
"t1",
")",
"t2",
"=",
"float",
"(",
"t2",
")",
"q1",
"=",
"IMU",
".",
"rotation_at_time",
"(",
"t1",
",",
"rotation_timestamps",
",",
"rotation_sequence",
")",
"q2",
"=",
"IMU",
".",
"rotation_at_time",
"(",
"t2",
",",
"rotation_timestamps",
",",
"rotation_sequence",
")",
"R1",
"=",
"rotations",
".",
"quat_to_rotation_matrix",
"(",
"q1",
")",
"R2",
"=",
"rotations",
".",
"quat_to_rotation_matrix",
"(",
"q2",
")",
"p1_rec",
"=",
"K",
".",
"dot",
"(",
"R1",
".",
"T",
")",
".",
"dot",
"(",
"R2",
")",
".",
"dot",
"(",
"K",
".",
"I",
")",
".",
"dot",
"(",
"np",
".",
"vstack",
"(",
"(",
"p2",
",",
"1",
")",
")",
")",
"if",
"p1_rec",
"[",
"2",
"]",
"==",
"0",
":",
"continue",
"else",
":",
"p1_rec",
"/=",
"p1_rec",
"[",
"2",
"]",
"res",
"+=",
"np",
".",
"sum",
"(",
"(",
"p1",
"-",
"np",
".",
"array",
"(",
"p1_rec",
"[",
"0",
":",
"2",
"]",
")",
")",
"**",
"2",
")",
"N",
"+=",
"1",
"return",
"res",
"/",
"N",
"# Bounded Brent optimizer",
"t0",
"=",
"time",
".",
"time",
"(",
")",
"tolerance",
"=",
"1e-4",
"# one tenth millisecond",
"(",
"refined_offset",
",",
"fval",
",",
"ierr",
",",
"numfunc",
")",
"=",
"scipy",
".",
"optimize",
".",
"fminbound",
"(",
"func_to_optimize",
",",
"-",
"0.12",
",",
"0.12",
",",
"xtol",
"=",
"tolerance",
",",
"full_output",
"=",
"True",
")",
"t1",
"=",
"time",
".",
"time",
"(",
")",
"if",
"ierr",
"==",
"0",
":",
"logger",
".",
"info",
"(",
"\"Time offset found by brent optimizer: %.4f. Elapsed: %.2f seconds (%d function calls)\"",
",",
"refined_offset",
",",
"t1",
"-",
"t0",
",",
"numfunc",
")",
"else",
":",
"logger",
".",
"error",
"(",
"\"Brent optimizer did not converge. Aborting!\"",
")",
"raise",
"Exception",
"(",
"\"Brent optimizer did not converge, when trying to refine offset.\"",
")",
"return",
"refined_offset"
] | Refine a time offset between camera and IMU using rolling shutter aware optimization.
To refine the time offset using this function, you must meet the following constraints
1) The data must already be roughly aligned. Only a few image frames of error
is allowed.
2) The images *must* have been captured by a *rolling shutter* camera.
This function finds a refined offset using optimization.
Points are first tracked from the start to the end of the provided images.
Then an optimization function looks at the reprojection error of the tracked points
given the IMU-data and the refined offset.
The found offset *d* is such that you want to perform the following time update
new_frame_timestamps = frame_timestamps + d
Parameters
------------
image_list : list of ndarray
A list of images to perform tracking on. High quality tracks are required,
so make sure the sequence you choose is easy to track in.
frame_timestamps : ndarray
Timestamps of image_list
rotation_sequence : (4, N) ndarray
Absolute rotations as a sequence of unit quaternions (first element is scalar).
rotation_timestamps : ndarray
Timestamps of rotation_sequence
camera_matrix : (3,3) ndarray
The internal camera calibration matrix of the camera.
readout_time : float
The readout time of the camera.
Returns
------------
offset : float
A refined offset that aligns the image data with the rotation data. | [
"Refine",
"a",
"time",
"offset",
"between",
"camera",
"and",
"IMU",
"using",
"rolling",
"shutter",
"aware",
"optimization",
".",
"To",
"refine",
"the",
"time",
"offset",
"using",
"this",
"function",
"you",
"must",
"meet",
"the",
"following",
"constraints",
"1",
")",
"The",
"data",
"must",
"already",
"be",
"roughly",
"aligned",
".",
"Only",
"a",
"few",
"image",
"frames",
"of",
"error",
"is",
"allowed",
".",
"2",
")",
"The",
"images",
"*",
"must",
"*",
"have",
"been",
"captured",
"by",
"a",
"*",
"rolling",
"shutter",
"*",
"camera",
".",
"This",
"function",
"finds",
"a",
"refined",
"offset",
"using",
"optimization",
".",
"Points",
"are",
"first",
"tracked",
"from",
"the",
"start",
"to",
"the",
"end",
"of",
"the",
"provided",
"images",
".",
"Then",
"an",
"optimization",
"function",
"looks",
"at",
"the",
"reprojection",
"error",
"of",
"the",
"tracked",
"points",
"given",
"the",
"IMU",
"-",
"data",
"and",
"the",
"refined",
"offset",
".",
"The",
"found",
"offset",
"*",
"d",
"*",
"is",
"such",
"that",
"you",
"want",
"to",
"perform",
"the",
"following",
"time",
"update",
"new_frame_timestamps",
"=",
"frame_timestamps",
"+",
"d",
"Parameters",
"------------",
"image_list",
":",
"list",
"of",
"ndarray",
"A",
"list",
"of",
"images",
"to",
"perform",
"tracking",
"on",
".",
"High",
"quality",
"tracks",
"are",
"required",
"so",
"make",
"sure",
"the",
"sequence",
"you",
"choose",
"is",
"easy",
"to",
"track",
"in",
".",
"frame_timestamps",
":",
"ndarray",
"Timestamps",
"of",
"image_list",
"rotation_sequence",
":",
"(",
"4",
"N",
")",
"ndarray",
"Absolute",
"rotations",
"as",
"a",
"sequence",
"of",
"unit",
"quaternions",
"(",
"first",
"element",
"is",
"scalar",
")",
".",
"rotation_timestamps",
":",
"ndarray",
"Timestamps",
"of",
"rotation_sequence",
"camera_matrix",
":",
"(",
"3",
"3",
")",
"ndarray",
"The",
"internal",
"camera",
"calibration",
"matrix",
"of",
"the",
"camera",
".",
"readout_time",
":",
"float",
"The",
"readout",
"time",
"of",
"the",
"camera",
".",
"Returns",
"------------",
"offset",
":",
"float",
"A",
"refined",
"offset",
"that",
"aligns",
"the",
"image",
"data",
"with",
"the",
"rotation",
"data",
"."
] | train | https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/timesync.py#L243-L333 |
hovren/crisp | crisp/timesync.py | good_sequences_to_track | def good_sequences_to_track(flow, motion_threshold=1.0):
"""Get list of good frames to do tracking in.
Looking at the optical flow, this function chooses a span of frames
that fulfill certain criteria.
These include
* not being too short or too long
* not too low or too high mean flow magnitude
* a low max value (avoids motion blur)
Currently, the cost function for a sequence is hard coded. Sorry about that.
Parameters
-------------
flow : ndarray
The optical flow magnitude
motion_threshold : float
The maximum amount of motion to consider for sequence endpoints.
Returns
------------
sequences : list
Sorted list of (a, b, score) elements (highest scpre first) of sequences
where a sequence is frames with frame indices in the span [a, b].
"""
endpoints = []
in_low = False
for i, val in enumerate(flow):
if val < motion_threshold:
if not in_low:
endpoints.append(i)
in_low = True
else:
if in_low:
endpoints.append(i-1) # Previous was last in a low spot
in_low = False
def mean_score_func(m):
mu = 15
sigma = 8
top_val = normpdf(mu, mu, sigma)
return normpdf(m, mu, sigma) / top_val
def max_score_func(m):
mu = 40
sigma = 8
if m <= mu:
return 1.
else:
top_val = normpdf(mu, mu, sigma)
return normpdf(m, mu, sigma) / top_val
def length_score_func(l):
mu = 30
sigma = 10
top_val = normpdf(mu, mu, sigma)
return normpdf(l, mu, sigma) / top_val
min_length = 5 # frames
sequences = []
for k, i in enumerate(endpoints[:-1]):
for j in endpoints[k+1:]:
length = j - i
if length < min_length:
continue
seq = flow[i:j+1]
m_score = mean_score_func(np.mean(seq))
mx_score = max_score_func(np.max(seq))
l_score = length_score_func(length)
logger.debug("%d, %d scores: (mean=%.5f, max=%.5f, length=%.5f)" % (i,j,m_score, mx_score, l_score))
if min(m_score, mx_score, l_score) < 0.2:
continue
score = m_score + mx_score + l_score
sequences.append((i, j, score))
return sorted(sequences, key=lambda x: x[2], reverse=True) | python | def good_sequences_to_track(flow, motion_threshold=1.0):
"""Get list of good frames to do tracking in.
Looking at the optical flow, this function chooses a span of frames
that fulfill certain criteria.
These include
* not being too short or too long
* not too low or too high mean flow magnitude
* a low max value (avoids motion blur)
Currently, the cost function for a sequence is hard coded. Sorry about that.
Parameters
-------------
flow : ndarray
The optical flow magnitude
motion_threshold : float
The maximum amount of motion to consider for sequence endpoints.
Returns
------------
sequences : list
Sorted list of (a, b, score) elements (highest scpre first) of sequences
where a sequence is frames with frame indices in the span [a, b].
"""
endpoints = []
in_low = False
for i, val in enumerate(flow):
if val < motion_threshold:
if not in_low:
endpoints.append(i)
in_low = True
else:
if in_low:
endpoints.append(i-1) # Previous was last in a low spot
in_low = False
def mean_score_func(m):
mu = 15
sigma = 8
top_val = normpdf(mu, mu, sigma)
return normpdf(m, mu, sigma) / top_val
def max_score_func(m):
mu = 40
sigma = 8
if m <= mu:
return 1.
else:
top_val = normpdf(mu, mu, sigma)
return normpdf(m, mu, sigma) / top_val
def length_score_func(l):
mu = 30
sigma = 10
top_val = normpdf(mu, mu, sigma)
return normpdf(l, mu, sigma) / top_val
min_length = 5 # frames
sequences = []
for k, i in enumerate(endpoints[:-1]):
for j in endpoints[k+1:]:
length = j - i
if length < min_length:
continue
seq = flow[i:j+1]
m_score = mean_score_func(np.mean(seq))
mx_score = max_score_func(np.max(seq))
l_score = length_score_func(length)
logger.debug("%d, %d scores: (mean=%.5f, max=%.5f, length=%.5f)" % (i,j,m_score, mx_score, l_score))
if min(m_score, mx_score, l_score) < 0.2:
continue
score = m_score + mx_score + l_score
sequences.append((i, j, score))
return sorted(sequences, key=lambda x: x[2], reverse=True) | [
"def",
"good_sequences_to_track",
"(",
"flow",
",",
"motion_threshold",
"=",
"1.0",
")",
":",
"endpoints",
"=",
"[",
"]",
"in_low",
"=",
"False",
"for",
"i",
",",
"val",
"in",
"enumerate",
"(",
"flow",
")",
":",
"if",
"val",
"<",
"motion_threshold",
":",
"if",
"not",
"in_low",
":",
"endpoints",
".",
"append",
"(",
"i",
")",
"in_low",
"=",
"True",
"else",
":",
"if",
"in_low",
":",
"endpoints",
".",
"append",
"(",
"i",
"-",
"1",
")",
"# Previous was last in a low spot",
"in_low",
"=",
"False",
"def",
"mean_score_func",
"(",
"m",
")",
":",
"mu",
"=",
"15",
"sigma",
"=",
"8",
"top_val",
"=",
"normpdf",
"(",
"mu",
",",
"mu",
",",
"sigma",
")",
"return",
"normpdf",
"(",
"m",
",",
"mu",
",",
"sigma",
")",
"/",
"top_val",
"def",
"max_score_func",
"(",
"m",
")",
":",
"mu",
"=",
"40",
"sigma",
"=",
"8",
"if",
"m",
"<=",
"mu",
":",
"return",
"1.",
"else",
":",
"top_val",
"=",
"normpdf",
"(",
"mu",
",",
"mu",
",",
"sigma",
")",
"return",
"normpdf",
"(",
"m",
",",
"mu",
",",
"sigma",
")",
"/",
"top_val",
"def",
"length_score_func",
"(",
"l",
")",
":",
"mu",
"=",
"30",
"sigma",
"=",
"10",
"top_val",
"=",
"normpdf",
"(",
"mu",
",",
"mu",
",",
"sigma",
")",
"return",
"normpdf",
"(",
"l",
",",
"mu",
",",
"sigma",
")",
"/",
"top_val",
"min_length",
"=",
"5",
"# frames",
"sequences",
"=",
"[",
"]",
"for",
"k",
",",
"i",
"in",
"enumerate",
"(",
"endpoints",
"[",
":",
"-",
"1",
"]",
")",
":",
"for",
"j",
"in",
"endpoints",
"[",
"k",
"+",
"1",
":",
"]",
":",
"length",
"=",
"j",
"-",
"i",
"if",
"length",
"<",
"min_length",
":",
"continue",
"seq",
"=",
"flow",
"[",
"i",
":",
"j",
"+",
"1",
"]",
"m_score",
"=",
"mean_score_func",
"(",
"np",
".",
"mean",
"(",
"seq",
")",
")",
"mx_score",
"=",
"max_score_func",
"(",
"np",
".",
"max",
"(",
"seq",
")",
")",
"l_score",
"=",
"length_score_func",
"(",
"length",
")",
"logger",
".",
"debug",
"(",
"\"%d, %d scores: (mean=%.5f, max=%.5f, length=%.5f)\"",
"%",
"(",
"i",
",",
"j",
",",
"m_score",
",",
"mx_score",
",",
"l_score",
")",
")",
"if",
"min",
"(",
"m_score",
",",
"mx_score",
",",
"l_score",
")",
"<",
"0.2",
":",
"continue",
"score",
"=",
"m_score",
"+",
"mx_score",
"+",
"l_score",
"sequences",
".",
"append",
"(",
"(",
"i",
",",
"j",
",",
"score",
")",
")",
"return",
"sorted",
"(",
"sequences",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"2",
"]",
",",
"reverse",
"=",
"True",
")"
] | Get list of good frames to do tracking in.
Looking at the optical flow, this function chooses a span of frames
that fulfill certain criteria.
These include
* not being too short or too long
* not too low or too high mean flow magnitude
* a low max value (avoids motion blur)
Currently, the cost function for a sequence is hard coded. Sorry about that.
Parameters
-------------
flow : ndarray
The optical flow magnitude
motion_threshold : float
The maximum amount of motion to consider for sequence endpoints.
Returns
------------
sequences : list
Sorted list of (a, b, score) elements (highest scpre first) of sequences
where a sequence is frames with frame indices in the span [a, b]. | [
"Get",
"list",
"of",
"good",
"frames",
"to",
"do",
"tracking",
"in",
"."
] | train | https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/timesync.py#L336-L411 |
hovren/crisp | crisp/calibration.py | AutoCalibrator.initialize | def initialize(self, gyro_rate, slices=None, skip_estimation=False):
"""Prepare calibrator for calibration
This method does three things:
1. Create slices from the video stream, if not already provided
2. Estimate time offset
3. Estimate rotation between camera and gyroscope
Parameters
------------------
gyro_rate : float
Estimated gyroscope sample rate
slices : list of Slice, optional
Slices to use for optimization
skip_estimation : bool
Do not estimate initial time offset and rotation.
Raises
--------------------
InitializationError
If the initialization fails
"""
self.params['user']['gyro_rate'] = gyro_rate
for p in ('gbias_x', 'gbias_y', 'gbias_z'):
self.params['initialized'][p] = 0.0
if slices is not None:
self.slices = slices
if self.slices is None:
self.slices = videoslice.Slice.from_stream_randomly(self.video)
logger.debug("Number of slices: {:d}".format(len(self.slices)))
if len(self.slices) < 2:
logger.error("Calibration requires at least 2 video slices to proceed, got %d", len(self.slices))
raise InitializationError("Calibration requires at least 2 video slices to proceed, got {:d}".format(len(self.slices)))
if not skip_estimation:
time_offset = self.find_initial_offset()
# TODO: Detect when time offset initialization fails, and raise InitializationError
R = self.find_initial_rotation()
if R is None:
raise InitializationError("Failed to calculate initial rotation") | python | def initialize(self, gyro_rate, slices=None, skip_estimation=False):
"""Prepare calibrator for calibration
This method does three things:
1. Create slices from the video stream, if not already provided
2. Estimate time offset
3. Estimate rotation between camera and gyroscope
Parameters
------------------
gyro_rate : float
Estimated gyroscope sample rate
slices : list of Slice, optional
Slices to use for optimization
skip_estimation : bool
Do not estimate initial time offset and rotation.
Raises
--------------------
InitializationError
If the initialization fails
"""
self.params['user']['gyro_rate'] = gyro_rate
for p in ('gbias_x', 'gbias_y', 'gbias_z'):
self.params['initialized'][p] = 0.0
if slices is not None:
self.slices = slices
if self.slices is None:
self.slices = videoslice.Slice.from_stream_randomly(self.video)
logger.debug("Number of slices: {:d}".format(len(self.slices)))
if len(self.slices) < 2:
logger.error("Calibration requires at least 2 video slices to proceed, got %d", len(self.slices))
raise InitializationError("Calibration requires at least 2 video slices to proceed, got {:d}".format(len(self.slices)))
if not skip_estimation:
time_offset = self.find_initial_offset()
# TODO: Detect when time offset initialization fails, and raise InitializationError
R = self.find_initial_rotation()
if R is None:
raise InitializationError("Failed to calculate initial rotation") | [
"def",
"initialize",
"(",
"self",
",",
"gyro_rate",
",",
"slices",
"=",
"None",
",",
"skip_estimation",
"=",
"False",
")",
":",
"self",
".",
"params",
"[",
"'user'",
"]",
"[",
"'gyro_rate'",
"]",
"=",
"gyro_rate",
"for",
"p",
"in",
"(",
"'gbias_x'",
",",
"'gbias_y'",
",",
"'gbias_z'",
")",
":",
"self",
".",
"params",
"[",
"'initialized'",
"]",
"[",
"p",
"]",
"=",
"0.0",
"if",
"slices",
"is",
"not",
"None",
":",
"self",
".",
"slices",
"=",
"slices",
"if",
"self",
".",
"slices",
"is",
"None",
":",
"self",
".",
"slices",
"=",
"videoslice",
".",
"Slice",
".",
"from_stream_randomly",
"(",
"self",
".",
"video",
")",
"logger",
".",
"debug",
"(",
"\"Number of slices: {:d}\"",
".",
"format",
"(",
"len",
"(",
"self",
".",
"slices",
")",
")",
")",
"if",
"len",
"(",
"self",
".",
"slices",
")",
"<",
"2",
":",
"logger",
".",
"error",
"(",
"\"Calibration requires at least 2 video slices to proceed, got %d\"",
",",
"len",
"(",
"self",
".",
"slices",
")",
")",
"raise",
"InitializationError",
"(",
"\"Calibration requires at least 2 video slices to proceed, got {:d}\"",
".",
"format",
"(",
"len",
"(",
"self",
".",
"slices",
")",
")",
")",
"if",
"not",
"skip_estimation",
":",
"time_offset",
"=",
"self",
".",
"find_initial_offset",
"(",
")",
"# TODO: Detect when time offset initialization fails, and raise InitializationError",
"R",
"=",
"self",
".",
"find_initial_rotation",
"(",
")",
"if",
"R",
"is",
"None",
":",
"raise",
"InitializationError",
"(",
"\"Failed to calculate initial rotation\"",
")"
] | Prepare calibrator for calibration
This method does three things:
1. Create slices from the video stream, if not already provided
2. Estimate time offset
3. Estimate rotation between camera and gyroscope
Parameters
------------------
gyro_rate : float
Estimated gyroscope sample rate
slices : list of Slice, optional
Slices to use for optimization
skip_estimation : bool
Do not estimate initial time offset and rotation.
Raises
--------------------
InitializationError
If the initialization fails | [
"Prepare",
"calibrator",
"for",
"calibration"
] | train | https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/calibration.py#L90-L134 |
hovren/crisp | crisp/calibration.py | AutoCalibrator.video_time_to_gyro_sample | def video_time_to_gyro_sample(self, t):
"""Convert video time to gyroscope sample index and interpolation factor
Parameters
-------------------
t : float
Video timestamp
Returns
--------------------
n : int
Sample index that precedes t
tau : float
Interpolation factor [0.0-1.0]. If tau=0, then t falls on exactly n. If tau=1 then t falls exactly on n+1
"""
f_g = self.parameter['gyro_rate']
d_c = self.parameter['time_offset']
n = f_g * (t + d_c)
n0 = int(np.floor(n))
tau = n - n0
return n0, tau | python | def video_time_to_gyro_sample(self, t):
"""Convert video time to gyroscope sample index and interpolation factor
Parameters
-------------------
t : float
Video timestamp
Returns
--------------------
n : int
Sample index that precedes t
tau : float
Interpolation factor [0.0-1.0]. If tau=0, then t falls on exactly n. If tau=1 then t falls exactly on n+1
"""
f_g = self.parameter['gyro_rate']
d_c = self.parameter['time_offset']
n = f_g * (t + d_c)
n0 = int(np.floor(n))
tau = n - n0
return n0, tau | [
"def",
"video_time_to_gyro_sample",
"(",
"self",
",",
"t",
")",
":",
"f_g",
"=",
"self",
".",
"parameter",
"[",
"'gyro_rate'",
"]",
"d_c",
"=",
"self",
".",
"parameter",
"[",
"'time_offset'",
"]",
"n",
"=",
"f_g",
"*",
"(",
"t",
"+",
"d_c",
")",
"n0",
"=",
"int",
"(",
"np",
".",
"floor",
"(",
"n",
")",
")",
"tau",
"=",
"n",
"-",
"n0",
"return",
"n0",
",",
"tau"
] | Convert video time to gyroscope sample index and interpolation factor
Parameters
-------------------
t : float
Video timestamp
Returns
--------------------
n : int
Sample index that precedes t
tau : float
Interpolation factor [0.0-1.0]. If tau=0, then t falls on exactly n. If tau=1 then t falls exactly on n+1 | [
"Convert",
"video",
"time",
"to",
"gyroscope",
"sample",
"index",
"and",
"interpolation",
"factor"
] | train | https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/calibration.py#L137-L157 |
hovren/crisp | crisp/calibration.py | AutoCalibrator.parameter | def parameter(self):
"""Return the current best value of a parameter"""
D = {}
for source in PARAM_SOURCE_ORDER:
D.update(self.params[source])
return D | python | def parameter(self):
"""Return the current best value of a parameter"""
D = {}
for source in PARAM_SOURCE_ORDER:
D.update(self.params[source])
return D | [
"def",
"parameter",
"(",
"self",
")",
":",
"D",
"=",
"{",
"}",
"for",
"source",
"in",
"PARAM_SOURCE_ORDER",
":",
"D",
".",
"update",
"(",
"self",
".",
"params",
"[",
"source",
"]",
")",
"return",
"D"
] | Return the current best value of a parameter | [
"Return",
"the",
"current",
"best",
"value",
"of",
"a",
"parameter"
] | train | https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/calibration.py#L160-L165 |
hovren/crisp | crisp/calibration.py | AutoCalibrator.calibrate | def calibrate(self, max_tracks=MAX_OPTIMIZATION_TRACKS, max_eval=MAX_OPTIMIZATION_FEV, norm_c=DEFAULT_NORM_C):
"""Perform calibration
Parameters
----------------------
max_eval : int
Maximum number of function evaluations
Returns
---------------------
dict
Optimization result
Raises
-----------------------
CalibrationError
If calibration fails
"""
x0 = np.array([self.parameter[param] for param in PARAM_ORDER])
available_tracks = np.sum([len(s.inliers) for s in self.slices])
if available_tracks < max_tracks:
warnings.warn("Could not use the requested {} tracks, since only {} were available in the slice data.".format(max_tracks, available_tracks))
max_tracks = available_tracks
# Get subset of available tracks such that all slices are still used
slice_sample_idxs = videoslice.fill_sampling(self.slices, max_tracks)
func_args = (self.slices, slice_sample_idxs, self.video.camera_model, self.gyro, norm_c)
self.slice_sample_idxs = slice_sample_idxs
logger.debug("Starting optimization on {:d} slices and {:d} tracks".format(len(self.slices), max_tracks))
start_time = time.time()
# TODO: Check what values of ftol and xtol are required for good results. The current setting is probably pessimistic.
leastsq_result = scipy.optimize.leastsq(optimization_func, x0, args=func_args, full_output=True, ftol=1e-10, xtol=1e-10, maxfev=max_eval)
elapsed = time.time() - start_time
x, covx, infodict, mesg, ier = leastsq_result
self.__debug_leastsq = leastsq_result
logger.debug("Optimization completed in {:.1f} seconds and {:d} function evaluations. ier={}, mesg='{}'".format(elapsed, infodict['nfev'], ier, mesg))
if ier in (1,2,3,4):
for pname, val in zip(PARAM_ORDER, x):
self.params['calibrated'][pname] = val
return self.parameter
else:
raise CalibrationError(mesg) | python | def calibrate(self, max_tracks=MAX_OPTIMIZATION_TRACKS, max_eval=MAX_OPTIMIZATION_FEV, norm_c=DEFAULT_NORM_C):
"""Perform calibration
Parameters
----------------------
max_eval : int
Maximum number of function evaluations
Returns
---------------------
dict
Optimization result
Raises
-----------------------
CalibrationError
If calibration fails
"""
x0 = np.array([self.parameter[param] for param in PARAM_ORDER])
available_tracks = np.sum([len(s.inliers) for s in self.slices])
if available_tracks < max_tracks:
warnings.warn("Could not use the requested {} tracks, since only {} were available in the slice data.".format(max_tracks, available_tracks))
max_tracks = available_tracks
# Get subset of available tracks such that all slices are still used
slice_sample_idxs = videoslice.fill_sampling(self.slices, max_tracks)
func_args = (self.slices, slice_sample_idxs, self.video.camera_model, self.gyro, norm_c)
self.slice_sample_idxs = slice_sample_idxs
logger.debug("Starting optimization on {:d} slices and {:d} tracks".format(len(self.slices), max_tracks))
start_time = time.time()
# TODO: Check what values of ftol and xtol are required for good results. The current setting is probably pessimistic.
leastsq_result = scipy.optimize.leastsq(optimization_func, x0, args=func_args, full_output=True, ftol=1e-10, xtol=1e-10, maxfev=max_eval)
elapsed = time.time() - start_time
x, covx, infodict, mesg, ier = leastsq_result
self.__debug_leastsq = leastsq_result
logger.debug("Optimization completed in {:.1f} seconds and {:d} function evaluations. ier={}, mesg='{}'".format(elapsed, infodict['nfev'], ier, mesg))
if ier in (1,2,3,4):
for pname, val in zip(PARAM_ORDER, x):
self.params['calibrated'][pname] = val
return self.parameter
else:
raise CalibrationError(mesg) | [
"def",
"calibrate",
"(",
"self",
",",
"max_tracks",
"=",
"MAX_OPTIMIZATION_TRACKS",
",",
"max_eval",
"=",
"MAX_OPTIMIZATION_FEV",
",",
"norm_c",
"=",
"DEFAULT_NORM_C",
")",
":",
"x0",
"=",
"np",
".",
"array",
"(",
"[",
"self",
".",
"parameter",
"[",
"param",
"]",
"for",
"param",
"in",
"PARAM_ORDER",
"]",
")",
"available_tracks",
"=",
"np",
".",
"sum",
"(",
"[",
"len",
"(",
"s",
".",
"inliers",
")",
"for",
"s",
"in",
"self",
".",
"slices",
"]",
")",
"if",
"available_tracks",
"<",
"max_tracks",
":",
"warnings",
".",
"warn",
"(",
"\"Could not use the requested {} tracks, since only {} were available in the slice data.\"",
".",
"format",
"(",
"max_tracks",
",",
"available_tracks",
")",
")",
"max_tracks",
"=",
"available_tracks",
"# Get subset of available tracks such that all slices are still used",
"slice_sample_idxs",
"=",
"videoslice",
".",
"fill_sampling",
"(",
"self",
".",
"slices",
",",
"max_tracks",
")",
"func_args",
"=",
"(",
"self",
".",
"slices",
",",
"slice_sample_idxs",
",",
"self",
".",
"video",
".",
"camera_model",
",",
"self",
".",
"gyro",
",",
"norm_c",
")",
"self",
".",
"slice_sample_idxs",
"=",
"slice_sample_idxs",
"logger",
".",
"debug",
"(",
"\"Starting optimization on {:d} slices and {:d} tracks\"",
".",
"format",
"(",
"len",
"(",
"self",
".",
"slices",
")",
",",
"max_tracks",
")",
")",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"# TODO: Check what values of ftol and xtol are required for good results. The current setting is probably pessimistic.",
"leastsq_result",
"=",
"scipy",
".",
"optimize",
".",
"leastsq",
"(",
"optimization_func",
",",
"x0",
",",
"args",
"=",
"func_args",
",",
"full_output",
"=",
"True",
",",
"ftol",
"=",
"1e-10",
",",
"xtol",
"=",
"1e-10",
",",
"maxfev",
"=",
"max_eval",
")",
"elapsed",
"=",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
"x",
",",
"covx",
",",
"infodict",
",",
"mesg",
",",
"ier",
"=",
"leastsq_result",
"self",
".",
"__debug_leastsq",
"=",
"leastsq_result",
"logger",
".",
"debug",
"(",
"\"Optimization completed in {:.1f} seconds and {:d} function evaluations. ier={}, mesg='{}'\"",
".",
"format",
"(",
"elapsed",
",",
"infodict",
"[",
"'nfev'",
"]",
",",
"ier",
",",
"mesg",
")",
")",
"if",
"ier",
"in",
"(",
"1",
",",
"2",
",",
"3",
",",
"4",
")",
":",
"for",
"pname",
",",
"val",
"in",
"zip",
"(",
"PARAM_ORDER",
",",
"x",
")",
":",
"self",
".",
"params",
"[",
"'calibrated'",
"]",
"[",
"pname",
"]",
"=",
"val",
"return",
"self",
".",
"parameter",
"else",
":",
"raise",
"CalibrationError",
"(",
"mesg",
")"
] | Perform calibration
Parameters
----------------------
max_eval : int
Maximum number of function evaluations
Returns
---------------------
dict
Optimization result
Raises
-----------------------
CalibrationError
If calibration fails | [
"Perform",
"calibration"
] | train | https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/calibration.py#L167-L209 |
hovren/crisp | crisp/calibration.py | AutoCalibrator.find_initial_offset | def find_initial_offset(self, pyramids=6):
"""Estimate time offset
This sets and returns the initial time offset estimation.
Parameters
---------------
pyramids : int
Number of pyramids to use for ZNCC calculations.
If initial estimation of time offset fails, try lowering this value.
Returns
---------------
float
Estimated time offset
"""
flow = self.video.flow
gyro_rate = self.parameter['gyro_rate']
frame_times = np.arange(len(flow)) / self.video.frame_rate
gyro_times = np.arange(self.gyro.num_samples) / gyro_rate
time_offset = timesync.sync_camera_gyro(flow, frame_times, self.gyro.data.T, gyro_times, levels=pyramids)
logger.debug("Initial time offset: {:.4f}".format(time_offset))
self.params['initialized']['time_offset'] = time_offset
return time_offset | python | def find_initial_offset(self, pyramids=6):
"""Estimate time offset
This sets and returns the initial time offset estimation.
Parameters
---------------
pyramids : int
Number of pyramids to use for ZNCC calculations.
If initial estimation of time offset fails, try lowering this value.
Returns
---------------
float
Estimated time offset
"""
flow = self.video.flow
gyro_rate = self.parameter['gyro_rate']
frame_times = np.arange(len(flow)) / self.video.frame_rate
gyro_times = np.arange(self.gyro.num_samples) / gyro_rate
time_offset = timesync.sync_camera_gyro(flow, frame_times, self.gyro.data.T, gyro_times, levels=pyramids)
logger.debug("Initial time offset: {:.4f}".format(time_offset))
self.params['initialized']['time_offset'] = time_offset
return time_offset | [
"def",
"find_initial_offset",
"(",
"self",
",",
"pyramids",
"=",
"6",
")",
":",
"flow",
"=",
"self",
".",
"video",
".",
"flow",
"gyro_rate",
"=",
"self",
".",
"parameter",
"[",
"'gyro_rate'",
"]",
"frame_times",
"=",
"np",
".",
"arange",
"(",
"len",
"(",
"flow",
")",
")",
"/",
"self",
".",
"video",
".",
"frame_rate",
"gyro_times",
"=",
"np",
".",
"arange",
"(",
"self",
".",
"gyro",
".",
"num_samples",
")",
"/",
"gyro_rate",
"time_offset",
"=",
"timesync",
".",
"sync_camera_gyro",
"(",
"flow",
",",
"frame_times",
",",
"self",
".",
"gyro",
".",
"data",
".",
"T",
",",
"gyro_times",
",",
"levels",
"=",
"pyramids",
")",
"logger",
".",
"debug",
"(",
"\"Initial time offset: {:.4f}\"",
".",
"format",
"(",
"time_offset",
")",
")",
"self",
".",
"params",
"[",
"'initialized'",
"]",
"[",
"'time_offset'",
"]",
"=",
"time_offset",
"return",
"time_offset"
] | Estimate time offset
This sets and returns the initial time offset estimation.
Parameters
---------------
pyramids : int
Number of pyramids to use for ZNCC calculations.
If initial estimation of time offset fails, try lowering this value.
Returns
---------------
float
Estimated time offset | [
"Estimate",
"time",
"offset",
"This",
"sets",
"and",
"returns",
"the",
"initial",
"time",
"offset",
"estimation",
".",
"Parameters",
"---------------",
"pyramids",
":",
"int",
"Number",
"of",
"pyramids",
"to",
"use",
"for",
"ZNCC",
"calculations",
".",
"If",
"initial",
"estimation",
"of",
"time",
"offset",
"fails",
"try",
"lowering",
"this",
"value",
"."
] | train | https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/calibration.py#L211-L236 |
hovren/crisp | crisp/calibration.py | AutoCalibrator.find_initial_rotation | def find_initial_rotation(self):
"""Estimate rotation between camera and gyroscope
This sets and returns the initial rotation estimate.
Note that the initial time offset must have been estimated before calling this function!
Returns
--------------------
(3,3) ndarray
Estimated rotation between camera and gyroscope
"""
if 'time_offset' not in self.parameter:
raise InitializationError("Can not estimate rotation without an estimate of time offset. Please estimate the offset and try again.")
dt = float(1.0 / self.parameter['gyro_rate']) # Must be python float for fastintegrate
q = self.gyro.integrate(dt)
video_axes = []
gyro_axes = []
for _slice in self.slices:
# Estimate rotation here
_slice.estimate_rotation(self.video.camera_model, ransac_threshold=7.0) # sets .axis and .angle memebers
if _slice.axis is None:
continue
assert _slice.angle > 0
t1 = _slice.start / self.video.frame_rate
n1, _ = self.video_time_to_gyro_sample(t1)
t2 = _slice.end / self.video.frame_rate
n2, _ = self.video_time_to_gyro_sample(t2)
try:
qx = q[n1]
qy = q[n2]
except IndexError:
continue # No gyro data -> nothing to do with this slice
Rx = rotations.quat_to_rotation_matrix(qx)
Ry = rotations.quat_to_rotation_matrix(qy)
R = np.dot(Rx.T, Ry)
v, theta = rotations.rotation_matrix_to_axis_angle(R)
if theta < 0:
v = -v
gyro_axes.append(v)
video_axes.append(_slice.axis)
if len(gyro_axes) < 2:
logger.warning("Rotation estimation requires at least 2 rotation axes, got {}".format(len(gyro_axes)))
return None
logger.debug("Using {:d} slices (from initial {:d} for rotation estimation".format(len(gyro_axes), len(self.slices)))
model_func = lambda data: rotations.procrustes(data[:3], data[3:6], remove_mean=False)[0]
def eval_func(model, data):
X = data[:3].reshape(3,-1)
Y = data[3:6].reshape(3,-1)
R = model
Xhat = np.dot(R, Y)
costheta = np.sum(Xhat*X, axis=0)
theta = np.arccos(costheta)
return theta
inlier_selection_prob = 0.99999
model_points = 2 # Set to 3 to use non-minimal case
inlier_ratio = 0.5
threshold = np.deg2rad(10.0)
ransac_iterations = int(np.log(1 - inlier_selection_prob) / np.log(1-inlier_ratio**model_points))
data = np.vstack((np.array(video_axes).T, np.array(gyro_axes).T))
assert data.shape == (6, len(gyro_axes))
R, ransac_conseus_idx = ransac.RANSAC(model_func, eval_func, data,
model_points, ransac_iterations,
threshold, recalculate=True)
n, theta = rotations.rotation_matrix_to_axis_angle(R)
logger.debug("Found rotation: n={} theta={}; r={}".format(n, theta, n*theta))
logger.debug(R)
rx, ry, rz = theta * n
self.params['initialized']['rot_x'] = rx
self.params['initialized']['rot_y'] = ry
self.params['initialized']['rot_z'] = rz
return R | python | def find_initial_rotation(self):
"""Estimate rotation between camera and gyroscope
This sets and returns the initial rotation estimate.
Note that the initial time offset must have been estimated before calling this function!
Returns
--------------------
(3,3) ndarray
Estimated rotation between camera and gyroscope
"""
if 'time_offset' not in self.parameter:
raise InitializationError("Can not estimate rotation without an estimate of time offset. Please estimate the offset and try again.")
dt = float(1.0 / self.parameter['gyro_rate']) # Must be python float for fastintegrate
q = self.gyro.integrate(dt)
video_axes = []
gyro_axes = []
for _slice in self.slices:
# Estimate rotation here
_slice.estimate_rotation(self.video.camera_model, ransac_threshold=7.0) # sets .axis and .angle memebers
if _slice.axis is None:
continue
assert _slice.angle > 0
t1 = _slice.start / self.video.frame_rate
n1, _ = self.video_time_to_gyro_sample(t1)
t2 = _slice.end / self.video.frame_rate
n2, _ = self.video_time_to_gyro_sample(t2)
try:
qx = q[n1]
qy = q[n2]
except IndexError:
continue # No gyro data -> nothing to do with this slice
Rx = rotations.quat_to_rotation_matrix(qx)
Ry = rotations.quat_to_rotation_matrix(qy)
R = np.dot(Rx.T, Ry)
v, theta = rotations.rotation_matrix_to_axis_angle(R)
if theta < 0:
v = -v
gyro_axes.append(v)
video_axes.append(_slice.axis)
if len(gyro_axes) < 2:
logger.warning("Rotation estimation requires at least 2 rotation axes, got {}".format(len(gyro_axes)))
return None
logger.debug("Using {:d} slices (from initial {:d} for rotation estimation".format(len(gyro_axes), len(self.slices)))
model_func = lambda data: rotations.procrustes(data[:3], data[3:6], remove_mean=False)[0]
def eval_func(model, data):
X = data[:3].reshape(3,-1)
Y = data[3:6].reshape(3,-1)
R = model
Xhat = np.dot(R, Y)
costheta = np.sum(Xhat*X, axis=0)
theta = np.arccos(costheta)
return theta
inlier_selection_prob = 0.99999
model_points = 2 # Set to 3 to use non-minimal case
inlier_ratio = 0.5
threshold = np.deg2rad(10.0)
ransac_iterations = int(np.log(1 - inlier_selection_prob) / np.log(1-inlier_ratio**model_points))
data = np.vstack((np.array(video_axes).T, np.array(gyro_axes).T))
assert data.shape == (6, len(gyro_axes))
R, ransac_conseus_idx = ransac.RANSAC(model_func, eval_func, data,
model_points, ransac_iterations,
threshold, recalculate=True)
n, theta = rotations.rotation_matrix_to_axis_angle(R)
logger.debug("Found rotation: n={} theta={}; r={}".format(n, theta, n*theta))
logger.debug(R)
rx, ry, rz = theta * n
self.params['initialized']['rot_x'] = rx
self.params['initialized']['rot_y'] = ry
self.params['initialized']['rot_z'] = rz
return R | [
"def",
"find_initial_rotation",
"(",
"self",
")",
":",
"if",
"'time_offset'",
"not",
"in",
"self",
".",
"parameter",
":",
"raise",
"InitializationError",
"(",
"\"Can not estimate rotation without an estimate of time offset. Please estimate the offset and try again.\"",
")",
"dt",
"=",
"float",
"(",
"1.0",
"/",
"self",
".",
"parameter",
"[",
"'gyro_rate'",
"]",
")",
"# Must be python float for fastintegrate",
"q",
"=",
"self",
".",
"gyro",
".",
"integrate",
"(",
"dt",
")",
"video_axes",
"=",
"[",
"]",
"gyro_axes",
"=",
"[",
"]",
"for",
"_slice",
"in",
"self",
".",
"slices",
":",
"# Estimate rotation here",
"_slice",
".",
"estimate_rotation",
"(",
"self",
".",
"video",
".",
"camera_model",
",",
"ransac_threshold",
"=",
"7.0",
")",
"# sets .axis and .angle memebers",
"if",
"_slice",
".",
"axis",
"is",
"None",
":",
"continue",
"assert",
"_slice",
".",
"angle",
">",
"0",
"t1",
"=",
"_slice",
".",
"start",
"/",
"self",
".",
"video",
".",
"frame_rate",
"n1",
",",
"_",
"=",
"self",
".",
"video_time_to_gyro_sample",
"(",
"t1",
")",
"t2",
"=",
"_slice",
".",
"end",
"/",
"self",
".",
"video",
".",
"frame_rate",
"n2",
",",
"_",
"=",
"self",
".",
"video_time_to_gyro_sample",
"(",
"t2",
")",
"try",
":",
"qx",
"=",
"q",
"[",
"n1",
"]",
"qy",
"=",
"q",
"[",
"n2",
"]",
"except",
"IndexError",
":",
"continue",
"# No gyro data -> nothing to do with this slice",
"Rx",
"=",
"rotations",
".",
"quat_to_rotation_matrix",
"(",
"qx",
")",
"Ry",
"=",
"rotations",
".",
"quat_to_rotation_matrix",
"(",
"qy",
")",
"R",
"=",
"np",
".",
"dot",
"(",
"Rx",
".",
"T",
",",
"Ry",
")",
"v",
",",
"theta",
"=",
"rotations",
".",
"rotation_matrix_to_axis_angle",
"(",
"R",
")",
"if",
"theta",
"<",
"0",
":",
"v",
"=",
"-",
"v",
"gyro_axes",
".",
"append",
"(",
"v",
")",
"video_axes",
".",
"append",
"(",
"_slice",
".",
"axis",
")",
"if",
"len",
"(",
"gyro_axes",
")",
"<",
"2",
":",
"logger",
".",
"warning",
"(",
"\"Rotation estimation requires at least 2 rotation axes, got {}\"",
".",
"format",
"(",
"len",
"(",
"gyro_axes",
")",
")",
")",
"return",
"None",
"logger",
".",
"debug",
"(",
"\"Using {:d} slices (from initial {:d} for rotation estimation\"",
".",
"format",
"(",
"len",
"(",
"gyro_axes",
")",
",",
"len",
"(",
"self",
".",
"slices",
")",
")",
")",
"model_func",
"=",
"lambda",
"data",
":",
"rotations",
".",
"procrustes",
"(",
"data",
"[",
":",
"3",
"]",
",",
"data",
"[",
"3",
":",
"6",
"]",
",",
"remove_mean",
"=",
"False",
")",
"[",
"0",
"]",
"def",
"eval_func",
"(",
"model",
",",
"data",
")",
":",
"X",
"=",
"data",
"[",
":",
"3",
"]",
".",
"reshape",
"(",
"3",
",",
"-",
"1",
")",
"Y",
"=",
"data",
"[",
"3",
":",
"6",
"]",
".",
"reshape",
"(",
"3",
",",
"-",
"1",
")",
"R",
"=",
"model",
"Xhat",
"=",
"np",
".",
"dot",
"(",
"R",
",",
"Y",
")",
"costheta",
"=",
"np",
".",
"sum",
"(",
"Xhat",
"*",
"X",
",",
"axis",
"=",
"0",
")",
"theta",
"=",
"np",
".",
"arccos",
"(",
"costheta",
")",
"return",
"theta",
"inlier_selection_prob",
"=",
"0.99999",
"model_points",
"=",
"2",
"# Set to 3 to use non-minimal case",
"inlier_ratio",
"=",
"0.5",
"threshold",
"=",
"np",
".",
"deg2rad",
"(",
"10.0",
")",
"ransac_iterations",
"=",
"int",
"(",
"np",
".",
"log",
"(",
"1",
"-",
"inlier_selection_prob",
")",
"/",
"np",
".",
"log",
"(",
"1",
"-",
"inlier_ratio",
"**",
"model_points",
")",
")",
"data",
"=",
"np",
".",
"vstack",
"(",
"(",
"np",
".",
"array",
"(",
"video_axes",
")",
".",
"T",
",",
"np",
".",
"array",
"(",
"gyro_axes",
")",
".",
"T",
")",
")",
"assert",
"data",
".",
"shape",
"==",
"(",
"6",
",",
"len",
"(",
"gyro_axes",
")",
")",
"R",
",",
"ransac_conseus_idx",
"=",
"ransac",
".",
"RANSAC",
"(",
"model_func",
",",
"eval_func",
",",
"data",
",",
"model_points",
",",
"ransac_iterations",
",",
"threshold",
",",
"recalculate",
"=",
"True",
")",
"n",
",",
"theta",
"=",
"rotations",
".",
"rotation_matrix_to_axis_angle",
"(",
"R",
")",
"logger",
".",
"debug",
"(",
"\"Found rotation: n={} theta={}; r={}\"",
".",
"format",
"(",
"n",
",",
"theta",
",",
"n",
"*",
"theta",
")",
")",
"logger",
".",
"debug",
"(",
"R",
")",
"rx",
",",
"ry",
",",
"rz",
"=",
"theta",
"*",
"n",
"self",
".",
"params",
"[",
"'initialized'",
"]",
"[",
"'rot_x'",
"]",
"=",
"rx",
"self",
".",
"params",
"[",
"'initialized'",
"]",
"[",
"'rot_y'",
"]",
"=",
"ry",
"self",
".",
"params",
"[",
"'initialized'",
"]",
"[",
"'rot_z'",
"]",
"=",
"rz",
"return",
"R"
] | Estimate rotation between camera and gyroscope
This sets and returns the initial rotation estimate.
Note that the initial time offset must have been estimated before calling this function!
Returns
--------------------
(3,3) ndarray
Estimated rotation between camera and gyroscope | [
"Estimate",
"rotation",
"between",
"camera",
"and",
"gyroscope",
"This",
"sets",
"and",
"returns",
"the",
"initial",
"rotation",
"estimate",
".",
"Note",
"that",
"the",
"initial",
"time",
"offset",
"must",
"have",
"been",
"estimated",
"before",
"calling",
"this",
"function!"
] | train | https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/calibration.py#L238-L326 |
hovren/crisp | crisp/calibration.py | AutoCalibrator.print_params | def print_params(self):
"""Print the current best set of parameters"""
print("Parameters")
print("--------------------")
for param in PARAM_ORDER:
print(' {:>11s} = {}'.format(param, self.parameter[param])) | python | def print_params(self):
"""Print the current best set of parameters"""
print("Parameters")
print("--------------------")
for param in PARAM_ORDER:
print(' {:>11s} = {}'.format(param, self.parameter[param])) | [
"def",
"print_params",
"(",
"self",
")",
":",
"print",
"(",
"\"Parameters\"",
")",
"print",
"(",
"\"--------------------\"",
")",
"for",
"param",
"in",
"PARAM_ORDER",
":",
"print",
"(",
"' {:>11s} = {}'",
".",
"format",
"(",
"param",
",",
"self",
".",
"parameter",
"[",
"param",
"]",
")",
")"
] | Print the current best set of parameters | [
"Print",
"the",
"current",
"best",
"set",
"of",
"parameters"
] | train | https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/calibration.py#L328-L333 |
hovren/crisp | crisp/remove_slp.py | remove_slp | def remove_slp(img, gstd1=GSTD1, gstd2=GSTD2, gstd3=GSTD3, ksize=KSIZE, w=W):
"""Remove the SLP from kinect IR image
The input image should be a float32 numpy array, and should NOT be a square root image
Parameters
------------------
img : (M, N) float ndarray
Kinect NIR image with SLP pattern
gstd1 : float
Standard deviation of gaussian kernel 1
gstd2 : float
Standard deviation of gaussian kernel 2
gstd3 : float
Standard deviation of gaussian kernel 3
ksize : int
Size of kernel (should be odd)
w : float
Weighting factor
Returns
------------------
img_noslp : (M,N) float ndarray
Input image with SLP removed
"""
gf1 = cv2.getGaussianKernel(ksize, gstd1)
gf2 = cv2.getGaussianKernel(ksize, gstd2)
gf3 = cv2.getGaussianKernel(ksize, gstd3)
sqrtimg = cv2.sqrt(img)
p1 = cv2.sepFilter2D(sqrtimg, -1, gf1, gf1)
p2 = cv2.sepFilter2D(sqrtimg, -1, gf2, gf2)
maxarr = np.maximum(0, (p1 - p2) / p2)
minarr = np.minimum(w * maxarr, 1)
p = 1 - minarr
nc = cv2.sepFilter2D(p, -1, gf3, gf3) + EPS
output = cv2.sepFilter2D(p*sqrtimg, -1, gf3, gf3)
output = (output / nc) ** 2 # Since input is sqrted
return output | python | def remove_slp(img, gstd1=GSTD1, gstd2=GSTD2, gstd3=GSTD3, ksize=KSIZE, w=W):
"""Remove the SLP from kinect IR image
The input image should be a float32 numpy array, and should NOT be a square root image
Parameters
------------------
img : (M, N) float ndarray
Kinect NIR image with SLP pattern
gstd1 : float
Standard deviation of gaussian kernel 1
gstd2 : float
Standard deviation of gaussian kernel 2
gstd3 : float
Standard deviation of gaussian kernel 3
ksize : int
Size of kernel (should be odd)
w : float
Weighting factor
Returns
------------------
img_noslp : (M,N) float ndarray
Input image with SLP removed
"""
gf1 = cv2.getGaussianKernel(ksize, gstd1)
gf2 = cv2.getGaussianKernel(ksize, gstd2)
gf3 = cv2.getGaussianKernel(ksize, gstd3)
sqrtimg = cv2.sqrt(img)
p1 = cv2.sepFilter2D(sqrtimg, -1, gf1, gf1)
p2 = cv2.sepFilter2D(sqrtimg, -1, gf2, gf2)
maxarr = np.maximum(0, (p1 - p2) / p2)
minarr = np.minimum(w * maxarr, 1)
p = 1 - minarr
nc = cv2.sepFilter2D(p, -1, gf3, gf3) + EPS
output = cv2.sepFilter2D(p*sqrtimg, -1, gf3, gf3)
output = (output / nc) ** 2 # Since input is sqrted
return output | [
"def",
"remove_slp",
"(",
"img",
",",
"gstd1",
"=",
"GSTD1",
",",
"gstd2",
"=",
"GSTD2",
",",
"gstd3",
"=",
"GSTD3",
",",
"ksize",
"=",
"KSIZE",
",",
"w",
"=",
"W",
")",
":",
"gf1",
"=",
"cv2",
".",
"getGaussianKernel",
"(",
"ksize",
",",
"gstd1",
")",
"gf2",
"=",
"cv2",
".",
"getGaussianKernel",
"(",
"ksize",
",",
"gstd2",
")",
"gf3",
"=",
"cv2",
".",
"getGaussianKernel",
"(",
"ksize",
",",
"gstd3",
")",
"sqrtimg",
"=",
"cv2",
".",
"sqrt",
"(",
"img",
")",
"p1",
"=",
"cv2",
".",
"sepFilter2D",
"(",
"sqrtimg",
",",
"-",
"1",
",",
"gf1",
",",
"gf1",
")",
"p2",
"=",
"cv2",
".",
"sepFilter2D",
"(",
"sqrtimg",
",",
"-",
"1",
",",
"gf2",
",",
"gf2",
")",
"maxarr",
"=",
"np",
".",
"maximum",
"(",
"0",
",",
"(",
"p1",
"-",
"p2",
")",
"/",
"p2",
")",
"minarr",
"=",
"np",
".",
"minimum",
"(",
"w",
"*",
"maxarr",
",",
"1",
")",
"p",
"=",
"1",
"-",
"minarr",
"nc",
"=",
"cv2",
".",
"sepFilter2D",
"(",
"p",
",",
"-",
"1",
",",
"gf3",
",",
"gf3",
")",
"+",
"EPS",
"output",
"=",
"cv2",
".",
"sepFilter2D",
"(",
"p",
"*",
"sqrtimg",
",",
"-",
"1",
",",
"gf3",
",",
"gf3",
")",
"output",
"=",
"(",
"output",
"/",
"nc",
")",
"**",
"2",
"# Since input is sqrted",
"return",
"output"
] | Remove the SLP from kinect IR image
The input image should be a float32 numpy array, and should NOT be a square root image
Parameters
------------------
img : (M, N) float ndarray
Kinect NIR image with SLP pattern
gstd1 : float
Standard deviation of gaussian kernel 1
gstd2 : float
Standard deviation of gaussian kernel 2
gstd3 : float
Standard deviation of gaussian kernel 3
ksize : int
Size of kernel (should be odd)
w : float
Weighting factor
Returns
------------------
img_noslp : (M,N) float ndarray
Input image with SLP removed | [
"Remove",
"the",
"SLP",
"from",
"kinect",
"IR",
"image",
"The",
"input",
"image",
"should",
"be",
"a",
"float32",
"numpy",
"array",
"and",
"should",
"NOT",
"be",
"a",
"square",
"root",
"image",
"Parameters",
"------------------",
"img",
":",
"(",
"M",
"N",
")",
"float",
"ndarray",
"Kinect",
"NIR",
"image",
"with",
"SLP",
"pattern",
"gstd1",
":",
"float",
"Standard",
"deviation",
"of",
"gaussian",
"kernel",
"1",
"gstd2",
":",
"float",
"Standard",
"deviation",
"of",
"gaussian",
"kernel",
"2",
"gstd3",
":",
"float",
"Standard",
"deviation",
"of",
"gaussian",
"kernel",
"3",
"ksize",
":",
"int",
"Size",
"of",
"kernel",
"(",
"should",
"be",
"odd",
")",
"w",
":",
"float",
"Weighting",
"factor"
] | train | https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/remove_slp.py#L37-L74 |
hovren/crisp | crisp/camera.py | AtanCameraModel.from_hdf | def from_hdf(cls, filename):
"""Load camera model params from a HDF5 file
The HDF5 file should contain the following datasets:
wc : (2,) float with distortion center
lgamma : float distortion parameter
readout : float readout value
size : (2,) int image size
fps : float frame rate
K : (3, 3) float camera matrix
Parameters
--------------------
filename : str
Path to file with parameters
Returns
---------------------
AtanCameraModel
Camera model instance
"""
import h5py
with h5py.File(filename, 'r') as f:
wc = f["wc"].value
lgamma = f["lgamma"].value
K = f["K"].value
readout = f["readout"].value
image_size = f["size"].value
fps = f["fps"].value
instance = cls(image_size, fps, readout, K, wc, lgamma)
return instance | python | def from_hdf(cls, filename):
"""Load camera model params from a HDF5 file
The HDF5 file should contain the following datasets:
wc : (2,) float with distortion center
lgamma : float distortion parameter
readout : float readout value
size : (2,) int image size
fps : float frame rate
K : (3, 3) float camera matrix
Parameters
--------------------
filename : str
Path to file with parameters
Returns
---------------------
AtanCameraModel
Camera model instance
"""
import h5py
with h5py.File(filename, 'r') as f:
wc = f["wc"].value
lgamma = f["lgamma"].value
K = f["K"].value
readout = f["readout"].value
image_size = f["size"].value
fps = f["fps"].value
instance = cls(image_size, fps, readout, K, wc, lgamma)
return instance | [
"def",
"from_hdf",
"(",
"cls",
",",
"filename",
")",
":",
"import",
"h5py",
"with",
"h5py",
".",
"File",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"wc",
"=",
"f",
"[",
"\"wc\"",
"]",
".",
"value",
"lgamma",
"=",
"f",
"[",
"\"lgamma\"",
"]",
".",
"value",
"K",
"=",
"f",
"[",
"\"K\"",
"]",
".",
"value",
"readout",
"=",
"f",
"[",
"\"readout\"",
"]",
".",
"value",
"image_size",
"=",
"f",
"[",
"\"size\"",
"]",
".",
"value",
"fps",
"=",
"f",
"[",
"\"fps\"",
"]",
".",
"value",
"instance",
"=",
"cls",
"(",
"image_size",
",",
"fps",
",",
"readout",
",",
"K",
",",
"wc",
",",
"lgamma",
")",
"return",
"instance"
] | Load camera model params from a HDF5 file
The HDF5 file should contain the following datasets:
wc : (2,) float with distortion center
lgamma : float distortion parameter
readout : float readout value
size : (2,) int image size
fps : float frame rate
K : (3, 3) float camera matrix
Parameters
--------------------
filename : str
Path to file with parameters
Returns
---------------------
AtanCameraModel
Camera model instance | [
"Load",
"camera",
"model",
"params",
"from",
"a",
"HDF5",
"file"
] | train | https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/camera.py#L128-L158 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.