id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
229,100 | stitchfix/pyxley | pyxley/utils/flask_helper.py | default_template_path | def default_template_path():
"""
Return the path to the index.html
"""
fdir = os.path.dirname(__file__)
return os.path.abspath(os.path.join(fdir, '../assets/')) | python | def default_template_path():
"""
Return the path to the index.html
"""
fdir = os.path.dirname(__file__)
return os.path.abspath(os.path.join(fdir, '../assets/')) | [
"def",
"default_template_path",
"(",
")",
":",
"fdir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"fdir",
",",
"'../assets/'",
")",
")"
] | Return the path to the index.html | [
"Return",
"the",
"path",
"to",
"the",
"index",
".",
"html"
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/utils/flask_helper.py#L38-L43 |
229,101 | stitchfix/pyxley | pyxley/charts/mg/axes.py | Axes.set_xlim | def set_xlim(self, xlim):
""" Set x-axis limits.
Accepts a two-element list to set the x-axis limits.
Args:
xlim (list): lower and upper bounds
Raises:
ValueError: xlim must contain two elements
ValueError: Min must be less than max
"""
if len(xlim) != 2:
raise ValueError("xlim must contain two elements")
if xlim[1] < xlim[0]:
raise ValueError("Min must be less than Max")
self.options["min_x"] = xlim[0]
self.options["max_x"] = xlim[1] | python | def set_xlim(self, xlim):
""" Set x-axis limits.
Accepts a two-element list to set the x-axis limits.
Args:
xlim (list): lower and upper bounds
Raises:
ValueError: xlim must contain two elements
ValueError: Min must be less than max
"""
if len(xlim) != 2:
raise ValueError("xlim must contain two elements")
if xlim[1] < xlim[0]:
raise ValueError("Min must be less than Max")
self.options["min_x"] = xlim[0]
self.options["max_x"] = xlim[1] | [
"def",
"set_xlim",
"(",
"self",
",",
"xlim",
")",
":",
"if",
"len",
"(",
"xlim",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"\"xlim must contain two elements\"",
")",
"if",
"xlim",
"[",
"1",
"]",
"<",
"xlim",
"[",
"0",
"]",
":",
"raise",
"ValueError",
"(",
"\"Min must be less than Max\"",
")",
"self",
".",
"options",
"[",
"\"min_x\"",
"]",
"=",
"xlim",
"[",
"0",
"]",
"self",
".",
"options",
"[",
"\"max_x\"",
"]",
"=",
"xlim",
"[",
"1",
"]"
] | Set x-axis limits.
Accepts a two-element list to set the x-axis limits.
Args:
xlim (list): lower and upper bounds
Raises:
ValueError: xlim must contain two elements
ValueError: Min must be less than max | [
"Set",
"x",
"-",
"axis",
"limits",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/mg/axes.py#L46-L65 |
229,102 | stitchfix/pyxley | pyxley/charts/mg/axes.py | Axes.set_ylim | def set_ylim(self, ylim):
""" Set y-axis limits.
Accepts a two-element list to set the y-axis limits.
Args:
ylim (list): lower and upper bounds
Raises:
ValueError: ylim must contain two elements
ValueError: Min must be less than max
"""
if len(ylim) != 2:
raise ValueError("ylim must contain two elements")
if ylim[1] < ylim[0]:
raise ValueError("Min must be less than Max")
self.options["min_y"] = ylim[0]
self.options["max_y"] = ylim[1] | python | def set_ylim(self, ylim):
""" Set y-axis limits.
Accepts a two-element list to set the y-axis limits.
Args:
ylim (list): lower and upper bounds
Raises:
ValueError: ylim must contain two elements
ValueError: Min must be less than max
"""
if len(ylim) != 2:
raise ValueError("ylim must contain two elements")
if ylim[1] < ylim[0]:
raise ValueError("Min must be less than Max")
self.options["min_y"] = ylim[0]
self.options["max_y"] = ylim[1] | [
"def",
"set_ylim",
"(",
"self",
",",
"ylim",
")",
":",
"if",
"len",
"(",
"ylim",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"\"ylim must contain two elements\"",
")",
"if",
"ylim",
"[",
"1",
"]",
"<",
"ylim",
"[",
"0",
"]",
":",
"raise",
"ValueError",
"(",
"\"Min must be less than Max\"",
")",
"self",
".",
"options",
"[",
"\"min_y\"",
"]",
"=",
"ylim",
"[",
"0",
"]",
"self",
".",
"options",
"[",
"\"max_y\"",
"]",
"=",
"ylim",
"[",
"1",
"]"
] | Set y-axis limits.
Accepts a two-element list to set the y-axis limits.
Args:
ylim (list): lower and upper bounds
Raises:
ValueError: ylim must contain two elements
ValueError: Min must be less than max | [
"Set",
"y",
"-",
"axis",
"limits",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/mg/axes.py#L67-L86 |
229,103 | stitchfix/pyxley | pyxley/charts/mg/axes.py | Axes.get | def get(self):
""" Retrieve options set by user."""
return {k:v for k,v in list(self.options.items()) if k in self._allowed_axes} | python | def get(self):
""" Retrieve options set by user."""
return {k:v for k,v in list(self.options.items()) if k in self._allowed_axes} | [
"def",
"get",
"(",
"self",
")",
":",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"self",
".",
"options",
".",
"items",
"(",
")",
")",
"if",
"k",
"in",
"self",
".",
"_allowed_axes",
"}"
] | Retrieve options set by user. | [
"Retrieve",
"options",
"set",
"by",
"user",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/mg/axes.py#L168-L170 |
229,104 | stitchfix/pyxley | pyxley/charts/plotly/base.py | PlotlyAPI.line_plot | def line_plot(df, xypairs, mode, layout={}, config=_BASE_CONFIG):
""" basic line plot
dataframe to json for a line plot
Args:
df (pandas.DataFrame): input dataframe
xypairs (list): list of tuples containing column names
mode (str): plotly.js mode (e.g. lines)
layout (dict): layout parameters
config (dict): config parameters
"""
if df.empty:
return {
"x": [],
"y": [],
"mode": mode
}
_data = []
for x, y in xypairs:
if (x in df.columns) and (y in df.columns):
_data.append(
{
"x": df[x].values.tolist(),
"y": df[y].values.tolist(),
"mode": mode
}
)
return {
"data": _data,
"layout": layout,
"config": config
} | python | def line_plot(df, xypairs, mode, layout={}, config=_BASE_CONFIG):
""" basic line plot
dataframe to json for a line plot
Args:
df (pandas.DataFrame): input dataframe
xypairs (list): list of tuples containing column names
mode (str): plotly.js mode (e.g. lines)
layout (dict): layout parameters
config (dict): config parameters
"""
if df.empty:
return {
"x": [],
"y": [],
"mode": mode
}
_data = []
for x, y in xypairs:
if (x in df.columns) and (y in df.columns):
_data.append(
{
"x": df[x].values.tolist(),
"y": df[y].values.tolist(),
"mode": mode
}
)
return {
"data": _data,
"layout": layout,
"config": config
} | [
"def",
"line_plot",
"(",
"df",
",",
"xypairs",
",",
"mode",
",",
"layout",
"=",
"{",
"}",
",",
"config",
"=",
"_BASE_CONFIG",
")",
":",
"if",
"df",
".",
"empty",
":",
"return",
"{",
"\"x\"",
":",
"[",
"]",
",",
"\"y\"",
":",
"[",
"]",
",",
"\"mode\"",
":",
"mode",
"}",
"_data",
"=",
"[",
"]",
"for",
"x",
",",
"y",
"in",
"xypairs",
":",
"if",
"(",
"x",
"in",
"df",
".",
"columns",
")",
"and",
"(",
"y",
"in",
"df",
".",
"columns",
")",
":",
"_data",
".",
"append",
"(",
"{",
"\"x\"",
":",
"df",
"[",
"x",
"]",
".",
"values",
".",
"tolist",
"(",
")",
",",
"\"y\"",
":",
"df",
"[",
"y",
"]",
".",
"values",
".",
"tolist",
"(",
")",
",",
"\"mode\"",
":",
"mode",
"}",
")",
"return",
"{",
"\"data\"",
":",
"_data",
",",
"\"layout\"",
":",
"layout",
",",
"\"config\"",
":",
"config",
"}"
] | basic line plot
dataframe to json for a line plot
Args:
df (pandas.DataFrame): input dataframe
xypairs (list): list of tuples containing column names
mode (str): plotly.js mode (e.g. lines)
layout (dict): layout parameters
config (dict): config parameters | [
"basic",
"line",
"plot"
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/plotly/base.py#L32-L66 |
229,105 | stitchfix/pyxley | pyxley/charts/nvd3/pie_chart.py | PieChart.to_json | def to_json(df, values):
"""Format output for the json response."""
records = []
if df.empty:
return {"data": []}
sum_ = float(np.sum([df[c].iloc[0] for c in values]))
for c in values:
records.append({
"label": values[c],
"value": "%.2f"%np.around(df[c].iloc[0] / sum_, decimals=2)
})
return {
"data" : records
} | python | def to_json(df, values):
"""Format output for the json response."""
records = []
if df.empty:
return {"data": []}
sum_ = float(np.sum([df[c].iloc[0] for c in values]))
for c in values:
records.append({
"label": values[c],
"value": "%.2f"%np.around(df[c].iloc[0] / sum_, decimals=2)
})
return {
"data" : records
} | [
"def",
"to_json",
"(",
"df",
",",
"values",
")",
":",
"records",
"=",
"[",
"]",
"if",
"df",
".",
"empty",
":",
"return",
"{",
"\"data\"",
":",
"[",
"]",
"}",
"sum_",
"=",
"float",
"(",
"np",
".",
"sum",
"(",
"[",
"df",
"[",
"c",
"]",
".",
"iloc",
"[",
"0",
"]",
"for",
"c",
"in",
"values",
"]",
")",
")",
"for",
"c",
"in",
"values",
":",
"records",
".",
"append",
"(",
"{",
"\"label\"",
":",
"values",
"[",
"c",
"]",
",",
"\"value\"",
":",
"\"%.2f\"",
"%",
"np",
".",
"around",
"(",
"df",
"[",
"c",
"]",
".",
"iloc",
"[",
"0",
"]",
"/",
"sum_",
",",
"decimals",
"=",
"2",
")",
"}",
")",
"return",
"{",
"\"data\"",
":",
"records",
"}"
] | Format output for the json response. | [
"Format",
"output",
"for",
"the",
"json",
"response",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/nvd3/pie_chart.py#L57-L71 |
229,106 | stitchfix/pyxley | pyxley/charts/datamaps/datamaps.py | DatamapUSA.to_json | def to_json(df, state_index, color_index, fills):
"""Transforms dataframe to json response"""
records = {}
for i, row in df.iterrows():
records[row[state_index]] = {
"fillKey": row[color_index]
}
return {
"data": records,
"fills": fills
} | python | def to_json(df, state_index, color_index, fills):
"""Transforms dataframe to json response"""
records = {}
for i, row in df.iterrows():
records[row[state_index]] = {
"fillKey": row[color_index]
}
return {
"data": records,
"fills": fills
} | [
"def",
"to_json",
"(",
"df",
",",
"state_index",
",",
"color_index",
",",
"fills",
")",
":",
"records",
"=",
"{",
"}",
"for",
"i",
",",
"row",
"in",
"df",
".",
"iterrows",
"(",
")",
":",
"records",
"[",
"row",
"[",
"state_index",
"]",
"]",
"=",
"{",
"\"fillKey\"",
":",
"row",
"[",
"color_index",
"]",
"}",
"return",
"{",
"\"data\"",
":",
"records",
",",
"\"fills\"",
":",
"fills",
"}"
] | Transforms dataframe to json response | [
"Transforms",
"dataframe",
"to",
"json",
"response"
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/datamaps/datamaps.py#L123-L135 |
229,107 | aws/aws-iot-device-sdk-python | AWSIoTPythonSDK/core/protocol/paho/client.py | error_string | def error_string(mqtt_errno):
"""Return the error string associated with an mqtt error number."""
if mqtt_errno == MQTT_ERR_SUCCESS:
return "No error."
elif mqtt_errno == MQTT_ERR_NOMEM:
return "Out of memory."
elif mqtt_errno == MQTT_ERR_PROTOCOL:
return "A network protocol error occurred when communicating with the broker."
elif mqtt_errno == MQTT_ERR_INVAL:
return "Invalid function arguments provided."
elif mqtt_errno == MQTT_ERR_NO_CONN:
return "The client is not currently connected."
elif mqtt_errno == MQTT_ERR_CONN_REFUSED:
return "The connection was refused."
elif mqtt_errno == MQTT_ERR_NOT_FOUND:
return "Message not found (internal error)."
elif mqtt_errno == MQTT_ERR_CONN_LOST:
return "The connection was lost."
elif mqtt_errno == MQTT_ERR_TLS:
return "A TLS error occurred."
elif mqtt_errno == MQTT_ERR_PAYLOAD_SIZE:
return "Payload too large."
elif mqtt_errno == MQTT_ERR_NOT_SUPPORTED:
return "This feature is not supported."
elif mqtt_errno == MQTT_ERR_AUTH:
return "Authorisation failed."
elif mqtt_errno == MQTT_ERR_ACL_DENIED:
return "Access denied by ACL."
elif mqtt_errno == MQTT_ERR_UNKNOWN:
return "Unknown error."
elif mqtt_errno == MQTT_ERR_ERRNO:
return "Error defined by errno."
else:
return "Unknown error." | python | def error_string(mqtt_errno):
"""Return the error string associated with an mqtt error number."""
if mqtt_errno == MQTT_ERR_SUCCESS:
return "No error."
elif mqtt_errno == MQTT_ERR_NOMEM:
return "Out of memory."
elif mqtt_errno == MQTT_ERR_PROTOCOL:
return "A network protocol error occurred when communicating with the broker."
elif mqtt_errno == MQTT_ERR_INVAL:
return "Invalid function arguments provided."
elif mqtt_errno == MQTT_ERR_NO_CONN:
return "The client is not currently connected."
elif mqtt_errno == MQTT_ERR_CONN_REFUSED:
return "The connection was refused."
elif mqtt_errno == MQTT_ERR_NOT_FOUND:
return "Message not found (internal error)."
elif mqtt_errno == MQTT_ERR_CONN_LOST:
return "The connection was lost."
elif mqtt_errno == MQTT_ERR_TLS:
return "A TLS error occurred."
elif mqtt_errno == MQTT_ERR_PAYLOAD_SIZE:
return "Payload too large."
elif mqtt_errno == MQTT_ERR_NOT_SUPPORTED:
return "This feature is not supported."
elif mqtt_errno == MQTT_ERR_AUTH:
return "Authorisation failed."
elif mqtt_errno == MQTT_ERR_ACL_DENIED:
return "Access denied by ACL."
elif mqtt_errno == MQTT_ERR_UNKNOWN:
return "Unknown error."
elif mqtt_errno == MQTT_ERR_ERRNO:
return "Error defined by errno."
else:
return "Unknown error." | [
"def",
"error_string",
"(",
"mqtt_errno",
")",
":",
"if",
"mqtt_errno",
"==",
"MQTT_ERR_SUCCESS",
":",
"return",
"\"No error.\"",
"elif",
"mqtt_errno",
"==",
"MQTT_ERR_NOMEM",
":",
"return",
"\"Out of memory.\"",
"elif",
"mqtt_errno",
"==",
"MQTT_ERR_PROTOCOL",
":",
"return",
"\"A network protocol error occurred when communicating with the broker.\"",
"elif",
"mqtt_errno",
"==",
"MQTT_ERR_INVAL",
":",
"return",
"\"Invalid function arguments provided.\"",
"elif",
"mqtt_errno",
"==",
"MQTT_ERR_NO_CONN",
":",
"return",
"\"The client is not currently connected.\"",
"elif",
"mqtt_errno",
"==",
"MQTT_ERR_CONN_REFUSED",
":",
"return",
"\"The connection was refused.\"",
"elif",
"mqtt_errno",
"==",
"MQTT_ERR_NOT_FOUND",
":",
"return",
"\"Message not found (internal error).\"",
"elif",
"mqtt_errno",
"==",
"MQTT_ERR_CONN_LOST",
":",
"return",
"\"The connection was lost.\"",
"elif",
"mqtt_errno",
"==",
"MQTT_ERR_TLS",
":",
"return",
"\"A TLS error occurred.\"",
"elif",
"mqtt_errno",
"==",
"MQTT_ERR_PAYLOAD_SIZE",
":",
"return",
"\"Payload too large.\"",
"elif",
"mqtt_errno",
"==",
"MQTT_ERR_NOT_SUPPORTED",
":",
"return",
"\"This feature is not supported.\"",
"elif",
"mqtt_errno",
"==",
"MQTT_ERR_AUTH",
":",
"return",
"\"Authorisation failed.\"",
"elif",
"mqtt_errno",
"==",
"MQTT_ERR_ACL_DENIED",
":",
"return",
"\"Access denied by ACL.\"",
"elif",
"mqtt_errno",
"==",
"MQTT_ERR_UNKNOWN",
":",
"return",
"\"Unknown error.\"",
"elif",
"mqtt_errno",
"==",
"MQTT_ERR_ERRNO",
":",
"return",
"\"Error defined by errno.\"",
"else",
":",
"return",
"\"Unknown error.\""
] | Return the error string associated with an mqtt error number. | [
"Return",
"the",
"error",
"string",
"associated",
"with",
"an",
"mqtt",
"error",
"number",
"."
] | f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62 | https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/core/protocol/paho/client.py#L145-L178 |
229,108 | aws/aws-iot-device-sdk-python | AWSIoTPythonSDK/core/protocol/paho/client.py | topic_matches_sub | def topic_matches_sub(sub, topic):
"""Check whether a topic matches a subscription.
For example:
foo/bar would match the subscription foo/# or +/bar
non/matching would not match the subscription non/+/+
"""
result = True
multilevel_wildcard = False
slen = len(sub)
tlen = len(topic)
if slen > 0 and tlen > 0:
if (sub[0] == '$' and topic[0] != '$') or (topic[0] == '$' and sub[0] != '$'):
return False
spos = 0
tpos = 0
while spos < slen and tpos < tlen:
if sub[spos] == topic[tpos]:
if tpos == tlen-1:
# Check for e.g. foo matching foo/#
if spos == slen-3 and sub[spos+1] == '/' and sub[spos+2] == '#':
result = True
multilevel_wildcard = True
break
spos += 1
tpos += 1
if tpos == tlen and spos == slen-1 and sub[spos] == '+':
spos += 1
result = True
break
else:
if sub[spos] == '+':
spos += 1
while tpos < tlen and topic[tpos] != '/':
tpos += 1
if tpos == tlen and spos == slen:
result = True
break
elif sub[spos] == '#':
multilevel_wildcard = True
if spos+1 != slen:
result = False
break
else:
result = True
break
else:
result = False
break
if not multilevel_wildcard and (tpos < tlen or spos < slen):
result = False
return result | python | def topic_matches_sub(sub, topic):
"""Check whether a topic matches a subscription.
For example:
foo/bar would match the subscription foo/# or +/bar
non/matching would not match the subscription non/+/+
"""
result = True
multilevel_wildcard = False
slen = len(sub)
tlen = len(topic)
if slen > 0 and tlen > 0:
if (sub[0] == '$' and topic[0] != '$') or (topic[0] == '$' and sub[0] != '$'):
return False
spos = 0
tpos = 0
while spos < slen and tpos < tlen:
if sub[spos] == topic[tpos]:
if tpos == tlen-1:
# Check for e.g. foo matching foo/#
if spos == slen-3 and sub[spos+1] == '/' and sub[spos+2] == '#':
result = True
multilevel_wildcard = True
break
spos += 1
tpos += 1
if tpos == tlen and spos == slen-1 and sub[spos] == '+':
spos += 1
result = True
break
else:
if sub[spos] == '+':
spos += 1
while tpos < tlen and topic[tpos] != '/':
tpos += 1
if tpos == tlen and spos == slen:
result = True
break
elif sub[spos] == '#':
multilevel_wildcard = True
if spos+1 != slen:
result = False
break
else:
result = True
break
else:
result = False
break
if not multilevel_wildcard and (tpos < tlen or spos < slen):
result = False
return result | [
"def",
"topic_matches_sub",
"(",
"sub",
",",
"topic",
")",
":",
"result",
"=",
"True",
"multilevel_wildcard",
"=",
"False",
"slen",
"=",
"len",
"(",
"sub",
")",
"tlen",
"=",
"len",
"(",
"topic",
")",
"if",
"slen",
">",
"0",
"and",
"tlen",
">",
"0",
":",
"if",
"(",
"sub",
"[",
"0",
"]",
"==",
"'$'",
"and",
"topic",
"[",
"0",
"]",
"!=",
"'$'",
")",
"or",
"(",
"topic",
"[",
"0",
"]",
"==",
"'$'",
"and",
"sub",
"[",
"0",
"]",
"!=",
"'$'",
")",
":",
"return",
"False",
"spos",
"=",
"0",
"tpos",
"=",
"0",
"while",
"spos",
"<",
"slen",
"and",
"tpos",
"<",
"tlen",
":",
"if",
"sub",
"[",
"spos",
"]",
"==",
"topic",
"[",
"tpos",
"]",
":",
"if",
"tpos",
"==",
"tlen",
"-",
"1",
":",
"# Check for e.g. foo matching foo/#",
"if",
"spos",
"==",
"slen",
"-",
"3",
"and",
"sub",
"[",
"spos",
"+",
"1",
"]",
"==",
"'/'",
"and",
"sub",
"[",
"spos",
"+",
"2",
"]",
"==",
"'#'",
":",
"result",
"=",
"True",
"multilevel_wildcard",
"=",
"True",
"break",
"spos",
"+=",
"1",
"tpos",
"+=",
"1",
"if",
"tpos",
"==",
"tlen",
"and",
"spos",
"==",
"slen",
"-",
"1",
"and",
"sub",
"[",
"spos",
"]",
"==",
"'+'",
":",
"spos",
"+=",
"1",
"result",
"=",
"True",
"break",
"else",
":",
"if",
"sub",
"[",
"spos",
"]",
"==",
"'+'",
":",
"spos",
"+=",
"1",
"while",
"tpos",
"<",
"tlen",
"and",
"topic",
"[",
"tpos",
"]",
"!=",
"'/'",
":",
"tpos",
"+=",
"1",
"if",
"tpos",
"==",
"tlen",
"and",
"spos",
"==",
"slen",
":",
"result",
"=",
"True",
"break",
"elif",
"sub",
"[",
"spos",
"]",
"==",
"'#'",
":",
"multilevel_wildcard",
"=",
"True",
"if",
"spos",
"+",
"1",
"!=",
"slen",
":",
"result",
"=",
"False",
"break",
"else",
":",
"result",
"=",
"True",
"break",
"else",
":",
"result",
"=",
"False",
"break",
"if",
"not",
"multilevel_wildcard",
"and",
"(",
"tpos",
"<",
"tlen",
"or",
"spos",
"<",
"slen",
")",
":",
"result",
"=",
"False",
"return",
"result"
] | Check whether a topic matches a subscription.
For example:
foo/bar would match the subscription foo/# or +/bar
non/matching would not match the subscription non/+/+ | [
"Check",
"whether",
"a",
"topic",
"matches",
"a",
"subscription",
"."
] | f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62 | https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/core/protocol/paho/client.py#L199-L261 |
229,109 | aws/aws-iot-device-sdk-python | AWSIoTPythonSDK/core/protocol/paho/client.py | Client.configIAMCredentials | def configIAMCredentials(self, srcAWSAccessKeyID, srcAWSSecretAccessKey, srcAWSSessionToken):
"""
Make custom settings for IAM credentials for websocket connection
srcAWSAccessKeyID - AWS IAM access key
srcAWSSecretAccessKey - AWS IAM secret key
srcAWSSessionToken - AWS Session Token
"""
self._AWSAccessKeyIDCustomConfig = srcAWSAccessKeyID
self._AWSSecretAccessKeyCustomConfig = srcAWSSecretAccessKey
self._AWSSessionTokenCustomConfig = srcAWSSessionToken | python | def configIAMCredentials(self, srcAWSAccessKeyID, srcAWSSecretAccessKey, srcAWSSessionToken):
"""
Make custom settings for IAM credentials for websocket connection
srcAWSAccessKeyID - AWS IAM access key
srcAWSSecretAccessKey - AWS IAM secret key
srcAWSSessionToken - AWS Session Token
"""
self._AWSAccessKeyIDCustomConfig = srcAWSAccessKeyID
self._AWSSecretAccessKeyCustomConfig = srcAWSSecretAccessKey
self._AWSSessionTokenCustomConfig = srcAWSSessionToken | [
"def",
"configIAMCredentials",
"(",
"self",
",",
"srcAWSAccessKeyID",
",",
"srcAWSSecretAccessKey",
",",
"srcAWSSessionToken",
")",
":",
"self",
".",
"_AWSAccessKeyIDCustomConfig",
"=",
"srcAWSAccessKeyID",
"self",
".",
"_AWSSecretAccessKeyCustomConfig",
"=",
"srcAWSSecretAccessKey",
"self",
".",
"_AWSSessionTokenCustomConfig",
"=",
"srcAWSSessionToken"
] | Make custom settings for IAM credentials for websocket connection
srcAWSAccessKeyID - AWS IAM access key
srcAWSSecretAccessKey - AWS IAM secret key
srcAWSSessionToken - AWS Session Token | [
"Make",
"custom",
"settings",
"for",
"IAM",
"credentials",
"for",
"websocket",
"connection",
"srcAWSAccessKeyID",
"-",
"AWS",
"IAM",
"access",
"key",
"srcAWSSecretAccessKey",
"-",
"AWS",
"IAM",
"secret",
"key",
"srcAWSSessionToken",
"-",
"AWS",
"Session",
"Token"
] | f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62 | https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/core/protocol/paho/client.py#L526-L535 |
229,110 | aws/aws-iot-device-sdk-python | AWSIoTPythonSDK/core/protocol/paho/client.py | Client.loop | def loop(self, timeout=1.0, max_packets=1):
"""Process network events.
This function must be called regularly to ensure communication with the
broker is carried out. It calls select() on the network socket to wait
for network events. If incoming data is present it will then be
processed. Outgoing commands, from e.g. publish(), are normally sent
immediately that their function is called, but this is not always
possible. loop() will also attempt to send any remaining outgoing
messages, which also includes commands that are part of the flow for
messages with QoS>0.
timeout: The time in seconds to wait for incoming/outgoing network
traffic before timing out and returning.
max_packets: Not currently used.
Returns MQTT_ERR_SUCCESS on success.
Returns >0 on error.
A ValueError will be raised if timeout < 0"""
if timeout < 0.0:
raise ValueError('Invalid timeout.')
self._current_out_packet_mutex.acquire()
self._out_packet_mutex.acquire()
if self._current_out_packet is None and len(self._out_packet) > 0:
self._current_out_packet = self._out_packet.pop(0)
if self._current_out_packet:
wlist = [self.socket()]
else:
wlist = []
self._out_packet_mutex.release()
self._current_out_packet_mutex.release()
# sockpairR is used to break out of select() before the timeout, on a
# call to publish() etc.
rlist = [self.socket(), self._sockpairR]
try:
socklist = select.select(rlist, wlist, [], timeout)
except TypeError as e:
# Socket isn't correct type, in likelihood connection is lost
return MQTT_ERR_CONN_LOST
except ValueError:
# Can occur if we just reconnected but rlist/wlist contain a -1 for
# some reason.
return MQTT_ERR_CONN_LOST
except:
return MQTT_ERR_UNKNOWN
if self.socket() in socklist[0]:
rc = self.loop_read(max_packets)
if rc or (self._ssl is None and self._sock is None):
return rc
if self._sockpairR in socklist[0]:
# Stimulate output write even though we didn't ask for it, because
# at that point the publish or other command wasn't present.
socklist[1].insert(0, self.socket())
# Clear sockpairR - only ever a single byte written.
try:
self._sockpairR.recv(1)
except socket.error as err:
if err.errno != EAGAIN:
raise
if self.socket() in socklist[1]:
rc = self.loop_write(max_packets)
if rc or (self._ssl is None and self._sock is None):
return rc
return self.loop_misc() | python | def loop(self, timeout=1.0, max_packets=1):
"""Process network events.
This function must be called regularly to ensure communication with the
broker is carried out. It calls select() on the network socket to wait
for network events. If incoming data is present it will then be
processed. Outgoing commands, from e.g. publish(), are normally sent
immediately that their function is called, but this is not always
possible. loop() will also attempt to send any remaining outgoing
messages, which also includes commands that are part of the flow for
messages with QoS>0.
timeout: The time in seconds to wait for incoming/outgoing network
traffic before timing out and returning.
max_packets: Not currently used.
Returns MQTT_ERR_SUCCESS on success.
Returns >0 on error.
A ValueError will be raised if timeout < 0"""
if timeout < 0.0:
raise ValueError('Invalid timeout.')
self._current_out_packet_mutex.acquire()
self._out_packet_mutex.acquire()
if self._current_out_packet is None and len(self._out_packet) > 0:
self._current_out_packet = self._out_packet.pop(0)
if self._current_out_packet:
wlist = [self.socket()]
else:
wlist = []
self._out_packet_mutex.release()
self._current_out_packet_mutex.release()
# sockpairR is used to break out of select() before the timeout, on a
# call to publish() etc.
rlist = [self.socket(), self._sockpairR]
try:
socklist = select.select(rlist, wlist, [], timeout)
except TypeError as e:
# Socket isn't correct type, in likelihood connection is lost
return MQTT_ERR_CONN_LOST
except ValueError:
# Can occur if we just reconnected but rlist/wlist contain a -1 for
# some reason.
return MQTT_ERR_CONN_LOST
except:
return MQTT_ERR_UNKNOWN
if self.socket() in socklist[0]:
rc = self.loop_read(max_packets)
if rc or (self._ssl is None and self._sock is None):
return rc
if self._sockpairR in socklist[0]:
# Stimulate output write even though we didn't ask for it, because
# at that point the publish or other command wasn't present.
socklist[1].insert(0, self.socket())
# Clear sockpairR - only ever a single byte written.
try:
self._sockpairR.recv(1)
except socket.error as err:
if err.errno != EAGAIN:
raise
if self.socket() in socklist[1]:
rc = self.loop_write(max_packets)
if rc or (self._ssl is None and self._sock is None):
return rc
return self.loop_misc() | [
"def",
"loop",
"(",
"self",
",",
"timeout",
"=",
"1.0",
",",
"max_packets",
"=",
"1",
")",
":",
"if",
"timeout",
"<",
"0.0",
":",
"raise",
"ValueError",
"(",
"'Invalid timeout.'",
")",
"self",
".",
"_current_out_packet_mutex",
".",
"acquire",
"(",
")",
"self",
".",
"_out_packet_mutex",
".",
"acquire",
"(",
")",
"if",
"self",
".",
"_current_out_packet",
"is",
"None",
"and",
"len",
"(",
"self",
".",
"_out_packet",
")",
">",
"0",
":",
"self",
".",
"_current_out_packet",
"=",
"self",
".",
"_out_packet",
".",
"pop",
"(",
"0",
")",
"if",
"self",
".",
"_current_out_packet",
":",
"wlist",
"=",
"[",
"self",
".",
"socket",
"(",
")",
"]",
"else",
":",
"wlist",
"=",
"[",
"]",
"self",
".",
"_out_packet_mutex",
".",
"release",
"(",
")",
"self",
".",
"_current_out_packet_mutex",
".",
"release",
"(",
")",
"# sockpairR is used to break out of select() before the timeout, on a",
"# call to publish() etc.",
"rlist",
"=",
"[",
"self",
".",
"socket",
"(",
")",
",",
"self",
".",
"_sockpairR",
"]",
"try",
":",
"socklist",
"=",
"select",
".",
"select",
"(",
"rlist",
",",
"wlist",
",",
"[",
"]",
",",
"timeout",
")",
"except",
"TypeError",
"as",
"e",
":",
"# Socket isn't correct type, in likelihood connection is lost",
"return",
"MQTT_ERR_CONN_LOST",
"except",
"ValueError",
":",
"# Can occur if we just reconnected but rlist/wlist contain a -1 for",
"# some reason.",
"return",
"MQTT_ERR_CONN_LOST",
"except",
":",
"return",
"MQTT_ERR_UNKNOWN",
"if",
"self",
".",
"socket",
"(",
")",
"in",
"socklist",
"[",
"0",
"]",
":",
"rc",
"=",
"self",
".",
"loop_read",
"(",
"max_packets",
")",
"if",
"rc",
"or",
"(",
"self",
".",
"_ssl",
"is",
"None",
"and",
"self",
".",
"_sock",
"is",
"None",
")",
":",
"return",
"rc",
"if",
"self",
".",
"_sockpairR",
"in",
"socklist",
"[",
"0",
"]",
":",
"# Stimulate output write even though we didn't ask for it, because",
"# at that point the publish or other command wasn't present.",
"socklist",
"[",
"1",
"]",
".",
"insert",
"(",
"0",
",",
"self",
".",
"socket",
"(",
")",
")",
"# Clear sockpairR - only ever a single byte written.",
"try",
":",
"self",
".",
"_sockpairR",
".",
"recv",
"(",
"1",
")",
"except",
"socket",
".",
"error",
"as",
"err",
":",
"if",
"err",
".",
"errno",
"!=",
"EAGAIN",
":",
"raise",
"if",
"self",
".",
"socket",
"(",
")",
"in",
"socklist",
"[",
"1",
"]",
":",
"rc",
"=",
"self",
".",
"loop_write",
"(",
"max_packets",
")",
"if",
"rc",
"or",
"(",
"self",
".",
"_ssl",
"is",
"None",
"and",
"self",
".",
"_sock",
"is",
"None",
")",
":",
"return",
"rc",
"return",
"self",
".",
"loop_misc",
"(",
")"
] | Process network events.
This function must be called regularly to ensure communication with the
broker is carried out. It calls select() on the network socket to wait
for network events. If incoming data is present it will then be
processed. Outgoing commands, from e.g. publish(), are normally sent
immediately that their function is called, but this is not always
possible. loop() will also attempt to send any remaining outgoing
messages, which also includes commands that are part of the flow for
messages with QoS>0.
timeout: The time in seconds to wait for incoming/outgoing network
traffic before timing out and returning.
max_packets: Not currently used.
Returns MQTT_ERR_SUCCESS on success.
Returns >0 on error.
A ValueError will be raised if timeout < 0 | [
"Process",
"network",
"events",
"."
] | f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62 | https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/core/protocol/paho/client.py#L842-L913 |
229,111 | aws/aws-iot-device-sdk-python | AWSIoTPythonSDK/core/protocol/paho/client.py | Client.publish | def publish(self, topic, payload=None, qos=0, retain=False):
"""Publish a message on a topic.
This causes a message to be sent to the broker and subsequently from
the broker to any clients subscribing to matching topics.
topic: The topic that the message should be published on.
payload: The actual message to send. If not given, or set to None a
zero length message will be used. Passing an int or float will result
in the payload being converted to a string representing that number. If
you wish to send a true int/float, use struct.pack() to create the
payload you require.
qos: The quality of service level to use.
retain: If set to true, the message will be set as the "last known
good"/retained message for the topic.
Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS to
indicate success or MQTT_ERR_NO_CONN if the client is not currently
connected. mid is the message ID for the publish request. The mid
value can be used to track the publish request by checking against the
mid argument in the on_publish() callback if it is defined.
A ValueError will be raised if topic is None, has zero length or is
invalid (contains a wildcard), if qos is not one of 0, 1 or 2, or if
the length of the payload is greater than 268435455 bytes."""
if topic is None or len(topic) == 0:
raise ValueError('Invalid topic.')
if qos<0 or qos>2:
raise ValueError('Invalid QoS level.')
if isinstance(payload, str) or isinstance(payload, bytearray):
local_payload = payload
elif sys.version_info[0] < 3 and isinstance(payload, unicode):
local_payload = payload
elif isinstance(payload, int) or isinstance(payload, float):
local_payload = str(payload)
elif payload is None:
local_payload = None
else:
raise TypeError('payload must be a string, bytearray, int, float or None.')
if local_payload is not None and len(local_payload) > 268435455:
raise ValueError('Payload too large.')
if self._topic_wildcard_len_check(topic) != MQTT_ERR_SUCCESS:
raise ValueError('Publish topic cannot contain wildcards.')
local_mid = self._mid_generate()
if qos == 0:
rc = self._send_publish(local_mid, topic, local_payload, qos, retain, False)
return (rc, local_mid)
else:
message = MQTTMessage()
message.timestamp = time.time()
message.mid = local_mid
message.topic = topic
if local_payload is None or len(local_payload) == 0:
message.payload = None
else:
message.payload = local_payload
message.qos = qos
message.retain = retain
message.dup = False
self._out_message_mutex.acquire()
self._out_messages.append(message)
if self._max_inflight_messages == 0 or self._inflight_messages < self._max_inflight_messages:
self._inflight_messages = self._inflight_messages+1
if qos == 1:
message.state = mqtt_ms_wait_for_puback
elif qos == 2:
message.state = mqtt_ms_wait_for_pubrec
self._out_message_mutex.release()
rc = self._send_publish(message.mid, message.topic, message.payload, message.qos, message.retain, message.dup)
# remove from inflight messages so it will be send after a connection is made
if rc is MQTT_ERR_NO_CONN:
with self._out_message_mutex:
self._inflight_messages -= 1
message.state = mqtt_ms_publish
return (rc, local_mid)
else:
message.state = mqtt_ms_queued;
self._out_message_mutex.release()
return (MQTT_ERR_SUCCESS, local_mid) | python | def publish(self, topic, payload=None, qos=0, retain=False):
"""Publish a message on a topic.
This causes a message to be sent to the broker and subsequently from
the broker to any clients subscribing to matching topics.
topic: The topic that the message should be published on.
payload: The actual message to send. If not given, or set to None a
zero length message will be used. Passing an int or float will result
in the payload being converted to a string representing that number. If
you wish to send a true int/float, use struct.pack() to create the
payload you require.
qos: The quality of service level to use.
retain: If set to true, the message will be set as the "last known
good"/retained message for the topic.
Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS to
indicate success or MQTT_ERR_NO_CONN if the client is not currently
connected. mid is the message ID for the publish request. The mid
value can be used to track the publish request by checking against the
mid argument in the on_publish() callback if it is defined.
A ValueError will be raised if topic is None, has zero length or is
invalid (contains a wildcard), if qos is not one of 0, 1 or 2, or if
the length of the payload is greater than 268435455 bytes."""
if topic is None or len(topic) == 0:
raise ValueError('Invalid topic.')
if qos<0 or qos>2:
raise ValueError('Invalid QoS level.')
if isinstance(payload, str) or isinstance(payload, bytearray):
local_payload = payload
elif sys.version_info[0] < 3 and isinstance(payload, unicode):
local_payload = payload
elif isinstance(payload, int) or isinstance(payload, float):
local_payload = str(payload)
elif payload is None:
local_payload = None
else:
raise TypeError('payload must be a string, bytearray, int, float or None.')
if local_payload is not None and len(local_payload) > 268435455:
raise ValueError('Payload too large.')
if self._topic_wildcard_len_check(topic) != MQTT_ERR_SUCCESS:
raise ValueError('Publish topic cannot contain wildcards.')
local_mid = self._mid_generate()
if qos == 0:
rc = self._send_publish(local_mid, topic, local_payload, qos, retain, False)
return (rc, local_mid)
else:
message = MQTTMessage()
message.timestamp = time.time()
message.mid = local_mid
message.topic = topic
if local_payload is None or len(local_payload) == 0:
message.payload = None
else:
message.payload = local_payload
message.qos = qos
message.retain = retain
message.dup = False
self._out_message_mutex.acquire()
self._out_messages.append(message)
if self._max_inflight_messages == 0 or self._inflight_messages < self._max_inflight_messages:
self._inflight_messages = self._inflight_messages+1
if qos == 1:
message.state = mqtt_ms_wait_for_puback
elif qos == 2:
message.state = mqtt_ms_wait_for_pubrec
self._out_message_mutex.release()
rc = self._send_publish(message.mid, message.topic, message.payload, message.qos, message.retain, message.dup)
# remove from inflight messages so it will be send after a connection is made
if rc is MQTT_ERR_NO_CONN:
with self._out_message_mutex:
self._inflight_messages -= 1
message.state = mqtt_ms_publish
return (rc, local_mid)
else:
message.state = mqtt_ms_queued;
self._out_message_mutex.release()
return (MQTT_ERR_SUCCESS, local_mid) | [
"def",
"publish",
"(",
"self",
",",
"topic",
",",
"payload",
"=",
"None",
",",
"qos",
"=",
"0",
",",
"retain",
"=",
"False",
")",
":",
"if",
"topic",
"is",
"None",
"or",
"len",
"(",
"topic",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'Invalid topic.'",
")",
"if",
"qos",
"<",
"0",
"or",
"qos",
">",
"2",
":",
"raise",
"ValueError",
"(",
"'Invalid QoS level.'",
")",
"if",
"isinstance",
"(",
"payload",
",",
"str",
")",
"or",
"isinstance",
"(",
"payload",
",",
"bytearray",
")",
":",
"local_payload",
"=",
"payload",
"elif",
"sys",
".",
"version_info",
"[",
"0",
"]",
"<",
"3",
"and",
"isinstance",
"(",
"payload",
",",
"unicode",
")",
":",
"local_payload",
"=",
"payload",
"elif",
"isinstance",
"(",
"payload",
",",
"int",
")",
"or",
"isinstance",
"(",
"payload",
",",
"float",
")",
":",
"local_payload",
"=",
"str",
"(",
"payload",
")",
"elif",
"payload",
"is",
"None",
":",
"local_payload",
"=",
"None",
"else",
":",
"raise",
"TypeError",
"(",
"'payload must be a string, bytearray, int, float or None.'",
")",
"if",
"local_payload",
"is",
"not",
"None",
"and",
"len",
"(",
"local_payload",
")",
">",
"268435455",
":",
"raise",
"ValueError",
"(",
"'Payload too large.'",
")",
"if",
"self",
".",
"_topic_wildcard_len_check",
"(",
"topic",
")",
"!=",
"MQTT_ERR_SUCCESS",
":",
"raise",
"ValueError",
"(",
"'Publish topic cannot contain wildcards.'",
")",
"local_mid",
"=",
"self",
".",
"_mid_generate",
"(",
")",
"if",
"qos",
"==",
"0",
":",
"rc",
"=",
"self",
".",
"_send_publish",
"(",
"local_mid",
",",
"topic",
",",
"local_payload",
",",
"qos",
",",
"retain",
",",
"False",
")",
"return",
"(",
"rc",
",",
"local_mid",
")",
"else",
":",
"message",
"=",
"MQTTMessage",
"(",
")",
"message",
".",
"timestamp",
"=",
"time",
".",
"time",
"(",
")",
"message",
".",
"mid",
"=",
"local_mid",
"message",
".",
"topic",
"=",
"topic",
"if",
"local_payload",
"is",
"None",
"or",
"len",
"(",
"local_payload",
")",
"==",
"0",
":",
"message",
".",
"payload",
"=",
"None",
"else",
":",
"message",
".",
"payload",
"=",
"local_payload",
"message",
".",
"qos",
"=",
"qos",
"message",
".",
"retain",
"=",
"retain",
"message",
".",
"dup",
"=",
"False",
"self",
".",
"_out_message_mutex",
".",
"acquire",
"(",
")",
"self",
".",
"_out_messages",
".",
"append",
"(",
"message",
")",
"if",
"self",
".",
"_max_inflight_messages",
"==",
"0",
"or",
"self",
".",
"_inflight_messages",
"<",
"self",
".",
"_max_inflight_messages",
":",
"self",
".",
"_inflight_messages",
"=",
"self",
".",
"_inflight_messages",
"+",
"1",
"if",
"qos",
"==",
"1",
":",
"message",
".",
"state",
"=",
"mqtt_ms_wait_for_puback",
"elif",
"qos",
"==",
"2",
":",
"message",
".",
"state",
"=",
"mqtt_ms_wait_for_pubrec",
"self",
".",
"_out_message_mutex",
".",
"release",
"(",
")",
"rc",
"=",
"self",
".",
"_send_publish",
"(",
"message",
".",
"mid",
",",
"message",
".",
"topic",
",",
"message",
".",
"payload",
",",
"message",
".",
"qos",
",",
"message",
".",
"retain",
",",
"message",
".",
"dup",
")",
"# remove from inflight messages so it will be send after a connection is made",
"if",
"rc",
"is",
"MQTT_ERR_NO_CONN",
":",
"with",
"self",
".",
"_out_message_mutex",
":",
"self",
".",
"_inflight_messages",
"-=",
"1",
"message",
".",
"state",
"=",
"mqtt_ms_publish",
"return",
"(",
"rc",
",",
"local_mid",
")",
"else",
":",
"message",
".",
"state",
"=",
"mqtt_ms_queued",
"self",
".",
"_out_message_mutex",
".",
"release",
"(",
")",
"return",
"(",
"MQTT_ERR_SUCCESS",
",",
"local_mid",
")"
] | Publish a message on a topic.
This causes a message to be sent to the broker and subsequently from
the broker to any clients subscribing to matching topics.
topic: The topic that the message should be published on.
payload: The actual message to send. If not given, or set to None a
zero length message will be used. Passing an int or float will result
in the payload being converted to a string representing that number. If
you wish to send a true int/float, use struct.pack() to create the
payload you require.
qos: The quality of service level to use.
retain: If set to true, the message will be set as the "last known
good"/retained message for the topic.
Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS to
indicate success or MQTT_ERR_NO_CONN if the client is not currently
connected. mid is the message ID for the publish request. The mid
value can be used to track the publish request by checking against the
mid argument in the on_publish() callback if it is defined.
A ValueError will be raised if topic is None, has zero length or is
invalid (contains a wildcard), if qos is not one of 0, 1 or 2, or if
the length of the payload is greater than 268435455 bytes. | [
"Publish",
"a",
"message",
"on",
"a",
"topic",
"."
] | f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62 | https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/core/protocol/paho/client.py#L915-L1003 |
229,112 | aws/aws-iot-device-sdk-python | AWSIoTPythonSDK/core/protocol/paho/client.py | Client.username_pw_set | def username_pw_set(self, username, password=None):
"""Set a username and optionally a password for broker authentication.
Must be called before connect() to have any effect.
Requires a broker that supports MQTT v3.1.
username: The username to authenticate with. Need have no relationship to the client id.
password: The password to authenticate with. Optional, set to None if not required.
"""
self._username = username.encode('utf-8')
self._password = password | python | def username_pw_set(self, username, password=None):
"""Set a username and optionally a password for broker authentication.
Must be called before connect() to have any effect.
Requires a broker that supports MQTT v3.1.
username: The username to authenticate with. Need have no relationship to the client id.
password: The password to authenticate with. Optional, set to None if not required.
"""
self._username = username.encode('utf-8')
self._password = password | [
"def",
"username_pw_set",
"(",
"self",
",",
"username",
",",
"password",
"=",
"None",
")",
":",
"self",
".",
"_username",
"=",
"username",
".",
"encode",
"(",
"'utf-8'",
")",
"self",
".",
"_password",
"=",
"password"
] | Set a username and optionally a password for broker authentication.
Must be called before connect() to have any effect.
Requires a broker that supports MQTT v3.1.
username: The username to authenticate with. Need have no relationship to the client id.
password: The password to authenticate with. Optional, set to None if not required. | [
"Set",
"a",
"username",
"and",
"optionally",
"a",
"password",
"for",
"broker",
"authentication",
"."
] | f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62 | https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/core/protocol/paho/client.py#L1005-L1015 |
229,113 | aws/aws-iot-device-sdk-python | AWSIoTPythonSDK/core/protocol/paho/client.py | Client.disconnect | def disconnect(self):
"""Disconnect a connected client from the broker."""
self._state_mutex.acquire()
self._state = mqtt_cs_disconnecting
self._state_mutex.release()
self._backoffCore.stopStableConnectionTimer()
if self._sock is None and self._ssl is None:
return MQTT_ERR_NO_CONN
return self._send_disconnect() | python | def disconnect(self):
"""Disconnect a connected client from the broker."""
self._state_mutex.acquire()
self._state = mqtt_cs_disconnecting
self._state_mutex.release()
self._backoffCore.stopStableConnectionTimer()
if self._sock is None and self._ssl is None:
return MQTT_ERR_NO_CONN
return self._send_disconnect() | [
"def",
"disconnect",
"(",
"self",
")",
":",
"self",
".",
"_state_mutex",
".",
"acquire",
"(",
")",
"self",
".",
"_state",
"=",
"mqtt_cs_disconnecting",
"self",
".",
"_state_mutex",
".",
"release",
"(",
")",
"self",
".",
"_backoffCore",
".",
"stopStableConnectionTimer",
"(",
")",
"if",
"self",
".",
"_sock",
"is",
"None",
"and",
"self",
".",
"_ssl",
"is",
"None",
":",
"return",
"MQTT_ERR_NO_CONN",
"return",
"self",
".",
"_send_disconnect",
"(",
")"
] | Disconnect a connected client from the broker. | [
"Disconnect",
"a",
"connected",
"client",
"from",
"the",
"broker",
"."
] | f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62 | https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/core/protocol/paho/client.py#L1017-L1028 |
229,114 | aws/aws-iot-device-sdk-python | AWSIoTPythonSDK/core/protocol/paho/client.py | Client.subscribe | def subscribe(self, topic, qos=0):
"""Subscribe the client to one or more topics.
This function may be called in three different ways:
Simple string and integer
-------------------------
e.g. subscribe("my/topic", 2)
topic: A string specifying the subscription topic to subscribe to.
qos: The desired quality of service level for the subscription.
Defaults to 0.
String and integer tuple
------------------------
e.g. subscribe(("my/topic", 1))
topic: A tuple of (topic, qos). Both topic and qos must be present in
the tuple.
qos: Not used.
List of string and integer tuples
------------------------
e.g. subscribe([("my/topic", 0), ("another/topic", 2)])
This allows multiple topic subscriptions in a single SUBSCRIPTION
command, which is more efficient than using multiple calls to
subscribe().
topic: A list of tuple of format (topic, qos). Both topic and qos must
be present in all of the tuples.
qos: Not used.
The function returns a tuple (result, mid), where result is
MQTT_ERR_SUCCESS to indicate success or (MQTT_ERR_NO_CONN, None) if the
client is not currently connected. mid is the message ID for the
subscribe request. The mid value can be used to track the subscribe
request by checking against the mid argument in the on_subscribe()
callback if it is defined.
Raises a ValueError if qos is not 0, 1 or 2, or if topic is None or has
zero string length, or if topic is not a string, tuple or list.
"""
topic_qos_list = None
if isinstance(topic, str):
if qos<0 or qos>2:
raise ValueError('Invalid QoS level.')
if topic is None or len(topic) == 0:
raise ValueError('Invalid topic.')
topic_qos_list = [(topic.encode('utf-8'), qos)]
elif isinstance(topic, tuple):
if topic[1]<0 or topic[1]>2:
raise ValueError('Invalid QoS level.')
if topic[0] is None or len(topic[0]) == 0 or not isinstance(topic[0], str):
raise ValueError('Invalid topic.')
topic_qos_list = [(topic[0].encode('utf-8'), topic[1])]
elif isinstance(topic, list):
topic_qos_list = []
for t in topic:
if t[1]<0 or t[1]>2:
raise ValueError('Invalid QoS level.')
if t[0] is None or len(t[0]) == 0 or not isinstance(t[0], str):
raise ValueError('Invalid topic.')
topic_qos_list.append((t[0].encode('utf-8'), t[1]))
if topic_qos_list is None:
raise ValueError("No topic specified, or incorrect topic type.")
if self._sock is None and self._ssl is None:
return (MQTT_ERR_NO_CONN, None)
return self._send_subscribe(False, topic_qos_list) | python | def subscribe(self, topic, qos=0):
"""Subscribe the client to one or more topics.
This function may be called in three different ways:
Simple string and integer
-------------------------
e.g. subscribe("my/topic", 2)
topic: A string specifying the subscription topic to subscribe to.
qos: The desired quality of service level for the subscription.
Defaults to 0.
String and integer tuple
------------------------
e.g. subscribe(("my/topic", 1))
topic: A tuple of (topic, qos). Both topic and qos must be present in
the tuple.
qos: Not used.
List of string and integer tuples
------------------------
e.g. subscribe([("my/topic", 0), ("another/topic", 2)])
This allows multiple topic subscriptions in a single SUBSCRIPTION
command, which is more efficient than using multiple calls to
subscribe().
topic: A list of tuple of format (topic, qos). Both topic and qos must
be present in all of the tuples.
qos: Not used.
The function returns a tuple (result, mid), where result is
MQTT_ERR_SUCCESS to indicate success or (MQTT_ERR_NO_CONN, None) if the
client is not currently connected. mid is the message ID for the
subscribe request. The mid value can be used to track the subscribe
request by checking against the mid argument in the on_subscribe()
callback if it is defined.
Raises a ValueError if qos is not 0, 1 or 2, or if topic is None or has
zero string length, or if topic is not a string, tuple or list.
"""
topic_qos_list = None
if isinstance(topic, str):
if qos<0 or qos>2:
raise ValueError('Invalid QoS level.')
if topic is None or len(topic) == 0:
raise ValueError('Invalid topic.')
topic_qos_list = [(topic.encode('utf-8'), qos)]
elif isinstance(topic, tuple):
if topic[1]<0 or topic[1]>2:
raise ValueError('Invalid QoS level.')
if topic[0] is None or len(topic[0]) == 0 or not isinstance(topic[0], str):
raise ValueError('Invalid topic.')
topic_qos_list = [(topic[0].encode('utf-8'), topic[1])]
elif isinstance(topic, list):
topic_qos_list = []
for t in topic:
if t[1]<0 or t[1]>2:
raise ValueError('Invalid QoS level.')
if t[0] is None or len(t[0]) == 0 or not isinstance(t[0], str):
raise ValueError('Invalid topic.')
topic_qos_list.append((t[0].encode('utf-8'), t[1]))
if topic_qos_list is None:
raise ValueError("No topic specified, or incorrect topic type.")
if self._sock is None and self._ssl is None:
return (MQTT_ERR_NO_CONN, None)
return self._send_subscribe(False, topic_qos_list) | [
"def",
"subscribe",
"(",
"self",
",",
"topic",
",",
"qos",
"=",
"0",
")",
":",
"topic_qos_list",
"=",
"None",
"if",
"isinstance",
"(",
"topic",
",",
"str",
")",
":",
"if",
"qos",
"<",
"0",
"or",
"qos",
">",
"2",
":",
"raise",
"ValueError",
"(",
"'Invalid QoS level.'",
")",
"if",
"topic",
"is",
"None",
"or",
"len",
"(",
"topic",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'Invalid topic.'",
")",
"topic_qos_list",
"=",
"[",
"(",
"topic",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"qos",
")",
"]",
"elif",
"isinstance",
"(",
"topic",
",",
"tuple",
")",
":",
"if",
"topic",
"[",
"1",
"]",
"<",
"0",
"or",
"topic",
"[",
"1",
"]",
">",
"2",
":",
"raise",
"ValueError",
"(",
"'Invalid QoS level.'",
")",
"if",
"topic",
"[",
"0",
"]",
"is",
"None",
"or",
"len",
"(",
"topic",
"[",
"0",
"]",
")",
"==",
"0",
"or",
"not",
"isinstance",
"(",
"topic",
"[",
"0",
"]",
",",
"str",
")",
":",
"raise",
"ValueError",
"(",
"'Invalid topic.'",
")",
"topic_qos_list",
"=",
"[",
"(",
"topic",
"[",
"0",
"]",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"topic",
"[",
"1",
"]",
")",
"]",
"elif",
"isinstance",
"(",
"topic",
",",
"list",
")",
":",
"topic_qos_list",
"=",
"[",
"]",
"for",
"t",
"in",
"topic",
":",
"if",
"t",
"[",
"1",
"]",
"<",
"0",
"or",
"t",
"[",
"1",
"]",
">",
"2",
":",
"raise",
"ValueError",
"(",
"'Invalid QoS level.'",
")",
"if",
"t",
"[",
"0",
"]",
"is",
"None",
"or",
"len",
"(",
"t",
"[",
"0",
"]",
")",
"==",
"0",
"or",
"not",
"isinstance",
"(",
"t",
"[",
"0",
"]",
",",
"str",
")",
":",
"raise",
"ValueError",
"(",
"'Invalid topic.'",
")",
"topic_qos_list",
".",
"append",
"(",
"(",
"t",
"[",
"0",
"]",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"t",
"[",
"1",
"]",
")",
")",
"if",
"topic_qos_list",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"No topic specified, or incorrect topic type.\"",
")",
"if",
"self",
".",
"_sock",
"is",
"None",
"and",
"self",
".",
"_ssl",
"is",
"None",
":",
"return",
"(",
"MQTT_ERR_NO_CONN",
",",
"None",
")",
"return",
"self",
".",
"_send_subscribe",
"(",
"False",
",",
"topic_qos_list",
")"
] | Subscribe the client to one or more topics.
This function may be called in three different ways:
Simple string and integer
-------------------------
e.g. subscribe("my/topic", 2)
topic: A string specifying the subscription topic to subscribe to.
qos: The desired quality of service level for the subscription.
Defaults to 0.
String and integer tuple
------------------------
e.g. subscribe(("my/topic", 1))
topic: A tuple of (topic, qos). Both topic and qos must be present in
the tuple.
qos: Not used.
List of string and integer tuples
------------------------
e.g. subscribe([("my/topic", 0), ("another/topic", 2)])
This allows multiple topic subscriptions in a single SUBSCRIPTION
command, which is more efficient than using multiple calls to
subscribe().
topic: A list of tuple of format (topic, qos). Both topic and qos must
be present in all of the tuples.
qos: Not used.
The function returns a tuple (result, mid), where result is
MQTT_ERR_SUCCESS to indicate success or (MQTT_ERR_NO_CONN, None) if the
client is not currently connected. mid is the message ID for the
subscribe request. The mid value can be used to track the subscribe
request by checking against the mid argument in the on_subscribe()
callback if it is defined.
Raises a ValueError if qos is not 0, 1 or 2, or if topic is None or has
zero string length, or if topic is not a string, tuple or list. | [
"Subscribe",
"the",
"client",
"to",
"one",
"or",
"more",
"topics",
"."
] | f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62 | https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/core/protocol/paho/client.py#L1030-L1101 |
229,115 | aws/aws-iot-device-sdk-python | AWSIoTPythonSDK/core/protocol/paho/client.py | Client.unsubscribe | def unsubscribe(self, topic):
"""Unsubscribe the client from one or more topics.
topic: A single string, or list of strings that are the subscription
topics to unsubscribe from.
Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS
to indicate success or (MQTT_ERR_NO_CONN, None) if the client is not
currently connected.
mid is the message ID for the unsubscribe request. The mid value can be
used to track the unsubscribe request by checking against the mid
argument in the on_unsubscribe() callback if it is defined.
Raises a ValueError if topic is None or has zero string length, or is
not a string or list.
"""
topic_list = None
if topic is None:
raise ValueError('Invalid topic.')
if isinstance(topic, str):
if len(topic) == 0:
raise ValueError('Invalid topic.')
topic_list = [topic.encode('utf-8')]
elif isinstance(topic, list):
topic_list = []
for t in topic:
if len(t) == 0 or not isinstance(t, str):
raise ValueError('Invalid topic.')
topic_list.append(t.encode('utf-8'))
if topic_list is None:
raise ValueError("No topic specified, or incorrect topic type.")
if self._sock is None and self._ssl is None:
return (MQTT_ERR_NO_CONN, None)
return self._send_unsubscribe(False, topic_list) | python | def unsubscribe(self, topic):
"""Unsubscribe the client from one or more topics.
topic: A single string, or list of strings that are the subscription
topics to unsubscribe from.
Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS
to indicate success or (MQTT_ERR_NO_CONN, None) if the client is not
currently connected.
mid is the message ID for the unsubscribe request. The mid value can be
used to track the unsubscribe request by checking against the mid
argument in the on_unsubscribe() callback if it is defined.
Raises a ValueError if topic is None or has zero string length, or is
not a string or list.
"""
topic_list = None
if topic is None:
raise ValueError('Invalid topic.')
if isinstance(topic, str):
if len(topic) == 0:
raise ValueError('Invalid topic.')
topic_list = [topic.encode('utf-8')]
elif isinstance(topic, list):
topic_list = []
for t in topic:
if len(t) == 0 or not isinstance(t, str):
raise ValueError('Invalid topic.')
topic_list.append(t.encode('utf-8'))
if topic_list is None:
raise ValueError("No topic specified, or incorrect topic type.")
if self._sock is None and self._ssl is None:
return (MQTT_ERR_NO_CONN, None)
return self._send_unsubscribe(False, topic_list) | [
"def",
"unsubscribe",
"(",
"self",
",",
"topic",
")",
":",
"topic_list",
"=",
"None",
"if",
"topic",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Invalid topic.'",
")",
"if",
"isinstance",
"(",
"topic",
",",
"str",
")",
":",
"if",
"len",
"(",
"topic",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'Invalid topic.'",
")",
"topic_list",
"=",
"[",
"topic",
".",
"encode",
"(",
"'utf-8'",
")",
"]",
"elif",
"isinstance",
"(",
"topic",
",",
"list",
")",
":",
"topic_list",
"=",
"[",
"]",
"for",
"t",
"in",
"topic",
":",
"if",
"len",
"(",
"t",
")",
"==",
"0",
"or",
"not",
"isinstance",
"(",
"t",
",",
"str",
")",
":",
"raise",
"ValueError",
"(",
"'Invalid topic.'",
")",
"topic_list",
".",
"append",
"(",
"t",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"if",
"topic_list",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"No topic specified, or incorrect topic type.\"",
")",
"if",
"self",
".",
"_sock",
"is",
"None",
"and",
"self",
".",
"_ssl",
"is",
"None",
":",
"return",
"(",
"MQTT_ERR_NO_CONN",
",",
"None",
")",
"return",
"self",
".",
"_send_unsubscribe",
"(",
"False",
",",
"topic_list",
")"
] | Unsubscribe the client from one or more topics.
topic: A single string, or list of strings that are the subscription
topics to unsubscribe from.
Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS
to indicate success or (MQTT_ERR_NO_CONN, None) if the client is not
currently connected.
mid is the message ID for the unsubscribe request. The mid value can be
used to track the unsubscribe request by checking against the mid
argument in the on_unsubscribe() callback if it is defined.
Raises a ValueError if topic is None or has zero string length, or is
not a string or list. | [
"Unsubscribe",
"the",
"client",
"from",
"one",
"or",
"more",
"topics",
"."
] | f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62 | https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/core/protocol/paho/client.py#L1103-L1139 |
229,116 | aws/aws-iot-device-sdk-python | AWSIoTPythonSDK/core/protocol/paho/client.py | Client.will_set | def will_set(self, topic, payload=None, qos=0, retain=False):
"""Set a Will to be sent by the broker in case the client disconnects unexpectedly.
This must be called before connect() to have any effect.
topic: The topic that the will message should be published on.
payload: The message to send as a will. If not given, or set to None a
zero length message will be used as the will. Passing an int or float
will result in the payload being converted to a string representing
that number. If you wish to send a true int/float, use struct.pack() to
create the payload you require.
qos: The quality of service level to use for the will.
retain: If set to true, the will message will be set as the "last known
good"/retained message for the topic.
Raises a ValueError if qos is not 0, 1 or 2, or if topic is None or has
zero string length.
"""
if topic is None or len(topic) == 0:
raise ValueError('Invalid topic.')
if qos<0 or qos>2:
raise ValueError('Invalid QoS level.')
if isinstance(payload, str):
self._will_payload = payload.encode('utf-8')
elif isinstance(payload, bytearray):
self._will_payload = payload
elif isinstance(payload, int) or isinstance(payload, float):
self._will_payload = str(payload)
elif payload is None:
self._will_payload = None
else:
raise TypeError('payload must be a string, bytearray, int, float or None.')
self._will = True
self._will_topic = topic.encode('utf-8')
self._will_qos = qos
self._will_retain = retain | python | def will_set(self, topic, payload=None, qos=0, retain=False):
"""Set a Will to be sent by the broker in case the client disconnects unexpectedly.
This must be called before connect() to have any effect.
topic: The topic that the will message should be published on.
payload: The message to send as a will. If not given, or set to None a
zero length message will be used as the will. Passing an int or float
will result in the payload being converted to a string representing
that number. If you wish to send a true int/float, use struct.pack() to
create the payload you require.
qos: The quality of service level to use for the will.
retain: If set to true, the will message will be set as the "last known
good"/retained message for the topic.
Raises a ValueError if qos is not 0, 1 or 2, or if topic is None or has
zero string length.
"""
if topic is None or len(topic) == 0:
raise ValueError('Invalid topic.')
if qos<0 or qos>2:
raise ValueError('Invalid QoS level.')
if isinstance(payload, str):
self._will_payload = payload.encode('utf-8')
elif isinstance(payload, bytearray):
self._will_payload = payload
elif isinstance(payload, int) or isinstance(payload, float):
self._will_payload = str(payload)
elif payload is None:
self._will_payload = None
else:
raise TypeError('payload must be a string, bytearray, int, float or None.')
self._will = True
self._will_topic = topic.encode('utf-8')
self._will_qos = qos
self._will_retain = retain | [
"def",
"will_set",
"(",
"self",
",",
"topic",
",",
"payload",
"=",
"None",
",",
"qos",
"=",
"0",
",",
"retain",
"=",
"False",
")",
":",
"if",
"topic",
"is",
"None",
"or",
"len",
"(",
"topic",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'Invalid topic.'",
")",
"if",
"qos",
"<",
"0",
"or",
"qos",
">",
"2",
":",
"raise",
"ValueError",
"(",
"'Invalid QoS level.'",
")",
"if",
"isinstance",
"(",
"payload",
",",
"str",
")",
":",
"self",
".",
"_will_payload",
"=",
"payload",
".",
"encode",
"(",
"'utf-8'",
")",
"elif",
"isinstance",
"(",
"payload",
",",
"bytearray",
")",
":",
"self",
".",
"_will_payload",
"=",
"payload",
"elif",
"isinstance",
"(",
"payload",
",",
"int",
")",
"or",
"isinstance",
"(",
"payload",
",",
"float",
")",
":",
"self",
".",
"_will_payload",
"=",
"str",
"(",
"payload",
")",
"elif",
"payload",
"is",
"None",
":",
"self",
".",
"_will_payload",
"=",
"None",
"else",
":",
"raise",
"TypeError",
"(",
"'payload must be a string, bytearray, int, float or None.'",
")",
"self",
".",
"_will",
"=",
"True",
"self",
".",
"_will_topic",
"=",
"topic",
".",
"encode",
"(",
"'utf-8'",
")",
"self",
".",
"_will_qos",
"=",
"qos",
"self",
".",
"_will_retain",
"=",
"retain"
] | Set a Will to be sent by the broker in case the client disconnects unexpectedly.
This must be called before connect() to have any effect.
topic: The topic that the will message should be published on.
payload: The message to send as a will. If not given, or set to None a
zero length message will be used as the will. Passing an int or float
will result in the payload being converted to a string representing
that number. If you wish to send a true int/float, use struct.pack() to
create the payload you require.
qos: The quality of service level to use for the will.
retain: If set to true, the will message will be set as the "last known
good"/retained message for the topic.
Raises a ValueError if qos is not 0, 1 or 2, or if topic is None or has
zero string length. | [
"Set",
"a",
"Will",
"to",
"be",
"sent",
"by",
"the",
"broker",
"in",
"case",
"the",
"client",
"disconnects",
"unexpectedly",
"."
] | f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62 | https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/core/protocol/paho/client.py#L1257-L1293 |
229,117 | aws/aws-iot-device-sdk-python | AWSIoTPythonSDK/core/protocol/paho/client.py | Client.socket | def socket(self):
"""Return the socket or ssl object for this client."""
if self._ssl:
if self._useSecuredWebsocket:
return self._ssl.getSSLSocket()
else:
return self._ssl
else:
return self._sock | python | def socket(self):
"""Return the socket or ssl object for this client."""
if self._ssl:
if self._useSecuredWebsocket:
return self._ssl.getSSLSocket()
else:
return self._ssl
else:
return self._sock | [
"def",
"socket",
"(",
"self",
")",
":",
"if",
"self",
".",
"_ssl",
":",
"if",
"self",
".",
"_useSecuredWebsocket",
":",
"return",
"self",
".",
"_ssl",
".",
"getSSLSocket",
"(",
")",
"else",
":",
"return",
"self",
".",
"_ssl",
"else",
":",
"return",
"self",
".",
"_sock"
] | Return the socket or ssl object for this client. | [
"Return",
"the",
"socket",
"or",
"ssl",
"object",
"for",
"this",
"client",
"."
] | f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62 | https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/core/protocol/paho/client.py#L1305-L1313 |
229,118 | mcneel/rhino3dm | src/build_python_project.py | createproject | def createproject():
""" compile for the platform we are running on """
os.chdir(build_dir)
if windows_build:
command = 'cmake -A {} -DPYTHON_EXECUTABLE:FILEPATH="{}" ../..'.format("win32" if bitness==32 else "x64", sys.executable)
os.system(command)
if bitness==64:
for line in fileinput.input("_rhino3dm.vcxproj", inplace=1):
print(line.replace("WIN32;", "WIN64;"))
for line in fileinput.input("opennurbs_static.vcxproj", inplace=1):
print(line.replace("WIN32;", "WIN64;"))
#os.system("cmake --build . --config Release --target _rhino3dm")
else:
rv = os.system("cmake -DPYTHON_EXECUTABLE:FILEPATH={} ../..".format(sys.executable))
if int(rv) > 0: sys.exit(1) | python | def createproject():
""" compile for the platform we are running on """
os.chdir(build_dir)
if windows_build:
command = 'cmake -A {} -DPYTHON_EXECUTABLE:FILEPATH="{}" ../..'.format("win32" if bitness==32 else "x64", sys.executable)
os.system(command)
if bitness==64:
for line in fileinput.input("_rhino3dm.vcxproj", inplace=1):
print(line.replace("WIN32;", "WIN64;"))
for line in fileinput.input("opennurbs_static.vcxproj", inplace=1):
print(line.replace("WIN32;", "WIN64;"))
#os.system("cmake --build . --config Release --target _rhino3dm")
else:
rv = os.system("cmake -DPYTHON_EXECUTABLE:FILEPATH={} ../..".format(sys.executable))
if int(rv) > 0: sys.exit(1) | [
"def",
"createproject",
"(",
")",
":",
"os",
".",
"chdir",
"(",
"build_dir",
")",
"if",
"windows_build",
":",
"command",
"=",
"'cmake -A {} -DPYTHON_EXECUTABLE:FILEPATH=\"{}\" ../..'",
".",
"format",
"(",
"\"win32\"",
"if",
"bitness",
"==",
"32",
"else",
"\"x64\"",
",",
"sys",
".",
"executable",
")",
"os",
".",
"system",
"(",
"command",
")",
"if",
"bitness",
"==",
"64",
":",
"for",
"line",
"in",
"fileinput",
".",
"input",
"(",
"\"_rhino3dm.vcxproj\"",
",",
"inplace",
"=",
"1",
")",
":",
"print",
"(",
"line",
".",
"replace",
"(",
"\"WIN32;\"",
",",
"\"WIN64;\"",
")",
")",
"for",
"line",
"in",
"fileinput",
".",
"input",
"(",
"\"opennurbs_static.vcxproj\"",
",",
"inplace",
"=",
"1",
")",
":",
"print",
"(",
"line",
".",
"replace",
"(",
"\"WIN32;\"",
",",
"\"WIN64;\"",
")",
")",
"#os.system(\"cmake --build . --config Release --target _rhino3dm\")",
"else",
":",
"rv",
"=",
"os",
".",
"system",
"(",
"\"cmake -DPYTHON_EXECUTABLE:FILEPATH={} ../..\"",
".",
"format",
"(",
"sys",
".",
"executable",
")",
")",
"if",
"int",
"(",
"rv",
")",
">",
"0",
":",
"sys",
".",
"exit",
"(",
"1",
")"
] | compile for the platform we are running on | [
"compile",
"for",
"the",
"platform",
"we",
"are",
"running",
"on"
] | 89e4e46c9a07c4243ea51572de7897e03a4acda2 | https://github.com/mcneel/rhino3dm/blob/89e4e46c9a07c4243ea51572de7897e03a4acda2/src/build_python_project.py#L24-L38 |
229,119 | getsentry/responses | responses.py | RequestsMock.add_passthru | def add_passthru(self, prefix):
"""
Register a URL prefix to passthru any non-matching mock requests to.
For example, to allow any request to 'https://example.com', but require
mocks for the remainder, you would add the prefix as so:
>>> responses.add_passthru('https://example.com')
"""
if _has_unicode(prefix):
prefix = _clean_unicode(prefix)
self.passthru_prefixes += (prefix,) | python | def add_passthru(self, prefix):
"""
Register a URL prefix to passthru any non-matching mock requests to.
For example, to allow any request to 'https://example.com', but require
mocks for the remainder, you would add the prefix as so:
>>> responses.add_passthru('https://example.com')
"""
if _has_unicode(prefix):
prefix = _clean_unicode(prefix)
self.passthru_prefixes += (prefix,) | [
"def",
"add_passthru",
"(",
"self",
",",
"prefix",
")",
":",
"if",
"_has_unicode",
"(",
"prefix",
")",
":",
"prefix",
"=",
"_clean_unicode",
"(",
"prefix",
")",
"self",
".",
"passthru_prefixes",
"+=",
"(",
"prefix",
",",
")"
] | Register a URL prefix to passthru any non-matching mock requests to.
For example, to allow any request to 'https://example.com', but require
mocks for the remainder, you would add the prefix as so:
>>> responses.add_passthru('https://example.com') | [
"Register",
"a",
"URL",
"prefix",
"to",
"passthru",
"any",
"non",
"-",
"matching",
"mock",
"requests",
"to",
"."
] | b7ab59513ffd52bf28808f45005f492f7d1bbd50 | https://github.com/getsentry/responses/blob/b7ab59513ffd52bf28808f45005f492f7d1bbd50/responses.py#L489-L500 |
229,120 | martinblech/xmltodict | ez_setup.py | _install | def _install(archive_filename, install_args=()):
"""Install Setuptools."""
with archive_context(archive_filename):
# installing
log.warn('Installing Setuptools')
if not _python_cmd('setup.py', 'install', *install_args):
log.warn('Something went wrong during the installation.')
log.warn('See the error message above.')
# exitcode will be 2
return 2 | python | def _install(archive_filename, install_args=()):
"""Install Setuptools."""
with archive_context(archive_filename):
# installing
log.warn('Installing Setuptools')
if not _python_cmd('setup.py', 'install', *install_args):
log.warn('Something went wrong during the installation.')
log.warn('See the error message above.')
# exitcode will be 2
return 2 | [
"def",
"_install",
"(",
"archive_filename",
",",
"install_args",
"=",
"(",
")",
")",
":",
"with",
"archive_context",
"(",
"archive_filename",
")",
":",
"# installing",
"log",
".",
"warn",
"(",
"'Installing Setuptools'",
")",
"if",
"not",
"_python_cmd",
"(",
"'setup.py'",
",",
"'install'",
",",
"*",
"install_args",
")",
":",
"log",
".",
"warn",
"(",
"'Something went wrong during the installation.'",
")",
"log",
".",
"warn",
"(",
"'See the error message above.'",
")",
"# exitcode will be 2",
"return",
"2"
] | Install Setuptools. | [
"Install",
"Setuptools",
"."
] | f3ab7e1740d37d585ffab0154edb4cb664afe4a9 | https://github.com/martinblech/xmltodict/blob/f3ab7e1740d37d585ffab0154edb4cb664afe4a9/ez_setup.py#L57-L66 |
229,121 | martinblech/xmltodict | ez_setup.py | _build_egg | def _build_egg(egg, archive_filename, to_dir):
"""Build Setuptools egg."""
with archive_context(archive_filename):
# building an egg
log.warn('Building a Setuptools egg in %s', to_dir)
_python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
# returning the result
log.warn(egg)
if not os.path.exists(egg):
raise IOError('Could not build the egg.') | python | def _build_egg(egg, archive_filename, to_dir):
"""Build Setuptools egg."""
with archive_context(archive_filename):
# building an egg
log.warn('Building a Setuptools egg in %s', to_dir)
_python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
# returning the result
log.warn(egg)
if not os.path.exists(egg):
raise IOError('Could not build the egg.') | [
"def",
"_build_egg",
"(",
"egg",
",",
"archive_filename",
",",
"to_dir",
")",
":",
"with",
"archive_context",
"(",
"archive_filename",
")",
":",
"# building an egg",
"log",
".",
"warn",
"(",
"'Building a Setuptools egg in %s'",
",",
"to_dir",
")",
"_python_cmd",
"(",
"'setup.py'",
",",
"'-q'",
",",
"'bdist_egg'",
",",
"'--dist-dir'",
",",
"to_dir",
")",
"# returning the result",
"log",
".",
"warn",
"(",
"egg",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"egg",
")",
":",
"raise",
"IOError",
"(",
"'Could not build the egg.'",
")"
] | Build Setuptools egg. | [
"Build",
"Setuptools",
"egg",
"."
] | f3ab7e1740d37d585ffab0154edb4cb664afe4a9 | https://github.com/martinblech/xmltodict/blob/f3ab7e1740d37d585ffab0154edb4cb664afe4a9/ez_setup.py#L69-L78 |
229,122 | martinblech/xmltodict | ez_setup.py | _do_download | def _do_download(version, download_base, to_dir, download_delay):
"""Download Setuptools."""
py_desig = 'py{sys.version_info[0]}.{sys.version_info[1]}'.format(sys=sys)
tp = 'setuptools-{version}-{py_desig}.egg'
egg = os.path.join(to_dir, tp.format(**locals()))
if not os.path.exists(egg):
archive = download_setuptools(version, download_base,
to_dir, download_delay)
_build_egg(egg, archive, to_dir)
sys.path.insert(0, egg)
# Remove previously-imported pkg_resources if present (see
# https://bitbucket.org/pypa/setuptools/pull-request/7/ for details).
if 'pkg_resources' in sys.modules:
_unload_pkg_resources()
import setuptools
setuptools.bootstrap_install_from = egg | python | def _do_download(version, download_base, to_dir, download_delay):
"""Download Setuptools."""
py_desig = 'py{sys.version_info[0]}.{sys.version_info[1]}'.format(sys=sys)
tp = 'setuptools-{version}-{py_desig}.egg'
egg = os.path.join(to_dir, tp.format(**locals()))
if not os.path.exists(egg):
archive = download_setuptools(version, download_base,
to_dir, download_delay)
_build_egg(egg, archive, to_dir)
sys.path.insert(0, egg)
# Remove previously-imported pkg_resources if present (see
# https://bitbucket.org/pypa/setuptools/pull-request/7/ for details).
if 'pkg_resources' in sys.modules:
_unload_pkg_resources()
import setuptools
setuptools.bootstrap_install_from = egg | [
"def",
"_do_download",
"(",
"version",
",",
"download_base",
",",
"to_dir",
",",
"download_delay",
")",
":",
"py_desig",
"=",
"'py{sys.version_info[0]}.{sys.version_info[1]}'",
".",
"format",
"(",
"sys",
"=",
"sys",
")",
"tp",
"=",
"'setuptools-{version}-{py_desig}.egg'",
"egg",
"=",
"os",
".",
"path",
".",
"join",
"(",
"to_dir",
",",
"tp",
".",
"format",
"(",
"*",
"*",
"locals",
"(",
")",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"egg",
")",
":",
"archive",
"=",
"download_setuptools",
"(",
"version",
",",
"download_base",
",",
"to_dir",
",",
"download_delay",
")",
"_build_egg",
"(",
"egg",
",",
"archive",
",",
"to_dir",
")",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"egg",
")",
"# Remove previously-imported pkg_resources if present (see",
"# https://bitbucket.org/pypa/setuptools/pull-request/7/ for details).",
"if",
"'pkg_resources'",
"in",
"sys",
".",
"modules",
":",
"_unload_pkg_resources",
"(",
")",
"import",
"setuptools",
"setuptools",
".",
"bootstrap_install_from",
"=",
"egg"
] | Download Setuptools. | [
"Download",
"Setuptools",
"."
] | f3ab7e1740d37d585ffab0154edb4cb664afe4a9 | https://github.com/martinblech/xmltodict/blob/f3ab7e1740d37d585ffab0154edb4cb664afe4a9/ez_setup.py#L132-L149 |
229,123 | martinblech/xmltodict | ez_setup.py | use_setuptools | def use_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=DEFAULT_SAVE_DIR, download_delay=15):
"""
Ensure that a setuptools version is installed.
Return None. Raise SystemExit if the requested version
or later cannot be installed.
"""
to_dir = os.path.abspath(to_dir)
# prior to importing, capture the module state for
# representative modules.
rep_modules = 'pkg_resources', 'setuptools'
imported = set(sys.modules).intersection(rep_modules)
try:
import pkg_resources
pkg_resources.require("setuptools>=" + version)
# a suitable version is already installed
return
except ImportError:
# pkg_resources not available; setuptools is not installed; download
pass
except pkg_resources.DistributionNotFound:
# no version of setuptools was found; allow download
pass
except pkg_resources.VersionConflict as VC_err:
if imported:
_conflict_bail(VC_err, version)
# otherwise, unload pkg_resources to allow the downloaded version to
# take precedence.
del pkg_resources
_unload_pkg_resources()
return _do_download(version, download_base, to_dir, download_delay) | python | def use_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=DEFAULT_SAVE_DIR, download_delay=15):
"""
Ensure that a setuptools version is installed.
Return None. Raise SystemExit if the requested version
or later cannot be installed.
"""
to_dir = os.path.abspath(to_dir)
# prior to importing, capture the module state for
# representative modules.
rep_modules = 'pkg_resources', 'setuptools'
imported = set(sys.modules).intersection(rep_modules)
try:
import pkg_resources
pkg_resources.require("setuptools>=" + version)
# a suitable version is already installed
return
except ImportError:
# pkg_resources not available; setuptools is not installed; download
pass
except pkg_resources.DistributionNotFound:
# no version of setuptools was found; allow download
pass
except pkg_resources.VersionConflict as VC_err:
if imported:
_conflict_bail(VC_err, version)
# otherwise, unload pkg_resources to allow the downloaded version to
# take precedence.
del pkg_resources
_unload_pkg_resources()
return _do_download(version, download_base, to_dir, download_delay) | [
"def",
"use_setuptools",
"(",
"version",
"=",
"DEFAULT_VERSION",
",",
"download_base",
"=",
"DEFAULT_URL",
",",
"to_dir",
"=",
"DEFAULT_SAVE_DIR",
",",
"download_delay",
"=",
"15",
")",
":",
"to_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"to_dir",
")",
"# prior to importing, capture the module state for",
"# representative modules.",
"rep_modules",
"=",
"'pkg_resources'",
",",
"'setuptools'",
"imported",
"=",
"set",
"(",
"sys",
".",
"modules",
")",
".",
"intersection",
"(",
"rep_modules",
")",
"try",
":",
"import",
"pkg_resources",
"pkg_resources",
".",
"require",
"(",
"\"setuptools>=\"",
"+",
"version",
")",
"# a suitable version is already installed",
"return",
"except",
"ImportError",
":",
"# pkg_resources not available; setuptools is not installed; download",
"pass",
"except",
"pkg_resources",
".",
"DistributionNotFound",
":",
"# no version of setuptools was found; allow download",
"pass",
"except",
"pkg_resources",
".",
"VersionConflict",
"as",
"VC_err",
":",
"if",
"imported",
":",
"_conflict_bail",
"(",
"VC_err",
",",
"version",
")",
"# otherwise, unload pkg_resources to allow the downloaded version to",
"# take precedence.",
"del",
"pkg_resources",
"_unload_pkg_resources",
"(",
")",
"return",
"_do_download",
"(",
"version",
",",
"download_base",
",",
"to_dir",
",",
"download_delay",
")"
] | Ensure that a setuptools version is installed.
Return None. Raise SystemExit if the requested version
or later cannot be installed. | [
"Ensure",
"that",
"a",
"setuptools",
"version",
"is",
"installed",
"."
] | f3ab7e1740d37d585ffab0154edb4cb664afe4a9 | https://github.com/martinblech/xmltodict/blob/f3ab7e1740d37d585ffab0154edb4cb664afe4a9/ez_setup.py#L152-L188 |
229,124 | martinblech/xmltodict | ez_setup.py | _conflict_bail | def _conflict_bail(VC_err, version):
"""
Setuptools was imported prior to invocation, so it is
unsafe to unload it. Bail out.
"""
conflict_tmpl = textwrap.dedent("""
The required version of setuptools (>={version}) is not available,
and can't be installed while this script is running. Please
install a more recent version first, using
'easy_install -U setuptools'.
(Currently using {VC_err.args[0]!r})
""")
msg = conflict_tmpl.format(**locals())
sys.stderr.write(msg)
sys.exit(2) | python | def _conflict_bail(VC_err, version):
"""
Setuptools was imported prior to invocation, so it is
unsafe to unload it. Bail out.
"""
conflict_tmpl = textwrap.dedent("""
The required version of setuptools (>={version}) is not available,
and can't be installed while this script is running. Please
install a more recent version first, using
'easy_install -U setuptools'.
(Currently using {VC_err.args[0]!r})
""")
msg = conflict_tmpl.format(**locals())
sys.stderr.write(msg)
sys.exit(2) | [
"def",
"_conflict_bail",
"(",
"VC_err",
",",
"version",
")",
":",
"conflict_tmpl",
"=",
"textwrap",
".",
"dedent",
"(",
"\"\"\"\n The required version of setuptools (>={version}) is not available,\n and can't be installed while this script is running. Please\n install a more recent version first, using\n 'easy_install -U setuptools'.\n\n (Currently using {VC_err.args[0]!r})\n \"\"\"",
")",
"msg",
"=",
"conflict_tmpl",
".",
"format",
"(",
"*",
"*",
"locals",
"(",
")",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"msg",
")",
"sys",
".",
"exit",
"(",
"2",
")"
] | Setuptools was imported prior to invocation, so it is
unsafe to unload it. Bail out. | [
"Setuptools",
"was",
"imported",
"prior",
"to",
"invocation",
"so",
"it",
"is",
"unsafe",
"to",
"unload",
"it",
".",
"Bail",
"out",
"."
] | f3ab7e1740d37d585ffab0154edb4cb664afe4a9 | https://github.com/martinblech/xmltodict/blob/f3ab7e1740d37d585ffab0154edb4cb664afe4a9/ez_setup.py#L191-L206 |
229,125 | martinblech/xmltodict | ez_setup.py | download_file_insecure | def download_file_insecure(url, target):
"""Use Python to download the file, without connection authentication."""
src = urlopen(url)
try:
# Read all the data in one block.
data = src.read()
finally:
src.close()
# Write all the data in one block to avoid creating a partial file.
with open(target, "wb") as dst:
dst.write(data) | python | def download_file_insecure(url, target):
"""Use Python to download the file, without connection authentication."""
src = urlopen(url)
try:
# Read all the data in one block.
data = src.read()
finally:
src.close()
# Write all the data in one block to avoid creating a partial file.
with open(target, "wb") as dst:
dst.write(data) | [
"def",
"download_file_insecure",
"(",
"url",
",",
"target",
")",
":",
"src",
"=",
"urlopen",
"(",
"url",
")",
"try",
":",
"# Read all the data in one block.",
"data",
"=",
"src",
".",
"read",
"(",
")",
"finally",
":",
"src",
".",
"close",
"(",
")",
"# Write all the data in one block to avoid creating a partial file.",
"with",
"open",
"(",
"target",
",",
"\"wb\"",
")",
"as",
"dst",
":",
"dst",
".",
"write",
"(",
"data",
")"
] | Use Python to download the file, without connection authentication. | [
"Use",
"Python",
"to",
"download",
"the",
"file",
"without",
"connection",
"authentication",
"."
] | f3ab7e1740d37d585ffab0154edb4cb664afe4a9 | https://github.com/martinblech/xmltodict/blob/f3ab7e1740d37d585ffab0154edb4cb664afe4a9/ez_setup.py#L305-L316 |
229,126 | martinblech/xmltodict | ez_setup.py | _download_args | def _download_args(options):
"""Return args for download_setuptools function from cmdline args."""
return dict(
version=options.version,
download_base=options.download_base,
downloader_factory=options.downloader_factory,
to_dir=options.to_dir,
) | python | def _download_args(options):
"""Return args for download_setuptools function from cmdline args."""
return dict(
version=options.version,
download_base=options.download_base,
downloader_factory=options.downloader_factory,
to_dir=options.to_dir,
) | [
"def",
"_download_args",
"(",
"options",
")",
":",
"return",
"dict",
"(",
"version",
"=",
"options",
".",
"version",
",",
"download_base",
"=",
"options",
".",
"download_base",
",",
"downloader_factory",
"=",
"options",
".",
"downloader_factory",
",",
"to_dir",
"=",
"options",
".",
"to_dir",
",",
")"
] | Return args for download_setuptools function from cmdline args. | [
"Return",
"args",
"for",
"download_setuptools",
"function",
"from",
"cmdline",
"args",
"."
] | f3ab7e1740d37d585ffab0154edb4cb664afe4a9 | https://github.com/martinblech/xmltodict/blob/f3ab7e1740d37d585ffab0154edb4cb664afe4a9/ez_setup.py#L397-L404 |
229,127 | martinblech/xmltodict | ez_setup.py | main | def main():
"""Install or upgrade setuptools and EasyInstall."""
options = _parse_args()
archive = download_setuptools(**_download_args(options))
return _install(archive, _build_install_args(options)) | python | def main():
"""Install or upgrade setuptools and EasyInstall."""
options = _parse_args()
archive = download_setuptools(**_download_args(options))
return _install(archive, _build_install_args(options)) | [
"def",
"main",
"(",
")",
":",
"options",
"=",
"_parse_args",
"(",
")",
"archive",
"=",
"download_setuptools",
"(",
"*",
"*",
"_download_args",
"(",
"options",
")",
")",
"return",
"_install",
"(",
"archive",
",",
"_build_install_args",
"(",
"options",
")",
")"
] | Install or upgrade setuptools and EasyInstall. | [
"Install",
"or",
"upgrade",
"setuptools",
"and",
"EasyInstall",
"."
] | f3ab7e1740d37d585ffab0154edb4cb664afe4a9 | https://github.com/martinblech/xmltodict/blob/f3ab7e1740d37d585ffab0154edb4cb664afe4a9/ez_setup.py#L407-L411 |
229,128 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.registerContract | def registerContract(self, contract):
""" used for when callback receives a contract
that isn't found in local database """
if contract.m_exchange == "":
return
"""
if contract not in self.contracts.values():
contract_tuple = self.contract_to_tuple(contract)
self.createContract(contract_tuple)
if self.tickerId(contract) not in self.contracts.keys():
contract_tuple = self.contract_to_tuple(contract)
self.createContract(contract_tuple)
"""
if self.getConId(contract) == 0:
contract_tuple = self.contract_to_tuple(contract)
self.createContract(contract_tuple) | python | def registerContract(self, contract):
""" used for when callback receives a contract
that isn't found in local database """
if contract.m_exchange == "":
return
"""
if contract not in self.contracts.values():
contract_tuple = self.contract_to_tuple(contract)
self.createContract(contract_tuple)
if self.tickerId(contract) not in self.contracts.keys():
contract_tuple = self.contract_to_tuple(contract)
self.createContract(contract_tuple)
"""
if self.getConId(contract) == 0:
contract_tuple = self.contract_to_tuple(contract)
self.createContract(contract_tuple) | [
"def",
"registerContract",
"(",
"self",
",",
"contract",
")",
":",
"if",
"contract",
".",
"m_exchange",
"==",
"\"\"",
":",
"return",
"\"\"\"\n if contract not in self.contracts.values():\n contract_tuple = self.contract_to_tuple(contract)\n self.createContract(contract_tuple)\n\n if self.tickerId(contract) not in self.contracts.keys():\n contract_tuple = self.contract_to_tuple(contract)\n self.createContract(contract_tuple)\n \"\"\"",
"if",
"self",
".",
"getConId",
"(",
"contract",
")",
"==",
"0",
":",
"contract_tuple",
"=",
"self",
".",
"contract_to_tuple",
"(",
"contract",
")",
"self",
".",
"createContract",
"(",
"contract_tuple",
")"
] | used for when callback receives a contract
that isn't found in local database | [
"used",
"for",
"when",
"callback",
"receives",
"a",
"contract",
"that",
"isn",
"t",
"found",
"in",
"local",
"database"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L245-L264 |
229,129 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.handleErrorEvents | def handleErrorEvents(self, msg):
""" logs error messages """
# https://www.interactivebrokers.com/en/software/api/apiguide/tables/api_message_codes.htm
if msg.errorCode is not None and msg.errorCode != -1 and \
msg.errorCode not in dataTypes["BENIGN_ERROR_CODES"]:
log = True
# log disconnect errors only once
if msg.errorCode in dataTypes["DISCONNECT_ERROR_CODES"]:
log = False
if msg.errorCode not in self.connection_tracking["errors"]:
self.connection_tracking["errors"].append(msg.errorCode)
log = True
if log:
self.log.error("[#%s] %s" % (msg.errorCode, msg.errorMsg))
self.ibCallback(caller="handleError", msg=msg) | python | def handleErrorEvents(self, msg):
""" logs error messages """
# https://www.interactivebrokers.com/en/software/api/apiguide/tables/api_message_codes.htm
if msg.errorCode is not None and msg.errorCode != -1 and \
msg.errorCode not in dataTypes["BENIGN_ERROR_CODES"]:
log = True
# log disconnect errors only once
if msg.errorCode in dataTypes["DISCONNECT_ERROR_CODES"]:
log = False
if msg.errorCode not in self.connection_tracking["errors"]:
self.connection_tracking["errors"].append(msg.errorCode)
log = True
if log:
self.log.error("[#%s] %s" % (msg.errorCode, msg.errorMsg))
self.ibCallback(caller="handleError", msg=msg) | [
"def",
"handleErrorEvents",
"(",
"self",
",",
"msg",
")",
":",
"# https://www.interactivebrokers.com/en/software/api/apiguide/tables/api_message_codes.htm",
"if",
"msg",
".",
"errorCode",
"is",
"not",
"None",
"and",
"msg",
".",
"errorCode",
"!=",
"-",
"1",
"and",
"msg",
".",
"errorCode",
"not",
"in",
"dataTypes",
"[",
"\"BENIGN_ERROR_CODES\"",
"]",
":",
"log",
"=",
"True",
"# log disconnect errors only once",
"if",
"msg",
".",
"errorCode",
"in",
"dataTypes",
"[",
"\"DISCONNECT_ERROR_CODES\"",
"]",
":",
"log",
"=",
"False",
"if",
"msg",
".",
"errorCode",
"not",
"in",
"self",
".",
"connection_tracking",
"[",
"\"errors\"",
"]",
":",
"self",
".",
"connection_tracking",
"[",
"\"errors\"",
"]",
".",
"append",
"(",
"msg",
".",
"errorCode",
")",
"log",
"=",
"True",
"if",
"log",
":",
"self",
".",
"log",
".",
"error",
"(",
"\"[#%s] %s\"",
"%",
"(",
"msg",
".",
"errorCode",
",",
"msg",
".",
"errorMsg",
")",
")",
"self",
".",
"ibCallback",
"(",
"caller",
"=",
"\"handleError\"",
",",
"msg",
"=",
"msg",
")"
] | logs error messages | [
"logs",
"error",
"messages"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L269-L286 |
229,130 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.handleServerEvents | def handleServerEvents(self, msg):
""" dispatch msg to the right handler """
self.log.debug('MSG %s', msg)
self.handleConnectionState(msg)
if msg.typeName == "error":
self.handleErrorEvents(msg)
elif msg.typeName == dataTypes["MSG_CURRENT_TIME"]:
if self.time < msg.time:
self.time = msg.time
elif (msg.typeName == dataTypes["MSG_TYPE_MKT_DEPTH"] or
msg.typeName == dataTypes["MSG_TYPE_MKT_DEPTH_L2"]):
self.handleMarketDepth(msg)
elif msg.typeName == dataTypes["MSG_TYPE_TICK_STRING"]:
self.handleTickString(msg)
elif msg.typeName == dataTypes["MSG_TYPE_TICK_PRICE"]:
self.handleTickPrice(msg)
elif msg.typeName == dataTypes["MSG_TYPE_TICK_GENERIC"]:
self.handleTickGeneric(msg)
elif msg.typeName == dataTypes["MSG_TYPE_TICK_SIZE"]:
self.handleTickSize(msg)
elif msg.typeName == dataTypes["MSG_TYPE_TICK_OPTION"]:
self.handleTickOptionComputation(msg)
elif (msg.typeName == dataTypes["MSG_TYPE_OPEN_ORDER"] or
msg.typeName == dataTypes["MSG_TYPE_OPEN_ORDER_END"] or
msg.typeName == dataTypes["MSG_TYPE_ORDER_STATUS"]):
self.handleOrders(msg)
elif msg.typeName == dataTypes["MSG_TYPE_HISTORICAL_DATA"]:
self.handleHistoricalData(msg)
elif msg.typeName == dataTypes["MSG_TYPE_ACCOUNT_UPDATES"]:
self.handleAccount(msg)
elif msg.typeName == dataTypes["MSG_TYPE_PORTFOLIO_UPDATES"]:
self.handlePortfolio(msg)
elif msg.typeName == dataTypes["MSG_TYPE_POSITION"]:
self.handlePosition(msg)
elif msg.typeName == dataTypes["MSG_TYPE_NEXT_ORDER_ID"]:
self.handleNextValidId(msg.orderId)
elif msg.typeName == dataTypes["MSG_CONNECTION_CLOSED"]:
self.handleConnectionClosed(msg)
# elif msg.typeName == dataTypes["MSG_TYPE_MANAGED_ACCOUNTS"]:
# self.accountCode = msg.accountsList
elif msg.typeName == dataTypes["MSG_COMMISSION_REPORT"]:
self.commission = msg.commissionReport.m_commission
elif msg.typeName == dataTypes["MSG_CONTRACT_DETAILS"]:
self.handleContractDetails(msg, end=False)
elif msg.typeName == dataTypes["MSG_CONTRACT_DETAILS_END"]:
self.handleContractDetails(msg, end=True)
elif msg.typeName == dataTypes["MSG_TICK_SNAPSHOT_END"]:
self.ibCallback(caller="handleTickSnapshotEnd", msg=msg)
else:
# log handler msg
self.log_msg("server", msg) | python | def handleServerEvents(self, msg):
""" dispatch msg to the right handler """
self.log.debug('MSG %s', msg)
self.handleConnectionState(msg)
if msg.typeName == "error":
self.handleErrorEvents(msg)
elif msg.typeName == dataTypes["MSG_CURRENT_TIME"]:
if self.time < msg.time:
self.time = msg.time
elif (msg.typeName == dataTypes["MSG_TYPE_MKT_DEPTH"] or
msg.typeName == dataTypes["MSG_TYPE_MKT_DEPTH_L2"]):
self.handleMarketDepth(msg)
elif msg.typeName == dataTypes["MSG_TYPE_TICK_STRING"]:
self.handleTickString(msg)
elif msg.typeName == dataTypes["MSG_TYPE_TICK_PRICE"]:
self.handleTickPrice(msg)
elif msg.typeName == dataTypes["MSG_TYPE_TICK_GENERIC"]:
self.handleTickGeneric(msg)
elif msg.typeName == dataTypes["MSG_TYPE_TICK_SIZE"]:
self.handleTickSize(msg)
elif msg.typeName == dataTypes["MSG_TYPE_TICK_OPTION"]:
self.handleTickOptionComputation(msg)
elif (msg.typeName == dataTypes["MSG_TYPE_OPEN_ORDER"] or
msg.typeName == dataTypes["MSG_TYPE_OPEN_ORDER_END"] or
msg.typeName == dataTypes["MSG_TYPE_ORDER_STATUS"]):
self.handleOrders(msg)
elif msg.typeName == dataTypes["MSG_TYPE_HISTORICAL_DATA"]:
self.handleHistoricalData(msg)
elif msg.typeName == dataTypes["MSG_TYPE_ACCOUNT_UPDATES"]:
self.handleAccount(msg)
elif msg.typeName == dataTypes["MSG_TYPE_PORTFOLIO_UPDATES"]:
self.handlePortfolio(msg)
elif msg.typeName == dataTypes["MSG_TYPE_POSITION"]:
self.handlePosition(msg)
elif msg.typeName == dataTypes["MSG_TYPE_NEXT_ORDER_ID"]:
self.handleNextValidId(msg.orderId)
elif msg.typeName == dataTypes["MSG_CONNECTION_CLOSED"]:
self.handleConnectionClosed(msg)
# elif msg.typeName == dataTypes["MSG_TYPE_MANAGED_ACCOUNTS"]:
# self.accountCode = msg.accountsList
elif msg.typeName == dataTypes["MSG_COMMISSION_REPORT"]:
self.commission = msg.commissionReport.m_commission
elif msg.typeName == dataTypes["MSG_CONTRACT_DETAILS"]:
self.handleContractDetails(msg, end=False)
elif msg.typeName == dataTypes["MSG_CONTRACT_DETAILS_END"]:
self.handleContractDetails(msg, end=True)
elif msg.typeName == dataTypes["MSG_TICK_SNAPSHOT_END"]:
self.ibCallback(caller="handleTickSnapshotEnd", msg=msg)
else:
# log handler msg
self.log_msg("server", msg) | [
"def",
"handleServerEvents",
"(",
"self",
",",
"msg",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'MSG %s'",
",",
"msg",
")",
"self",
".",
"handleConnectionState",
"(",
"msg",
")",
"if",
"msg",
".",
"typeName",
"==",
"\"error\"",
":",
"self",
".",
"handleErrorEvents",
"(",
"msg",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_CURRENT_TIME\"",
"]",
":",
"if",
"self",
".",
"time",
"<",
"msg",
".",
"time",
":",
"self",
".",
"time",
"=",
"msg",
".",
"time",
"elif",
"(",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_MKT_DEPTH\"",
"]",
"or",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_MKT_DEPTH_L2\"",
"]",
")",
":",
"self",
".",
"handleMarketDepth",
"(",
"msg",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_TICK_STRING\"",
"]",
":",
"self",
".",
"handleTickString",
"(",
"msg",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_TICK_PRICE\"",
"]",
":",
"self",
".",
"handleTickPrice",
"(",
"msg",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_TICK_GENERIC\"",
"]",
":",
"self",
".",
"handleTickGeneric",
"(",
"msg",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_TICK_SIZE\"",
"]",
":",
"self",
".",
"handleTickSize",
"(",
"msg",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_TICK_OPTION\"",
"]",
":",
"self",
".",
"handleTickOptionComputation",
"(",
"msg",
")",
"elif",
"(",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_OPEN_ORDER\"",
"]",
"or",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_OPEN_ORDER_END\"",
"]",
"or",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_ORDER_STATUS\"",
"]",
")",
":",
"self",
".",
"handleOrders",
"(",
"msg",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_HISTORICAL_DATA\"",
"]",
":",
"self",
".",
"handleHistoricalData",
"(",
"msg",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_ACCOUNT_UPDATES\"",
"]",
":",
"self",
".",
"handleAccount",
"(",
"msg",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_PORTFOLIO_UPDATES\"",
"]",
":",
"self",
".",
"handlePortfolio",
"(",
"msg",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_POSITION\"",
"]",
":",
"self",
".",
"handlePosition",
"(",
"msg",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_NEXT_ORDER_ID\"",
"]",
":",
"self",
".",
"handleNextValidId",
"(",
"msg",
".",
"orderId",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_CONNECTION_CLOSED\"",
"]",
":",
"self",
".",
"handleConnectionClosed",
"(",
"msg",
")",
"# elif msg.typeName == dataTypes[\"MSG_TYPE_MANAGED_ACCOUNTS\"]:",
"# self.accountCode = msg.accountsList",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_COMMISSION_REPORT\"",
"]",
":",
"self",
".",
"commission",
"=",
"msg",
".",
"commissionReport",
".",
"m_commission",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_CONTRACT_DETAILS\"",
"]",
":",
"self",
".",
"handleContractDetails",
"(",
"msg",
",",
"end",
"=",
"False",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_CONTRACT_DETAILS_END\"",
"]",
":",
"self",
".",
"handleContractDetails",
"(",
"msg",
",",
"end",
"=",
"True",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TICK_SNAPSHOT_END\"",
"]",
":",
"self",
".",
"ibCallback",
"(",
"caller",
"=",
"\"handleTickSnapshotEnd\"",
",",
"msg",
"=",
"msg",
")",
"else",
":",
"# log handler msg",
"self",
".",
"log_msg",
"(",
"\"server\"",
",",
"msg",
")"
] | dispatch msg to the right handler | [
"dispatch",
"msg",
"to",
"the",
"right",
"handler"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L289-L361 |
229,131 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.handleContractDetails | def handleContractDetails(self, msg, end=False):
""" handles contractDetails and contractDetailsEnd """
if end:
# mark as downloaded
self._contract_details[msg.reqId]['downloaded'] = True
# move details from temp to permanent collector
self.contract_details[msg.reqId] = self._contract_details[msg.reqId]
del self._contract_details[msg.reqId]
# adjust fields if multi contract
if len(self.contract_details[msg.reqId]["contracts"]) > 1:
self.contract_details[msg.reqId]["m_contractMonth"] = ""
# m_summary should hold closest expiration
expirations = self.getExpirations(self.contracts[msg.reqId], expired=0)
contract = self.contract_details[msg.reqId]["contracts"][-len(expirations)]
self.contract_details[msg.reqId]["m_summary"] = vars(contract)
else:
self.contract_details[msg.reqId]["m_summary"] = vars(
self.contract_details[msg.reqId]["contracts"][0])
# update local db with correct contractString
for tid in self.contract_details:
oldString = self.tickerIds[tid]
newString = self.contractString(self.contract_details[tid]["contracts"][0])
if len(self.contract_details[msg.reqId]["contracts"]) > 1:
self.tickerIds[tid] = newString
if newString != oldString:
if oldString in self._portfolios:
self._portfolios[newString] = self._portfolios[oldString]
if oldString in self._positions:
self._positions[newString] = self._positions[oldString]
# fire callback
self.ibCallback(caller="handleContractDetailsEnd", msg=msg)
# exit
return
# continue...
# collect data on all contract details
# (including those with multiple expiry/strike/sides)
details = vars(msg.contractDetails)
contract = details["m_summary"]
if msg.reqId in self._contract_details:
details['contracts'] = self._contract_details[msg.reqId]["contracts"]
else:
details['contracts'] = []
details['contracts'].append(contract)
details['downloaded'] = False
self._contract_details[msg.reqId] = details
# add details to local symbol list
if contract.m_localSymbol not in self.localSymbolExpiry:
self.localSymbolExpiry[contract.m_localSymbol] = details["m_contractMonth"]
# add contract's multiple expiry/strike/sides to class collectors
contractString = self.contractString(contract)
tickerId = self.tickerId(contractString)
self.contracts[tickerId] = contract
# continue if this is a "multi" contract
if tickerId == msg.reqId:
self._contract_details[msg.reqId]["m_summary"] = vars(contract)
else:
# print("+++", tickerId, contractString)
self.contract_details[tickerId] = details.copy()
self.contract_details[tickerId]["m_summary"] = vars(contract)
self.contract_details[tickerId]["contracts"] = [contract]
# fire callback
self.ibCallback(caller="handleContractDetails", msg=msg) | python | def handleContractDetails(self, msg, end=False):
""" handles contractDetails and contractDetailsEnd """
if end:
# mark as downloaded
self._contract_details[msg.reqId]['downloaded'] = True
# move details from temp to permanent collector
self.contract_details[msg.reqId] = self._contract_details[msg.reqId]
del self._contract_details[msg.reqId]
# adjust fields if multi contract
if len(self.contract_details[msg.reqId]["contracts"]) > 1:
self.contract_details[msg.reqId]["m_contractMonth"] = ""
# m_summary should hold closest expiration
expirations = self.getExpirations(self.contracts[msg.reqId], expired=0)
contract = self.contract_details[msg.reqId]["contracts"][-len(expirations)]
self.contract_details[msg.reqId]["m_summary"] = vars(contract)
else:
self.contract_details[msg.reqId]["m_summary"] = vars(
self.contract_details[msg.reqId]["contracts"][0])
# update local db with correct contractString
for tid in self.contract_details:
oldString = self.tickerIds[tid]
newString = self.contractString(self.contract_details[tid]["contracts"][0])
if len(self.contract_details[msg.reqId]["contracts"]) > 1:
self.tickerIds[tid] = newString
if newString != oldString:
if oldString in self._portfolios:
self._portfolios[newString] = self._portfolios[oldString]
if oldString in self._positions:
self._positions[newString] = self._positions[oldString]
# fire callback
self.ibCallback(caller="handleContractDetailsEnd", msg=msg)
# exit
return
# continue...
# collect data on all contract details
# (including those with multiple expiry/strike/sides)
details = vars(msg.contractDetails)
contract = details["m_summary"]
if msg.reqId in self._contract_details:
details['contracts'] = self._contract_details[msg.reqId]["contracts"]
else:
details['contracts'] = []
details['contracts'].append(contract)
details['downloaded'] = False
self._contract_details[msg.reqId] = details
# add details to local symbol list
if contract.m_localSymbol not in self.localSymbolExpiry:
self.localSymbolExpiry[contract.m_localSymbol] = details["m_contractMonth"]
# add contract's multiple expiry/strike/sides to class collectors
contractString = self.contractString(contract)
tickerId = self.tickerId(contractString)
self.contracts[tickerId] = contract
# continue if this is a "multi" contract
if tickerId == msg.reqId:
self._contract_details[msg.reqId]["m_summary"] = vars(contract)
else:
# print("+++", tickerId, contractString)
self.contract_details[tickerId] = details.copy()
self.contract_details[tickerId]["m_summary"] = vars(contract)
self.contract_details[tickerId]["contracts"] = [contract]
# fire callback
self.ibCallback(caller="handleContractDetails", msg=msg) | [
"def",
"handleContractDetails",
"(",
"self",
",",
"msg",
",",
"end",
"=",
"False",
")",
":",
"if",
"end",
":",
"# mark as downloaded",
"self",
".",
"_contract_details",
"[",
"msg",
".",
"reqId",
"]",
"[",
"'downloaded'",
"]",
"=",
"True",
"# move details from temp to permanent collector",
"self",
".",
"contract_details",
"[",
"msg",
".",
"reqId",
"]",
"=",
"self",
".",
"_contract_details",
"[",
"msg",
".",
"reqId",
"]",
"del",
"self",
".",
"_contract_details",
"[",
"msg",
".",
"reqId",
"]",
"# adjust fields if multi contract",
"if",
"len",
"(",
"self",
".",
"contract_details",
"[",
"msg",
".",
"reqId",
"]",
"[",
"\"contracts\"",
"]",
")",
">",
"1",
":",
"self",
".",
"contract_details",
"[",
"msg",
".",
"reqId",
"]",
"[",
"\"m_contractMonth\"",
"]",
"=",
"\"\"",
"# m_summary should hold closest expiration",
"expirations",
"=",
"self",
".",
"getExpirations",
"(",
"self",
".",
"contracts",
"[",
"msg",
".",
"reqId",
"]",
",",
"expired",
"=",
"0",
")",
"contract",
"=",
"self",
".",
"contract_details",
"[",
"msg",
".",
"reqId",
"]",
"[",
"\"contracts\"",
"]",
"[",
"-",
"len",
"(",
"expirations",
")",
"]",
"self",
".",
"contract_details",
"[",
"msg",
".",
"reqId",
"]",
"[",
"\"m_summary\"",
"]",
"=",
"vars",
"(",
"contract",
")",
"else",
":",
"self",
".",
"contract_details",
"[",
"msg",
".",
"reqId",
"]",
"[",
"\"m_summary\"",
"]",
"=",
"vars",
"(",
"self",
".",
"contract_details",
"[",
"msg",
".",
"reqId",
"]",
"[",
"\"contracts\"",
"]",
"[",
"0",
"]",
")",
"# update local db with correct contractString",
"for",
"tid",
"in",
"self",
".",
"contract_details",
":",
"oldString",
"=",
"self",
".",
"tickerIds",
"[",
"tid",
"]",
"newString",
"=",
"self",
".",
"contractString",
"(",
"self",
".",
"contract_details",
"[",
"tid",
"]",
"[",
"\"contracts\"",
"]",
"[",
"0",
"]",
")",
"if",
"len",
"(",
"self",
".",
"contract_details",
"[",
"msg",
".",
"reqId",
"]",
"[",
"\"contracts\"",
"]",
")",
">",
"1",
":",
"self",
".",
"tickerIds",
"[",
"tid",
"]",
"=",
"newString",
"if",
"newString",
"!=",
"oldString",
":",
"if",
"oldString",
"in",
"self",
".",
"_portfolios",
":",
"self",
".",
"_portfolios",
"[",
"newString",
"]",
"=",
"self",
".",
"_portfolios",
"[",
"oldString",
"]",
"if",
"oldString",
"in",
"self",
".",
"_positions",
":",
"self",
".",
"_positions",
"[",
"newString",
"]",
"=",
"self",
".",
"_positions",
"[",
"oldString",
"]",
"# fire callback",
"self",
".",
"ibCallback",
"(",
"caller",
"=",
"\"handleContractDetailsEnd\"",
",",
"msg",
"=",
"msg",
")",
"# exit",
"return",
"# continue...",
"# collect data on all contract details",
"# (including those with multiple expiry/strike/sides)",
"details",
"=",
"vars",
"(",
"msg",
".",
"contractDetails",
")",
"contract",
"=",
"details",
"[",
"\"m_summary\"",
"]",
"if",
"msg",
".",
"reqId",
"in",
"self",
".",
"_contract_details",
":",
"details",
"[",
"'contracts'",
"]",
"=",
"self",
".",
"_contract_details",
"[",
"msg",
".",
"reqId",
"]",
"[",
"\"contracts\"",
"]",
"else",
":",
"details",
"[",
"'contracts'",
"]",
"=",
"[",
"]",
"details",
"[",
"'contracts'",
"]",
".",
"append",
"(",
"contract",
")",
"details",
"[",
"'downloaded'",
"]",
"=",
"False",
"self",
".",
"_contract_details",
"[",
"msg",
".",
"reqId",
"]",
"=",
"details",
"# add details to local symbol list",
"if",
"contract",
".",
"m_localSymbol",
"not",
"in",
"self",
".",
"localSymbolExpiry",
":",
"self",
".",
"localSymbolExpiry",
"[",
"contract",
".",
"m_localSymbol",
"]",
"=",
"details",
"[",
"\"m_contractMonth\"",
"]",
"# add contract's multiple expiry/strike/sides to class collectors",
"contractString",
"=",
"self",
".",
"contractString",
"(",
"contract",
")",
"tickerId",
"=",
"self",
".",
"tickerId",
"(",
"contractString",
")",
"self",
".",
"contracts",
"[",
"tickerId",
"]",
"=",
"contract",
"# continue if this is a \"multi\" contract",
"if",
"tickerId",
"==",
"msg",
".",
"reqId",
":",
"self",
".",
"_contract_details",
"[",
"msg",
".",
"reqId",
"]",
"[",
"\"m_summary\"",
"]",
"=",
"vars",
"(",
"contract",
")",
"else",
":",
"# print(\"+++\", tickerId, contractString)",
"self",
".",
"contract_details",
"[",
"tickerId",
"]",
"=",
"details",
".",
"copy",
"(",
")",
"self",
".",
"contract_details",
"[",
"tickerId",
"]",
"[",
"\"m_summary\"",
"]",
"=",
"vars",
"(",
"contract",
")",
"self",
".",
"contract_details",
"[",
"tickerId",
"]",
"[",
"\"contracts\"",
"]",
"=",
"[",
"contract",
"]",
"# fire callback",
"self",
".",
"ibCallback",
"(",
"caller",
"=",
"\"handleContractDetails\"",
",",
"msg",
"=",
"msg",
")"
] | handles contractDetails and contractDetailsEnd | [
"handles",
"contractDetails",
"and",
"contractDetailsEnd"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L411-L487 |
229,132 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.handlePosition | def handlePosition(self, msg):
""" handle positions changes """
# log handler msg
self.log_msg("position", msg)
# contract identifier
contract_tuple = self.contract_to_tuple(msg.contract)
contractString = self.contractString(contract_tuple)
# try creating the contract
self.registerContract(msg.contract)
# new account?
if msg.account not in self._positions.keys():
self._positions[msg.account] = {}
# if msg.pos != 0 or contractString in self.contracts.keys():
self._positions[msg.account][contractString] = {
"symbol": contractString,
"position": int(msg.pos),
"avgCost": float(msg.avgCost),
"account": msg.account
}
# fire callback
self.ibCallback(caller="handlePosition", msg=msg) | python | def handlePosition(self, msg):
""" handle positions changes """
# log handler msg
self.log_msg("position", msg)
# contract identifier
contract_tuple = self.contract_to_tuple(msg.contract)
contractString = self.contractString(contract_tuple)
# try creating the contract
self.registerContract(msg.contract)
# new account?
if msg.account not in self._positions.keys():
self._positions[msg.account] = {}
# if msg.pos != 0 or contractString in self.contracts.keys():
self._positions[msg.account][contractString] = {
"symbol": contractString,
"position": int(msg.pos),
"avgCost": float(msg.avgCost),
"account": msg.account
}
# fire callback
self.ibCallback(caller="handlePosition", msg=msg) | [
"def",
"handlePosition",
"(",
"self",
",",
"msg",
")",
":",
"# log handler msg",
"self",
".",
"log_msg",
"(",
"\"position\"",
",",
"msg",
")",
"# contract identifier",
"contract_tuple",
"=",
"self",
".",
"contract_to_tuple",
"(",
"msg",
".",
"contract",
")",
"contractString",
"=",
"self",
".",
"contractString",
"(",
"contract_tuple",
")",
"# try creating the contract",
"self",
".",
"registerContract",
"(",
"msg",
".",
"contract",
")",
"# new account?",
"if",
"msg",
".",
"account",
"not",
"in",
"self",
".",
"_positions",
".",
"keys",
"(",
")",
":",
"self",
".",
"_positions",
"[",
"msg",
".",
"account",
"]",
"=",
"{",
"}",
"# if msg.pos != 0 or contractString in self.contracts.keys():",
"self",
".",
"_positions",
"[",
"msg",
".",
"account",
"]",
"[",
"contractString",
"]",
"=",
"{",
"\"symbol\"",
":",
"contractString",
",",
"\"position\"",
":",
"int",
"(",
"msg",
".",
"pos",
")",
",",
"\"avgCost\"",
":",
"float",
"(",
"msg",
".",
"avgCost",
")",
",",
"\"account\"",
":",
"msg",
".",
"account",
"}",
"# fire callback",
"self",
".",
"ibCallback",
"(",
"caller",
"=",
"\"handlePosition\"",
",",
"msg",
"=",
"msg",
")"
] | handle positions changes | [
"handle",
"positions",
"changes"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L553-L579 |
229,133 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.handlePortfolio | def handlePortfolio(self, msg):
""" handle portfolio updates """
# log handler msg
self.log_msg("portfolio", msg)
# contract identifier
contract_tuple = self.contract_to_tuple(msg.contract)
contractString = self.contractString(contract_tuple)
# try creating the contract
self.registerContract(msg.contract)
# new account?
if msg.accountName not in self._portfolios.keys():
self._portfolios[msg.accountName] = {}
self._portfolios[msg.accountName][contractString] = {
"symbol": contractString,
"position": int(msg.position),
"marketPrice": float(msg.marketPrice),
"marketValue": float(msg.marketValue),
"averageCost": float(msg.averageCost),
"unrealizedPNL": float(msg.unrealizedPNL),
"realizedPNL": float(msg.realizedPNL),
"totalPNL": float(msg.realizedPNL) + float(msg.unrealizedPNL),
"account": msg.accountName
}
# fire callback
self.ibCallback(caller="handlePortfolio", msg=msg) | python | def handlePortfolio(self, msg):
""" handle portfolio updates """
# log handler msg
self.log_msg("portfolio", msg)
# contract identifier
contract_tuple = self.contract_to_tuple(msg.contract)
contractString = self.contractString(contract_tuple)
# try creating the contract
self.registerContract(msg.contract)
# new account?
if msg.accountName not in self._portfolios.keys():
self._portfolios[msg.accountName] = {}
self._portfolios[msg.accountName][contractString] = {
"symbol": contractString,
"position": int(msg.position),
"marketPrice": float(msg.marketPrice),
"marketValue": float(msg.marketValue),
"averageCost": float(msg.averageCost),
"unrealizedPNL": float(msg.unrealizedPNL),
"realizedPNL": float(msg.realizedPNL),
"totalPNL": float(msg.realizedPNL) + float(msg.unrealizedPNL),
"account": msg.accountName
}
# fire callback
self.ibCallback(caller="handlePortfolio", msg=msg) | [
"def",
"handlePortfolio",
"(",
"self",
",",
"msg",
")",
":",
"# log handler msg",
"self",
".",
"log_msg",
"(",
"\"portfolio\"",
",",
"msg",
")",
"# contract identifier",
"contract_tuple",
"=",
"self",
".",
"contract_to_tuple",
"(",
"msg",
".",
"contract",
")",
"contractString",
"=",
"self",
".",
"contractString",
"(",
"contract_tuple",
")",
"# try creating the contract",
"self",
".",
"registerContract",
"(",
"msg",
".",
"contract",
")",
"# new account?",
"if",
"msg",
".",
"accountName",
"not",
"in",
"self",
".",
"_portfolios",
".",
"keys",
"(",
")",
":",
"self",
".",
"_portfolios",
"[",
"msg",
".",
"accountName",
"]",
"=",
"{",
"}",
"self",
".",
"_portfolios",
"[",
"msg",
".",
"accountName",
"]",
"[",
"contractString",
"]",
"=",
"{",
"\"symbol\"",
":",
"contractString",
",",
"\"position\"",
":",
"int",
"(",
"msg",
".",
"position",
")",
",",
"\"marketPrice\"",
":",
"float",
"(",
"msg",
".",
"marketPrice",
")",
",",
"\"marketValue\"",
":",
"float",
"(",
"msg",
".",
"marketValue",
")",
",",
"\"averageCost\"",
":",
"float",
"(",
"msg",
".",
"averageCost",
")",
",",
"\"unrealizedPNL\"",
":",
"float",
"(",
"msg",
".",
"unrealizedPNL",
")",
",",
"\"realizedPNL\"",
":",
"float",
"(",
"msg",
".",
"realizedPNL",
")",
",",
"\"totalPNL\"",
":",
"float",
"(",
"msg",
".",
"realizedPNL",
")",
"+",
"float",
"(",
"msg",
".",
"unrealizedPNL",
")",
",",
"\"account\"",
":",
"msg",
".",
"accountName",
"}",
"# fire callback",
"self",
".",
"ibCallback",
"(",
"caller",
"=",
"\"handlePortfolio\"",
",",
"msg",
"=",
"msg",
")"
] | handle portfolio updates | [
"handle",
"portfolio",
"updates"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L600-L630 |
229,134 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.handleOrders | def handleOrders(self, msg):
""" handle order open & status """
"""
It is possible that orderStatus() may return duplicate messages.
It is essential that you filter the message accordingly.
"""
# log handler msg
self.log_msg("order", msg)
# get server time
self.getServerTime()
time.sleep(0.001)
# we need to handle mutiple events for the same order status
duplicateMessage = False
# open order
if msg.typeName == dataTypes["MSG_TYPE_OPEN_ORDER"]:
# contract identifier
contractString = self.contractString(msg.contract)
order_account = ""
if msg.orderId in self.orders and self.orders[msg.orderId]["status"] == "SENT":
order_account = self.orders[msg.orderId]["account"]
try:
del self.orders[msg.orderId]
except Exception:
pass
if msg.orderId in self.orders:
duplicateMessage = True
else:
self.orders[msg.orderId] = {
"id": msg.orderId,
"symbol": contractString,
"contract": msg.contract,
"order": msg.order,
"status": "OPENED",
"reason": None,
"avgFillPrice": 0.,
"parentId": 0,
"time": datetime.fromtimestamp(int(self.time)),
"account": order_account
}
self._assgin_order_to_account(self.orders[msg.orderId])
# order status
elif msg.typeName == dataTypes["MSG_TYPE_ORDER_STATUS"]:
if msg.orderId in self.orders and self.orders[msg.orderId]['status'] == msg.status.upper():
duplicateMessage = True
else:
# remove cancelled orphan orders
# if "CANCELLED" in msg.status.upper() and msg.parentId not in self.orders.keys():
# try: del self.orders[msg.orderId]
# except Exception: pass
# # otherwise, update order status
# else:
self.orders[msg.orderId]['status'] = msg.status.upper()
self.orders[msg.orderId]['reason'] = msg.whyHeld
self.orders[msg.orderId]['avgFillPrice'] = float(msg.avgFillPrice)
self.orders[msg.orderId]['parentId'] = int(msg.parentId)
self.orders[msg.orderId]['time'] = datetime.fromtimestamp(int(self.time))
# remove from orders?
# if msg.status.upper() == 'CANCELLED':
# del self.orders[msg.orderId]
# fire callback
if duplicateMessage is False:
# group orders by symbol
self.symbol_orders = self.group_orders("symbol")
self.ibCallback(caller="handleOrders", msg=msg) | python | def handleOrders(self, msg):
""" handle order open & status """
"""
It is possible that orderStatus() may return duplicate messages.
It is essential that you filter the message accordingly.
"""
# log handler msg
self.log_msg("order", msg)
# get server time
self.getServerTime()
time.sleep(0.001)
# we need to handle mutiple events for the same order status
duplicateMessage = False
# open order
if msg.typeName == dataTypes["MSG_TYPE_OPEN_ORDER"]:
# contract identifier
contractString = self.contractString(msg.contract)
order_account = ""
if msg.orderId in self.orders and self.orders[msg.orderId]["status"] == "SENT":
order_account = self.orders[msg.orderId]["account"]
try:
del self.orders[msg.orderId]
except Exception:
pass
if msg.orderId in self.orders:
duplicateMessage = True
else:
self.orders[msg.orderId] = {
"id": msg.orderId,
"symbol": contractString,
"contract": msg.contract,
"order": msg.order,
"status": "OPENED",
"reason": None,
"avgFillPrice": 0.,
"parentId": 0,
"time": datetime.fromtimestamp(int(self.time)),
"account": order_account
}
self._assgin_order_to_account(self.orders[msg.orderId])
# order status
elif msg.typeName == dataTypes["MSG_TYPE_ORDER_STATUS"]:
if msg.orderId in self.orders and self.orders[msg.orderId]['status'] == msg.status.upper():
duplicateMessage = True
else:
# remove cancelled orphan orders
# if "CANCELLED" in msg.status.upper() and msg.parentId not in self.orders.keys():
# try: del self.orders[msg.orderId]
# except Exception: pass
# # otherwise, update order status
# else:
self.orders[msg.orderId]['status'] = msg.status.upper()
self.orders[msg.orderId]['reason'] = msg.whyHeld
self.orders[msg.orderId]['avgFillPrice'] = float(msg.avgFillPrice)
self.orders[msg.orderId]['parentId'] = int(msg.parentId)
self.orders[msg.orderId]['time'] = datetime.fromtimestamp(int(self.time))
# remove from orders?
# if msg.status.upper() == 'CANCELLED':
# del self.orders[msg.orderId]
# fire callback
if duplicateMessage is False:
# group orders by symbol
self.symbol_orders = self.group_orders("symbol")
self.ibCallback(caller="handleOrders", msg=msg) | [
"def",
"handleOrders",
"(",
"self",
",",
"msg",
")",
":",
"\"\"\"\n It is possible that orderStatus() may return duplicate messages.\n It is essential that you filter the message accordingly.\n \"\"\"",
"# log handler msg",
"self",
".",
"log_msg",
"(",
"\"order\"",
",",
"msg",
")",
"# get server time",
"self",
".",
"getServerTime",
"(",
")",
"time",
".",
"sleep",
"(",
"0.001",
")",
"# we need to handle mutiple events for the same order status",
"duplicateMessage",
"=",
"False",
"# open order",
"if",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_OPEN_ORDER\"",
"]",
":",
"# contract identifier",
"contractString",
"=",
"self",
".",
"contractString",
"(",
"msg",
".",
"contract",
")",
"order_account",
"=",
"\"\"",
"if",
"msg",
".",
"orderId",
"in",
"self",
".",
"orders",
"and",
"self",
".",
"orders",
"[",
"msg",
".",
"orderId",
"]",
"[",
"\"status\"",
"]",
"==",
"\"SENT\"",
":",
"order_account",
"=",
"self",
".",
"orders",
"[",
"msg",
".",
"orderId",
"]",
"[",
"\"account\"",
"]",
"try",
":",
"del",
"self",
".",
"orders",
"[",
"msg",
".",
"orderId",
"]",
"except",
"Exception",
":",
"pass",
"if",
"msg",
".",
"orderId",
"in",
"self",
".",
"orders",
":",
"duplicateMessage",
"=",
"True",
"else",
":",
"self",
".",
"orders",
"[",
"msg",
".",
"orderId",
"]",
"=",
"{",
"\"id\"",
":",
"msg",
".",
"orderId",
",",
"\"symbol\"",
":",
"contractString",
",",
"\"contract\"",
":",
"msg",
".",
"contract",
",",
"\"order\"",
":",
"msg",
".",
"order",
",",
"\"status\"",
":",
"\"OPENED\"",
",",
"\"reason\"",
":",
"None",
",",
"\"avgFillPrice\"",
":",
"0.",
",",
"\"parentId\"",
":",
"0",
",",
"\"time\"",
":",
"datetime",
".",
"fromtimestamp",
"(",
"int",
"(",
"self",
".",
"time",
")",
")",
",",
"\"account\"",
":",
"order_account",
"}",
"self",
".",
"_assgin_order_to_account",
"(",
"self",
".",
"orders",
"[",
"msg",
".",
"orderId",
"]",
")",
"# order status",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_ORDER_STATUS\"",
"]",
":",
"if",
"msg",
".",
"orderId",
"in",
"self",
".",
"orders",
"and",
"self",
".",
"orders",
"[",
"msg",
".",
"orderId",
"]",
"[",
"'status'",
"]",
"==",
"msg",
".",
"status",
".",
"upper",
"(",
")",
":",
"duplicateMessage",
"=",
"True",
"else",
":",
"# remove cancelled orphan orders",
"# if \"CANCELLED\" in msg.status.upper() and msg.parentId not in self.orders.keys():",
"# try: del self.orders[msg.orderId]",
"# except Exception: pass",
"# # otherwise, update order status",
"# else:",
"self",
".",
"orders",
"[",
"msg",
".",
"orderId",
"]",
"[",
"'status'",
"]",
"=",
"msg",
".",
"status",
".",
"upper",
"(",
")",
"self",
".",
"orders",
"[",
"msg",
".",
"orderId",
"]",
"[",
"'reason'",
"]",
"=",
"msg",
".",
"whyHeld",
"self",
".",
"orders",
"[",
"msg",
".",
"orderId",
"]",
"[",
"'avgFillPrice'",
"]",
"=",
"float",
"(",
"msg",
".",
"avgFillPrice",
")",
"self",
".",
"orders",
"[",
"msg",
".",
"orderId",
"]",
"[",
"'parentId'",
"]",
"=",
"int",
"(",
"msg",
".",
"parentId",
")",
"self",
".",
"orders",
"[",
"msg",
".",
"orderId",
"]",
"[",
"'time'",
"]",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"int",
"(",
"self",
".",
"time",
")",
")",
"# remove from orders?",
"# if msg.status.upper() == 'CANCELLED':",
"# del self.orders[msg.orderId]",
"# fire callback",
"if",
"duplicateMessage",
"is",
"False",
":",
"# group orders by symbol",
"self",
".",
"symbol_orders",
"=",
"self",
".",
"group_orders",
"(",
"\"symbol\"",
")",
"self",
".",
"ibCallback",
"(",
"caller",
"=",
"\"handleOrders\"",
",",
"msg",
"=",
"msg",
")"
] | handle order open & status | [
"handle",
"order",
"open",
"&",
"status"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L655-L727 |
229,135 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.createTriggerableTrailingStop | def createTriggerableTrailingStop(self, symbol, quantity=1,
triggerPrice=0, trailPercent=100., trailAmount=0.,
parentId=0, stopOrderId=None, **kwargs):
""" adds order to triggerable list """
ticksize = self.contractDetails(symbol)["m_minTick"]
self.triggerableTrailingStops[symbol] = {
"parentId": parentId,
"stopOrderId": stopOrderId,
"triggerPrice": triggerPrice,
"trailAmount": abs(trailAmount),
"trailPercent": abs(trailPercent),
"quantity": quantity,
"ticksize": ticksize
}
return self.triggerableTrailingStops[symbol] | python | def createTriggerableTrailingStop(self, symbol, quantity=1,
triggerPrice=0, trailPercent=100., trailAmount=0.,
parentId=0, stopOrderId=None, **kwargs):
""" adds order to triggerable list """
ticksize = self.contractDetails(symbol)["m_minTick"]
self.triggerableTrailingStops[symbol] = {
"parentId": parentId,
"stopOrderId": stopOrderId,
"triggerPrice": triggerPrice,
"trailAmount": abs(trailAmount),
"trailPercent": abs(trailPercent),
"quantity": quantity,
"ticksize": ticksize
}
return self.triggerableTrailingStops[symbol] | [
"def",
"createTriggerableTrailingStop",
"(",
"self",
",",
"symbol",
",",
"quantity",
"=",
"1",
",",
"triggerPrice",
"=",
"0",
",",
"trailPercent",
"=",
"100.",
",",
"trailAmount",
"=",
"0.",
",",
"parentId",
"=",
"0",
",",
"stopOrderId",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ticksize",
"=",
"self",
".",
"contractDetails",
"(",
"symbol",
")",
"[",
"\"m_minTick\"",
"]",
"self",
".",
"triggerableTrailingStops",
"[",
"symbol",
"]",
"=",
"{",
"\"parentId\"",
":",
"parentId",
",",
"\"stopOrderId\"",
":",
"stopOrderId",
",",
"\"triggerPrice\"",
":",
"triggerPrice",
",",
"\"trailAmount\"",
":",
"abs",
"(",
"trailAmount",
")",
",",
"\"trailPercent\"",
":",
"abs",
"(",
"trailPercent",
")",
",",
"\"quantity\"",
":",
"quantity",
",",
"\"ticksize\"",
":",
"ticksize",
"}",
"return",
"self",
".",
"triggerableTrailingStops",
"[",
"symbol",
"]"
] | adds order to triggerable list | [
"adds",
"order",
"to",
"triggerable",
"list"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1101-L1118 |
229,136 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.registerTrailingStop | def registerTrailingStop(self, tickerId, orderId=0, quantity=1,
lastPrice=0, trailPercent=100., trailAmount=0., parentId=0, **kwargs):
""" adds trailing stop to monitor list """
ticksize = self.contractDetails(tickerId)["m_minTick"]
trailingStop = self.trailingStops[tickerId] = {
"orderId": orderId,
"parentId": parentId,
"lastPrice": lastPrice,
"trailAmount": trailAmount,
"trailPercent": trailPercent,
"quantity": quantity,
"ticksize": ticksize
}
return trailingStop | python | def registerTrailingStop(self, tickerId, orderId=0, quantity=1,
lastPrice=0, trailPercent=100., trailAmount=0., parentId=0, **kwargs):
""" adds trailing stop to monitor list """
ticksize = self.contractDetails(tickerId)["m_minTick"]
trailingStop = self.trailingStops[tickerId] = {
"orderId": orderId,
"parentId": parentId,
"lastPrice": lastPrice,
"trailAmount": trailAmount,
"trailPercent": trailPercent,
"quantity": quantity,
"ticksize": ticksize
}
return trailingStop | [
"def",
"registerTrailingStop",
"(",
"self",
",",
"tickerId",
",",
"orderId",
"=",
"0",
",",
"quantity",
"=",
"1",
",",
"lastPrice",
"=",
"0",
",",
"trailPercent",
"=",
"100.",
",",
"trailAmount",
"=",
"0.",
",",
"parentId",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"ticksize",
"=",
"self",
".",
"contractDetails",
"(",
"tickerId",
")",
"[",
"\"m_minTick\"",
"]",
"trailingStop",
"=",
"self",
".",
"trailingStops",
"[",
"tickerId",
"]",
"=",
"{",
"\"orderId\"",
":",
"orderId",
",",
"\"parentId\"",
":",
"parentId",
",",
"\"lastPrice\"",
":",
"lastPrice",
",",
"\"trailAmount\"",
":",
"trailAmount",
",",
"\"trailPercent\"",
":",
"trailPercent",
",",
"\"quantity\"",
":",
"quantity",
",",
"\"ticksize\"",
":",
"ticksize",
"}",
"return",
"trailingStop"
] | adds trailing stop to monitor list | [
"adds",
"trailing",
"stop",
"to",
"monitor",
"list"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1121-L1137 |
229,137 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.modifyStopOrder | def modifyStopOrder(self, orderId, parentId, newStop, quantity,
transmit=True, account=None):
""" modify stop order """
if orderId in self.orders.keys():
order = self.createStopOrder(
quantity = quantity,
parentId = parentId,
stop = newStop,
trail = False,
transmit = transmit,
account = account
)
return self.placeOrder(self.orders[orderId]['contract'], order, orderId)
return None | python | def modifyStopOrder(self, orderId, parentId, newStop, quantity,
transmit=True, account=None):
""" modify stop order """
if orderId in self.orders.keys():
order = self.createStopOrder(
quantity = quantity,
parentId = parentId,
stop = newStop,
trail = False,
transmit = transmit,
account = account
)
return self.placeOrder(self.orders[orderId]['contract'], order, orderId)
return None | [
"def",
"modifyStopOrder",
"(",
"self",
",",
"orderId",
",",
"parentId",
",",
"newStop",
",",
"quantity",
",",
"transmit",
"=",
"True",
",",
"account",
"=",
"None",
")",
":",
"if",
"orderId",
"in",
"self",
".",
"orders",
".",
"keys",
"(",
")",
":",
"order",
"=",
"self",
".",
"createStopOrder",
"(",
"quantity",
"=",
"quantity",
",",
"parentId",
"=",
"parentId",
",",
"stop",
"=",
"newStop",
",",
"trail",
"=",
"False",
",",
"transmit",
"=",
"transmit",
",",
"account",
"=",
"account",
")",
"return",
"self",
".",
"placeOrder",
"(",
"self",
".",
"orders",
"[",
"orderId",
"]",
"[",
"'contract'",
"]",
",",
"order",
",",
"orderId",
")",
"return",
"None"
] | modify stop order | [
"modify",
"stop",
"order"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1140-L1154 |
229,138 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.handleTrailingStops | def handleTrailingStops(self, tickerId):
""" software-based trailing stop """
# existing?
if tickerId not in self.trailingStops.keys():
return None
# continue
trailingStop = self.trailingStops[tickerId]
price = self.marketData[tickerId]['last'][0]
symbol = self.tickerSymbol(tickerId)
# contract = self.contracts[tickerId]
# contractString = self.contractString(contract)
# filled / no positions?
if (self._positions[symbol] == 0) | \
(self.orders[trailingStop['orderId']]['status'] == "FILLED"):
del self.trailingStops[tickerId]
return None
# continue...
newStop = trailingStop['lastPrice']
ticksize = trailingStop['ticksize']
# long
if (trailingStop['quantity'] < 0) & (trailingStop['lastPrice'] < price):
if abs(trailingStop['trailAmount']) >= 0:
newStop = price - abs(trailingStop['trailAmount'])
elif trailingStop['trailPercent'] >= 0:
newStop = price - (price * (abs(trailingStop['trailPercent']) / 100))
# short
elif (trailingStop['quantity'] > 0) & (trailingStop['lastPrice'] > price):
if abs(trailingStop['trailAmount']) >= 0:
newStop = price + abs(trailingStop['trailAmount'])
elif trailingStop['trailPercent'] >= 0:
newStop = price + (price * (abs(trailingStop['trailPercent']) / 100))
# valid newStop
newStop = self.roundClosestValid(newStop, ticksize)
# print("\n\n", trailingStop['lastPrice'], newStop, price, "\n\n")
# no change?
if newStop == trailingStop['lastPrice']:
return None
# submit order
trailingStopOrderId = self.modifyStopOrder(
orderId = trailingStop['orderId'],
parentId = trailingStop['parentId'],
newStop = newStop,
quantity = trailingStop['quantity']
)
if trailingStopOrderId:
self.trailingStops[tickerId]['lastPrice'] = price
return trailingStopOrderId | python | def handleTrailingStops(self, tickerId):
""" software-based trailing stop """
# existing?
if tickerId not in self.trailingStops.keys():
return None
# continue
trailingStop = self.trailingStops[tickerId]
price = self.marketData[tickerId]['last'][0]
symbol = self.tickerSymbol(tickerId)
# contract = self.contracts[tickerId]
# contractString = self.contractString(contract)
# filled / no positions?
if (self._positions[symbol] == 0) | \
(self.orders[trailingStop['orderId']]['status'] == "FILLED"):
del self.trailingStops[tickerId]
return None
# continue...
newStop = trailingStop['lastPrice']
ticksize = trailingStop['ticksize']
# long
if (trailingStop['quantity'] < 0) & (trailingStop['lastPrice'] < price):
if abs(trailingStop['trailAmount']) >= 0:
newStop = price - abs(trailingStop['trailAmount'])
elif trailingStop['trailPercent'] >= 0:
newStop = price - (price * (abs(trailingStop['trailPercent']) / 100))
# short
elif (trailingStop['quantity'] > 0) & (trailingStop['lastPrice'] > price):
if abs(trailingStop['trailAmount']) >= 0:
newStop = price + abs(trailingStop['trailAmount'])
elif trailingStop['trailPercent'] >= 0:
newStop = price + (price * (abs(trailingStop['trailPercent']) / 100))
# valid newStop
newStop = self.roundClosestValid(newStop, ticksize)
# print("\n\n", trailingStop['lastPrice'], newStop, price, "\n\n")
# no change?
if newStop == trailingStop['lastPrice']:
return None
# submit order
trailingStopOrderId = self.modifyStopOrder(
orderId = trailingStop['orderId'],
parentId = trailingStop['parentId'],
newStop = newStop,
quantity = trailingStop['quantity']
)
if trailingStopOrderId:
self.trailingStops[tickerId]['lastPrice'] = price
return trailingStopOrderId | [
"def",
"handleTrailingStops",
"(",
"self",
",",
"tickerId",
")",
":",
"# existing?",
"if",
"tickerId",
"not",
"in",
"self",
".",
"trailingStops",
".",
"keys",
"(",
")",
":",
"return",
"None",
"# continue",
"trailingStop",
"=",
"self",
".",
"trailingStops",
"[",
"tickerId",
"]",
"price",
"=",
"self",
".",
"marketData",
"[",
"tickerId",
"]",
"[",
"'last'",
"]",
"[",
"0",
"]",
"symbol",
"=",
"self",
".",
"tickerSymbol",
"(",
"tickerId",
")",
"# contract = self.contracts[tickerId]",
"# contractString = self.contractString(contract)",
"# filled / no positions?",
"if",
"(",
"self",
".",
"_positions",
"[",
"symbol",
"]",
"==",
"0",
")",
"|",
"(",
"self",
".",
"orders",
"[",
"trailingStop",
"[",
"'orderId'",
"]",
"]",
"[",
"'status'",
"]",
"==",
"\"FILLED\"",
")",
":",
"del",
"self",
".",
"trailingStops",
"[",
"tickerId",
"]",
"return",
"None",
"# continue...",
"newStop",
"=",
"trailingStop",
"[",
"'lastPrice'",
"]",
"ticksize",
"=",
"trailingStop",
"[",
"'ticksize'",
"]",
"# long",
"if",
"(",
"trailingStop",
"[",
"'quantity'",
"]",
"<",
"0",
")",
"&",
"(",
"trailingStop",
"[",
"'lastPrice'",
"]",
"<",
"price",
")",
":",
"if",
"abs",
"(",
"trailingStop",
"[",
"'trailAmount'",
"]",
")",
">=",
"0",
":",
"newStop",
"=",
"price",
"-",
"abs",
"(",
"trailingStop",
"[",
"'trailAmount'",
"]",
")",
"elif",
"trailingStop",
"[",
"'trailPercent'",
"]",
">=",
"0",
":",
"newStop",
"=",
"price",
"-",
"(",
"price",
"*",
"(",
"abs",
"(",
"trailingStop",
"[",
"'trailPercent'",
"]",
")",
"/",
"100",
")",
")",
"# short",
"elif",
"(",
"trailingStop",
"[",
"'quantity'",
"]",
">",
"0",
")",
"&",
"(",
"trailingStop",
"[",
"'lastPrice'",
"]",
">",
"price",
")",
":",
"if",
"abs",
"(",
"trailingStop",
"[",
"'trailAmount'",
"]",
")",
">=",
"0",
":",
"newStop",
"=",
"price",
"+",
"abs",
"(",
"trailingStop",
"[",
"'trailAmount'",
"]",
")",
"elif",
"trailingStop",
"[",
"'trailPercent'",
"]",
">=",
"0",
":",
"newStop",
"=",
"price",
"+",
"(",
"price",
"*",
"(",
"abs",
"(",
"trailingStop",
"[",
"'trailPercent'",
"]",
")",
"/",
"100",
")",
")",
"# valid newStop",
"newStop",
"=",
"self",
".",
"roundClosestValid",
"(",
"newStop",
",",
"ticksize",
")",
"# print(\"\\n\\n\", trailingStop['lastPrice'], newStop, price, \"\\n\\n\")",
"# no change?",
"if",
"newStop",
"==",
"trailingStop",
"[",
"'lastPrice'",
"]",
":",
"return",
"None",
"# submit order",
"trailingStopOrderId",
"=",
"self",
".",
"modifyStopOrder",
"(",
"orderId",
"=",
"trailingStop",
"[",
"'orderId'",
"]",
",",
"parentId",
"=",
"trailingStop",
"[",
"'parentId'",
"]",
",",
"newStop",
"=",
"newStop",
",",
"quantity",
"=",
"trailingStop",
"[",
"'quantity'",
"]",
")",
"if",
"trailingStopOrderId",
":",
"self",
".",
"trailingStops",
"[",
"tickerId",
"]",
"[",
"'lastPrice'",
"]",
"=",
"price",
"return",
"trailingStopOrderId"
] | software-based trailing stop | [
"software",
"-",
"based",
"trailing",
"stop"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1157-L1214 |
229,139 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.triggerTrailingStops | def triggerTrailingStops(self, tickerId):
""" trigger waiting trailing stops """
# print('.')
# test
symbol = self.tickerSymbol(tickerId)
price = self.marketData[tickerId]['last'][0]
# contract = self.contracts[tickerId]
if symbol in self.triggerableTrailingStops.keys():
pendingOrder = self.triggerableTrailingStops[symbol]
parentId = pendingOrder["parentId"]
stopOrderId = pendingOrder["stopOrderId"]
triggerPrice = pendingOrder["triggerPrice"]
trailAmount = pendingOrder["trailAmount"]
trailPercent = pendingOrder["trailPercent"]
quantity = pendingOrder["quantity"]
ticksize = pendingOrder["ticksize"]
# print(">>>>>>>", pendingOrder)
# print(">>>>>>>", parentId)
# print(">>>>>>>", self.orders)
# abort
if parentId not in self.orders.keys():
# print("DELETING")
del self.triggerableTrailingStops[symbol]
return None
else:
if self.orders[parentId]["status"] != "FILLED":
return None
# print("\n\n", quantity, triggerPrice, price, "\n\n")
# create the order
if ((quantity > 0) & (triggerPrice >= price)) | ((quantity < 0) & (triggerPrice <= price)):
newStop = price
if trailAmount > 0:
if quantity > 0:
newStop += trailAmount
else:
newStop -= trailAmount
elif trailPercent > 0:
if quantity > 0:
newStop += price * (trailPercent / 100)
else:
newStop -= price * (trailPercent / 100)
else:
del self.triggerableTrailingStops[symbol]
return 0
# print("------", stopOrderId , parentId, newStop , quantity, "------")
# use valid newStop
newStop = self.roundClosestValid(newStop, ticksize)
trailingStopOrderId = self.modifyStopOrder(
orderId = stopOrderId,
parentId = parentId,
newStop = newStop,
quantity = quantity
)
if trailingStopOrderId:
# print(">>> TRAILING STOP")
del self.triggerableTrailingStops[symbol]
# register trailing stop
tickerId = self.tickerId(symbol)
self.registerTrailingStop(
tickerId = tickerId,
parentId = parentId,
orderId = stopOrderId,
lastPrice = price,
trailAmount = trailAmount,
trailPercent = trailPercent,
quantity = quantity,
ticksize = ticksize
)
return trailingStopOrderId
return None | python | def triggerTrailingStops(self, tickerId):
""" trigger waiting trailing stops """
# print('.')
# test
symbol = self.tickerSymbol(tickerId)
price = self.marketData[tickerId]['last'][0]
# contract = self.contracts[tickerId]
if symbol in self.triggerableTrailingStops.keys():
pendingOrder = self.triggerableTrailingStops[symbol]
parentId = pendingOrder["parentId"]
stopOrderId = pendingOrder["stopOrderId"]
triggerPrice = pendingOrder["triggerPrice"]
trailAmount = pendingOrder["trailAmount"]
trailPercent = pendingOrder["trailPercent"]
quantity = pendingOrder["quantity"]
ticksize = pendingOrder["ticksize"]
# print(">>>>>>>", pendingOrder)
# print(">>>>>>>", parentId)
# print(">>>>>>>", self.orders)
# abort
if parentId not in self.orders.keys():
# print("DELETING")
del self.triggerableTrailingStops[symbol]
return None
else:
if self.orders[parentId]["status"] != "FILLED":
return None
# print("\n\n", quantity, triggerPrice, price, "\n\n")
# create the order
if ((quantity > 0) & (triggerPrice >= price)) | ((quantity < 0) & (triggerPrice <= price)):
newStop = price
if trailAmount > 0:
if quantity > 0:
newStop += trailAmount
else:
newStop -= trailAmount
elif trailPercent > 0:
if quantity > 0:
newStop += price * (trailPercent / 100)
else:
newStop -= price * (trailPercent / 100)
else:
del self.triggerableTrailingStops[symbol]
return 0
# print("------", stopOrderId , parentId, newStop , quantity, "------")
# use valid newStop
newStop = self.roundClosestValid(newStop, ticksize)
trailingStopOrderId = self.modifyStopOrder(
orderId = stopOrderId,
parentId = parentId,
newStop = newStop,
quantity = quantity
)
if trailingStopOrderId:
# print(">>> TRAILING STOP")
del self.triggerableTrailingStops[symbol]
# register trailing stop
tickerId = self.tickerId(symbol)
self.registerTrailingStop(
tickerId = tickerId,
parentId = parentId,
orderId = stopOrderId,
lastPrice = price,
trailAmount = trailAmount,
trailPercent = trailPercent,
quantity = quantity,
ticksize = ticksize
)
return trailingStopOrderId
return None | [
"def",
"triggerTrailingStops",
"(",
"self",
",",
"tickerId",
")",
":",
"# print('.')",
"# test",
"symbol",
"=",
"self",
".",
"tickerSymbol",
"(",
"tickerId",
")",
"price",
"=",
"self",
".",
"marketData",
"[",
"tickerId",
"]",
"[",
"'last'",
"]",
"[",
"0",
"]",
"# contract = self.contracts[tickerId]",
"if",
"symbol",
"in",
"self",
".",
"triggerableTrailingStops",
".",
"keys",
"(",
")",
":",
"pendingOrder",
"=",
"self",
".",
"triggerableTrailingStops",
"[",
"symbol",
"]",
"parentId",
"=",
"pendingOrder",
"[",
"\"parentId\"",
"]",
"stopOrderId",
"=",
"pendingOrder",
"[",
"\"stopOrderId\"",
"]",
"triggerPrice",
"=",
"pendingOrder",
"[",
"\"triggerPrice\"",
"]",
"trailAmount",
"=",
"pendingOrder",
"[",
"\"trailAmount\"",
"]",
"trailPercent",
"=",
"pendingOrder",
"[",
"\"trailPercent\"",
"]",
"quantity",
"=",
"pendingOrder",
"[",
"\"quantity\"",
"]",
"ticksize",
"=",
"pendingOrder",
"[",
"\"ticksize\"",
"]",
"# print(\">>>>>>>\", pendingOrder)",
"# print(\">>>>>>>\", parentId)",
"# print(\">>>>>>>\", self.orders)",
"# abort",
"if",
"parentId",
"not",
"in",
"self",
".",
"orders",
".",
"keys",
"(",
")",
":",
"# print(\"DELETING\")",
"del",
"self",
".",
"triggerableTrailingStops",
"[",
"symbol",
"]",
"return",
"None",
"else",
":",
"if",
"self",
".",
"orders",
"[",
"parentId",
"]",
"[",
"\"status\"",
"]",
"!=",
"\"FILLED\"",
":",
"return",
"None",
"# print(\"\\n\\n\", quantity, triggerPrice, price, \"\\n\\n\")",
"# create the order",
"if",
"(",
"(",
"quantity",
">",
"0",
")",
"&",
"(",
"triggerPrice",
">=",
"price",
")",
")",
"|",
"(",
"(",
"quantity",
"<",
"0",
")",
"&",
"(",
"triggerPrice",
"<=",
"price",
")",
")",
":",
"newStop",
"=",
"price",
"if",
"trailAmount",
">",
"0",
":",
"if",
"quantity",
">",
"0",
":",
"newStop",
"+=",
"trailAmount",
"else",
":",
"newStop",
"-=",
"trailAmount",
"elif",
"trailPercent",
">",
"0",
":",
"if",
"quantity",
">",
"0",
":",
"newStop",
"+=",
"price",
"*",
"(",
"trailPercent",
"/",
"100",
")",
"else",
":",
"newStop",
"-=",
"price",
"*",
"(",
"trailPercent",
"/",
"100",
")",
"else",
":",
"del",
"self",
".",
"triggerableTrailingStops",
"[",
"symbol",
"]",
"return",
"0",
"# print(\"------\", stopOrderId , parentId, newStop , quantity, \"------\")",
"# use valid newStop",
"newStop",
"=",
"self",
".",
"roundClosestValid",
"(",
"newStop",
",",
"ticksize",
")",
"trailingStopOrderId",
"=",
"self",
".",
"modifyStopOrder",
"(",
"orderId",
"=",
"stopOrderId",
",",
"parentId",
"=",
"parentId",
",",
"newStop",
"=",
"newStop",
",",
"quantity",
"=",
"quantity",
")",
"if",
"trailingStopOrderId",
":",
"# print(\">>> TRAILING STOP\")",
"del",
"self",
".",
"triggerableTrailingStops",
"[",
"symbol",
"]",
"# register trailing stop",
"tickerId",
"=",
"self",
".",
"tickerId",
"(",
"symbol",
")",
"self",
".",
"registerTrailingStop",
"(",
"tickerId",
"=",
"tickerId",
",",
"parentId",
"=",
"parentId",
",",
"orderId",
"=",
"stopOrderId",
",",
"lastPrice",
"=",
"price",
",",
"trailAmount",
"=",
"trailAmount",
",",
"trailPercent",
"=",
"trailPercent",
",",
"quantity",
"=",
"quantity",
",",
"ticksize",
"=",
"ticksize",
")",
"return",
"trailingStopOrderId",
"return",
"None"
] | trigger waiting trailing stops | [
"trigger",
"waiting",
"trailing",
"stops"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1217-L1299 |
229,140 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.tickerId | def tickerId(self, contract_identifier):
"""
returns the tickerId for the symbol or
sets one if it doesn't exits
"""
# contract passed instead of symbol?
symbol = contract_identifier
if isinstance(symbol, Contract):
symbol = self.contractString(symbol)
for tickerId in self.tickerIds:
if symbol == self.tickerIds[tickerId]:
return tickerId
else:
tickerId = len(self.tickerIds)
self.tickerIds[tickerId] = symbol
return tickerId | python | def tickerId(self, contract_identifier):
"""
returns the tickerId for the symbol or
sets one if it doesn't exits
"""
# contract passed instead of symbol?
symbol = contract_identifier
if isinstance(symbol, Contract):
symbol = self.contractString(symbol)
for tickerId in self.tickerIds:
if symbol == self.tickerIds[tickerId]:
return tickerId
else:
tickerId = len(self.tickerIds)
self.tickerIds[tickerId] = symbol
return tickerId | [
"def",
"tickerId",
"(",
"self",
",",
"contract_identifier",
")",
":",
"# contract passed instead of symbol?",
"symbol",
"=",
"contract_identifier",
"if",
"isinstance",
"(",
"symbol",
",",
"Contract",
")",
":",
"symbol",
"=",
"self",
".",
"contractString",
"(",
"symbol",
")",
"for",
"tickerId",
"in",
"self",
".",
"tickerIds",
":",
"if",
"symbol",
"==",
"self",
".",
"tickerIds",
"[",
"tickerId",
"]",
":",
"return",
"tickerId",
"else",
":",
"tickerId",
"=",
"len",
"(",
"self",
".",
"tickerIds",
")",
"self",
".",
"tickerIds",
"[",
"tickerId",
"]",
"=",
"symbol",
"return",
"tickerId"
] | returns the tickerId for the symbol or
sets one if it doesn't exits | [
"returns",
"the",
"tickerId",
"for",
"the",
"symbol",
"or",
"sets",
"one",
"if",
"it",
"doesn",
"t",
"exits"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1304-L1320 |
229,141 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.createTargetOrder | def createTargetOrder(self, quantity, parentId=0,
target=0., orderType=None, transmit=True, group=None, tif="DAY",
rth=False, account=None):
""" Creates TARGET order """
order = self.createOrder(quantity,
price = target,
transmit = transmit,
orderType = dataTypes["ORDER_TYPE_LIMIT"] if orderType == None else orderType,
ocaGroup = group,
parentId = parentId,
rth = rth,
tif = tif,
account = account
)
return order | python | def createTargetOrder(self, quantity, parentId=0,
target=0., orderType=None, transmit=True, group=None, tif="DAY",
rth=False, account=None):
""" Creates TARGET order """
order = self.createOrder(quantity,
price = target,
transmit = transmit,
orderType = dataTypes["ORDER_TYPE_LIMIT"] if orderType == None else orderType,
ocaGroup = group,
parentId = parentId,
rth = rth,
tif = tif,
account = account
)
return order | [
"def",
"createTargetOrder",
"(",
"self",
",",
"quantity",
",",
"parentId",
"=",
"0",
",",
"target",
"=",
"0.",
",",
"orderType",
"=",
"None",
",",
"transmit",
"=",
"True",
",",
"group",
"=",
"None",
",",
"tif",
"=",
"\"DAY\"",
",",
"rth",
"=",
"False",
",",
"account",
"=",
"None",
")",
":",
"order",
"=",
"self",
".",
"createOrder",
"(",
"quantity",
",",
"price",
"=",
"target",
",",
"transmit",
"=",
"transmit",
",",
"orderType",
"=",
"dataTypes",
"[",
"\"ORDER_TYPE_LIMIT\"",
"]",
"if",
"orderType",
"==",
"None",
"else",
"orderType",
",",
"ocaGroup",
"=",
"group",
",",
"parentId",
"=",
"parentId",
",",
"rth",
"=",
"rth",
",",
"tif",
"=",
"tif",
",",
"account",
"=",
"account",
")",
"return",
"order"
] | Creates TARGET order | [
"Creates",
"TARGET",
"order"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1598-L1612 |
229,142 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.createStopOrder | def createStopOrder(self, quantity, parentId=0, stop=0., trail=None,
transmit=True, group=None, stop_limit=False, rth=False, tif="DAY",
account=None):
""" Creates STOP order """
if trail:
if trail == "percent":
order = self.createOrder(quantity,
trailingPercent = stop,
transmit = transmit,
orderType = dataTypes["ORDER_TYPE_TRAIL_STOP"],
ocaGroup = group,
parentId = parentId,
rth = rth,
tif = tif,
account = account
)
else:
order = self.createOrder(quantity,
trailStopPrice = stop,
stop = stop,
transmit = transmit,
orderType = dataTypes["ORDER_TYPE_TRAIL_STOP"],
ocaGroup = group,
parentId = parentId,
rth = rth,
tif = tif,
account = account
)
else:
order = self.createOrder(quantity,
stop = stop,
price = stop if stop_limit else 0.,
transmit = transmit,
orderType = dataTypes["ORDER_TYPE_STOP_LIMIT"] if stop_limit else dataTypes["ORDER_TYPE_STOP"],
ocaGroup = group,
parentId = parentId,
rth = rth,
tif = tif,
account = account
)
return order | python | def createStopOrder(self, quantity, parentId=0, stop=0., trail=None,
transmit=True, group=None, stop_limit=False, rth=False, tif="DAY",
account=None):
""" Creates STOP order """
if trail:
if trail == "percent":
order = self.createOrder(quantity,
trailingPercent = stop,
transmit = transmit,
orderType = dataTypes["ORDER_TYPE_TRAIL_STOP"],
ocaGroup = group,
parentId = parentId,
rth = rth,
tif = tif,
account = account
)
else:
order = self.createOrder(quantity,
trailStopPrice = stop,
stop = stop,
transmit = transmit,
orderType = dataTypes["ORDER_TYPE_TRAIL_STOP"],
ocaGroup = group,
parentId = parentId,
rth = rth,
tif = tif,
account = account
)
else:
order = self.createOrder(quantity,
stop = stop,
price = stop if stop_limit else 0.,
transmit = transmit,
orderType = dataTypes["ORDER_TYPE_STOP_LIMIT"] if stop_limit else dataTypes["ORDER_TYPE_STOP"],
ocaGroup = group,
parentId = parentId,
rth = rth,
tif = tif,
account = account
)
return order | [
"def",
"createStopOrder",
"(",
"self",
",",
"quantity",
",",
"parentId",
"=",
"0",
",",
"stop",
"=",
"0.",
",",
"trail",
"=",
"None",
",",
"transmit",
"=",
"True",
",",
"group",
"=",
"None",
",",
"stop_limit",
"=",
"False",
",",
"rth",
"=",
"False",
",",
"tif",
"=",
"\"DAY\"",
",",
"account",
"=",
"None",
")",
":",
"if",
"trail",
":",
"if",
"trail",
"==",
"\"percent\"",
":",
"order",
"=",
"self",
".",
"createOrder",
"(",
"quantity",
",",
"trailingPercent",
"=",
"stop",
",",
"transmit",
"=",
"transmit",
",",
"orderType",
"=",
"dataTypes",
"[",
"\"ORDER_TYPE_TRAIL_STOP\"",
"]",
",",
"ocaGroup",
"=",
"group",
",",
"parentId",
"=",
"parentId",
",",
"rth",
"=",
"rth",
",",
"tif",
"=",
"tif",
",",
"account",
"=",
"account",
")",
"else",
":",
"order",
"=",
"self",
".",
"createOrder",
"(",
"quantity",
",",
"trailStopPrice",
"=",
"stop",
",",
"stop",
"=",
"stop",
",",
"transmit",
"=",
"transmit",
",",
"orderType",
"=",
"dataTypes",
"[",
"\"ORDER_TYPE_TRAIL_STOP\"",
"]",
",",
"ocaGroup",
"=",
"group",
",",
"parentId",
"=",
"parentId",
",",
"rth",
"=",
"rth",
",",
"tif",
"=",
"tif",
",",
"account",
"=",
"account",
")",
"else",
":",
"order",
"=",
"self",
".",
"createOrder",
"(",
"quantity",
",",
"stop",
"=",
"stop",
",",
"price",
"=",
"stop",
"if",
"stop_limit",
"else",
"0.",
",",
"transmit",
"=",
"transmit",
",",
"orderType",
"=",
"dataTypes",
"[",
"\"ORDER_TYPE_STOP_LIMIT\"",
"]",
"if",
"stop_limit",
"else",
"dataTypes",
"[",
"\"ORDER_TYPE_STOP\"",
"]",
",",
"ocaGroup",
"=",
"group",
",",
"parentId",
"=",
"parentId",
",",
"rth",
"=",
"rth",
",",
"tif",
"=",
"tif",
",",
"account",
"=",
"account",
")",
"return",
"order"
] | Creates STOP order | [
"Creates",
"STOP",
"order"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1615-L1657 |
229,143 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.createTrailingStopOrder | def createTrailingStopOrder(self, contract, quantity,
parentId=0, trailPercent=100., group=None, triggerPrice=None,
account=None):
""" convert hard stop order to trailing stop order """
if parentId not in self.orders:
raise ValueError("Order #" + str(parentId) + " doesn't exist or wasn't submitted")
order = self.createStopOrder(quantity,
stop = trailPercent,
transmit = True,
trail = True,
# ocaGroup = group
parentId = parentId,
account = account
)
self.requestOrderIds()
return self.placeOrder(contract, order, self.orderId + 1) | python | def createTrailingStopOrder(self, contract, quantity,
parentId=0, trailPercent=100., group=None, triggerPrice=None,
account=None):
""" convert hard stop order to trailing stop order """
if parentId not in self.orders:
raise ValueError("Order #" + str(parentId) + " doesn't exist or wasn't submitted")
order = self.createStopOrder(quantity,
stop = trailPercent,
transmit = True,
trail = True,
# ocaGroup = group
parentId = parentId,
account = account
)
self.requestOrderIds()
return self.placeOrder(contract, order, self.orderId + 1) | [
"def",
"createTrailingStopOrder",
"(",
"self",
",",
"contract",
",",
"quantity",
",",
"parentId",
"=",
"0",
",",
"trailPercent",
"=",
"100.",
",",
"group",
"=",
"None",
",",
"triggerPrice",
"=",
"None",
",",
"account",
"=",
"None",
")",
":",
"if",
"parentId",
"not",
"in",
"self",
".",
"orders",
":",
"raise",
"ValueError",
"(",
"\"Order #\"",
"+",
"str",
"(",
"parentId",
")",
"+",
"\" doesn't exist or wasn't submitted\"",
")",
"order",
"=",
"self",
".",
"createStopOrder",
"(",
"quantity",
",",
"stop",
"=",
"trailPercent",
",",
"transmit",
"=",
"True",
",",
"trail",
"=",
"True",
",",
"# ocaGroup = group",
"parentId",
"=",
"parentId",
",",
"account",
"=",
"account",
")",
"self",
".",
"requestOrderIds",
"(",
")",
"return",
"self",
".",
"placeOrder",
"(",
"contract",
",",
"order",
",",
"self",
".",
"orderId",
"+",
"1",
")"
] | convert hard stop order to trailing stop order | [
"convert",
"hard",
"stop",
"order",
"to",
"trailing",
"stop",
"order"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1660-L1678 |
229,144 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.placeOrder | def placeOrder(self, contract, order, orderId=None, account=None):
""" Place order on IB TWS """
# get latest order id before submitting an order
self.requestOrderIds()
# continue...
useOrderId = self.orderId if orderId == None else orderId
if account:
order.m_account = account
self.ibConn.placeOrder(useOrderId, contract, order)
account_key = order.m_account
self.orders[useOrderId] = {
"id": useOrderId,
"symbol": self.contractString(contract),
"contract": contract,
"status": "SENT",
"reason": None,
"avgFillPrice": 0.,
"parentId": 0,
"time": datetime.fromtimestamp(int(self.time)),
"account": None
}
if hasattr(order, "m_account"):
self.orders[useOrderId]["account"] = order.m_account
# return order id
return useOrderId | python | def placeOrder(self, contract, order, orderId=None, account=None):
""" Place order on IB TWS """
# get latest order id before submitting an order
self.requestOrderIds()
# continue...
useOrderId = self.orderId if orderId == None else orderId
if account:
order.m_account = account
self.ibConn.placeOrder(useOrderId, contract, order)
account_key = order.m_account
self.orders[useOrderId] = {
"id": useOrderId,
"symbol": self.contractString(contract),
"contract": contract,
"status": "SENT",
"reason": None,
"avgFillPrice": 0.,
"parentId": 0,
"time": datetime.fromtimestamp(int(self.time)),
"account": None
}
if hasattr(order, "m_account"):
self.orders[useOrderId]["account"] = order.m_account
# return order id
return useOrderId | [
"def",
"placeOrder",
"(",
"self",
",",
"contract",
",",
"order",
",",
"orderId",
"=",
"None",
",",
"account",
"=",
"None",
")",
":",
"# get latest order id before submitting an order",
"self",
".",
"requestOrderIds",
"(",
")",
"# continue...",
"useOrderId",
"=",
"self",
".",
"orderId",
"if",
"orderId",
"==",
"None",
"else",
"orderId",
"if",
"account",
":",
"order",
".",
"m_account",
"=",
"account",
"self",
".",
"ibConn",
".",
"placeOrder",
"(",
"useOrderId",
",",
"contract",
",",
"order",
")",
"account_key",
"=",
"order",
".",
"m_account",
"self",
".",
"orders",
"[",
"useOrderId",
"]",
"=",
"{",
"\"id\"",
":",
"useOrderId",
",",
"\"symbol\"",
":",
"self",
".",
"contractString",
"(",
"contract",
")",
",",
"\"contract\"",
":",
"contract",
",",
"\"status\"",
":",
"\"SENT\"",
",",
"\"reason\"",
":",
"None",
",",
"\"avgFillPrice\"",
":",
"0.",
",",
"\"parentId\"",
":",
"0",
",",
"\"time\"",
":",
"datetime",
".",
"fromtimestamp",
"(",
"int",
"(",
"self",
".",
"time",
")",
")",
",",
"\"account\"",
":",
"None",
"}",
"if",
"hasattr",
"(",
"order",
",",
"\"m_account\"",
")",
":",
"self",
".",
"orders",
"[",
"useOrderId",
"]",
"[",
"\"account\"",
"]",
"=",
"order",
".",
"m_account",
"# return order id",
"return",
"useOrderId"
] | Place order on IB TWS | [
"Place",
"order",
"on",
"IB",
"TWS"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1750-L1778 |
229,145 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.cancelOrder | def cancelOrder(self, orderId):
""" cancel order on IB TWS """
self.ibConn.cancelOrder(orderId)
# update order id for next time
self.requestOrderIds()
return orderId | python | def cancelOrder(self, orderId):
""" cancel order on IB TWS """
self.ibConn.cancelOrder(orderId)
# update order id for next time
self.requestOrderIds()
return orderId | [
"def",
"cancelOrder",
"(",
"self",
",",
"orderId",
")",
":",
"self",
".",
"ibConn",
".",
"cancelOrder",
"(",
"orderId",
")",
"# update order id for next time",
"self",
".",
"requestOrderIds",
"(",
")",
"return",
"orderId"
] | cancel order on IB TWS | [
"cancel",
"order",
"on",
"IB",
"TWS"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1781-L1787 |
229,146 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.requestOpenOrders | def requestOpenOrders(self, all_clients=False):
"""
Request open orders - loads up orders that wasn't created using this session
"""
if all_clients:
self.ibConn.reqAllOpenOrders()
self.ibConn.reqOpenOrders() | python | def requestOpenOrders(self, all_clients=False):
"""
Request open orders - loads up orders that wasn't created using this session
"""
if all_clients:
self.ibConn.reqAllOpenOrders()
self.ibConn.reqOpenOrders() | [
"def",
"requestOpenOrders",
"(",
"self",
",",
"all_clients",
"=",
"False",
")",
":",
"if",
"all_clients",
":",
"self",
".",
"ibConn",
".",
"reqAllOpenOrders",
"(",
")",
"self",
".",
"ibConn",
".",
"reqOpenOrders",
"(",
")"
] | Request open orders - loads up orders that wasn't created using this session | [
"Request",
"open",
"orders",
"-",
"loads",
"up",
"orders",
"that",
"wasn",
"t",
"created",
"using",
"this",
"session"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1793-L1799 |
229,147 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.cancelHistoricalData | def cancelHistoricalData(self, contracts=None):
""" cancel historical data stream """
if contracts == None:
contracts = list(self.contracts.values())
elif not isinstance(contracts, list):
contracts = [contracts]
for contract in contracts:
# tickerId = self.tickerId(contract.m_symbol)
tickerId = self.tickerId(self.contractString(contract))
self.ibConn.cancelHistoricalData(tickerId=tickerId) | python | def cancelHistoricalData(self, contracts=None):
""" cancel historical data stream """
if contracts == None:
contracts = list(self.contracts.values())
elif not isinstance(contracts, list):
contracts = [contracts]
for contract in contracts:
# tickerId = self.tickerId(contract.m_symbol)
tickerId = self.tickerId(self.contractString(contract))
self.ibConn.cancelHistoricalData(tickerId=tickerId) | [
"def",
"cancelHistoricalData",
"(",
"self",
",",
"contracts",
"=",
"None",
")",
":",
"if",
"contracts",
"==",
"None",
":",
"contracts",
"=",
"list",
"(",
"self",
".",
"contracts",
".",
"values",
"(",
")",
")",
"elif",
"not",
"isinstance",
"(",
"contracts",
",",
"list",
")",
":",
"contracts",
"=",
"[",
"contracts",
"]",
"for",
"contract",
"in",
"contracts",
":",
"# tickerId = self.tickerId(contract.m_symbol)",
"tickerId",
"=",
"self",
".",
"tickerId",
"(",
"self",
".",
"contractString",
"(",
"contract",
")",
")",
"self",
".",
"ibConn",
".",
"cancelHistoricalData",
"(",
"tickerId",
"=",
"tickerId",
")"
] | cancel historical data stream | [
"cancel",
"historical",
"data",
"stream"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1931-L1941 |
229,148 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.getConId | def getConId(self, contract_identifier):
""" Get contracts conId """
details = self.contractDetails(contract_identifier)
if len(details["contracts"]) > 1:
return details["m_underConId"]
return details["m_summary"]["m_conId"] | python | def getConId(self, contract_identifier):
""" Get contracts conId """
details = self.contractDetails(contract_identifier)
if len(details["contracts"]) > 1:
return details["m_underConId"]
return details["m_summary"]["m_conId"] | [
"def",
"getConId",
"(",
"self",
",",
"contract_identifier",
")",
":",
"details",
"=",
"self",
".",
"contractDetails",
"(",
"contract_identifier",
")",
"if",
"len",
"(",
"details",
"[",
"\"contracts\"",
"]",
")",
">",
"1",
":",
"return",
"details",
"[",
"\"m_underConId\"",
"]",
"return",
"details",
"[",
"\"m_summary\"",
"]",
"[",
"\"m_conId\"",
"]"
] | Get contracts conId | [
"Get",
"contracts",
"conId"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1974-L1979 |
229,149 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.createComboContract | def createComboContract(self, symbol, legs, currency="USD", exchange=None):
""" Used for ComboLegs. Expecting list of legs """
exchange = legs[0].m_exchange if exchange is None else exchange
contract_tuple = (symbol, "BAG", exchange, currency, "", 0.0, "")
contract = self.createContract(contract_tuple, comboLegs=legs)
return contract | python | def createComboContract(self, symbol, legs, currency="USD", exchange=None):
""" Used for ComboLegs. Expecting list of legs """
exchange = legs[0].m_exchange if exchange is None else exchange
contract_tuple = (symbol, "BAG", exchange, currency, "", 0.0, "")
contract = self.createContract(contract_tuple, comboLegs=legs)
return contract | [
"def",
"createComboContract",
"(",
"self",
",",
"symbol",
",",
"legs",
",",
"currency",
"=",
"\"USD\"",
",",
"exchange",
"=",
"None",
")",
":",
"exchange",
"=",
"legs",
"[",
"0",
"]",
".",
"m_exchange",
"if",
"exchange",
"is",
"None",
"else",
"exchange",
"contract_tuple",
"=",
"(",
"symbol",
",",
"\"BAG\"",
",",
"exchange",
",",
"currency",
",",
"\"\"",
",",
"0.0",
",",
"\"\"",
")",
"contract",
"=",
"self",
".",
"createContract",
"(",
"contract_tuple",
",",
"comboLegs",
"=",
"legs",
")",
"return",
"contract"
] | Used for ComboLegs. Expecting list of legs | [
"Used",
"for",
"ComboLegs",
".",
"Expecting",
"list",
"of",
"legs"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L2008-L2013 |
229,150 | ranaroussi/ezibpy | ezibpy/utils.py | order_to_dict | def order_to_dict(order):
"""Convert an IBPy Order object to a dict containing any non-default values."""
default = Order()
return {field: val for field, val in vars(order).items() if val != getattr(default, field, None)} | python | def order_to_dict(order):
"""Convert an IBPy Order object to a dict containing any non-default values."""
default = Order()
return {field: val for field, val in vars(order).items() if val != getattr(default, field, None)} | [
"def",
"order_to_dict",
"(",
"order",
")",
":",
"default",
"=",
"Order",
"(",
")",
"return",
"{",
"field",
":",
"val",
"for",
"field",
",",
"val",
"in",
"vars",
"(",
"order",
")",
".",
"items",
"(",
")",
"if",
"val",
"!=",
"getattr",
"(",
"default",
",",
"field",
",",
"None",
")",
"}"
] | Convert an IBPy Order object to a dict containing any non-default values. | [
"Convert",
"an",
"IBPy",
"Order",
"object",
"to",
"a",
"dict",
"containing",
"any",
"non",
"-",
"default",
"values",
"."
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/utils.py#L204-L207 |
229,151 | ranaroussi/ezibpy | ezibpy/utils.py | contract_to_dict | def contract_to_dict(contract):
"""Convert an IBPy Contract object to a dict containing any non-default values."""
default = Contract()
return {field: val for field, val in vars(contract).items() if val != getattr(default, field, None)} | python | def contract_to_dict(contract):
"""Convert an IBPy Contract object to a dict containing any non-default values."""
default = Contract()
return {field: val for field, val in vars(contract).items() if val != getattr(default, field, None)} | [
"def",
"contract_to_dict",
"(",
"contract",
")",
":",
"default",
"=",
"Contract",
"(",
")",
"return",
"{",
"field",
":",
"val",
"for",
"field",
",",
"val",
"in",
"vars",
"(",
"contract",
")",
".",
"items",
"(",
")",
"if",
"val",
"!=",
"getattr",
"(",
"default",
",",
"field",
",",
"None",
")",
"}"
] | Convert an IBPy Contract object to a dict containing any non-default values. | [
"Convert",
"an",
"IBPy",
"Contract",
"object",
"to",
"a",
"dict",
"containing",
"any",
"non",
"-",
"default",
"values",
"."
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/utils.py#L212-L215 |
229,152 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | _get_utm_code | def _get_utm_code(zone, direction):
""" Get UTM code given a zone and direction
Direction is encoded as NORTH=6, SOUTH=7, while zone is the UTM zone number zero-padded.
For instance, the code 32604 is returned for zone number 4, north direction.
:param zone: UTM zone number
:type zone: int
:param direction: Direction enum type
:type direction: Enum
:return: UTM code
:rtype: str
"""
dir_dict = {_Direction.NORTH: '6', _Direction.SOUTH: '7'}
return '{}{}{}'.format('32', dir_dict[direction], str(zone).zfill(2)) | python | def _get_utm_code(zone, direction):
""" Get UTM code given a zone and direction
Direction is encoded as NORTH=6, SOUTH=7, while zone is the UTM zone number zero-padded.
For instance, the code 32604 is returned for zone number 4, north direction.
:param zone: UTM zone number
:type zone: int
:param direction: Direction enum type
:type direction: Enum
:return: UTM code
:rtype: str
"""
dir_dict = {_Direction.NORTH: '6', _Direction.SOUTH: '7'}
return '{}{}{}'.format('32', dir_dict[direction], str(zone).zfill(2)) | [
"def",
"_get_utm_code",
"(",
"zone",
",",
"direction",
")",
":",
"dir_dict",
"=",
"{",
"_Direction",
".",
"NORTH",
":",
"'6'",
",",
"_Direction",
".",
"SOUTH",
":",
"'7'",
"}",
"return",
"'{}{}{}'",
".",
"format",
"(",
"'32'",
",",
"dir_dict",
"[",
"direction",
"]",
",",
"str",
"(",
"zone",
")",
".",
"zfill",
"(",
"2",
")",
")"
] | Get UTM code given a zone and direction
Direction is encoded as NORTH=6, SOUTH=7, while zone is the UTM zone number zero-padded.
For instance, the code 32604 is returned for zone number 4, north direction.
:param zone: UTM zone number
:type zone: int
:param direction: Direction enum type
:type direction: Enum
:return: UTM code
:rtype: str | [
"Get",
"UTM",
"code",
"given",
"a",
"zone",
"and",
"direction"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L225-L239 |
229,153 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | _get_utm_name_value_pair | def _get_utm_name_value_pair(zone, direction=_Direction.NORTH):
""" Get name and code for UTM coordinates
:param zone: UTM zone number
:type zone: int
:param direction: Direction enum type
:type direction: Enum, optional (default=NORTH)
:return: Name and code of UTM coordinates
:rtype: str, str
"""
name = 'UTM_{}{}'.format(zone, direction.value)
epsg = _get_utm_code(zone, direction)
return name, epsg | python | def _get_utm_name_value_pair(zone, direction=_Direction.NORTH):
""" Get name and code for UTM coordinates
:param zone: UTM zone number
:type zone: int
:param direction: Direction enum type
:type direction: Enum, optional (default=NORTH)
:return: Name and code of UTM coordinates
:rtype: str, str
"""
name = 'UTM_{}{}'.format(zone, direction.value)
epsg = _get_utm_code(zone, direction)
return name, epsg | [
"def",
"_get_utm_name_value_pair",
"(",
"zone",
",",
"direction",
"=",
"_Direction",
".",
"NORTH",
")",
":",
"name",
"=",
"'UTM_{}{}'",
".",
"format",
"(",
"zone",
",",
"direction",
".",
"value",
")",
"epsg",
"=",
"_get_utm_code",
"(",
"zone",
",",
"direction",
")",
"return",
"name",
",",
"epsg"
] | Get name and code for UTM coordinates
:param zone: UTM zone number
:type zone: int
:param direction: Direction enum type
:type direction: Enum, optional (default=NORTH)
:return: Name and code of UTM coordinates
:rtype: str, str | [
"Get",
"name",
"and",
"code",
"for",
"UTM",
"coordinates"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L242-L254 |
229,154 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | _crs_parser | def _crs_parser(cls, value):
""" Parses user input for class CRS
:param cls: class object
:param value: user input for CRS
:type value: str, int or CRS
"""
parsed_value = value
if isinstance(parsed_value, int):
parsed_value = str(parsed_value)
if isinstance(parsed_value, str):
parsed_value = parsed_value.strip('epsgEPSG: ')
return super(_BaseCRS, cls).__new__(cls, parsed_value) | python | def _crs_parser(cls, value):
""" Parses user input for class CRS
:param cls: class object
:param value: user input for CRS
:type value: str, int or CRS
"""
parsed_value = value
if isinstance(parsed_value, int):
parsed_value = str(parsed_value)
if isinstance(parsed_value, str):
parsed_value = parsed_value.strip('epsgEPSG: ')
return super(_BaseCRS, cls).__new__(cls, parsed_value) | [
"def",
"_crs_parser",
"(",
"cls",
",",
"value",
")",
":",
"parsed_value",
"=",
"value",
"if",
"isinstance",
"(",
"parsed_value",
",",
"int",
")",
":",
"parsed_value",
"=",
"str",
"(",
"parsed_value",
")",
"if",
"isinstance",
"(",
"parsed_value",
",",
"str",
")",
":",
"parsed_value",
"=",
"parsed_value",
".",
"strip",
"(",
"'epsgEPSG: '",
")",
"return",
"super",
"(",
"_BaseCRS",
",",
"cls",
")",
".",
"__new__",
"(",
"cls",
",",
"parsed_value",
")"
] | Parses user input for class CRS
:param cls: class object
:param value: user input for CRS
:type value: str, int or CRS | [
"Parses",
"user",
"input",
"for",
"class",
"CRS"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L327-L339 |
229,155 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | DataSource.get_wfs_typename | def get_wfs_typename(cls, data_source):
""" Maps data source to string identifier for WFS
:param data_source: One of the supported data sources
:type: DataSource
:return: Product identifier for WFS
:rtype: str
"""
is_eocloud = SHConfig().is_eocloud_ogc_url()
return {
cls.SENTINEL2_L1C: 'S2.TILE',
cls.SENTINEL2_L2A: 'SEN4CAP_S2L2A.TILE' if is_eocloud else 'DSS2',
cls.SENTINEL1_IW: 'S1.TILE' if is_eocloud else 'DSS3',
cls.SENTINEL1_EW: 'S1_EW.TILE' if is_eocloud else 'DSS3',
cls.SENTINEL1_EW_SH: 'S1_EW_SH.TILE' if is_eocloud else 'DSS3',
cls.DEM: 'DSS4',
cls.MODIS: 'DSS5',
cls.LANDSAT8: 'L8.TILE' if is_eocloud else 'DSS6',
# eocloud sources only:
cls.LANDSAT5: 'L5.TILE',
cls.LANDSAT7: 'L7.TILE',
cls.SENTINEL3: 'S3.TILE',
cls.SENTINEL5P: 'S5p_L2.TILE',
cls.ENVISAT_MERIS: 'ENV.TILE',
cls.SENTINEL2_L3B: 'SEN4CAP_S2L3B.TILE',
cls.LANDSAT8_L2A: 'SEN4CAP_L8L2A.TILE'
}[data_source] | python | def get_wfs_typename(cls, data_source):
""" Maps data source to string identifier for WFS
:param data_source: One of the supported data sources
:type: DataSource
:return: Product identifier for WFS
:rtype: str
"""
is_eocloud = SHConfig().is_eocloud_ogc_url()
return {
cls.SENTINEL2_L1C: 'S2.TILE',
cls.SENTINEL2_L2A: 'SEN4CAP_S2L2A.TILE' if is_eocloud else 'DSS2',
cls.SENTINEL1_IW: 'S1.TILE' if is_eocloud else 'DSS3',
cls.SENTINEL1_EW: 'S1_EW.TILE' if is_eocloud else 'DSS3',
cls.SENTINEL1_EW_SH: 'S1_EW_SH.TILE' if is_eocloud else 'DSS3',
cls.DEM: 'DSS4',
cls.MODIS: 'DSS5',
cls.LANDSAT8: 'L8.TILE' if is_eocloud else 'DSS6',
# eocloud sources only:
cls.LANDSAT5: 'L5.TILE',
cls.LANDSAT7: 'L7.TILE',
cls.SENTINEL3: 'S3.TILE',
cls.SENTINEL5P: 'S5p_L2.TILE',
cls.ENVISAT_MERIS: 'ENV.TILE',
cls.SENTINEL2_L3B: 'SEN4CAP_S2L3B.TILE',
cls.LANDSAT8_L2A: 'SEN4CAP_L8L2A.TILE'
}[data_source] | [
"def",
"get_wfs_typename",
"(",
"cls",
",",
"data_source",
")",
":",
"is_eocloud",
"=",
"SHConfig",
"(",
")",
".",
"is_eocloud_ogc_url",
"(",
")",
"return",
"{",
"cls",
".",
"SENTINEL2_L1C",
":",
"'S2.TILE'",
",",
"cls",
".",
"SENTINEL2_L2A",
":",
"'SEN4CAP_S2L2A.TILE'",
"if",
"is_eocloud",
"else",
"'DSS2'",
",",
"cls",
".",
"SENTINEL1_IW",
":",
"'S1.TILE'",
"if",
"is_eocloud",
"else",
"'DSS3'",
",",
"cls",
".",
"SENTINEL1_EW",
":",
"'S1_EW.TILE'",
"if",
"is_eocloud",
"else",
"'DSS3'",
",",
"cls",
".",
"SENTINEL1_EW_SH",
":",
"'S1_EW_SH.TILE'",
"if",
"is_eocloud",
"else",
"'DSS3'",
",",
"cls",
".",
"DEM",
":",
"'DSS4'",
",",
"cls",
".",
"MODIS",
":",
"'DSS5'",
",",
"cls",
".",
"LANDSAT8",
":",
"'L8.TILE'",
"if",
"is_eocloud",
"else",
"'DSS6'",
",",
"# eocloud sources only:",
"cls",
".",
"LANDSAT5",
":",
"'L5.TILE'",
",",
"cls",
".",
"LANDSAT7",
":",
"'L7.TILE'",
",",
"cls",
".",
"SENTINEL3",
":",
"'S3.TILE'",
",",
"cls",
".",
"SENTINEL5P",
":",
"'S5p_L2.TILE'",
",",
"cls",
".",
"ENVISAT_MERIS",
":",
"'ENV.TILE'",
",",
"cls",
".",
"SENTINEL2_L3B",
":",
"'SEN4CAP_S2L3B.TILE'",
",",
"cls",
".",
"LANDSAT8_L2A",
":",
"'SEN4CAP_L8L2A.TILE'",
"}",
"[",
"data_source",
"]"
] | Maps data source to string identifier for WFS
:param data_source: One of the supported data sources
:type: DataSource
:return: Product identifier for WFS
:rtype: str | [
"Maps",
"data",
"source",
"to",
"string",
"identifier",
"for",
"WFS"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L140-L166 |
229,156 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | DataSource.is_uswest_source | def is_uswest_source(self):
"""Checks if data source via Sentinel Hub services is available at US West server
Example: ``DataSource.LANDSAT8.is_uswest_source()`` or ``DataSource.is_uswest_source(DataSource.LANDSAT8)``
:param self: One of the supported data sources
:type self: DataSource
:return: ``True`` if data source exists at US West server and ``False`` otherwise
:rtype: bool
"""
return not SHConfig().is_eocloud_ogc_url() and self.value[0] in [_Source.LANDSAT8, _Source.MODIS, _Source.DEM] | python | def is_uswest_source(self):
"""Checks if data source via Sentinel Hub services is available at US West server
Example: ``DataSource.LANDSAT8.is_uswest_source()`` or ``DataSource.is_uswest_source(DataSource.LANDSAT8)``
:param self: One of the supported data sources
:type self: DataSource
:return: ``True`` if data source exists at US West server and ``False`` otherwise
:rtype: bool
"""
return not SHConfig().is_eocloud_ogc_url() and self.value[0] in [_Source.LANDSAT8, _Source.MODIS, _Source.DEM] | [
"def",
"is_uswest_source",
"(",
"self",
")",
":",
"return",
"not",
"SHConfig",
"(",
")",
".",
"is_eocloud_ogc_url",
"(",
")",
"and",
"self",
".",
"value",
"[",
"0",
"]",
"in",
"[",
"_Source",
".",
"LANDSAT8",
",",
"_Source",
".",
"MODIS",
",",
"_Source",
".",
"DEM",
"]"
] | Checks if data source via Sentinel Hub services is available at US West server
Example: ``DataSource.LANDSAT8.is_uswest_source()`` or ``DataSource.is_uswest_source(DataSource.LANDSAT8)``
:param self: One of the supported data sources
:type self: DataSource
:return: ``True`` if data source exists at US West server and ``False`` otherwise
:rtype: bool | [
"Checks",
"if",
"data",
"source",
"via",
"Sentinel",
"Hub",
"services",
"is",
"available",
"at",
"US",
"West",
"server"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L192-L202 |
229,157 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | DataSource.get_available_sources | def get_available_sources(cls):
""" Returns which data sources are available for configured Sentinel Hub OGC URL
:return: List of available data sources
:rtype: list(sentinelhub.DataSource)
"""
if SHConfig().is_eocloud_ogc_url():
return [cls.SENTINEL2_L1C, cls.SENTINEL2_L2A, cls.SENTINEL2_L3B, cls.SENTINEL1_IW, cls.SENTINEL1_EW,
cls.SENTINEL1_EW_SH, cls.SENTINEL3, cls.SENTINEL5P, cls.LANDSAT5, cls.LANDSAT7, cls.LANDSAT8,
cls.LANDSAT8_L2A, cls.ENVISAT_MERIS]
return [cls.SENTINEL2_L1C, cls.SENTINEL2_L2A, cls.SENTINEL1_IW, cls.SENTINEL1_EW, cls.SENTINEL1_EW_SH, cls.DEM,
cls.MODIS, cls.LANDSAT8] | python | def get_available_sources(cls):
""" Returns which data sources are available for configured Sentinel Hub OGC URL
:return: List of available data sources
:rtype: list(sentinelhub.DataSource)
"""
if SHConfig().is_eocloud_ogc_url():
return [cls.SENTINEL2_L1C, cls.SENTINEL2_L2A, cls.SENTINEL2_L3B, cls.SENTINEL1_IW, cls.SENTINEL1_EW,
cls.SENTINEL1_EW_SH, cls.SENTINEL3, cls.SENTINEL5P, cls.LANDSAT5, cls.LANDSAT7, cls.LANDSAT8,
cls.LANDSAT8_L2A, cls.ENVISAT_MERIS]
return [cls.SENTINEL2_L1C, cls.SENTINEL2_L2A, cls.SENTINEL1_IW, cls.SENTINEL1_EW, cls.SENTINEL1_EW_SH, cls.DEM,
cls.MODIS, cls.LANDSAT8] | [
"def",
"get_available_sources",
"(",
"cls",
")",
":",
"if",
"SHConfig",
"(",
")",
".",
"is_eocloud_ogc_url",
"(",
")",
":",
"return",
"[",
"cls",
".",
"SENTINEL2_L1C",
",",
"cls",
".",
"SENTINEL2_L2A",
",",
"cls",
".",
"SENTINEL2_L3B",
",",
"cls",
".",
"SENTINEL1_IW",
",",
"cls",
".",
"SENTINEL1_EW",
",",
"cls",
".",
"SENTINEL1_EW_SH",
",",
"cls",
".",
"SENTINEL3",
",",
"cls",
".",
"SENTINEL5P",
",",
"cls",
".",
"LANDSAT5",
",",
"cls",
".",
"LANDSAT7",
",",
"cls",
".",
"LANDSAT8",
",",
"cls",
".",
"LANDSAT8_L2A",
",",
"cls",
".",
"ENVISAT_MERIS",
"]",
"return",
"[",
"cls",
".",
"SENTINEL2_L1C",
",",
"cls",
".",
"SENTINEL2_L2A",
",",
"cls",
".",
"SENTINEL1_IW",
",",
"cls",
".",
"SENTINEL1_EW",
",",
"cls",
".",
"SENTINEL1_EW_SH",
",",
"cls",
".",
"DEM",
",",
"cls",
".",
"MODIS",
",",
"cls",
".",
"LANDSAT8",
"]"
] | Returns which data sources are available for configured Sentinel Hub OGC URL
:return: List of available data sources
:rtype: list(sentinelhub.DataSource) | [
"Returns",
"which",
"data",
"sources",
"are",
"available",
"for",
"configured",
"Sentinel",
"Hub",
"OGC",
"URL"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L205-L216 |
229,158 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | _BaseCRS.get_utm_from_wgs84 | def get_utm_from_wgs84(lng, lat):
""" Convert from WGS84 to UTM coordinate system
:param lng: Longitude
:type lng: float
:param lat: Latitude
:type lat: float
:return: UTM coordinates
:rtype: tuple
"""
_, _, zone, _ = utm.from_latlon(lat, lng)
direction = 'N' if lat >= 0 else 'S'
return CRS['UTM_{}{}'.format(str(zone), direction)] | python | def get_utm_from_wgs84(lng, lat):
""" Convert from WGS84 to UTM coordinate system
:param lng: Longitude
:type lng: float
:param lat: Latitude
:type lat: float
:return: UTM coordinates
:rtype: tuple
"""
_, _, zone, _ = utm.from_latlon(lat, lng)
direction = 'N' if lat >= 0 else 'S'
return CRS['UTM_{}{}'.format(str(zone), direction)] | [
"def",
"get_utm_from_wgs84",
"(",
"lng",
",",
"lat",
")",
":",
"_",
",",
"_",
",",
"zone",
",",
"_",
"=",
"utm",
".",
"from_latlon",
"(",
"lat",
",",
"lng",
")",
"direction",
"=",
"'N'",
"if",
"lat",
">=",
"0",
"else",
"'S'",
"return",
"CRS",
"[",
"'UTM_{}{}'",
".",
"format",
"(",
"str",
"(",
"zone",
")",
",",
"direction",
")",
"]"
] | Convert from WGS84 to UTM coordinate system
:param lng: Longitude
:type lng: float
:param lat: Latitude
:type lat: float
:return: UTM coordinates
:rtype: tuple | [
"Convert",
"from",
"WGS84",
"to",
"UTM",
"coordinate",
"system"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L263-L275 |
229,159 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | CustomUrlParam.has_value | def has_value(cls, value):
""" Tests whether CustomUrlParam contains a constant defined with a string `value`
:param value: The string representation of the enum constant
:type value: str
:return: `True` if there exists a constant with a string value `value`, `False` otherwise
:rtype: bool
"""
return any(value.lower() == item.value.lower() for item in cls) | python | def has_value(cls, value):
""" Tests whether CustomUrlParam contains a constant defined with a string `value`
:param value: The string representation of the enum constant
:type value: str
:return: `True` if there exists a constant with a string value `value`, `False` otherwise
:rtype: bool
"""
return any(value.lower() == item.value.lower() for item in cls) | [
"def",
"has_value",
"(",
"cls",
",",
"value",
")",
":",
"return",
"any",
"(",
"value",
".",
"lower",
"(",
")",
"==",
"item",
".",
"value",
".",
"lower",
"(",
")",
"for",
"item",
"in",
"cls",
")"
] | Tests whether CustomUrlParam contains a constant defined with a string `value`
:param value: The string representation of the enum constant
:type value: str
:return: `True` if there exists a constant with a string value `value`, `False` otherwise
:rtype: bool | [
"Tests",
"whether",
"CustomUrlParam",
"contains",
"a",
"constant",
"defined",
"with",
"a",
"string",
"value"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L367-L375 |
229,160 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | MimeType.canonical_extension | def canonical_extension(fmt_ext):
""" Canonical extension of file format extension
Converts the format extension fmt_ext into the canonical extension for that format. For example,
``canonical_extension('tif') == 'tiff'``. Here we agree that the canonical extension for format F is F.value
:param fmt_ext: A string representing an extension (e.g. ``'txt'``, ``'png'``, etc.)
:type fmt_ext: str
:return: The canonical form of the extension (e.g. if ``fmt_ext='tif'`` then we return ``'tiff'``)
:rtype: str
"""
if MimeType.has_value(fmt_ext):
return fmt_ext
try:
return {
'tif': MimeType.TIFF.value,
'jpeg': MimeType.JPG.value,
'hdf5': MimeType.HDF.value,
'h5': MimeType.HDF.value
}[fmt_ext]
except KeyError:
raise ValueError('Data format .{} is not supported'.format(fmt_ext)) | python | def canonical_extension(fmt_ext):
""" Canonical extension of file format extension
Converts the format extension fmt_ext into the canonical extension for that format. For example,
``canonical_extension('tif') == 'tiff'``. Here we agree that the canonical extension for format F is F.value
:param fmt_ext: A string representing an extension (e.g. ``'txt'``, ``'png'``, etc.)
:type fmt_ext: str
:return: The canonical form of the extension (e.g. if ``fmt_ext='tif'`` then we return ``'tiff'``)
:rtype: str
"""
if MimeType.has_value(fmt_ext):
return fmt_ext
try:
return {
'tif': MimeType.TIFF.value,
'jpeg': MimeType.JPG.value,
'hdf5': MimeType.HDF.value,
'h5': MimeType.HDF.value
}[fmt_ext]
except KeyError:
raise ValueError('Data format .{} is not supported'.format(fmt_ext)) | [
"def",
"canonical_extension",
"(",
"fmt_ext",
")",
":",
"if",
"MimeType",
".",
"has_value",
"(",
"fmt_ext",
")",
":",
"return",
"fmt_ext",
"try",
":",
"return",
"{",
"'tif'",
":",
"MimeType",
".",
"TIFF",
".",
"value",
",",
"'jpeg'",
":",
"MimeType",
".",
"JPG",
".",
"value",
",",
"'hdf5'",
":",
"MimeType",
".",
"HDF",
".",
"value",
",",
"'h5'",
":",
"MimeType",
".",
"HDF",
".",
"value",
"}",
"[",
"fmt_ext",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"'Data format .{} is not supported'",
".",
"format",
"(",
"fmt_ext",
")",
")"
] | Canonical extension of file format extension
Converts the format extension fmt_ext into the canonical extension for that format. For example,
``canonical_extension('tif') == 'tiff'``. Here we agree that the canonical extension for format F is F.value
:param fmt_ext: A string representing an extension (e.g. ``'txt'``, ``'png'``, etc.)
:type fmt_ext: str
:return: The canonical form of the extension (e.g. if ``fmt_ext='tif'`` then we return ``'tiff'``)
:rtype: str | [
"Canonical",
"extension",
"of",
"file",
"format",
"extension"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L424-L445 |
229,161 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | MimeType.is_image_format | def is_image_format(self):
""" Checks whether file format is an image format
Example: ``MimeType.PNG.is_image_format()`` or ``MimeType.is_image_format(MimeType.PNG)``
:param self: File format
:type self: MimeType
:return: ``True`` if file is in image format, ``False`` otherwise
:rtype: bool
"""
return self in frozenset([MimeType.TIFF, MimeType.TIFF_d8, MimeType.TIFF_d16, MimeType.TIFF_d32f, MimeType.PNG,
MimeType.JP2, MimeType.JPG]) | python | def is_image_format(self):
""" Checks whether file format is an image format
Example: ``MimeType.PNG.is_image_format()`` or ``MimeType.is_image_format(MimeType.PNG)``
:param self: File format
:type self: MimeType
:return: ``True`` if file is in image format, ``False`` otherwise
:rtype: bool
"""
return self in frozenset([MimeType.TIFF, MimeType.TIFF_d8, MimeType.TIFF_d16, MimeType.TIFF_d32f, MimeType.PNG,
MimeType.JP2, MimeType.JPG]) | [
"def",
"is_image_format",
"(",
"self",
")",
":",
"return",
"self",
"in",
"frozenset",
"(",
"[",
"MimeType",
".",
"TIFF",
",",
"MimeType",
".",
"TIFF_d8",
",",
"MimeType",
".",
"TIFF_d16",
",",
"MimeType",
".",
"TIFF_d32f",
",",
"MimeType",
".",
"PNG",
",",
"MimeType",
".",
"JP2",
",",
"MimeType",
".",
"JPG",
"]",
")"
] | Checks whether file format is an image format
Example: ``MimeType.PNG.is_image_format()`` or ``MimeType.is_image_format(MimeType.PNG)``
:param self: File format
:type self: MimeType
:return: ``True`` if file is in image format, ``False`` otherwise
:rtype: bool | [
"Checks",
"whether",
"file",
"format",
"is",
"an",
"image",
"format"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L447-L458 |
229,162 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | MimeType.is_tiff_format | def is_tiff_format(self):
""" Checks whether file format is a TIFF image format
Example: ``MimeType.TIFF.is_tiff_format()`` or ``MimeType.is_tiff_format(MimeType.TIFF)``
:param self: File format
:type self: MimeType
:return: ``True`` if file is in image format, ``False`` otherwise
:rtype: bool
"""
return self in frozenset([MimeType.TIFF, MimeType.TIFF_d8, MimeType.TIFF_d16, MimeType.TIFF_d32f]) | python | def is_tiff_format(self):
""" Checks whether file format is a TIFF image format
Example: ``MimeType.TIFF.is_tiff_format()`` or ``MimeType.is_tiff_format(MimeType.TIFF)``
:param self: File format
:type self: MimeType
:return: ``True`` if file is in image format, ``False`` otherwise
:rtype: bool
"""
return self in frozenset([MimeType.TIFF, MimeType.TIFF_d8, MimeType.TIFF_d16, MimeType.TIFF_d32f]) | [
"def",
"is_tiff_format",
"(",
"self",
")",
":",
"return",
"self",
"in",
"frozenset",
"(",
"[",
"MimeType",
".",
"TIFF",
",",
"MimeType",
".",
"TIFF_d8",
",",
"MimeType",
".",
"TIFF_d16",
",",
"MimeType",
".",
"TIFF_d32f",
"]",
")"
] | Checks whether file format is a TIFF image format
Example: ``MimeType.TIFF.is_tiff_format()`` or ``MimeType.is_tiff_format(MimeType.TIFF)``
:param self: File format
:type self: MimeType
:return: ``True`` if file is in image format, ``False`` otherwise
:rtype: bool | [
"Checks",
"whether",
"file",
"format",
"is",
"a",
"TIFF",
"image",
"format"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L460-L470 |
229,163 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | MimeType.get_string | def get_string(self):
""" Get file format as string
:return: String describing the file format
:rtype: str
"""
if self in [MimeType.TIFF_d8, MimeType.TIFF_d16, MimeType.TIFF_d32f]:
return 'image/{}'.format(self.value)
if self is MimeType.JP2:
return 'image/jpeg2000'
if self in [MimeType.RAW, MimeType.REQUESTS_RESPONSE]:
return self.value
return mimetypes.types_map['.' + self.value] | python | def get_string(self):
""" Get file format as string
:return: String describing the file format
:rtype: str
"""
if self in [MimeType.TIFF_d8, MimeType.TIFF_d16, MimeType.TIFF_d32f]:
return 'image/{}'.format(self.value)
if self is MimeType.JP2:
return 'image/jpeg2000'
if self in [MimeType.RAW, MimeType.REQUESTS_RESPONSE]:
return self.value
return mimetypes.types_map['.' + self.value] | [
"def",
"get_string",
"(",
"self",
")",
":",
"if",
"self",
"in",
"[",
"MimeType",
".",
"TIFF_d8",
",",
"MimeType",
".",
"TIFF_d16",
",",
"MimeType",
".",
"TIFF_d32f",
"]",
":",
"return",
"'image/{}'",
".",
"format",
"(",
"self",
".",
"value",
")",
"if",
"self",
"is",
"MimeType",
".",
"JP2",
":",
"return",
"'image/jpeg2000'",
"if",
"self",
"in",
"[",
"MimeType",
".",
"RAW",
",",
"MimeType",
".",
"REQUESTS_RESPONSE",
"]",
":",
"return",
"self",
".",
"value",
"return",
"mimetypes",
".",
"types_map",
"[",
"'.'",
"+",
"self",
".",
"value",
"]"
] | Get file format as string
:return: String describing the file format
:rtype: str | [
"Get",
"file",
"format",
"as",
"string"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L483-L495 |
229,164 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | MimeType.get_expected_max_value | def get_expected_max_value(self):
""" Returns max value of image `MimeType` format and raises an error if it is not an image format
Note: For `MimeType.TIFF_d32f` it will return ``1.0`` as that is expected maximum for an image even though it
could be higher.
:return: A maximum value of specified image format
:rtype: int or float
:raises: ValueError
"""
try:
return {
MimeType.TIFF: 65535,
MimeType.TIFF_d8: 255,
MimeType.TIFF_d16: 65535,
MimeType.TIFF_d32f: 1.0,
MimeType.PNG: 255,
MimeType.JPG: 255,
MimeType.JP2: 10000
}[self]
except IndexError:
raise ValueError('Type {} is not supported by this method'.format(self)) | python | def get_expected_max_value(self):
""" Returns max value of image `MimeType` format and raises an error if it is not an image format
Note: For `MimeType.TIFF_d32f` it will return ``1.0`` as that is expected maximum for an image even though it
could be higher.
:return: A maximum value of specified image format
:rtype: int or float
:raises: ValueError
"""
try:
return {
MimeType.TIFF: 65535,
MimeType.TIFF_d8: 255,
MimeType.TIFF_d16: 65535,
MimeType.TIFF_d32f: 1.0,
MimeType.PNG: 255,
MimeType.JPG: 255,
MimeType.JP2: 10000
}[self]
except IndexError:
raise ValueError('Type {} is not supported by this method'.format(self)) | [
"def",
"get_expected_max_value",
"(",
"self",
")",
":",
"try",
":",
"return",
"{",
"MimeType",
".",
"TIFF",
":",
"65535",
",",
"MimeType",
".",
"TIFF_d8",
":",
"255",
",",
"MimeType",
".",
"TIFF_d16",
":",
"65535",
",",
"MimeType",
".",
"TIFF_d32f",
":",
"1.0",
",",
"MimeType",
".",
"PNG",
":",
"255",
",",
"MimeType",
".",
"JPG",
":",
"255",
",",
"MimeType",
".",
"JP2",
":",
"10000",
"}",
"[",
"self",
"]",
"except",
"IndexError",
":",
"raise",
"ValueError",
"(",
"'Type {} is not supported by this method'",
".",
"format",
"(",
"self",
")",
")"
] | Returns max value of image `MimeType` format and raises an error if it is not an image format
Note: For `MimeType.TIFF_d32f` it will return ``1.0`` as that is expected maximum for an image even though it
could be higher.
:return: A maximum value of specified image format
:rtype: int or float
:raises: ValueError | [
"Returns",
"max",
"value",
"of",
"image",
"MimeType",
"format",
"and",
"raises",
"an",
"error",
"if",
"it",
"is",
"not",
"an",
"image",
"format"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L497-L518 |
229,165 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcService._filter_dates | def _filter_dates(dates, time_difference):
"""
Filters out dates within time_difference, preserving only the oldest date.
:param dates: a list of datetime objects
:param time_difference: a ``datetime.timedelta`` representing the time difference threshold
:return: an ordered list of datetimes `d1<=d2<=...<=dn` such that `d[i+1]-di > time_difference`
:rtype: list(datetime.datetime)
"""
LOGGER.debug("dates=%s", dates)
if len(dates) <= 1:
return dates
sorted_dates = sorted(dates)
separate_dates = [sorted_dates[0]]
for curr_date in sorted_dates[1:]:
if curr_date - separate_dates[-1] > time_difference:
separate_dates.append(curr_date)
return separate_dates | python | def _filter_dates(dates, time_difference):
"""
Filters out dates within time_difference, preserving only the oldest date.
:param dates: a list of datetime objects
:param time_difference: a ``datetime.timedelta`` representing the time difference threshold
:return: an ordered list of datetimes `d1<=d2<=...<=dn` such that `d[i+1]-di > time_difference`
:rtype: list(datetime.datetime)
"""
LOGGER.debug("dates=%s", dates)
if len(dates) <= 1:
return dates
sorted_dates = sorted(dates)
separate_dates = [sorted_dates[0]]
for curr_date in sorted_dates[1:]:
if curr_date - separate_dates[-1] > time_difference:
separate_dates.append(curr_date)
return separate_dates | [
"def",
"_filter_dates",
"(",
"dates",
",",
"time_difference",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"dates=%s\"",
",",
"dates",
")",
"if",
"len",
"(",
"dates",
")",
"<=",
"1",
":",
"return",
"dates",
"sorted_dates",
"=",
"sorted",
"(",
"dates",
")",
"separate_dates",
"=",
"[",
"sorted_dates",
"[",
"0",
"]",
"]",
"for",
"curr_date",
"in",
"sorted_dates",
"[",
"1",
":",
"]",
":",
"if",
"curr_date",
"-",
"separate_dates",
"[",
"-",
"1",
"]",
">",
"time_difference",
":",
"separate_dates",
".",
"append",
"(",
"curr_date",
")",
"return",
"separate_dates"
] | Filters out dates within time_difference, preserving only the oldest date.
:param dates: a list of datetime objects
:param time_difference: a ``datetime.timedelta`` representing the time difference threshold
:return: an ordered list of datetimes `d1<=d2<=...<=dn` such that `d[i+1]-di > time_difference`
:rtype: list(datetime.datetime) | [
"Filters",
"out",
"dates",
"within",
"time_difference",
"preserving",
"only",
"the",
"oldest",
"date",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L44-L65 |
229,166 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcService._sentinel1_product_check | def _sentinel1_product_check(product_id, data_source):
"""Checks if Sentinel-1 product ID matches Sentinel-1 DataSource configuration
:param product_id: Sentinel-1 product ID
:type product_id: str
:param data_source: One of the supported Sentinel-1 data sources
:type data_source: constants.DataSource
:return: True if data_source contains product_id and False otherwise
:rtype: bool
"""
props = product_id.split('_')
acquisition, resolution, polarisation = props[1], props[2][3], props[3][2:4]
if acquisition in ['IW', 'EW'] and resolution in ['M', 'H'] and polarisation in ['DV', 'DH', 'SV', 'SH']:
return acquisition == data_source.value[2].name and polarisation == data_source.value[3].name and \
resolution == data_source.value[4].name[0]
raise ValueError('Unknown Sentinel-1 tile type: {}'.format(product_id)) | python | def _sentinel1_product_check(product_id, data_source):
"""Checks if Sentinel-1 product ID matches Sentinel-1 DataSource configuration
:param product_id: Sentinel-1 product ID
:type product_id: str
:param data_source: One of the supported Sentinel-1 data sources
:type data_source: constants.DataSource
:return: True if data_source contains product_id and False otherwise
:rtype: bool
"""
props = product_id.split('_')
acquisition, resolution, polarisation = props[1], props[2][3], props[3][2:4]
if acquisition in ['IW', 'EW'] and resolution in ['M', 'H'] and polarisation in ['DV', 'DH', 'SV', 'SH']:
return acquisition == data_source.value[2].name and polarisation == data_source.value[3].name and \
resolution == data_source.value[4].name[0]
raise ValueError('Unknown Sentinel-1 tile type: {}'.format(product_id)) | [
"def",
"_sentinel1_product_check",
"(",
"product_id",
",",
"data_source",
")",
":",
"props",
"=",
"product_id",
".",
"split",
"(",
"'_'",
")",
"acquisition",
",",
"resolution",
",",
"polarisation",
"=",
"props",
"[",
"1",
"]",
",",
"props",
"[",
"2",
"]",
"[",
"3",
"]",
",",
"props",
"[",
"3",
"]",
"[",
"2",
":",
"4",
"]",
"if",
"acquisition",
"in",
"[",
"'IW'",
",",
"'EW'",
"]",
"and",
"resolution",
"in",
"[",
"'M'",
",",
"'H'",
"]",
"and",
"polarisation",
"in",
"[",
"'DV'",
",",
"'DH'",
",",
"'SV'",
",",
"'SH'",
"]",
":",
"return",
"acquisition",
"==",
"data_source",
".",
"value",
"[",
"2",
"]",
".",
"name",
"and",
"polarisation",
"==",
"data_source",
".",
"value",
"[",
"3",
"]",
".",
"name",
"and",
"resolution",
"==",
"data_source",
".",
"value",
"[",
"4",
"]",
".",
"name",
"[",
"0",
"]",
"raise",
"ValueError",
"(",
"'Unknown Sentinel-1 tile type: {}'",
".",
"format",
"(",
"product_id",
")",
")"
] | Checks if Sentinel-1 product ID matches Sentinel-1 DataSource configuration
:param product_id: Sentinel-1 product ID
:type product_id: str
:param data_source: One of the supported Sentinel-1 data sources
:type data_source: constants.DataSource
:return: True if data_source contains product_id and False otherwise
:rtype: bool | [
"Checks",
"if",
"Sentinel",
"-",
"1",
"product",
"ID",
"matches",
"Sentinel",
"-",
"1",
"DataSource",
"configuration"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L68-L83 |
229,167 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService.get_url | def get_url(self, request, *, date=None, size_x=None, size_y=None, geometry=None):
""" Returns url to Sentinel Hub's OGC service for the product specified by the OgcRequest and date.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param date: acquisition date or None
:type date: datetime.datetime or None
:param size_x: horizontal image dimension
:type size_x: int or str
:param size_y: vertical image dimension
:type size_y: int or str
:type geometry: list of BBox or Geometry
:return: dictionary with parameters
:return: url to Sentinel Hub's OGC service for this product.
:rtype: str
"""
url = self.get_base_url(request)
authority = self.instance_id if hasattr(self, 'instance_id') else request.theme
params = self._get_common_url_parameters(request)
if request.service_type in (ServiceType.WMS, ServiceType.WCS):
params = {**params, **self._get_wms_wcs_url_parameters(request, date)}
if request.service_type is ServiceType.WMS:
params = {**params, **self._get_wms_url_parameters(request, size_x, size_y)}
elif request.service_type is ServiceType.WCS:
params = {**params, **self._get_wcs_url_parameters(request, size_x, size_y)}
elif request.service_type is ServiceType.FIS:
params = {**params, **self._get_fis_parameters(request, geometry)}
return '{}/{}?{}'.format(url, authority, urlencode(params)) | python | def get_url(self, request, *, date=None, size_x=None, size_y=None, geometry=None):
""" Returns url to Sentinel Hub's OGC service for the product specified by the OgcRequest and date.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param date: acquisition date or None
:type date: datetime.datetime or None
:param size_x: horizontal image dimension
:type size_x: int or str
:param size_y: vertical image dimension
:type size_y: int or str
:type geometry: list of BBox or Geometry
:return: dictionary with parameters
:return: url to Sentinel Hub's OGC service for this product.
:rtype: str
"""
url = self.get_base_url(request)
authority = self.instance_id if hasattr(self, 'instance_id') else request.theme
params = self._get_common_url_parameters(request)
if request.service_type in (ServiceType.WMS, ServiceType.WCS):
params = {**params, **self._get_wms_wcs_url_parameters(request, date)}
if request.service_type is ServiceType.WMS:
params = {**params, **self._get_wms_url_parameters(request, size_x, size_y)}
elif request.service_type is ServiceType.WCS:
params = {**params, **self._get_wcs_url_parameters(request, size_x, size_y)}
elif request.service_type is ServiceType.FIS:
params = {**params, **self._get_fis_parameters(request, geometry)}
return '{}/{}?{}'.format(url, authority, urlencode(params)) | [
"def",
"get_url",
"(",
"self",
",",
"request",
",",
"*",
",",
"date",
"=",
"None",
",",
"size_x",
"=",
"None",
",",
"size_y",
"=",
"None",
",",
"geometry",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"get_base_url",
"(",
"request",
")",
"authority",
"=",
"self",
".",
"instance_id",
"if",
"hasattr",
"(",
"self",
",",
"'instance_id'",
")",
"else",
"request",
".",
"theme",
"params",
"=",
"self",
".",
"_get_common_url_parameters",
"(",
"request",
")",
"if",
"request",
".",
"service_type",
"in",
"(",
"ServiceType",
".",
"WMS",
",",
"ServiceType",
".",
"WCS",
")",
":",
"params",
"=",
"{",
"*",
"*",
"params",
",",
"*",
"*",
"self",
".",
"_get_wms_wcs_url_parameters",
"(",
"request",
",",
"date",
")",
"}",
"if",
"request",
".",
"service_type",
"is",
"ServiceType",
".",
"WMS",
":",
"params",
"=",
"{",
"*",
"*",
"params",
",",
"*",
"*",
"self",
".",
"_get_wms_url_parameters",
"(",
"request",
",",
"size_x",
",",
"size_y",
")",
"}",
"elif",
"request",
".",
"service_type",
"is",
"ServiceType",
".",
"WCS",
":",
"params",
"=",
"{",
"*",
"*",
"params",
",",
"*",
"*",
"self",
".",
"_get_wcs_url_parameters",
"(",
"request",
",",
"size_x",
",",
"size_y",
")",
"}",
"elif",
"request",
".",
"service_type",
"is",
"ServiceType",
".",
"FIS",
":",
"params",
"=",
"{",
"*",
"*",
"params",
",",
"*",
"*",
"self",
".",
"_get_fis_parameters",
"(",
"request",
",",
"geometry",
")",
"}",
"return",
"'{}/{}?{}'",
".",
"format",
"(",
"url",
",",
"authority",
",",
"urlencode",
"(",
"params",
")",
")"
] | Returns url to Sentinel Hub's OGC service for the product specified by the OgcRequest and date.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param date: acquisition date or None
:type date: datetime.datetime or None
:param size_x: horizontal image dimension
:type size_x: int or str
:param size_y: vertical image dimension
:type size_y: int or str
:type geometry: list of BBox or Geometry
:return: dictionary with parameters
:return: url to Sentinel Hub's OGC service for this product.
:rtype: str | [
"Returns",
"url",
"to",
"Sentinel",
"Hub",
"s",
"OGC",
"service",
"for",
"the",
"product",
"specified",
"by",
"the",
"OgcRequest",
"and",
"date",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L121-L150 |
229,168 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService.get_base_url | def get_base_url(self, request):
""" Creates base url string.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:return: base string for url to Sentinel Hub's OGC service for this product.
:rtype: str
"""
url = self.base_url + request.service_type.value
# These 2 lines are temporal and will be removed after the use of uswest url wont be required anymore:
if hasattr(request, 'data_source') and request.data_source.is_uswest_source():
url = 'https://services-uswest2.sentinel-hub.com/ogc/{}'.format(request.service_type.value)
if hasattr(request, 'data_source') and request.data_source not in DataSource.get_available_sources():
raise ValueError("{} is not available for service at ogc_base_url={}".format(request.data_source,
SHConfig().ogc_base_url))
return url | python | def get_base_url(self, request):
""" Creates base url string.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:return: base string for url to Sentinel Hub's OGC service for this product.
:rtype: str
"""
url = self.base_url + request.service_type.value
# These 2 lines are temporal and will be removed after the use of uswest url wont be required anymore:
if hasattr(request, 'data_source') and request.data_source.is_uswest_source():
url = 'https://services-uswest2.sentinel-hub.com/ogc/{}'.format(request.service_type.value)
if hasattr(request, 'data_source') and request.data_source not in DataSource.get_available_sources():
raise ValueError("{} is not available for service at ogc_base_url={}".format(request.data_source,
SHConfig().ogc_base_url))
return url | [
"def",
"get_base_url",
"(",
"self",
",",
"request",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"request",
".",
"service_type",
".",
"value",
"# These 2 lines are temporal and will be removed after the use of uswest url wont be required anymore:",
"if",
"hasattr",
"(",
"request",
",",
"'data_source'",
")",
"and",
"request",
".",
"data_source",
".",
"is_uswest_source",
"(",
")",
":",
"url",
"=",
"'https://services-uswest2.sentinel-hub.com/ogc/{}'",
".",
"format",
"(",
"request",
".",
"service_type",
".",
"value",
")",
"if",
"hasattr",
"(",
"request",
",",
"'data_source'",
")",
"and",
"request",
".",
"data_source",
"not",
"in",
"DataSource",
".",
"get_available_sources",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"{} is not available for service at ogc_base_url={}\"",
".",
"format",
"(",
"request",
".",
"data_source",
",",
"SHConfig",
"(",
")",
".",
"ogc_base_url",
")",
")",
"return",
"url"
] | Creates base url string.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:return: base string for url to Sentinel Hub's OGC service for this product.
:rtype: str | [
"Creates",
"base",
"url",
"string",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L152-L168 |
229,169 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService._get_common_url_parameters | def _get_common_url_parameters(request):
""" Returns parameters common dictionary for WMS, WCS and FIS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:return: dictionary with parameters
:rtype: dict
"""
params = {
'SERVICE': request.service_type.value
}
if hasattr(request, 'maxcc'):
params['MAXCC'] = 100.0 * request.maxcc
if hasattr(request, 'custom_url_params') and request.custom_url_params is not None:
params = {**params,
**{k.value: str(v) for k, v in request.custom_url_params.items()}}
if CustomUrlParam.EVALSCRIPT.value in params:
evalscript = params[CustomUrlParam.EVALSCRIPT.value]
params[CustomUrlParam.EVALSCRIPT.value] = b64encode(evalscript.encode()).decode()
if CustomUrlParam.GEOMETRY.value in params:
geometry = params[CustomUrlParam.GEOMETRY.value]
crs = request.bbox.crs
if isinstance(geometry, Geometry):
if geometry.crs is not crs:
raise ValueError('Geometry object in custom_url_params should have the same CRS as given BBox')
else:
geometry = Geometry(geometry, crs)
if geometry.crs is CRS.WGS84:
geometry = geometry.reverse()
params[CustomUrlParam.GEOMETRY.value] = geometry.wkt
return params | python | def _get_common_url_parameters(request):
""" Returns parameters common dictionary for WMS, WCS and FIS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:return: dictionary with parameters
:rtype: dict
"""
params = {
'SERVICE': request.service_type.value
}
if hasattr(request, 'maxcc'):
params['MAXCC'] = 100.0 * request.maxcc
if hasattr(request, 'custom_url_params') and request.custom_url_params is not None:
params = {**params,
**{k.value: str(v) for k, v in request.custom_url_params.items()}}
if CustomUrlParam.EVALSCRIPT.value in params:
evalscript = params[CustomUrlParam.EVALSCRIPT.value]
params[CustomUrlParam.EVALSCRIPT.value] = b64encode(evalscript.encode()).decode()
if CustomUrlParam.GEOMETRY.value in params:
geometry = params[CustomUrlParam.GEOMETRY.value]
crs = request.bbox.crs
if isinstance(geometry, Geometry):
if geometry.crs is not crs:
raise ValueError('Geometry object in custom_url_params should have the same CRS as given BBox')
else:
geometry = Geometry(geometry, crs)
if geometry.crs is CRS.WGS84:
geometry = geometry.reverse()
params[CustomUrlParam.GEOMETRY.value] = geometry.wkt
return params | [
"def",
"_get_common_url_parameters",
"(",
"request",
")",
":",
"params",
"=",
"{",
"'SERVICE'",
":",
"request",
".",
"service_type",
".",
"value",
"}",
"if",
"hasattr",
"(",
"request",
",",
"'maxcc'",
")",
":",
"params",
"[",
"'MAXCC'",
"]",
"=",
"100.0",
"*",
"request",
".",
"maxcc",
"if",
"hasattr",
"(",
"request",
",",
"'custom_url_params'",
")",
"and",
"request",
".",
"custom_url_params",
"is",
"not",
"None",
":",
"params",
"=",
"{",
"*",
"*",
"params",
",",
"*",
"*",
"{",
"k",
".",
"value",
":",
"str",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"request",
".",
"custom_url_params",
".",
"items",
"(",
")",
"}",
"}",
"if",
"CustomUrlParam",
".",
"EVALSCRIPT",
".",
"value",
"in",
"params",
":",
"evalscript",
"=",
"params",
"[",
"CustomUrlParam",
".",
"EVALSCRIPT",
".",
"value",
"]",
"params",
"[",
"CustomUrlParam",
".",
"EVALSCRIPT",
".",
"value",
"]",
"=",
"b64encode",
"(",
"evalscript",
".",
"encode",
"(",
")",
")",
".",
"decode",
"(",
")",
"if",
"CustomUrlParam",
".",
"GEOMETRY",
".",
"value",
"in",
"params",
":",
"geometry",
"=",
"params",
"[",
"CustomUrlParam",
".",
"GEOMETRY",
".",
"value",
"]",
"crs",
"=",
"request",
".",
"bbox",
".",
"crs",
"if",
"isinstance",
"(",
"geometry",
",",
"Geometry",
")",
":",
"if",
"geometry",
".",
"crs",
"is",
"not",
"crs",
":",
"raise",
"ValueError",
"(",
"'Geometry object in custom_url_params should have the same CRS as given BBox'",
")",
"else",
":",
"geometry",
"=",
"Geometry",
"(",
"geometry",
",",
"crs",
")",
"if",
"geometry",
".",
"crs",
"is",
"CRS",
".",
"WGS84",
":",
"geometry",
"=",
"geometry",
".",
"reverse",
"(",
")",
"params",
"[",
"CustomUrlParam",
".",
"GEOMETRY",
".",
"value",
"]",
"=",
"geometry",
".",
"wkt",
"return",
"params"
] | Returns parameters common dictionary for WMS, WCS and FIS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:return: dictionary with parameters
:rtype: dict | [
"Returns",
"parameters",
"common",
"dictionary",
"for",
"WMS",
"WCS",
"and",
"FIS",
"request",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L171-L209 |
229,170 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService._get_wms_wcs_url_parameters | def _get_wms_wcs_url_parameters(request, date):
""" Returns parameters common dictionary for WMS and WCS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param date: acquisition date or None
:type date: datetime.datetime or None
:return: dictionary with parameters
:rtype: dict
"""
params = {
'BBOX': str(request.bbox.reverse()) if request.bbox.crs is CRS.WGS84 else str(request.bbox),
'FORMAT': MimeType.get_string(request.image_format),
'CRS': CRS.ogc_string(request.bbox.crs),
}
if date is not None:
start_date = date if request.time_difference < datetime.timedelta(
seconds=0) else date - request.time_difference
end_date = date if request.time_difference < datetime.timedelta(
seconds=0) else date + request.time_difference
params['TIME'] = '{}/{}'.format(start_date.isoformat(), end_date.isoformat())
return params | python | def _get_wms_wcs_url_parameters(request, date):
""" Returns parameters common dictionary for WMS and WCS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param date: acquisition date or None
:type date: datetime.datetime or None
:return: dictionary with parameters
:rtype: dict
"""
params = {
'BBOX': str(request.bbox.reverse()) if request.bbox.crs is CRS.WGS84 else str(request.bbox),
'FORMAT': MimeType.get_string(request.image_format),
'CRS': CRS.ogc_string(request.bbox.crs),
}
if date is not None:
start_date = date if request.time_difference < datetime.timedelta(
seconds=0) else date - request.time_difference
end_date = date if request.time_difference < datetime.timedelta(
seconds=0) else date + request.time_difference
params['TIME'] = '{}/{}'.format(start_date.isoformat(), end_date.isoformat())
return params | [
"def",
"_get_wms_wcs_url_parameters",
"(",
"request",
",",
"date",
")",
":",
"params",
"=",
"{",
"'BBOX'",
":",
"str",
"(",
"request",
".",
"bbox",
".",
"reverse",
"(",
")",
")",
"if",
"request",
".",
"bbox",
".",
"crs",
"is",
"CRS",
".",
"WGS84",
"else",
"str",
"(",
"request",
".",
"bbox",
")",
",",
"'FORMAT'",
":",
"MimeType",
".",
"get_string",
"(",
"request",
".",
"image_format",
")",
",",
"'CRS'",
":",
"CRS",
".",
"ogc_string",
"(",
"request",
".",
"bbox",
".",
"crs",
")",
",",
"}",
"if",
"date",
"is",
"not",
"None",
":",
"start_date",
"=",
"date",
"if",
"request",
".",
"time_difference",
"<",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"0",
")",
"else",
"date",
"-",
"request",
".",
"time_difference",
"end_date",
"=",
"date",
"if",
"request",
".",
"time_difference",
"<",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"0",
")",
"else",
"date",
"+",
"request",
".",
"time_difference",
"params",
"[",
"'TIME'",
"]",
"=",
"'{}/{}'",
".",
"format",
"(",
"start_date",
".",
"isoformat",
"(",
")",
",",
"end_date",
".",
"isoformat",
"(",
")",
")",
"return",
"params"
] | Returns parameters common dictionary for WMS and WCS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param date: acquisition date or None
:type date: datetime.datetime or None
:return: dictionary with parameters
:rtype: dict | [
"Returns",
"parameters",
"common",
"dictionary",
"for",
"WMS",
"and",
"WCS",
"request",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L212-L235 |
229,171 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService._get_fis_parameters | def _get_fis_parameters(request, geometry):
""" Returns parameters dictionary for FIS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param geometry: list of bounding boxes or geometries
:type geometry: list of BBox or Geometry
:return: dictionary with parameters
:rtype: dict
"""
date_interval = parse_time_interval(request.time)
params = {
'CRS': CRS.ogc_string(geometry.crs),
'LAYER': request.layer,
'RESOLUTION': request.resolution,
'TIME': '{}/{}'.format(date_interval[0], date_interval[1])
}
if not isinstance(geometry, (BBox, Geometry)):
raise ValueError('Each geometry must be an instance of sentinelhub.{} or sentinelhub.{} but {} '
'found'.format(BBox.__name__, Geometry.__name__, geometry))
if geometry.crs is CRS.WGS84:
geometry = geometry.reverse()
if isinstance(geometry, Geometry):
params['GEOMETRY'] = geometry.wkt
else:
params['BBOX'] = str(geometry)
if request.bins:
params['BINS'] = request.bins
if request.histogram_type:
params['TYPE'] = request.histogram_type.value
return params | python | def _get_fis_parameters(request, geometry):
""" Returns parameters dictionary for FIS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param geometry: list of bounding boxes or geometries
:type geometry: list of BBox or Geometry
:return: dictionary with parameters
:rtype: dict
"""
date_interval = parse_time_interval(request.time)
params = {
'CRS': CRS.ogc_string(geometry.crs),
'LAYER': request.layer,
'RESOLUTION': request.resolution,
'TIME': '{}/{}'.format(date_interval[0], date_interval[1])
}
if not isinstance(geometry, (BBox, Geometry)):
raise ValueError('Each geometry must be an instance of sentinelhub.{} or sentinelhub.{} but {} '
'found'.format(BBox.__name__, Geometry.__name__, geometry))
if geometry.crs is CRS.WGS84:
geometry = geometry.reverse()
if isinstance(geometry, Geometry):
params['GEOMETRY'] = geometry.wkt
else:
params['BBOX'] = str(geometry)
if request.bins:
params['BINS'] = request.bins
if request.histogram_type:
params['TYPE'] = request.histogram_type.value
return params | [
"def",
"_get_fis_parameters",
"(",
"request",
",",
"geometry",
")",
":",
"date_interval",
"=",
"parse_time_interval",
"(",
"request",
".",
"time",
")",
"params",
"=",
"{",
"'CRS'",
":",
"CRS",
".",
"ogc_string",
"(",
"geometry",
".",
"crs",
")",
",",
"'LAYER'",
":",
"request",
".",
"layer",
",",
"'RESOLUTION'",
":",
"request",
".",
"resolution",
",",
"'TIME'",
":",
"'{}/{}'",
".",
"format",
"(",
"date_interval",
"[",
"0",
"]",
",",
"date_interval",
"[",
"1",
"]",
")",
"}",
"if",
"not",
"isinstance",
"(",
"geometry",
",",
"(",
"BBox",
",",
"Geometry",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Each geometry must be an instance of sentinelhub.{} or sentinelhub.{} but {} '",
"'found'",
".",
"format",
"(",
"BBox",
".",
"__name__",
",",
"Geometry",
".",
"__name__",
",",
"geometry",
")",
")",
"if",
"geometry",
".",
"crs",
"is",
"CRS",
".",
"WGS84",
":",
"geometry",
"=",
"geometry",
".",
"reverse",
"(",
")",
"if",
"isinstance",
"(",
"geometry",
",",
"Geometry",
")",
":",
"params",
"[",
"'GEOMETRY'",
"]",
"=",
"geometry",
".",
"wkt",
"else",
":",
"params",
"[",
"'BBOX'",
"]",
"=",
"str",
"(",
"geometry",
")",
"if",
"request",
".",
"bins",
":",
"params",
"[",
"'BINS'",
"]",
"=",
"request",
".",
"bins",
"if",
"request",
".",
"histogram_type",
":",
"params",
"[",
"'TYPE'",
"]",
"=",
"request",
".",
"histogram_type",
".",
"value",
"return",
"params"
] | Returns parameters dictionary for FIS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param geometry: list of bounding boxes or geometries
:type geometry: list of BBox or Geometry
:return: dictionary with parameters
:rtype: dict | [
"Returns",
"parameters",
"dictionary",
"for",
"FIS",
"request",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L280-L315 |
229,172 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService.get_filename | def get_filename(request, date, size_x, size_y):
""" Get filename location
Returns the filename's location on disk where data is or is going to be stored.
The files are stored in the folder specified by the user when initialising OGC-type
of request. The name of the file has the following structure:
{service_type}_{layer}_{crs}_{bbox}_{time}_{size_x}X{size_y}_*{custom_url_params}.{image_format}
In case of `TIFF_d32f` a `'_tiff_depth32f'` is added at the end of the filename (before format suffix)
to differentiate it from 16-bit float tiff.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param date: acquisition date or None
:type date: datetime.datetime or None
:param size_x: horizontal image dimension
:type size_x: int or str
:param size_y: vertical image dimension
:type size_y: int or str
:return: filename for this request and date
:rtype: str
"""
filename = '_'.join([
str(request.service_type.value),
request.layer,
str(request.bbox.crs),
str(request.bbox).replace(',', '_'),
'' if date is None else date.strftime("%Y-%m-%dT%H-%M-%S"),
'{}X{}'.format(size_x, size_y)
])
filename = OgcImageService.filename_add_custom_url_params(filename, request)
return OgcImageService.finalize_filename(filename, request.image_format) | python | def get_filename(request, date, size_x, size_y):
""" Get filename location
Returns the filename's location on disk where data is or is going to be stored.
The files are stored in the folder specified by the user when initialising OGC-type
of request. The name of the file has the following structure:
{service_type}_{layer}_{crs}_{bbox}_{time}_{size_x}X{size_y}_*{custom_url_params}.{image_format}
In case of `TIFF_d32f` a `'_tiff_depth32f'` is added at the end of the filename (before format suffix)
to differentiate it from 16-bit float tiff.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param date: acquisition date or None
:type date: datetime.datetime or None
:param size_x: horizontal image dimension
:type size_x: int or str
:param size_y: vertical image dimension
:type size_y: int or str
:return: filename for this request and date
:rtype: str
"""
filename = '_'.join([
str(request.service_type.value),
request.layer,
str(request.bbox.crs),
str(request.bbox).replace(',', '_'),
'' if date is None else date.strftime("%Y-%m-%dT%H-%M-%S"),
'{}X{}'.format(size_x, size_y)
])
filename = OgcImageService.filename_add_custom_url_params(filename, request)
return OgcImageService.finalize_filename(filename, request.image_format) | [
"def",
"get_filename",
"(",
"request",
",",
"date",
",",
"size_x",
",",
"size_y",
")",
":",
"filename",
"=",
"'_'",
".",
"join",
"(",
"[",
"str",
"(",
"request",
".",
"service_type",
".",
"value",
")",
",",
"request",
".",
"layer",
",",
"str",
"(",
"request",
".",
"bbox",
".",
"crs",
")",
",",
"str",
"(",
"request",
".",
"bbox",
")",
".",
"replace",
"(",
"','",
",",
"'_'",
")",
",",
"''",
"if",
"date",
"is",
"None",
"else",
"date",
".",
"strftime",
"(",
"\"%Y-%m-%dT%H-%M-%S\"",
")",
",",
"'{}X{}'",
".",
"format",
"(",
"size_x",
",",
"size_y",
")",
"]",
")",
"filename",
"=",
"OgcImageService",
".",
"filename_add_custom_url_params",
"(",
"filename",
",",
"request",
")",
"return",
"OgcImageService",
".",
"finalize_filename",
"(",
"filename",
",",
"request",
".",
"image_format",
")"
] | Get filename location
Returns the filename's location on disk where data is or is going to be stored.
The files are stored in the folder specified by the user when initialising OGC-type
of request. The name of the file has the following structure:
{service_type}_{layer}_{crs}_{bbox}_{time}_{size_x}X{size_y}_*{custom_url_params}.{image_format}
In case of `TIFF_d32f` a `'_tiff_depth32f'` is added at the end of the filename (before format suffix)
to differentiate it from 16-bit float tiff.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param date: acquisition date or None
:type date: datetime.datetime or None
:param size_x: horizontal image dimension
:type size_x: int or str
:param size_y: vertical image dimension
:type size_y: int or str
:return: filename for this request and date
:rtype: str | [
"Get",
"filename",
"location"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L318-L352 |
229,173 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService.filename_add_custom_url_params | def filename_add_custom_url_params(filename, request):
""" Adds custom url parameters to filename string
:param filename: Initial filename
:type filename: str
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:return: Filename with custom url parameters in the name
:rtype: str
"""
if hasattr(request, 'custom_url_params') and request.custom_url_params is not None:
for param, value in sorted(request.custom_url_params.items(),
key=lambda parameter_item: parameter_item[0].value):
filename = '_'.join([filename, param.value, str(value)])
return filename | python | def filename_add_custom_url_params(filename, request):
""" Adds custom url parameters to filename string
:param filename: Initial filename
:type filename: str
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:return: Filename with custom url parameters in the name
:rtype: str
"""
if hasattr(request, 'custom_url_params') and request.custom_url_params is not None:
for param, value in sorted(request.custom_url_params.items(),
key=lambda parameter_item: parameter_item[0].value):
filename = '_'.join([filename, param.value, str(value)])
return filename | [
"def",
"filename_add_custom_url_params",
"(",
"filename",
",",
"request",
")",
":",
"if",
"hasattr",
"(",
"request",
",",
"'custom_url_params'",
")",
"and",
"request",
".",
"custom_url_params",
"is",
"not",
"None",
":",
"for",
"param",
",",
"value",
"in",
"sorted",
"(",
"request",
".",
"custom_url_params",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"parameter_item",
":",
"parameter_item",
"[",
"0",
"]",
".",
"value",
")",
":",
"filename",
"=",
"'_'",
".",
"join",
"(",
"[",
"filename",
",",
"param",
".",
"value",
",",
"str",
"(",
"value",
")",
"]",
")",
"return",
"filename"
] | Adds custom url parameters to filename string
:param filename: Initial filename
:type filename: str
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:return: Filename with custom url parameters in the name
:rtype: str | [
"Adds",
"custom",
"url",
"parameters",
"to",
"filename",
"string"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L355-L370 |
229,174 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService.finalize_filename | def finalize_filename(filename, file_format=None):
""" Replaces invalid characters in filename string, adds image extension and reduces filename length
:param filename: Incomplete filename string
:type filename: str
:param file_format: Format which will be used for filename extension
:type file_format: MimeType
:return: Final filename string
:rtype: str
"""
for char in [' ', '/', '\\', '|', ';', ':', '\n', '\t']:
filename = filename.replace(char, '')
if file_format:
suffix = str(file_format.value)
if file_format.is_tiff_format() and file_format is not MimeType.TIFF:
suffix = str(MimeType.TIFF.value)
filename = '_'.join([filename, str(file_format.value).replace(';', '_')])
filename = '.'.join([filename[:254 - len(suffix)], suffix])
LOGGER.debug("filename=%s", filename)
return filename | python | def finalize_filename(filename, file_format=None):
""" Replaces invalid characters in filename string, adds image extension and reduces filename length
:param filename: Incomplete filename string
:type filename: str
:param file_format: Format which will be used for filename extension
:type file_format: MimeType
:return: Final filename string
:rtype: str
"""
for char in [' ', '/', '\\', '|', ';', ':', '\n', '\t']:
filename = filename.replace(char, '')
if file_format:
suffix = str(file_format.value)
if file_format.is_tiff_format() and file_format is not MimeType.TIFF:
suffix = str(MimeType.TIFF.value)
filename = '_'.join([filename, str(file_format.value).replace(';', '_')])
filename = '.'.join([filename[:254 - len(suffix)], suffix])
LOGGER.debug("filename=%s", filename)
return filename | [
"def",
"finalize_filename",
"(",
"filename",
",",
"file_format",
"=",
"None",
")",
":",
"for",
"char",
"in",
"[",
"' '",
",",
"'/'",
",",
"'\\\\'",
",",
"'|'",
",",
"';'",
",",
"':'",
",",
"'\\n'",
",",
"'\\t'",
"]",
":",
"filename",
"=",
"filename",
".",
"replace",
"(",
"char",
",",
"''",
")",
"if",
"file_format",
":",
"suffix",
"=",
"str",
"(",
"file_format",
".",
"value",
")",
"if",
"file_format",
".",
"is_tiff_format",
"(",
")",
"and",
"file_format",
"is",
"not",
"MimeType",
".",
"TIFF",
":",
"suffix",
"=",
"str",
"(",
"MimeType",
".",
"TIFF",
".",
"value",
")",
"filename",
"=",
"'_'",
".",
"join",
"(",
"[",
"filename",
",",
"str",
"(",
"file_format",
".",
"value",
")",
".",
"replace",
"(",
"';'",
",",
"'_'",
")",
"]",
")",
"filename",
"=",
"'.'",
".",
"join",
"(",
"[",
"filename",
"[",
":",
"254",
"-",
"len",
"(",
"suffix",
")",
"]",
",",
"suffix",
"]",
")",
"LOGGER",
".",
"debug",
"(",
"\"filename=%s\"",
",",
"filename",
")",
"return",
"filename"
] | Replaces invalid characters in filename string, adds image extension and reduces filename length
:param filename: Incomplete filename string
:type filename: str
:param file_format: Format which will be used for filename extension
:type file_format: MimeType
:return: Final filename string
:rtype: str | [
"Replaces",
"invalid",
"characters",
"in",
"filename",
"string",
"adds",
"image",
"extension",
"and",
"reduces",
"filename",
"length"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L373-L396 |
229,175 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService.get_dates | def get_dates(self, request):
""" Get available Sentinel-2 acquisitions at least time_difference apart
List of all available Sentinel-2 acquisitions for given bbox with max cloud coverage and the specified
time interval. When a single time is specified the request will return that specific date, if it exists.
If a time range is specified the result is a list of all scenes between the specified dates conforming to
the cloud coverage criteria. Most recent acquisition being first in the list.
When a time_difference threshold is set to a positive value, the function filters out all datetimes which
are within the time difference. The oldest datetime is preserved, all others all deleted.
:param request: OGC-type request
:type request: WmsRequest or WcsRequest
:return: List of dates of existing acquisitions for the given request
:rtype: list(datetime.datetime) or [None]
"""
if DataSource.is_timeless(request.data_source):
return [None]
date_interval = parse_time_interval(request.time)
LOGGER.debug('date_interval=%s', date_interval)
if request.wfs_iterator is None:
self.wfs_iterator = WebFeatureService(request.bbox, date_interval, data_source=request.data_source,
maxcc=request.maxcc, base_url=self.base_url,
instance_id=self.instance_id)
else:
self.wfs_iterator = request.wfs_iterator
dates = sorted(set(self.wfs_iterator.get_dates()))
if request.time is OgcConstants.LATEST:
dates = dates[-1:]
return OgcService._filter_dates(dates, request.time_difference) | python | def get_dates(self, request):
""" Get available Sentinel-2 acquisitions at least time_difference apart
List of all available Sentinel-2 acquisitions for given bbox with max cloud coverage and the specified
time interval. When a single time is specified the request will return that specific date, if it exists.
If a time range is specified the result is a list of all scenes between the specified dates conforming to
the cloud coverage criteria. Most recent acquisition being first in the list.
When a time_difference threshold is set to a positive value, the function filters out all datetimes which
are within the time difference. The oldest datetime is preserved, all others all deleted.
:param request: OGC-type request
:type request: WmsRequest or WcsRequest
:return: List of dates of existing acquisitions for the given request
:rtype: list(datetime.datetime) or [None]
"""
if DataSource.is_timeless(request.data_source):
return [None]
date_interval = parse_time_interval(request.time)
LOGGER.debug('date_interval=%s', date_interval)
if request.wfs_iterator is None:
self.wfs_iterator = WebFeatureService(request.bbox, date_interval, data_source=request.data_source,
maxcc=request.maxcc, base_url=self.base_url,
instance_id=self.instance_id)
else:
self.wfs_iterator = request.wfs_iterator
dates = sorted(set(self.wfs_iterator.get_dates()))
if request.time is OgcConstants.LATEST:
dates = dates[-1:]
return OgcService._filter_dates(dates, request.time_difference) | [
"def",
"get_dates",
"(",
"self",
",",
"request",
")",
":",
"if",
"DataSource",
".",
"is_timeless",
"(",
"request",
".",
"data_source",
")",
":",
"return",
"[",
"None",
"]",
"date_interval",
"=",
"parse_time_interval",
"(",
"request",
".",
"time",
")",
"LOGGER",
".",
"debug",
"(",
"'date_interval=%s'",
",",
"date_interval",
")",
"if",
"request",
".",
"wfs_iterator",
"is",
"None",
":",
"self",
".",
"wfs_iterator",
"=",
"WebFeatureService",
"(",
"request",
".",
"bbox",
",",
"date_interval",
",",
"data_source",
"=",
"request",
".",
"data_source",
",",
"maxcc",
"=",
"request",
".",
"maxcc",
",",
"base_url",
"=",
"self",
".",
"base_url",
",",
"instance_id",
"=",
"self",
".",
"instance_id",
")",
"else",
":",
"self",
".",
"wfs_iterator",
"=",
"request",
".",
"wfs_iterator",
"dates",
"=",
"sorted",
"(",
"set",
"(",
"self",
".",
"wfs_iterator",
".",
"get_dates",
"(",
")",
")",
")",
"if",
"request",
".",
"time",
"is",
"OgcConstants",
".",
"LATEST",
":",
"dates",
"=",
"dates",
"[",
"-",
"1",
":",
"]",
"return",
"OgcService",
".",
"_filter_dates",
"(",
"dates",
",",
"request",
".",
"time_difference",
")"
] | Get available Sentinel-2 acquisitions at least time_difference apart
List of all available Sentinel-2 acquisitions for given bbox with max cloud coverage and the specified
time interval. When a single time is specified the request will return that specific date, if it exists.
If a time range is specified the result is a list of all scenes between the specified dates conforming to
the cloud coverage criteria. Most recent acquisition being first in the list.
When a time_difference threshold is set to a positive value, the function filters out all datetimes which
are within the time difference. The oldest datetime is preserved, all others all deleted.
:param request: OGC-type request
:type request: WmsRequest or WcsRequest
:return: List of dates of existing acquisitions for the given request
:rtype: list(datetime.datetime) or [None] | [
"Get",
"available",
"Sentinel",
"-",
"2",
"acquisitions",
"at",
"least",
"time_difference",
"apart"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L398-L432 |
229,176 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService.get_image_dimensions | def get_image_dimensions(request):
"""
Verifies or calculates image dimensions.
:param request: OGC-type request
:type request: WmsRequest or WcsRequest
:return: horizontal and vertical dimensions of requested image
:rtype: (int or str, int or str)
"""
if request.service_type is ServiceType.WCS or (isinstance(request.size_x, int) and
isinstance(request.size_y, int)):
return request.size_x, request.size_y
if not isinstance(request.size_x, int) and not isinstance(request.size_y, int):
raise ValueError("At least one of parameters 'width' and 'height' must have an integer value")
missing_dimension = get_image_dimension(request.bbox, width=request.size_x, height=request.size_y)
if request.size_x is None:
return missing_dimension, request.size_y
if request.size_y is None:
return request.size_x, missing_dimension
raise ValueError("Parameters 'width' and 'height' must be integers or None") | python | def get_image_dimensions(request):
"""
Verifies or calculates image dimensions.
:param request: OGC-type request
:type request: WmsRequest or WcsRequest
:return: horizontal and vertical dimensions of requested image
:rtype: (int or str, int or str)
"""
if request.service_type is ServiceType.WCS or (isinstance(request.size_x, int) and
isinstance(request.size_y, int)):
return request.size_x, request.size_y
if not isinstance(request.size_x, int) and not isinstance(request.size_y, int):
raise ValueError("At least one of parameters 'width' and 'height' must have an integer value")
missing_dimension = get_image_dimension(request.bbox, width=request.size_x, height=request.size_y)
if request.size_x is None:
return missing_dimension, request.size_y
if request.size_y is None:
return request.size_x, missing_dimension
raise ValueError("Parameters 'width' and 'height' must be integers or None") | [
"def",
"get_image_dimensions",
"(",
"request",
")",
":",
"if",
"request",
".",
"service_type",
"is",
"ServiceType",
".",
"WCS",
"or",
"(",
"isinstance",
"(",
"request",
".",
"size_x",
",",
"int",
")",
"and",
"isinstance",
"(",
"request",
".",
"size_y",
",",
"int",
")",
")",
":",
"return",
"request",
".",
"size_x",
",",
"request",
".",
"size_y",
"if",
"not",
"isinstance",
"(",
"request",
".",
"size_x",
",",
"int",
")",
"and",
"not",
"isinstance",
"(",
"request",
".",
"size_y",
",",
"int",
")",
":",
"raise",
"ValueError",
"(",
"\"At least one of parameters 'width' and 'height' must have an integer value\"",
")",
"missing_dimension",
"=",
"get_image_dimension",
"(",
"request",
".",
"bbox",
",",
"width",
"=",
"request",
".",
"size_x",
",",
"height",
"=",
"request",
".",
"size_y",
")",
"if",
"request",
".",
"size_x",
"is",
"None",
":",
"return",
"missing_dimension",
",",
"request",
".",
"size_y",
"if",
"request",
".",
"size_y",
"is",
"None",
":",
"return",
"request",
".",
"size_x",
",",
"missing_dimension",
"raise",
"ValueError",
"(",
"\"Parameters 'width' and 'height' must be integers or None\"",
")"
] | Verifies or calculates image dimensions.
:param request: OGC-type request
:type request: WmsRequest or WcsRequest
:return: horizontal and vertical dimensions of requested image
:rtype: (int or str, int or str) | [
"Verifies",
"or",
"calculates",
"image",
"dimensions",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L435-L454 |
229,177 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | WebFeatureService._fetch_features | def _fetch_features(self):
"""Collects data from WFS service
:return: dictionary containing info about product tiles
:rtype: dict
"""
if self.feature_offset is None:
return
main_url = '{}{}/{}?'.format(self.base_url, ServiceType.WFS.value, self.instance_id)
params = {'SERVICE': ServiceType.WFS.value,
'REQUEST': 'GetFeature',
'TYPENAMES': DataSource.get_wfs_typename(self.data_source),
'BBOX': str(self.bbox.reverse()) if self.bbox.crs is CRS.WGS84 else str(self.bbox),
'OUTPUTFORMAT': MimeType.get_string(MimeType.JSON),
'SRSNAME': CRS.ogc_string(self.bbox.crs),
'TIME': '{}/{}'.format(self.time_interval[0], self.time_interval[1]),
'MAXCC': 100.0 * self.maxcc,
'MAXFEATURES': SHConfig().max_wfs_records_per_query,
'FEATURE_OFFSET': self.feature_offset}
url = main_url + urlencode(params)
LOGGER.debug("URL=%s", url)
response = get_json(url)
is_sentinel1 = self.data_source.is_sentinel1()
for tile_info in response["features"]:
if not is_sentinel1 or self._sentinel1_product_check(tile_info['properties']['id'], self.data_source):
self.tile_list.append(tile_info)
if len(response["features"]) < SHConfig().max_wfs_records_per_query:
self.feature_offset = None
else:
self.feature_offset += SHConfig().max_wfs_records_per_query | python | def _fetch_features(self):
"""Collects data from WFS service
:return: dictionary containing info about product tiles
:rtype: dict
"""
if self.feature_offset is None:
return
main_url = '{}{}/{}?'.format(self.base_url, ServiceType.WFS.value, self.instance_id)
params = {'SERVICE': ServiceType.WFS.value,
'REQUEST': 'GetFeature',
'TYPENAMES': DataSource.get_wfs_typename(self.data_source),
'BBOX': str(self.bbox.reverse()) if self.bbox.crs is CRS.WGS84 else str(self.bbox),
'OUTPUTFORMAT': MimeType.get_string(MimeType.JSON),
'SRSNAME': CRS.ogc_string(self.bbox.crs),
'TIME': '{}/{}'.format(self.time_interval[0], self.time_interval[1]),
'MAXCC': 100.0 * self.maxcc,
'MAXFEATURES': SHConfig().max_wfs_records_per_query,
'FEATURE_OFFSET': self.feature_offset}
url = main_url + urlencode(params)
LOGGER.debug("URL=%s", url)
response = get_json(url)
is_sentinel1 = self.data_source.is_sentinel1()
for tile_info in response["features"]:
if not is_sentinel1 or self._sentinel1_product_check(tile_info['properties']['id'], self.data_source):
self.tile_list.append(tile_info)
if len(response["features"]) < SHConfig().max_wfs_records_per_query:
self.feature_offset = None
else:
self.feature_offset += SHConfig().max_wfs_records_per_query | [
"def",
"_fetch_features",
"(",
"self",
")",
":",
"if",
"self",
".",
"feature_offset",
"is",
"None",
":",
"return",
"main_url",
"=",
"'{}{}/{}?'",
".",
"format",
"(",
"self",
".",
"base_url",
",",
"ServiceType",
".",
"WFS",
".",
"value",
",",
"self",
".",
"instance_id",
")",
"params",
"=",
"{",
"'SERVICE'",
":",
"ServiceType",
".",
"WFS",
".",
"value",
",",
"'REQUEST'",
":",
"'GetFeature'",
",",
"'TYPENAMES'",
":",
"DataSource",
".",
"get_wfs_typename",
"(",
"self",
".",
"data_source",
")",
",",
"'BBOX'",
":",
"str",
"(",
"self",
".",
"bbox",
".",
"reverse",
"(",
")",
")",
"if",
"self",
".",
"bbox",
".",
"crs",
"is",
"CRS",
".",
"WGS84",
"else",
"str",
"(",
"self",
".",
"bbox",
")",
",",
"'OUTPUTFORMAT'",
":",
"MimeType",
".",
"get_string",
"(",
"MimeType",
".",
"JSON",
")",
",",
"'SRSNAME'",
":",
"CRS",
".",
"ogc_string",
"(",
"self",
".",
"bbox",
".",
"crs",
")",
",",
"'TIME'",
":",
"'{}/{}'",
".",
"format",
"(",
"self",
".",
"time_interval",
"[",
"0",
"]",
",",
"self",
".",
"time_interval",
"[",
"1",
"]",
")",
",",
"'MAXCC'",
":",
"100.0",
"*",
"self",
".",
"maxcc",
",",
"'MAXFEATURES'",
":",
"SHConfig",
"(",
")",
".",
"max_wfs_records_per_query",
",",
"'FEATURE_OFFSET'",
":",
"self",
".",
"feature_offset",
"}",
"url",
"=",
"main_url",
"+",
"urlencode",
"(",
"params",
")",
"LOGGER",
".",
"debug",
"(",
"\"URL=%s\"",
",",
"url",
")",
"response",
"=",
"get_json",
"(",
"url",
")",
"is_sentinel1",
"=",
"self",
".",
"data_source",
".",
"is_sentinel1",
"(",
")",
"for",
"tile_info",
"in",
"response",
"[",
"\"features\"",
"]",
":",
"if",
"not",
"is_sentinel1",
"or",
"self",
".",
"_sentinel1_product_check",
"(",
"tile_info",
"[",
"'properties'",
"]",
"[",
"'id'",
"]",
",",
"self",
".",
"data_source",
")",
":",
"self",
".",
"tile_list",
".",
"append",
"(",
"tile_info",
")",
"if",
"len",
"(",
"response",
"[",
"\"features\"",
"]",
")",
"<",
"SHConfig",
"(",
")",
".",
"max_wfs_records_per_query",
":",
"self",
".",
"feature_offset",
"=",
"None",
"else",
":",
"self",
".",
"feature_offset",
"+=",
"SHConfig",
"(",
")",
".",
"max_wfs_records_per_query"
] | Collects data from WFS service
:return: dictionary containing info about product tiles
:rtype: dict | [
"Collects",
"data",
"from",
"WFS",
"service"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L524-L558 |
229,178 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | WebFeatureService.get_dates | def get_dates(self):
""" Returns a list of acquisition times from tile info data
:return: List of acquisition times in the order returned by WFS service.
:rtype: list(datetime.datetime)
"""
return [datetime.datetime.strptime('{}T{}'.format(tile_info['properties']['date'],
tile_info['properties']['time'].split('.')[0]),
'%Y-%m-%dT%H:%M:%S') for tile_info in self] | python | def get_dates(self):
""" Returns a list of acquisition times from tile info data
:return: List of acquisition times in the order returned by WFS service.
:rtype: list(datetime.datetime)
"""
return [datetime.datetime.strptime('{}T{}'.format(tile_info['properties']['date'],
tile_info['properties']['time'].split('.')[0]),
'%Y-%m-%dT%H:%M:%S') for tile_info in self] | [
"def",
"get_dates",
"(",
"self",
")",
":",
"return",
"[",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"'{}T{}'",
".",
"format",
"(",
"tile_info",
"[",
"'properties'",
"]",
"[",
"'date'",
"]",
",",
"tile_info",
"[",
"'properties'",
"]",
"[",
"'time'",
"]",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
")",
",",
"'%Y-%m-%dT%H:%M:%S'",
")",
"for",
"tile_info",
"in",
"self",
"]"
] | Returns a list of acquisition times from tile info data
:return: List of acquisition times in the order returned by WFS service.
:rtype: list(datetime.datetime) | [
"Returns",
"a",
"list",
"of",
"acquisition",
"times",
"from",
"tile",
"info",
"data"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L560-L568 |
229,179 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | WebFeatureService._parse_tile_url | def _parse_tile_url(tile_url):
""" Extracts tile name, data and AWS index from tile URL
:param tile_url: Location of tile at AWS
:type: tile_url: str
:return: Tuple in a form (tile_name, date, aws_index)
:rtype: (str, str, int)
"""
props = tile_url.rsplit('/', 7)
return ''.join(props[1:4]), '-'.join(props[4:7]), int(props[7]) | python | def _parse_tile_url(tile_url):
""" Extracts tile name, data and AWS index from tile URL
:param tile_url: Location of tile at AWS
:type: tile_url: str
:return: Tuple in a form (tile_name, date, aws_index)
:rtype: (str, str, int)
"""
props = tile_url.rsplit('/', 7)
return ''.join(props[1:4]), '-'.join(props[4:7]), int(props[7]) | [
"def",
"_parse_tile_url",
"(",
"tile_url",
")",
":",
"props",
"=",
"tile_url",
".",
"rsplit",
"(",
"'/'",
",",
"7",
")",
"return",
"''",
".",
"join",
"(",
"props",
"[",
"1",
":",
"4",
"]",
")",
",",
"'-'",
".",
"join",
"(",
"props",
"[",
"4",
":",
"7",
"]",
")",
",",
"int",
"(",
"props",
"[",
"7",
"]",
")"
] | Extracts tile name, data and AWS index from tile URL
:param tile_url: Location of tile at AWS
:type: tile_url: str
:return: Tuple in a form (tile_name, date, aws_index)
:rtype: (str, str, int) | [
"Extracts",
"tile",
"name",
"data",
"and",
"AWS",
"index",
"from",
"tile",
"URL"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L587-L596 |
229,180 | sentinel-hub/sentinelhub-py | sentinelhub/time_utils.py | get_dates_in_range | def get_dates_in_range(start_date, end_date):
""" Get all dates within input start and end date in ISO 8601 format
:param start_date: start date in ISO 8601 format
:type start_date: str
:param end_date: end date in ISO 8601 format
:type end_date: str
:return: list of dates between start_date and end_date in ISO 8601 format
:rtype: list of str
"""
start_dt = iso_to_datetime(start_date)
end_dt = iso_to_datetime(end_date)
num_days = int((end_dt - start_dt).days)
return [datetime_to_iso(start_dt + datetime.timedelta(i)) for i in range(num_days + 1)] | python | def get_dates_in_range(start_date, end_date):
""" Get all dates within input start and end date in ISO 8601 format
:param start_date: start date in ISO 8601 format
:type start_date: str
:param end_date: end date in ISO 8601 format
:type end_date: str
:return: list of dates between start_date and end_date in ISO 8601 format
:rtype: list of str
"""
start_dt = iso_to_datetime(start_date)
end_dt = iso_to_datetime(end_date)
num_days = int((end_dt - start_dt).days)
return [datetime_to_iso(start_dt + datetime.timedelta(i)) for i in range(num_days + 1)] | [
"def",
"get_dates_in_range",
"(",
"start_date",
",",
"end_date",
")",
":",
"start_dt",
"=",
"iso_to_datetime",
"(",
"start_date",
")",
"end_dt",
"=",
"iso_to_datetime",
"(",
"end_date",
")",
"num_days",
"=",
"int",
"(",
"(",
"end_dt",
"-",
"start_dt",
")",
".",
"days",
")",
"return",
"[",
"datetime_to_iso",
"(",
"start_dt",
"+",
"datetime",
".",
"timedelta",
"(",
"i",
")",
")",
"for",
"i",
"in",
"range",
"(",
"num_days",
"+",
"1",
")",
"]"
] | Get all dates within input start and end date in ISO 8601 format
:param start_date: start date in ISO 8601 format
:type start_date: str
:param end_date: end date in ISO 8601 format
:type end_date: str
:return: list of dates between start_date and end_date in ISO 8601 format
:rtype: list of str | [
"Get",
"all",
"dates",
"within",
"input",
"start",
"and",
"end",
"date",
"in",
"ISO",
"8601",
"format"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/time_utils.py#L12-L25 |
229,181 | sentinel-hub/sentinelhub-py | sentinelhub/time_utils.py | iso_to_datetime | def iso_to_datetime(date):
""" Convert ISO 8601 time format to datetime format
This function converts a date in ISO format, e.g. ``2017-09-14`` to a `datetime` instance, e.g.
``datetime.datetime(2017,9,14,0,0)``
:param date: date in ISO 8601 format
:type date: str
:return: datetime instance
:rtype: datetime
"""
chunks = list(map(int, date.split('T')[0].split('-')))
return datetime.datetime(chunks[0], chunks[1], chunks[2]) | python | def iso_to_datetime(date):
""" Convert ISO 8601 time format to datetime format
This function converts a date in ISO format, e.g. ``2017-09-14`` to a `datetime` instance, e.g.
``datetime.datetime(2017,9,14,0,0)``
:param date: date in ISO 8601 format
:type date: str
:return: datetime instance
:rtype: datetime
"""
chunks = list(map(int, date.split('T')[0].split('-')))
return datetime.datetime(chunks[0], chunks[1], chunks[2]) | [
"def",
"iso_to_datetime",
"(",
"date",
")",
":",
"chunks",
"=",
"list",
"(",
"map",
"(",
"int",
",",
"date",
".",
"split",
"(",
"'T'",
")",
"[",
"0",
"]",
".",
"split",
"(",
"'-'",
")",
")",
")",
"return",
"datetime",
".",
"datetime",
"(",
"chunks",
"[",
"0",
"]",
",",
"chunks",
"[",
"1",
"]",
",",
"chunks",
"[",
"2",
"]",
")"
] | Convert ISO 8601 time format to datetime format
This function converts a date in ISO format, e.g. ``2017-09-14`` to a `datetime` instance, e.g.
``datetime.datetime(2017,9,14,0,0)``
:param date: date in ISO 8601 format
:type date: str
:return: datetime instance
:rtype: datetime | [
"Convert",
"ISO",
"8601",
"time",
"format",
"to",
"datetime",
"format"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/time_utils.py#L56-L68 |
229,182 | sentinel-hub/sentinelhub-py | sentinelhub/time_utils.py | datetime_to_iso | def datetime_to_iso(date, only_date=True):
""" Convert datetime format to ISO 8601 time format
This function converts a date in datetime instance, e.g. ``datetime.datetime(2017,9,14,0,0)`` to ISO format,
e.g. ``2017-09-14``
:param date: datetime instance to convert
:type date: datetime
:param only_date: whether to return date only or also time information. Default is ``True``
:type only_date: bool
:return: date in ISO 8601 format
:rtype: str
"""
if only_date:
return date.isoformat().split('T')[0]
return date.isoformat() | python | def datetime_to_iso(date, only_date=True):
""" Convert datetime format to ISO 8601 time format
This function converts a date in datetime instance, e.g. ``datetime.datetime(2017,9,14,0,0)`` to ISO format,
e.g. ``2017-09-14``
:param date: datetime instance to convert
:type date: datetime
:param only_date: whether to return date only or also time information. Default is ``True``
:type only_date: bool
:return: date in ISO 8601 format
:rtype: str
"""
if only_date:
return date.isoformat().split('T')[0]
return date.isoformat() | [
"def",
"datetime_to_iso",
"(",
"date",
",",
"only_date",
"=",
"True",
")",
":",
"if",
"only_date",
":",
"return",
"date",
".",
"isoformat",
"(",
")",
".",
"split",
"(",
"'T'",
")",
"[",
"0",
"]",
"return",
"date",
".",
"isoformat",
"(",
")"
] | Convert datetime format to ISO 8601 time format
This function converts a date in datetime instance, e.g. ``datetime.datetime(2017,9,14,0,0)`` to ISO format,
e.g. ``2017-09-14``
:param date: datetime instance to convert
:type date: datetime
:param only_date: whether to return date only or also time information. Default is ``True``
:type only_date: bool
:return: date in ISO 8601 format
:rtype: str | [
"Convert",
"datetime",
"format",
"to",
"ISO",
"8601",
"time",
"format"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/time_utils.py#L71-L86 |
229,183 | sentinel-hub/sentinelhub-py | sentinelhub/commands.py | aws | def aws(product, tile, folder, redownload, info, entire, bands, l2a):
"""Download Sentinel-2 data from Sentinel-2 on AWS to ESA SAFE format. Download uses multiple threads.
\b
Examples with Sentinel-2 L1C data:
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551 -i
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551 -f /home/ESA_Products
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551 --bands B08,B11
sentinelhub.aws --tile T54HVH 2017-04-14
sentinelhub.aws --tile T54HVH 2017-04-14 -e
\b
Examples with Sentinel-2 L2A data:
sentinelhub.aws --product S2A_MSIL2A_20180402T151801_N0207_R068_T33XWJ_20180402T202222
sentinelhub.aws --tile T33XWJ 2018-04-02 --l2a
"""
band_list = None if bands is None else bands.split(',')
data_source = DataSource.SENTINEL2_L2A if l2a else DataSource.SENTINEL2_L1C
if info:
if product is None:
click.echo(get_safe_format(tile=tile, entire_product=entire, data_source=data_source))
else:
click.echo(get_safe_format(product_id=product))
else:
if product is None:
download_safe_format(tile=tile, folder=folder, redownload=redownload, entire_product=entire,
bands=band_list, data_source=data_source)
else:
download_safe_format(product_id=product, folder=folder, redownload=redownload, bands=band_list) | python | def aws(product, tile, folder, redownload, info, entire, bands, l2a):
"""Download Sentinel-2 data from Sentinel-2 on AWS to ESA SAFE format. Download uses multiple threads.
\b
Examples with Sentinel-2 L1C data:
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551 -i
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551 -f /home/ESA_Products
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551 --bands B08,B11
sentinelhub.aws --tile T54HVH 2017-04-14
sentinelhub.aws --tile T54HVH 2017-04-14 -e
\b
Examples with Sentinel-2 L2A data:
sentinelhub.aws --product S2A_MSIL2A_20180402T151801_N0207_R068_T33XWJ_20180402T202222
sentinelhub.aws --tile T33XWJ 2018-04-02 --l2a
"""
band_list = None if bands is None else bands.split(',')
data_source = DataSource.SENTINEL2_L2A if l2a else DataSource.SENTINEL2_L1C
if info:
if product is None:
click.echo(get_safe_format(tile=tile, entire_product=entire, data_source=data_source))
else:
click.echo(get_safe_format(product_id=product))
else:
if product is None:
download_safe_format(tile=tile, folder=folder, redownload=redownload, entire_product=entire,
bands=band_list, data_source=data_source)
else:
download_safe_format(product_id=product, folder=folder, redownload=redownload, bands=band_list) | [
"def",
"aws",
"(",
"product",
",",
"tile",
",",
"folder",
",",
"redownload",
",",
"info",
",",
"entire",
",",
"bands",
",",
"l2a",
")",
":",
"band_list",
"=",
"None",
"if",
"bands",
"is",
"None",
"else",
"bands",
".",
"split",
"(",
"','",
")",
"data_source",
"=",
"DataSource",
".",
"SENTINEL2_L2A",
"if",
"l2a",
"else",
"DataSource",
".",
"SENTINEL2_L1C",
"if",
"info",
":",
"if",
"product",
"is",
"None",
":",
"click",
".",
"echo",
"(",
"get_safe_format",
"(",
"tile",
"=",
"tile",
",",
"entire_product",
"=",
"entire",
",",
"data_source",
"=",
"data_source",
")",
")",
"else",
":",
"click",
".",
"echo",
"(",
"get_safe_format",
"(",
"product_id",
"=",
"product",
")",
")",
"else",
":",
"if",
"product",
"is",
"None",
":",
"download_safe_format",
"(",
"tile",
"=",
"tile",
",",
"folder",
"=",
"folder",
",",
"redownload",
"=",
"redownload",
",",
"entire_product",
"=",
"entire",
",",
"bands",
"=",
"band_list",
",",
"data_source",
"=",
"data_source",
")",
"else",
":",
"download_safe_format",
"(",
"product_id",
"=",
"product",
",",
"folder",
"=",
"folder",
",",
"redownload",
"=",
"redownload",
",",
"bands",
"=",
"band_list",
")"
] | Download Sentinel-2 data from Sentinel-2 on AWS to ESA SAFE format. Download uses multiple threads.
\b
Examples with Sentinel-2 L1C data:
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551 -i
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551 -f /home/ESA_Products
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551 --bands B08,B11
sentinelhub.aws --tile T54HVH 2017-04-14
sentinelhub.aws --tile T54HVH 2017-04-14 -e
\b
Examples with Sentinel-2 L2A data:
sentinelhub.aws --product S2A_MSIL2A_20180402T151801_N0207_R068_T33XWJ_20180402T202222
sentinelhub.aws --tile T33XWJ 2018-04-02 --l2a | [
"Download",
"Sentinel",
"-",
"2",
"data",
"from",
"Sentinel",
"-",
"2",
"on",
"AWS",
"to",
"ESA",
"SAFE",
"format",
".",
"Download",
"uses",
"multiple",
"threads",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/commands.py#L38-L67 |
229,184 | sentinel-hub/sentinelhub-py | sentinelhub/commands.py | _config_options | def _config_options(func):
""" A helper function which joins click.option functions of each parameter from config.json
"""
for param in SHConfig().get_params()[-1::-1]:
func = click.option('--{}'.format(param), param,
help='Set new values to configuration parameter "{}"'.format(param))(func)
return func | python | def _config_options(func):
""" A helper function which joins click.option functions of each parameter from config.json
"""
for param in SHConfig().get_params()[-1::-1]:
func = click.option('--{}'.format(param), param,
help='Set new values to configuration parameter "{}"'.format(param))(func)
return func | [
"def",
"_config_options",
"(",
"func",
")",
":",
"for",
"param",
"in",
"SHConfig",
"(",
")",
".",
"get_params",
"(",
")",
"[",
"-",
"1",
":",
":",
"-",
"1",
"]",
":",
"func",
"=",
"click",
".",
"option",
"(",
"'--{}'",
".",
"format",
"(",
"param",
")",
",",
"param",
",",
"help",
"=",
"'Set new values to configuration parameter \"{}\"'",
".",
"format",
"(",
"param",
")",
")",
"(",
"func",
")",
"return",
"func"
] | A helper function which joins click.option functions of each parameter from config.json | [
"A",
"helper",
"function",
"which",
"joins",
"click",
".",
"option",
"functions",
"of",
"each",
"parameter",
"from",
"config",
".",
"json"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/commands.py#L70-L76 |
229,185 | sentinel-hub/sentinelhub-py | sentinelhub/commands.py | config | def config(show, reset, **params):
"""Inspect and configure parameters in your local sentinelhub configuration file
\b
Example:
sentinelhub.config --show
sentinelhub.config --instance_id <new instance id>
sentinelhub.config --max_download_attempts 5 --download_sleep_time 20 --download_timeout_seconds 120
"""
sh_config = SHConfig()
if reset:
sh_config.reset()
for param, value in params.items():
if value is not None:
try:
value = int(value)
except ValueError:
if value.lower() == 'true':
value = True
elif value.lower() == 'false':
value = False
if getattr(sh_config, param) != value:
setattr(sh_config, param, value)
old_config = SHConfig()
sh_config.save()
for param in sh_config.get_params():
if sh_config[param] != old_config[param]:
value = sh_config[param]
if isinstance(value, str):
value = "'{}'".format(value)
click.echo("The value of parameter '{}' was updated to {}".format(param, value))
if show:
click.echo(str(sh_config))
click.echo('Configuration file location: {}'.format(sh_config.get_config_location())) | python | def config(show, reset, **params):
"""Inspect and configure parameters in your local sentinelhub configuration file
\b
Example:
sentinelhub.config --show
sentinelhub.config --instance_id <new instance id>
sentinelhub.config --max_download_attempts 5 --download_sleep_time 20 --download_timeout_seconds 120
"""
sh_config = SHConfig()
if reset:
sh_config.reset()
for param, value in params.items():
if value is not None:
try:
value = int(value)
except ValueError:
if value.lower() == 'true':
value = True
elif value.lower() == 'false':
value = False
if getattr(sh_config, param) != value:
setattr(sh_config, param, value)
old_config = SHConfig()
sh_config.save()
for param in sh_config.get_params():
if sh_config[param] != old_config[param]:
value = sh_config[param]
if isinstance(value, str):
value = "'{}'".format(value)
click.echo("The value of parameter '{}' was updated to {}".format(param, value))
if show:
click.echo(str(sh_config))
click.echo('Configuration file location: {}'.format(sh_config.get_config_location())) | [
"def",
"config",
"(",
"show",
",",
"reset",
",",
"*",
"*",
"params",
")",
":",
"sh_config",
"=",
"SHConfig",
"(",
")",
"if",
"reset",
":",
"sh_config",
".",
"reset",
"(",
")",
"for",
"param",
",",
"value",
"in",
"params",
".",
"items",
"(",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"int",
"(",
"value",
")",
"except",
"ValueError",
":",
"if",
"value",
".",
"lower",
"(",
")",
"==",
"'true'",
":",
"value",
"=",
"True",
"elif",
"value",
".",
"lower",
"(",
")",
"==",
"'false'",
":",
"value",
"=",
"False",
"if",
"getattr",
"(",
"sh_config",
",",
"param",
")",
"!=",
"value",
":",
"setattr",
"(",
"sh_config",
",",
"param",
",",
"value",
")",
"old_config",
"=",
"SHConfig",
"(",
")",
"sh_config",
".",
"save",
"(",
")",
"for",
"param",
"in",
"sh_config",
".",
"get_params",
"(",
")",
":",
"if",
"sh_config",
"[",
"param",
"]",
"!=",
"old_config",
"[",
"param",
"]",
":",
"value",
"=",
"sh_config",
"[",
"param",
"]",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"value",
"=",
"\"'{}'\"",
".",
"format",
"(",
"value",
")",
"click",
".",
"echo",
"(",
"\"The value of parameter '{}' was updated to {}\"",
".",
"format",
"(",
"param",
",",
"value",
")",
")",
"if",
"show",
":",
"click",
".",
"echo",
"(",
"str",
"(",
"sh_config",
")",
")",
"click",
".",
"echo",
"(",
"'Configuration file location: {}'",
".",
"format",
"(",
"sh_config",
".",
"get_config_location",
"(",
")",
")",
")"
] | Inspect and configure parameters in your local sentinelhub configuration file
\b
Example:
sentinelhub.config --show
sentinelhub.config --instance_id <new instance id>
sentinelhub.config --max_download_attempts 5 --download_sleep_time 20 --download_timeout_seconds 120 | [
"Inspect",
"and",
"configure",
"parameters",
"in",
"your",
"local",
"sentinelhub",
"configuration",
"file"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/commands.py#L83-L121 |
229,186 | sentinel-hub/sentinelhub-py | sentinelhub/commands.py | download | def download(url, filename, redownload):
"""Download from custom created URL into custom created file path
\b
Example:
sentinelhub.download http://sentinel-s2-l1c.s3.amazonaws.com/tiles/54/H/VH/2017/4/14/0/metadata.xml home/example.xml
"""
data_folder, filename = filename.rsplit('/', 1)
download_list = [DownloadRequest(url=url, data_folder=data_folder, filename=filename, save_response=True,
return_data=False)]
download_data(download_list, redownload=redownload) | python | def download(url, filename, redownload):
"""Download from custom created URL into custom created file path
\b
Example:
sentinelhub.download http://sentinel-s2-l1c.s3.amazonaws.com/tiles/54/H/VH/2017/4/14/0/metadata.xml home/example.xml
"""
data_folder, filename = filename.rsplit('/', 1)
download_list = [DownloadRequest(url=url, data_folder=data_folder, filename=filename, save_response=True,
return_data=False)]
download_data(download_list, redownload=redownload) | [
"def",
"download",
"(",
"url",
",",
"filename",
",",
"redownload",
")",
":",
"data_folder",
",",
"filename",
"=",
"filename",
".",
"rsplit",
"(",
"'/'",
",",
"1",
")",
"download_list",
"=",
"[",
"DownloadRequest",
"(",
"url",
"=",
"url",
",",
"data_folder",
"=",
"data_folder",
",",
"filename",
"=",
"filename",
",",
"save_response",
"=",
"True",
",",
"return_data",
"=",
"False",
")",
"]",
"download_data",
"(",
"download_list",
",",
"redownload",
"=",
"redownload",
")"
] | Download from custom created URL into custom created file path
\b
Example:
sentinelhub.download http://sentinel-s2-l1c.s3.amazonaws.com/tiles/54/H/VH/2017/4/14/0/metadata.xml home/example.xml | [
"Download",
"from",
"custom",
"created",
"URL",
"into",
"custom",
"created",
"file",
"path"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/commands.py#L128-L138 |
229,187 | sentinel-hub/sentinelhub-py | sentinelhub/config.py | SHConfig.save | def save(self):
"""Method that saves configuration parameter changes from instance of SHConfig class to global config class and
to `config.json` file.
Example of use case
``my_config = SHConfig()`` \n
``my_config.instance_id = '<new instance id>'`` \n
``my_config.save()``
"""
is_changed = False
for prop in self._instance.CONFIG_PARAMS:
if getattr(self, prop) != getattr(self._instance, prop):
is_changed = True
setattr(self._instance, prop, getattr(self, prop))
if is_changed:
self._instance.save_configuration() | python | def save(self):
"""Method that saves configuration parameter changes from instance of SHConfig class to global config class and
to `config.json` file.
Example of use case
``my_config = SHConfig()`` \n
``my_config.instance_id = '<new instance id>'`` \n
``my_config.save()``
"""
is_changed = False
for prop in self._instance.CONFIG_PARAMS:
if getattr(self, prop) != getattr(self._instance, prop):
is_changed = True
setattr(self._instance, prop, getattr(self, prop))
if is_changed:
self._instance.save_configuration() | [
"def",
"save",
"(",
"self",
")",
":",
"is_changed",
"=",
"False",
"for",
"prop",
"in",
"self",
".",
"_instance",
".",
"CONFIG_PARAMS",
":",
"if",
"getattr",
"(",
"self",
",",
"prop",
")",
"!=",
"getattr",
"(",
"self",
".",
"_instance",
",",
"prop",
")",
":",
"is_changed",
"=",
"True",
"setattr",
"(",
"self",
".",
"_instance",
",",
"prop",
",",
"getattr",
"(",
"self",
",",
"prop",
")",
")",
"if",
"is_changed",
":",
"self",
".",
"_instance",
".",
"save_configuration",
"(",
")"
] | Method that saves configuration parameter changes from instance of SHConfig class to global config class and
to `config.json` file.
Example of use case
``my_config = SHConfig()`` \n
``my_config.instance_id = '<new instance id>'`` \n
``my_config.save()`` | [
"Method",
"that",
"saves",
"configuration",
"parameter",
"changes",
"from",
"instance",
"of",
"SHConfig",
"class",
"to",
"global",
"config",
"class",
"and",
"to",
"config",
".",
"json",
"file",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/config.py#L158-L173 |
229,188 | sentinel-hub/sentinelhub-py | sentinelhub/config.py | SHConfig._reset_param | def _reset_param(self, param):
""" Resets a single parameter
:param param: A configuration parameter
:type param: str
"""
if param not in self._instance.CONFIG_PARAMS:
raise ValueError("Cannot reset unknown parameter '{}'".format(param))
setattr(self, param, self._instance.CONFIG_PARAMS[param]) | python | def _reset_param(self, param):
""" Resets a single parameter
:param param: A configuration parameter
:type param: str
"""
if param not in self._instance.CONFIG_PARAMS:
raise ValueError("Cannot reset unknown parameter '{}'".format(param))
setattr(self, param, self._instance.CONFIG_PARAMS[param]) | [
"def",
"_reset_param",
"(",
"self",
",",
"param",
")",
":",
"if",
"param",
"not",
"in",
"self",
".",
"_instance",
".",
"CONFIG_PARAMS",
":",
"raise",
"ValueError",
"(",
"\"Cannot reset unknown parameter '{}'\"",
".",
"format",
"(",
"param",
")",
")",
"setattr",
"(",
"self",
",",
"param",
",",
"self",
".",
"_instance",
".",
"CONFIG_PARAMS",
"[",
"param",
"]",
")"
] | Resets a single parameter
:param param: A configuration parameter
:type param: str | [
"Resets",
"a",
"single",
"parameter"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/config.py#L195-L203 |
229,189 | sentinel-hub/sentinelhub-py | sentinelhub/config.py | SHConfig.get_config_dict | def get_config_dict(self):
""" Get a dictionary representation of `SHConfig` class
:return: A dictionary with configuration parameters
:rtype: OrderedDict
"""
return OrderedDict((prop, getattr(self, prop)) for prop in self._instance.CONFIG_PARAMS) | python | def get_config_dict(self):
""" Get a dictionary representation of `SHConfig` class
:return: A dictionary with configuration parameters
:rtype: OrderedDict
"""
return OrderedDict((prop, getattr(self, prop)) for prop in self._instance.CONFIG_PARAMS) | [
"def",
"get_config_dict",
"(",
"self",
")",
":",
"return",
"OrderedDict",
"(",
"(",
"prop",
",",
"getattr",
"(",
"self",
",",
"prop",
")",
")",
"for",
"prop",
"in",
"self",
".",
"_instance",
".",
"CONFIG_PARAMS",
")"
] | Get a dictionary representation of `SHConfig` class
:return: A dictionary with configuration parameters
:rtype: OrderedDict | [
"Get",
"a",
"dictionary",
"representation",
"of",
"SHConfig",
"class"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/config.py#L213-L219 |
229,190 | sentinel-hub/sentinelhub-py | sentinelhub/geo_utils.py | bbox_to_resolution | def bbox_to_resolution(bbox, width, height):
""" Calculates pixel resolution in meters for a given bbox of a given width and height.
:param bbox: bounding box
:type bbox: geometry.BBox
:param width: width of bounding box in pixels
:type width: int
:param height: height of bounding box in pixels
:type height: int
:return: resolution east-west at north and south, and resolution north-south in meters for given CRS
:rtype: float, float
:raises: ValueError if CRS is not supported
"""
utm_bbox = to_utm_bbox(bbox)
east1, north1 = utm_bbox.lower_left
east2, north2 = utm_bbox.upper_right
return abs(east2 - east1) / width, abs(north2 - north1) / height | python | def bbox_to_resolution(bbox, width, height):
""" Calculates pixel resolution in meters for a given bbox of a given width and height.
:param bbox: bounding box
:type bbox: geometry.BBox
:param width: width of bounding box in pixels
:type width: int
:param height: height of bounding box in pixels
:type height: int
:return: resolution east-west at north and south, and resolution north-south in meters for given CRS
:rtype: float, float
:raises: ValueError if CRS is not supported
"""
utm_bbox = to_utm_bbox(bbox)
east1, north1 = utm_bbox.lower_left
east2, north2 = utm_bbox.upper_right
return abs(east2 - east1) / width, abs(north2 - north1) / height | [
"def",
"bbox_to_resolution",
"(",
"bbox",
",",
"width",
",",
"height",
")",
":",
"utm_bbox",
"=",
"to_utm_bbox",
"(",
"bbox",
")",
"east1",
",",
"north1",
"=",
"utm_bbox",
".",
"lower_left",
"east2",
",",
"north2",
"=",
"utm_bbox",
".",
"upper_right",
"return",
"abs",
"(",
"east2",
"-",
"east1",
")",
"/",
"width",
",",
"abs",
"(",
"north2",
"-",
"north1",
")",
"/",
"height"
] | Calculates pixel resolution in meters for a given bbox of a given width and height.
:param bbox: bounding box
:type bbox: geometry.BBox
:param width: width of bounding box in pixels
:type width: int
:param height: height of bounding box in pixels
:type height: int
:return: resolution east-west at north and south, and resolution north-south in meters for given CRS
:rtype: float, float
:raises: ValueError if CRS is not supported | [
"Calculates",
"pixel",
"resolution",
"in",
"meters",
"for",
"a",
"given",
"bbox",
"of",
"a",
"given",
"width",
"and",
"height",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geo_utils.py#L38-L54 |
229,191 | sentinel-hub/sentinelhub-py | sentinelhub/geo_utils.py | get_image_dimension | def get_image_dimension(bbox, width=None, height=None):
""" Given bounding box and one of the parameters width or height it will return the other parameter that will best
fit the bounding box dimensions
:param bbox: bounding box
:type bbox: geometry.BBox
:param width: image width or None if height is unknown
:type width: int or None
:param height: image height or None if height is unknown
:type height: int or None
:return: width or height rounded to integer
:rtype: int
"""
utm_bbox = to_utm_bbox(bbox)
east1, north1 = utm_bbox.lower_left
east2, north2 = utm_bbox.upper_right
if isinstance(width, int):
return round(width * abs(north2 - north1) / abs(east2 - east1))
return round(height * abs(east2 - east1) / abs(north2 - north1)) | python | def get_image_dimension(bbox, width=None, height=None):
""" Given bounding box and one of the parameters width or height it will return the other parameter that will best
fit the bounding box dimensions
:param bbox: bounding box
:type bbox: geometry.BBox
:param width: image width or None if height is unknown
:type width: int or None
:param height: image height or None if height is unknown
:type height: int or None
:return: width or height rounded to integer
:rtype: int
"""
utm_bbox = to_utm_bbox(bbox)
east1, north1 = utm_bbox.lower_left
east2, north2 = utm_bbox.upper_right
if isinstance(width, int):
return round(width * abs(north2 - north1) / abs(east2 - east1))
return round(height * abs(east2 - east1) / abs(north2 - north1)) | [
"def",
"get_image_dimension",
"(",
"bbox",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
")",
":",
"utm_bbox",
"=",
"to_utm_bbox",
"(",
"bbox",
")",
"east1",
",",
"north1",
"=",
"utm_bbox",
".",
"lower_left",
"east2",
",",
"north2",
"=",
"utm_bbox",
".",
"upper_right",
"if",
"isinstance",
"(",
"width",
",",
"int",
")",
":",
"return",
"round",
"(",
"width",
"*",
"abs",
"(",
"north2",
"-",
"north1",
")",
"/",
"abs",
"(",
"east2",
"-",
"east1",
")",
")",
"return",
"round",
"(",
"height",
"*",
"abs",
"(",
"east2",
"-",
"east1",
")",
"/",
"abs",
"(",
"north2",
"-",
"north1",
")",
")"
] | Given bounding box and one of the parameters width or height it will return the other parameter that will best
fit the bounding box dimensions
:param bbox: bounding box
:type bbox: geometry.BBox
:param width: image width or None if height is unknown
:type width: int or None
:param height: image height or None if height is unknown
:type height: int or None
:return: width or height rounded to integer
:rtype: int | [
"Given",
"bounding",
"box",
"and",
"one",
"of",
"the",
"parameters",
"width",
"or",
"height",
"it",
"will",
"return",
"the",
"other",
"parameter",
"that",
"will",
"best",
"fit",
"the",
"bounding",
"box",
"dimensions"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geo_utils.py#L57-L75 |
229,192 | sentinel-hub/sentinelhub-py | sentinelhub/geo_utils.py | to_utm_bbox | def to_utm_bbox(bbox):
""" Transform bbox into UTM CRS
:param bbox: bounding box
:type bbox: geometry.BBox
:return: bounding box in UTM CRS
:rtype: geometry.BBox
"""
if CRS.is_utm(bbox.crs):
return bbox
lng, lat = bbox.middle
utm_crs = get_utm_crs(lng, lat, source_crs=bbox.crs)
return bbox.transform(utm_crs) | python | def to_utm_bbox(bbox):
""" Transform bbox into UTM CRS
:param bbox: bounding box
:type bbox: geometry.BBox
:return: bounding box in UTM CRS
:rtype: geometry.BBox
"""
if CRS.is_utm(bbox.crs):
return bbox
lng, lat = bbox.middle
utm_crs = get_utm_crs(lng, lat, source_crs=bbox.crs)
return bbox.transform(utm_crs) | [
"def",
"to_utm_bbox",
"(",
"bbox",
")",
":",
"if",
"CRS",
".",
"is_utm",
"(",
"bbox",
".",
"crs",
")",
":",
"return",
"bbox",
"lng",
",",
"lat",
"=",
"bbox",
".",
"middle",
"utm_crs",
"=",
"get_utm_crs",
"(",
"lng",
",",
"lat",
",",
"source_crs",
"=",
"bbox",
".",
"crs",
")",
"return",
"bbox",
".",
"transform",
"(",
"utm_crs",
")"
] | Transform bbox into UTM CRS
:param bbox: bounding box
:type bbox: geometry.BBox
:return: bounding box in UTM CRS
:rtype: geometry.BBox | [
"Transform",
"bbox",
"into",
"UTM",
"CRS"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geo_utils.py#L78-L90 |
229,193 | sentinel-hub/sentinelhub-py | sentinelhub/geo_utils.py | get_utm_bbox | def get_utm_bbox(img_bbox, transform):
""" Get UTM coordinates given a bounding box in pixels and a transform
:param img_bbox: boundaries of bounding box in pixels as `[row1, col1, row2, col2]`
:type img_bbox: list
:param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)`
:type transform: tuple or list
:return: UTM coordinates as [east1, north1, east2, north2]
:rtype: list
"""
east1, north1 = pixel_to_utm(img_bbox[0], img_bbox[1], transform)
east2, north2 = pixel_to_utm(img_bbox[2], img_bbox[3], transform)
return [east1, north1, east2, north2] | python | def get_utm_bbox(img_bbox, transform):
""" Get UTM coordinates given a bounding box in pixels and a transform
:param img_bbox: boundaries of bounding box in pixels as `[row1, col1, row2, col2]`
:type img_bbox: list
:param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)`
:type transform: tuple or list
:return: UTM coordinates as [east1, north1, east2, north2]
:rtype: list
"""
east1, north1 = pixel_to_utm(img_bbox[0], img_bbox[1], transform)
east2, north2 = pixel_to_utm(img_bbox[2], img_bbox[3], transform)
return [east1, north1, east2, north2] | [
"def",
"get_utm_bbox",
"(",
"img_bbox",
",",
"transform",
")",
":",
"east1",
",",
"north1",
"=",
"pixel_to_utm",
"(",
"img_bbox",
"[",
"0",
"]",
",",
"img_bbox",
"[",
"1",
"]",
",",
"transform",
")",
"east2",
",",
"north2",
"=",
"pixel_to_utm",
"(",
"img_bbox",
"[",
"2",
"]",
",",
"img_bbox",
"[",
"3",
"]",
",",
"transform",
")",
"return",
"[",
"east1",
",",
"north1",
",",
"east2",
",",
"north2",
"]"
] | Get UTM coordinates given a bounding box in pixels and a transform
:param img_bbox: boundaries of bounding box in pixels as `[row1, col1, row2, col2]`
:type img_bbox: list
:param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)`
:type transform: tuple or list
:return: UTM coordinates as [east1, north1, east2, north2]
:rtype: list | [
"Get",
"UTM",
"coordinates",
"given",
"a",
"bounding",
"box",
"in",
"pixels",
"and",
"a",
"transform"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geo_utils.py#L93-L105 |
229,194 | sentinel-hub/sentinelhub-py | sentinelhub/geo_utils.py | wgs84_to_utm | def wgs84_to_utm(lng, lat, utm_crs=None):
""" Convert WGS84 coordinates to UTM. If UTM CRS is not set it will be calculated automatically.
:param lng: longitude in WGS84 system
:type lng: float
:param lat: latitude in WGS84 system
:type lat: float
:param utm_crs: UTM coordinate reference system enum constants
:type utm_crs: constants.CRS or None
:return: east, north coordinates in UTM system
:rtype: float, float
"""
if utm_crs is None:
utm_crs = get_utm_crs(lng, lat)
return transform_point((lng, lat), CRS.WGS84, utm_crs) | python | def wgs84_to_utm(lng, lat, utm_crs=None):
""" Convert WGS84 coordinates to UTM. If UTM CRS is not set it will be calculated automatically.
:param lng: longitude in WGS84 system
:type lng: float
:param lat: latitude in WGS84 system
:type lat: float
:param utm_crs: UTM coordinate reference system enum constants
:type utm_crs: constants.CRS or None
:return: east, north coordinates in UTM system
:rtype: float, float
"""
if utm_crs is None:
utm_crs = get_utm_crs(lng, lat)
return transform_point((lng, lat), CRS.WGS84, utm_crs) | [
"def",
"wgs84_to_utm",
"(",
"lng",
",",
"lat",
",",
"utm_crs",
"=",
"None",
")",
":",
"if",
"utm_crs",
"is",
"None",
":",
"utm_crs",
"=",
"get_utm_crs",
"(",
"lng",
",",
"lat",
")",
"return",
"transform_point",
"(",
"(",
"lng",
",",
"lat",
")",
",",
"CRS",
".",
"WGS84",
",",
"utm_crs",
")"
] | Convert WGS84 coordinates to UTM. If UTM CRS is not set it will be calculated automatically.
:param lng: longitude in WGS84 system
:type lng: float
:param lat: latitude in WGS84 system
:type lat: float
:param utm_crs: UTM coordinate reference system enum constants
:type utm_crs: constants.CRS or None
:return: east, north coordinates in UTM system
:rtype: float, float | [
"Convert",
"WGS84",
"coordinates",
"to",
"UTM",
".",
"If",
"UTM",
"CRS",
"is",
"not",
"set",
"it",
"will",
"be",
"calculated",
"automatically",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geo_utils.py#L108-L122 |
229,195 | sentinel-hub/sentinelhub-py | sentinelhub/geo_utils.py | utm_to_pixel | def utm_to_pixel(east, north, transform, truncate=True):
""" Convert UTM coordinate to image coordinate given a transform
:param east: east coordinate of point
:type east: float
:param north: north coordinate of point
:type north: float
:param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)`
:type transform: tuple or list
:param truncate: Whether to truncate pixel coordinates. Default is ``True``
:type truncate: bool
:return: row and column pixel image coordinates
:rtype: float, float or int, int
"""
column = (east - transform[0]) / transform[1]
row = (north - transform[3]) / transform[5]
if truncate:
return int(row + ERR), int(column + ERR)
return row, column | python | def utm_to_pixel(east, north, transform, truncate=True):
""" Convert UTM coordinate to image coordinate given a transform
:param east: east coordinate of point
:type east: float
:param north: north coordinate of point
:type north: float
:param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)`
:type transform: tuple or list
:param truncate: Whether to truncate pixel coordinates. Default is ``True``
:type truncate: bool
:return: row and column pixel image coordinates
:rtype: float, float or int, int
"""
column = (east - transform[0]) / transform[1]
row = (north - transform[3]) / transform[5]
if truncate:
return int(row + ERR), int(column + ERR)
return row, column | [
"def",
"utm_to_pixel",
"(",
"east",
",",
"north",
",",
"transform",
",",
"truncate",
"=",
"True",
")",
":",
"column",
"=",
"(",
"east",
"-",
"transform",
"[",
"0",
"]",
")",
"/",
"transform",
"[",
"1",
"]",
"row",
"=",
"(",
"north",
"-",
"transform",
"[",
"3",
"]",
")",
"/",
"transform",
"[",
"5",
"]",
"if",
"truncate",
":",
"return",
"int",
"(",
"row",
"+",
"ERR",
")",
",",
"int",
"(",
"column",
"+",
"ERR",
")",
"return",
"row",
",",
"column"
] | Convert UTM coordinate to image coordinate given a transform
:param east: east coordinate of point
:type east: float
:param north: north coordinate of point
:type north: float
:param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)`
:type transform: tuple or list
:param truncate: Whether to truncate pixel coordinates. Default is ``True``
:type truncate: bool
:return: row and column pixel image coordinates
:rtype: float, float or int, int | [
"Convert",
"UTM",
"coordinate",
"to",
"image",
"coordinate",
"given",
"a",
"transform"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geo_utils.py#L140-L158 |
229,196 | sentinel-hub/sentinelhub-py | sentinelhub/geo_utils.py | pixel_to_utm | def pixel_to_utm(row, column, transform):
""" Convert pixel coordinate to UTM coordinate given a transform
:param row: row pixel coordinate
:type row: int or float
:param column: column pixel coordinate
:type column: int or float
:param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)`
:type transform: tuple or list
:return: east, north UTM coordinates
:rtype: float, float
"""
east = transform[0] + column * transform[1]
north = transform[3] + row * transform[5]
return east, north | python | def pixel_to_utm(row, column, transform):
""" Convert pixel coordinate to UTM coordinate given a transform
:param row: row pixel coordinate
:type row: int or float
:param column: column pixel coordinate
:type column: int or float
:param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)`
:type transform: tuple or list
:return: east, north UTM coordinates
:rtype: float, float
"""
east = transform[0] + column * transform[1]
north = transform[3] + row * transform[5]
return east, north | [
"def",
"pixel_to_utm",
"(",
"row",
",",
"column",
",",
"transform",
")",
":",
"east",
"=",
"transform",
"[",
"0",
"]",
"+",
"column",
"*",
"transform",
"[",
"1",
"]",
"north",
"=",
"transform",
"[",
"3",
"]",
"+",
"row",
"*",
"transform",
"[",
"5",
"]",
"return",
"east",
",",
"north"
] | Convert pixel coordinate to UTM coordinate given a transform
:param row: row pixel coordinate
:type row: int or float
:param column: column pixel coordinate
:type column: int or float
:param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)`
:type transform: tuple or list
:return: east, north UTM coordinates
:rtype: float, float | [
"Convert",
"pixel",
"coordinate",
"to",
"UTM",
"coordinate",
"given",
"a",
"transform"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geo_utils.py#L161-L175 |
229,197 | sentinel-hub/sentinelhub-py | sentinelhub/geo_utils.py | wgs84_to_pixel | def wgs84_to_pixel(lng, lat, transform, utm_epsg=None, truncate=True):
""" Convert WGS84 coordinates to pixel image coordinates given transform and UTM CRS. If no CRS is given it will be
calculated it automatically.
:param lng: longitude of point
:type lng: float
:param lat: latitude of point
:type lat: float
:param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)`
:type transform: tuple or list
:param utm_epsg: UTM coordinate reference system enum constants
:type utm_epsg: constants.CRS or None
:param truncate: Whether to truncate pixel coordinates. Default is ``True``
:type truncate: bool
:return: row and column pixel image coordinates
:rtype: float, float or int, int
"""
east, north = wgs84_to_utm(lng, lat, utm_epsg)
row, column = utm_to_pixel(east, north, transform, truncate=truncate)
return row, column | python | def wgs84_to_pixel(lng, lat, transform, utm_epsg=None, truncate=True):
""" Convert WGS84 coordinates to pixel image coordinates given transform and UTM CRS. If no CRS is given it will be
calculated it automatically.
:param lng: longitude of point
:type lng: float
:param lat: latitude of point
:type lat: float
:param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)`
:type transform: tuple or list
:param utm_epsg: UTM coordinate reference system enum constants
:type utm_epsg: constants.CRS or None
:param truncate: Whether to truncate pixel coordinates. Default is ``True``
:type truncate: bool
:return: row and column pixel image coordinates
:rtype: float, float or int, int
"""
east, north = wgs84_to_utm(lng, lat, utm_epsg)
row, column = utm_to_pixel(east, north, transform, truncate=truncate)
return row, column | [
"def",
"wgs84_to_pixel",
"(",
"lng",
",",
"lat",
",",
"transform",
",",
"utm_epsg",
"=",
"None",
",",
"truncate",
"=",
"True",
")",
":",
"east",
",",
"north",
"=",
"wgs84_to_utm",
"(",
"lng",
",",
"lat",
",",
"utm_epsg",
")",
"row",
",",
"column",
"=",
"utm_to_pixel",
"(",
"east",
",",
"north",
",",
"transform",
",",
"truncate",
"=",
"truncate",
")",
"return",
"row",
",",
"column"
] | Convert WGS84 coordinates to pixel image coordinates given transform and UTM CRS. If no CRS is given it will be
calculated it automatically.
:param lng: longitude of point
:type lng: float
:param lat: latitude of point
:type lat: float
:param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)`
:type transform: tuple or list
:param utm_epsg: UTM coordinate reference system enum constants
:type utm_epsg: constants.CRS or None
:param truncate: Whether to truncate pixel coordinates. Default is ``True``
:type truncate: bool
:return: row and column pixel image coordinates
:rtype: float, float or int, int | [
"Convert",
"WGS84",
"coordinates",
"to",
"pixel",
"image",
"coordinates",
"given",
"transform",
"and",
"UTM",
"CRS",
".",
"If",
"no",
"CRS",
"is",
"given",
"it",
"will",
"be",
"calculated",
"it",
"automatically",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geo_utils.py#L178-L197 |
229,198 | sentinel-hub/sentinelhub-py | sentinelhub/geo_utils.py | transform_point | def transform_point(point, source_crs, target_crs):
""" Maps point form src_crs to tgt_crs
:param point: a tuple `(x, y)`
:type point: (float, float)
:param source_crs: source CRS
:type source_crs: constants.CRS
:param target_crs: target CRS
:type target_crs: constants.CRS
:return: point in target CRS
:rtype: (float, float)
"""
if source_crs == target_crs:
return point
old_x, old_y = point
new_x, new_y = pyproj.transform(CRS.projection(source_crs), CRS.projection(target_crs), old_x, old_y)
return new_x, new_y | python | def transform_point(point, source_crs, target_crs):
""" Maps point form src_crs to tgt_crs
:param point: a tuple `(x, y)`
:type point: (float, float)
:param source_crs: source CRS
:type source_crs: constants.CRS
:param target_crs: target CRS
:type target_crs: constants.CRS
:return: point in target CRS
:rtype: (float, float)
"""
if source_crs == target_crs:
return point
old_x, old_y = point
new_x, new_y = pyproj.transform(CRS.projection(source_crs), CRS.projection(target_crs), old_x, old_y)
return new_x, new_y | [
"def",
"transform_point",
"(",
"point",
",",
"source_crs",
",",
"target_crs",
")",
":",
"if",
"source_crs",
"==",
"target_crs",
":",
"return",
"point",
"old_x",
",",
"old_y",
"=",
"point",
"new_x",
",",
"new_y",
"=",
"pyproj",
".",
"transform",
"(",
"CRS",
".",
"projection",
"(",
"source_crs",
")",
",",
"CRS",
".",
"projection",
"(",
"target_crs",
")",
",",
"old_x",
",",
"old_y",
")",
"return",
"new_x",
",",
"new_y"
] | Maps point form src_crs to tgt_crs
:param point: a tuple `(x, y)`
:type point: (float, float)
:param source_crs: source CRS
:type source_crs: constants.CRS
:param target_crs: target CRS
:type target_crs: constants.CRS
:return: point in target CRS
:rtype: (float, float) | [
"Maps",
"point",
"form",
"src_crs",
"to",
"tgt_crs"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geo_utils.py#L217-L233 |
229,199 | sentinel-hub/sentinelhub-py | sentinelhub/geo_utils.py | transform_bbox | def transform_bbox(bbox, target_crs):
""" Maps bbox from current crs to target_crs
:param bbox: bounding box
:type bbox: geometry.BBox
:param target_crs: target CRS
:type target_crs: constants.CRS
:return: bounding box in target CRS
:rtype: geometry.BBox
"""
warnings.warn("This function is deprecated, use BBox.transform method instead", DeprecationWarning, stacklevel=2)
return bbox.transform(target_crs) | python | def transform_bbox(bbox, target_crs):
""" Maps bbox from current crs to target_crs
:param bbox: bounding box
:type bbox: geometry.BBox
:param target_crs: target CRS
:type target_crs: constants.CRS
:return: bounding box in target CRS
:rtype: geometry.BBox
"""
warnings.warn("This function is deprecated, use BBox.transform method instead", DeprecationWarning, stacklevel=2)
return bbox.transform(target_crs) | [
"def",
"transform_bbox",
"(",
"bbox",
",",
"target_crs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"This function is deprecated, use BBox.transform method instead\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"bbox",
".",
"transform",
"(",
"target_crs",
")"
] | Maps bbox from current crs to target_crs
:param bbox: bounding box
:type bbox: geometry.BBox
:param target_crs: target CRS
:type target_crs: constants.CRS
:return: bounding box in target CRS
:rtype: geometry.BBox | [
"Maps",
"bbox",
"from",
"current",
"crs",
"to",
"target_crs"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geo_utils.py#L236-L248 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.