_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q224400 | drawQuad | train | def drawQuad(page, quad, color=None, fill=None, dashes=None,
width=1, roundCap=False, morph=None, overlay=True):
"""Draw a quadrilateral.
"""
img = page.newShape()
Q = img.drawQuad(Quad(quad))
img.finish(color=color, fill=fill, dashes=dashes, width=width,
roundCap=rou... | python | {
"resource": ""
} |
q224401 | drawPolyline | train | def drawPolyline(page, points, color=None, fill=None, dashes=None,
width=1, morph=None, roundCap=False, overlay=True,
closePath=False):
"""Draw multiple connected line segments.
"""
img = page.newShape()
Q = img.drawPolyline(points)
img.finish(color=color, fill=fill... | python | {
"resource": ""
} |
q224402 | drawBezier | train | def drawBezier(page, p1, p2, p3, p4, color=None, fill=None,
dashes=None, width=1, morph=None,
closePath=False, roundCap=False, overlay=True):
"""Draw a general cubic Bezier curve from p1 to p4 using control points p2 and p3.
"""
img = page.newShape()
Q = img.drawBezier(Poin... | python | {
"resource": ""
} |
q224403 | getColor | train | def getColor(name):
"""Retrieve RGB color in PDF format by name.
Returns:
a triple of floats in range 0 to 1. In case of name-not-found, "white" is returned.
"""
try:
c = getColorInfoList()[getColorList().index(name.upper())]
return (c[1] / 255., c[2] / 255., c[3] / 255.)
ex... | python | {
"resource": ""
} |
q224404 | getColorHSV | train | def getColorHSV(name):
"""Retrieve the hue, saturation, value triple of a color name.
Returns:
a triple (degree, percent, percent). If not found (-1, -1, -1) is returned.
"""
try:
x = getColorInfoList()[getColorList().index(name.upper())]
except:
return (-1, -1, -1)
... | python | {
"resource": ""
} |
q224405 | Shape.horizontal_angle | train | def horizontal_angle(C, P):
"""Return the angle to the horizontal for the connection from C to P.
This uses the arcus sine function and resolves its inherent ambiguity by
looking up in which quadrant vector S = P - C is located.
"""
S = Point(P - C).unit # unit ... | python | {
"resource": ""
} |
q224406 | Shape.drawLine | train | def drawLine(self, p1, p2):
"""Draw a line between two points.
"""
p1 = Point(p1)
p2 = Point(p2)
if not (self.lastPoint == p1):
self.draw_cont += "%g %g m\n" % JM_TUPLE(p1 * self.ipctm)
self.lastPoint = p1
self.updateRect(p1)
self.draw... | python | {
"resource": ""
} |
q224407 | Shape.drawPolyline | train | def drawPolyline(self, points):
"""Draw several connected line segments.
"""
for i, p in enumerate(points):
if i == 0:
if not (self.lastPoint == Point(p)):
self.draw_cont += "%g %g m\n" % JM_TUPLE(Point(p) * self.ipctm)
self.las... | python | {
"resource": ""
} |
q224408 | Shape.drawBezier | train | def drawBezier(self, p1, p2, p3, p4):
"""Draw a standard cubic Bezier curve.
"""
p1 = Point(p1)
p2 = Point(p2)
p3 = Point(p3)
p4 = Point(p4)
if not (self.lastPoint == p1):
self.draw_cont += "%g %g m\n" % JM_TUPLE(p1 * self.ipctm)
self.draw_cont... | python | {
"resource": ""
} |
q224409 | Shape.drawOval | train | def drawOval(self, tetra):
"""Draw an ellipse inside a tetrapod.
"""
if len(tetra) != 4:
raise ValueError("invalid arg length")
if hasattr(tetra[0], "__float__"):
q = Rect(tetra).quad
else:
q = Quad(tetra)
mt = q.ul + (q.ur - q.ul) * 0... | python | {
"resource": ""
} |
q224410 | Shape.drawCurve | train | def drawCurve(self, p1, p2, p3):
"""Draw a curve between points using one control point.
"""
kappa = 0.55228474983
p1 = Point(p1)
p2 = Point(p2)
p3 = Point(p3)
k1 = p1 + (p2 - p1) * kappa
k2 = p3 + (p2 - p3) * kappa
return self.drawBezier(p1, k1, k... | python | {
"resource": ""
} |
q224411 | Shape.drawQuad | train | def drawQuad(self, quad):
"""Draw a Quad.
"""
q = Quad(quad)
return self.drawPolyline([q.ul, q.ll, q.lr, q.ur, q.ul]) | python | {
"resource": ""
} |
q224412 | Shape.drawZigzag | train | def drawZigzag(self, p1, p2, breadth = 2):
"""Draw a zig-zagged line from p1 to p2.
"""
p1 = Point(p1)
p2 = Point(p2)
S = p2 - p1 # vector start - end
rad = abs(S) # distance of points
cnt = 4 * int(round(rad ... | python | {
"resource": ""
} |
q224413 | Shape.drawSquiggle | train | def drawSquiggle(self, p1, p2, breadth = 2):
"""Draw a squiggly line from p1 to p2.
"""
p1 = Point(p1)
p2 = Point(p2)
S = p2 - p1 # vector start - end
rad = abs(S) # distance of points
cnt = 4 * int(round(rad ... | python | {
"resource": ""
} |
q224414 | Shape.finish | train | def finish(
self,
width=1,
color=None,
fill=None,
roundCap=False,
dashes=None,
even_odd=False,
morph=None,
closePath=True
):
"""Finish the current drawing segment.
Notes:
Appl... | python | {
"resource": ""
} |
q224415 | OptionHelper.set_float | train | def set_float(self, option, value):
"""Set a float option.
Args:
option (str): name of option.
value (float): value of the option.
Raises:
TypeError: Value must be a float.
"""
if not isinstance(value, float):
... | python | {
"resource": ""
} |
q224416 | OptionHelper.set_integer | train | def set_integer(self, option, value):
"""Set an integer option.
Args:
option (str): name of option.
value (int): value of the option.
Raises:
ValueError: Value must be an integer.
"""
try:
int_value = int(value... | python | {
"resource": ""
} |
q224417 | OptionHelper.set_boolean | train | def set_boolean(self, option, value):
"""Set a boolean option.
Args:
option (str): name of option.
value (bool): value of the option.
Raises:
TypeError: Value must be a boolean.
"""
if not isinstance(value, bool):
... | python | {
"resource": ""
} |
q224418 | OptionHelper.set_string | train | def set_string(self, option, value):
"""Set a string option.
Args:
option (str): name of option.
value (str): value of the option.
Raises:
TypeError: Value must be a string.
"""
if not isinstance(value, str):
r... | python | {
"resource": ""
} |
q224419 | Graphic.custom_line_color_map | train | def custom_line_color_map(self, values):
"""Set the custom line color map.
Args:
values (list): list of colors.
Raises:
TypeError: Custom line color map must be a list.
"""
if not isinstance(values, list):
raise TypeError("cus... | python | {
"resource": ""
} |
q224420 | Graphic.legend | train | def legend(self, values):
"""Set the legend labels.
Args:
values (list): list of labels.
Raises:
ValueError: legend must be a list of labels.
"""
if not isinstance(values, list):
raise TypeError("legend must be a list of label... | python | {
"resource": ""
} |
q224421 | Graphic.markers | train | def markers(self, values):
"""Set the markers.
Args:
values (list): list of marker objects.
Raises:
ValueError: Markers must be a list of objects.
"""
if not isinstance(values, list):
raise TypeError("Markers must be a list of... | python | {
"resource": ""
} |
q224422 | Graphic.get | train | def get(self):
"""Get graphics options."""
return {k:v for k,v in list(self.options.items()) if k in self._allowed_graphics} | python | {
"resource": ""
} |
q224423 | Chart.apply_filters | train | def apply_filters(df, filters):
"""Basic filtering for a dataframe."""
idx = pd.Series([True]*df.shape[0])
for k, v in list(filters.items()):
if k not in df.columns:
continue
idx &= (df[k] == v)
return df.loc[idx] | python | {
"resource": ""
} |
q224424 | DataTable.format_row | train | def format_row(row, bounds, columns):
"""Formats a single row of the dataframe"""
for c in columns:
if c not in row:
continue
if "format" in columns[c]:
row[c] = columns[c]["format"] % row[c]
if c in bounds:
b = bounds... | python | {
"resource": ""
} |
q224425 | DataTable.to_json | train | def to_json(df, columns, confidence={}):
"""Transforms dataframe to properly formatted json response"""
records = []
display_cols = list(columns.keys())
if not display_cols:
display_cols = list(df.columns)
bounds = {}
for c in confidence:
bounds[... | python | {
"resource": ""
} |
q224426 | Figure.get | train | def get(self):
"""Return axes, graphics, and layout options."""
options = {}
for x in [self.axes, self.graphics, self.layout]:
for k, v in list(x.get().items()):
options[k] = v
return options | python | {
"resource": ""
} |
q224427 | Layout.set_margin | train | def set_margin(self, top=40, bottom=30, left=50, right=10, buffer_size=8):
"""Set margin of the chart.
Args:
top (int): size of top margin in pixels.
bottom (int): size of bottom margin in pixels.
left (int): size of left margin in pixels.
... | python | {
"resource": ""
} |
q224428 | Layout.set_size | train | def set_size(self, height=220, width=350,
height_threshold=120,
width_threshold=160):
"""Set the size of the chart.
Args:
height (int): height in pixels.
width (int): width in pixels.
height_threshold (int): height th... | python | {
"resource": ""
} |
q224429 | Layout.get | train | def get(self):
"""Get layout options."""
return {k:v for k,v in list(self.options.items()) if k in self._allowed_layout} | python | {
"resource": ""
} |
q224430 | format_props | train | def format_props(props, prop_template="{{k}} = { {{v}} }", delim="\n"):
""" Formats props for the React template.
Args:
props (dict): properties to be written to the template.
Returns:
Two lists, one containing variable names and the other
containing a list of p... | python | {
"resource": ""
} |
q224431 | register_layouts | train | def register_layouts(layouts, app, url="/api/props/", brand="Pyxley"):
""" register UILayout with the flask app
create a function that will send props for each UILayout
Args:
layouts (dict): dict of UILayout objects by name
app (object): flask app
url (string): ... | python | {
"resource": ""
} |
q224432 | UIComponent.register_route | train | def register_route(self, app):
"""Register the api route function with the app."""
if "url" not in self.params["options"]:
raise Exception("Component does not have a URL property")
if not hasattr(self.route_func, "__call__"):
raise Exception("No app route function suppli... | python | {
"resource": ""
} |
q224433 | SimpleComponent.render | train | def render(self, path):
"""Render the component to a javascript file."""
return ReactComponent(
self.layout,
self.src_file,
self.component_id,
props=self.props,
static_path=path) | python | {
"resource": ""
} |
q224434 | UILayout.add_filter | train | def add_filter(self, component, filter_group="pyxley-filter"):
"""Add a filter to the layout."""
if getattr(component, "name") != "Filter":
raise Exception("Component is not an instance of Filter")
if filter_group not in self.filters:
self.filters[filter_group] = []
... | python | {
"resource": ""
} |
q224435 | UILayout.add_chart | train | def add_chart(self, component):
"""Add a chart to the layout."""
if getattr(component, "name") != "Chart":
raise Exception("Component is not an instance of Chart")
self.charts.append(component) | python | {
"resource": ""
} |
q224436 | UILayout.build_props | train | def build_props(self):
"""Build the props dictionary."""
props = {}
if self.filters:
props["filters"] = {}
for grp in self.filters:
props["filters"][grp] = [f.params for f in self.filters[grp]]
if self.charts:
props["charts"] = [c.param... | python | {
"resource": ""
} |
q224437 | UILayout.assign_routes | train | def assign_routes(self, app):
"""Register routes with the app."""
for grp in self.filters:
for f in self.filters[grp]:
if f.route_func:
f.register_route(app)
for c in self.charts:
if c.route_func:
c.register_route(app) | python | {
"resource": ""
} |
q224438 | UILayout.render_layout | train | def render_layout(self, app, path, alias=None):
"""Write to javascript."""
self.assign_routes(app)
return ReactComponent(
self.layout,
self.src_file,
self.component_id,
props=self.build_props(),
static_path=path,
alias=alias... | python | {
"resource": ""
} |
q224439 | default_static_path | train | def default_static_path():
"""
Return the path to the javascript bundle
"""
fdir = os.path.dirname(__file__)
return os.path.abspath(os.path.join(fdir, '../assets/')) | python | {
"resource": ""
} |
q224440 | default_template_path | train | 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 | {
"resource": ""
} |
q224441 | Axes.set_xlim | train | 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 t... | python | {
"resource": ""
} |
q224442 | Axes.set_ylim | train | 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 t... | python | {
"resource": ""
} |
q224443 | Axes.get | train | 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 | {
"resource": ""
} |
q224444 | PlotlyAPI.line_plot | train | 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... | python | {
"resource": ""
} |
q224445 | PieChart.to_json | train | 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],
"... | python | {
"resource": ""
} |
q224446 | DatamapUSA.to_json | train | 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,
... | python | {
"resource": ""
} |
q224447 | error_string | train | 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 erro... | python | {
"resource": ""
} |
q224448 | topic_matches_sub | train | 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... | python | {
"resource": ""
} |
q224449 | Client.configIAMCredentials | train | 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 T... | python | {
"resource": ""
} |
q224450 | Client.loop | train | 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
p... | python | {
"resource": ""
} |
q224451 | Client.publish | train | 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.
... | python | {
"resource": ""
} |
q224452 | Client.username_pw_set | train | 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 relationsh... | python | {
"resource": ""
} |
q224453 | Client.disconnect | train | 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:
... | python | {
"resource": ""
} |
q224454 | Client.subscribe | train | 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... | python | {
"resource": ""
} |
q224455 | Client.unsubscribe | train | 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_... | python | {
"resource": ""
} |
q224456 | Client.will_set | train | 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... | python | {
"resource": ""
} |
q224457 | Client.socket | train | 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 | {
"resource": ""
} |
q224458 | createproject | train | 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 l... | python | {
"resource": ""
} |
q224459 | RequestsMock.add_passthru | train | 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.... | python | {
"resource": ""
} |
q224460 | _install | train | 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.'... | python | {
"resource": ""
} |
q224461 | _build_egg | train | 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.war... | python | {
"resource": ""
} |
q224462 | _do_download | train | 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):
arc... | python | {
"resource": ""
} |
q224463 | use_setuptools | train | 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.abspa... | python | {
"resource": ""
} |
q224464 | _conflict_bail | train | 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... | python | {
"resource": ""
} |
q224465 | download_file_insecure | train | 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 f... | python | {
"resource": ""
} |
q224466 | _download_args | train | 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 | {
"resource": ""
} |
q224467 | main | train | 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 | {
"resource": ""
} |
q224468 | ezIBpy.registerContract | train | 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(contr... | python | {
"resource": ""
} |
q224469 | ezIBpy.handleErrorEvents | train | 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"]:
l... | python | {
"resource": ""
} |
q224470 | ezIBpy.handleServerEvents | train | 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 sel... | python | {
"resource": ""
} |
q224471 | ezIBpy.handleContractDetails | train | 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_deta... | python | {
"resource": ""
} |
q224472 | ezIBpy.handlePosition | train | 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 c... | python | {
"resource": ""
} |
q224473 | ezIBpy.handlePortfolio | train | 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... | python | {
"resource": ""
} |
q224474 | ezIBpy.handleOrders | train | 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 ti... | python | {
"resource": ""
} |
q224475 | ezIBpy.createTriggerableTrailingStop | train | 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.triggerableTrailingSt... | python | {
"resource": ""
} |
q224476 | ezIBpy.registerTrailingStop | train | 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] = {
... | python | {
"resource": ""
} |
q224477 | ezIBpy.modifyStopOrder | train | 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,
... | python | {
"resource": ""
} |
q224478 | ezIBpy.handleTrailingStops | train | 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]... | python | {
"resource": ""
} |
q224479 | ezIBpy.triggerTrailingStops | train | 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.triggerableTrailingStop... | python | {
"resource": ""
} |
q224480 | ezIBpy.tickerId | train | 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)... | python | {
"resource": ""
} |
q224481 | ezIBpy.createTargetOrder | train | 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 = tra... | python | {
"resource": ""
} |
q224482 | ezIBpy.createStopOrder | train | 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,
... | python | {
"resource": ""
} |
q224483 | ezIBpy.createTrailingStopOrder | train | 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) + " do... | python | {
"resource": ""
} |
q224484 | ezIBpy.placeOrder | train | 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... | python | {
"resource": ""
} |
q224485 | ezIBpy.cancelOrder | train | def cancelOrder(self, orderId):
""" cancel order on IB TWS """
self.ibConn.cancelOrder(orderId)
# update order id for next time
self.requestOrderIds()
return orderId | python | {
"resource": ""
} |
q224486 | ezIBpy.requestOpenOrders | train | 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 | {
"resource": ""
} |
q224487 | ezIBpy.cancelHistoricalData | train | 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 =... | python | {
"resource": ""
} |
q224488 | ezIBpy.getConId | train | 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 | {
"resource": ""
} |
q224489 | ezIBpy.createComboContract | train | 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(... | python | {
"resource": ""
} |
q224490 | order_to_dict | train | 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 | {
"resource": ""
} |
q224491 | contract_to_dict | train | 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 | {
"resource": ""
} |
q224492 | _get_utm_code | train | 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
:pa... | python | {
"resource": ""
} |
q224493 | _get_utm_name_value_pair | train | 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,... | python | {
"resource": ""
} |
q224494 | _crs_parser | train | 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):
... | python | {
"resource": ""
} |
q224495 | DataSource.get_wfs_typename | train | 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()
... | python | {
"resource": ""
} |
q224496 | DataSource.is_uswest_source | train | 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: DataSourc... | python | {
"resource": ""
} |
q224497 | DataSource.get_available_sources | train | 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.SENTIN... | python | {
"resource": ""
} |
q224498 | _BaseCRS.get_utm_from_wgs84 | train | 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)
... | python | {
"resource": ""
} |
q224499 | CustomUrlParam.has_value | train | 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
:... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.