repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
pymupdf/PyMuPDF | examples/PDFLinkMaint.py | PDFdisplay.Rect_to_wxRect | def Rect_to_wxRect(self, fr):
""" Return a zoomed wx.Rect for given fitz.Rect."""
r = (fr * self.zoom).irect # zoomed IRect
return wx.Rect(r.x0, r.y0, r.width, r.height) | python | def Rect_to_wxRect(self, fr):
""" Return a zoomed wx.Rect for given fitz.Rect."""
r = (fr * self.zoom).irect # zoomed IRect
return wx.Rect(r.x0, r.y0, r.width, r.height) | [
"def",
"Rect_to_wxRect",
"(",
"self",
",",
"fr",
")",
":",
"r",
"=",
"(",
"fr",
"*",
"self",
".",
"zoom",
")",
".",
"irect",
"# zoomed IRect",
"return",
"wx",
".",
"Rect",
"(",
"r",
".",
"x0",
",",
"r",
".",
"y0",
",",
"r",
".",
"width",
",",
... | Return a zoomed wx.Rect for given fitz.Rect. | [
"Return",
"a",
"zoomed",
"wx",
".",
"Rect",
"for",
"given",
"fitz",
".",
"Rect",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/examples/PDFLinkMaint.py#L903-L906 | train | 223,900 |
pymupdf/PyMuPDF | examples/PDFLinkMaint.py | PDFdisplay.wxRect_to_Rect | def wxRect_to_Rect(self, wr):
""" Return a shrunk fitz.Rect for given wx.Rect."""
r = fitz.Rect(wr.x, wr.y, wr.x + wr.width, wr.y + wr.height)
return r * self.shrink | python | def wxRect_to_Rect(self, wr):
""" Return a shrunk fitz.Rect for given wx.Rect."""
r = fitz.Rect(wr.x, wr.y, wr.x + wr.width, wr.y + wr.height)
return r * self.shrink | [
"def",
"wxRect_to_Rect",
"(",
"self",
",",
"wr",
")",
":",
"r",
"=",
"fitz",
".",
"Rect",
"(",
"wr",
".",
"x",
",",
"wr",
".",
"y",
",",
"wr",
".",
"x",
"+",
"wr",
".",
"width",
",",
"wr",
".",
"y",
"+",
"wr",
".",
"height",
")",
"return",
... | Return a shrunk fitz.Rect for given wx.Rect. | [
"Return",
"a",
"shrunk",
"fitz",
".",
"Rect",
"for",
"given",
"wx",
".",
"Rect",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/examples/PDFLinkMaint.py#L908-L911 | train | 223,901 |
pymupdf/PyMuPDF | examples/PDFLinkMaint.py | PDFdisplay.is_in_free_area | def is_in_free_area(self, nr, ok = -1):
""" Determine if rect covers a free area inside the bitmap."""
for i, r in enumerate(self.link_rects):
if r.Intersects(nr) and i != ok:
return False
bmrect = wx.Rect(0,0,dlg.bitmap.Size[0],dlg.bitmap.Size[1])
return bmrect.Contains(nr) | python | def is_in_free_area(self, nr, ok = -1):
""" Determine if rect covers a free area inside the bitmap."""
for i, r in enumerate(self.link_rects):
if r.Intersects(nr) and i != ok:
return False
bmrect = wx.Rect(0,0,dlg.bitmap.Size[0],dlg.bitmap.Size[1])
return bmrect.Contains(nr) | [
"def",
"is_in_free_area",
"(",
"self",
",",
"nr",
",",
"ok",
"=",
"-",
"1",
")",
":",
"for",
"i",
",",
"r",
"in",
"enumerate",
"(",
"self",
".",
"link_rects",
")",
":",
"if",
"r",
".",
"Intersects",
"(",
"nr",
")",
"and",
"i",
"!=",
"ok",
":",
... | Determine if rect covers a free area inside the bitmap. | [
"Determine",
"if",
"rect",
"covers",
"a",
"free",
"area",
"inside",
"the",
"bitmap",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/examples/PDFLinkMaint.py#L913-L919 | train | 223,902 |
pymupdf/PyMuPDF | examples/PDFLinkMaint.py | PDFdisplay.get_linkrect_idx | def get_linkrect_idx(self, pos):
""" Determine if cursor is inside one of the link hot spots."""
for i, r in enumerate(self.link_rects):
if r.Contains(pos):
return i
return -1 | python | def get_linkrect_idx(self, pos):
""" Determine if cursor is inside one of the link hot spots."""
for i, r in enumerate(self.link_rects):
if r.Contains(pos):
return i
return -1 | [
"def",
"get_linkrect_idx",
"(",
"self",
",",
"pos",
")",
":",
"for",
"i",
",",
"r",
"in",
"enumerate",
"(",
"self",
".",
"link_rects",
")",
":",
"if",
"r",
".",
"Contains",
"(",
"pos",
")",
":",
"return",
"i",
"return",
"-",
"1"
] | Determine if cursor is inside one of the link hot spots. | [
"Determine",
"if",
"cursor",
"is",
"inside",
"one",
"of",
"the",
"link",
"hot",
"spots",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/examples/PDFLinkMaint.py#L921-L926 | train | 223,903 |
pymupdf/PyMuPDF | examples/PDFLinkMaint.py | PDFdisplay.get_bottomrect_idx | def get_bottomrect_idx(self, pos):
""" Determine if cursor is on bottom right corner of a hot spot."""
for i, r in enumerate(self.link_bottom_rects):
if r.Contains(pos):
return i
return -1 | python | def get_bottomrect_idx(self, pos):
""" Determine if cursor is on bottom right corner of a hot spot."""
for i, r in enumerate(self.link_bottom_rects):
if r.Contains(pos):
return i
return -1 | [
"def",
"get_bottomrect_idx",
"(",
"self",
",",
"pos",
")",
":",
"for",
"i",
",",
"r",
"in",
"enumerate",
"(",
"self",
".",
"link_bottom_rects",
")",
":",
"if",
"r",
".",
"Contains",
"(",
"pos",
")",
":",
"return",
"i",
"return",
"-",
"1"
] | Determine if cursor is on bottom right corner of a hot spot. | [
"Determine",
"if",
"cursor",
"is",
"on",
"bottom",
"right",
"corner",
"of",
"a",
"hot",
"spot",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/examples/PDFLinkMaint.py#L928-L933 | train | 223,904 |
pymupdf/PyMuPDF | fitz/utils.py | getTextWords | def getTextWords(page):
"""Return the text words as a list with the bbox for each word.
"""
CheckParent(page)
dl = page.getDisplayList()
tp = dl.getTextPage()
l = tp._extractTextWords_AsList()
del dl
del tp
return l | python | def getTextWords(page):
"""Return the text words as a list with the bbox for each word.
"""
CheckParent(page)
dl = page.getDisplayList()
tp = dl.getTextPage()
l = tp._extractTextWords_AsList()
del dl
del tp
return l | [
"def",
"getTextWords",
"(",
"page",
")",
":",
"CheckParent",
"(",
"page",
")",
"dl",
"=",
"page",
".",
"getDisplayList",
"(",
")",
"tp",
"=",
"dl",
".",
"getTextPage",
"(",
")",
"l",
"=",
"tp",
".",
"_extractTextWords_AsList",
"(",
")",
"del",
"dl",
... | Return the text words as a list with the bbox for each word. | [
"Return",
"the",
"text",
"words",
"as",
"a",
"list",
"with",
"the",
"bbox",
"for",
"each",
"word",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L349-L358 | train | 223,905 |
pymupdf/PyMuPDF | fitz/utils.py | getText | def getText(page, output = "text"):
""" Extract a document page's text.
Args:
output: (str) text, html, dict, json, rawdict, xhtml or xml.
Returns:
the output of TextPage methods extractText, extractHTML, extractDICT, extractJSON, extractRAWDICT, extractXHTML or etractXML respectively. Default and misspelling choice is "text".
"""
CheckParent(page)
dl = page.getDisplayList()
# available output types
formats = ("text", "html", "json", "xml", "xhtml", "dict", "rawdict")
# choose which of them also include images in the TextPage
images = (0, 1, 1, 0, 1, 1, 1) # controls image inclusion in text page
try:
f = formats.index(output.lower())
except:
f = 0
flags = TEXT_PRESERVE_LIGATURES | TEXT_PRESERVE_WHITESPACE
if images[f] :
flags |= TEXT_PRESERVE_IMAGES
tp = dl.getTextPage(flags) # TextPage with / without images
t = tp._extractText(f)
del dl
del tp
return t | python | def getText(page, output = "text"):
""" Extract a document page's text.
Args:
output: (str) text, html, dict, json, rawdict, xhtml or xml.
Returns:
the output of TextPage methods extractText, extractHTML, extractDICT, extractJSON, extractRAWDICT, extractXHTML or etractXML respectively. Default and misspelling choice is "text".
"""
CheckParent(page)
dl = page.getDisplayList()
# available output types
formats = ("text", "html", "json", "xml", "xhtml", "dict", "rawdict")
# choose which of them also include images in the TextPage
images = (0, 1, 1, 0, 1, 1, 1) # controls image inclusion in text page
try:
f = formats.index(output.lower())
except:
f = 0
flags = TEXT_PRESERVE_LIGATURES | TEXT_PRESERVE_WHITESPACE
if images[f] :
flags |= TEXT_PRESERVE_IMAGES
tp = dl.getTextPage(flags) # TextPage with / without images
t = tp._extractText(f)
del dl
del tp
return t | [
"def",
"getText",
"(",
"page",
",",
"output",
"=",
"\"text\"",
")",
":",
"CheckParent",
"(",
"page",
")",
"dl",
"=",
"page",
".",
"getDisplayList",
"(",
")",
"# available output types",
"formats",
"=",
"(",
"\"text\"",
",",
"\"html\"",
",",
"\"json\"",
","... | Extract a document page's text.
Args:
output: (str) text, html, dict, json, rawdict, xhtml or xml.
Returns:
the output of TextPage methods extractText, extractHTML, extractDICT, extractJSON, extractRAWDICT, extractXHTML or etractXML respectively. Default and misspelling choice is "text". | [
"Extract",
"a",
"document",
"page",
"s",
"text",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L360-L386 | train | 223,906 |
pymupdf/PyMuPDF | fitz/utils.py | getPagePixmap | def getPagePixmap(doc, pno, matrix = None, colorspace = csRGB,
clip = None, alpha = True):
"""Create pixmap of document page by page number.
Notes:
Convenience function calling page.getPixmap.
Args:
pno: (int) page number
matrix: Matrix for transformation (default: Identity).
colorspace: (str/Colorspace) rgb, rgb, gray - case ignored, default csRGB.
clip: (irect-like) restrict rendering to this area.
alpha: (bool) include alpha channel
"""
return doc[pno].getPixmap(matrix = matrix, colorspace = colorspace,
clip = clip, alpha = alpha) | python | def getPagePixmap(doc, pno, matrix = None, colorspace = csRGB,
clip = None, alpha = True):
"""Create pixmap of document page by page number.
Notes:
Convenience function calling page.getPixmap.
Args:
pno: (int) page number
matrix: Matrix for transformation (default: Identity).
colorspace: (str/Colorspace) rgb, rgb, gray - case ignored, default csRGB.
clip: (irect-like) restrict rendering to this area.
alpha: (bool) include alpha channel
"""
return doc[pno].getPixmap(matrix = matrix, colorspace = colorspace,
clip = clip, alpha = alpha) | [
"def",
"getPagePixmap",
"(",
"doc",
",",
"pno",
",",
"matrix",
"=",
"None",
",",
"colorspace",
"=",
"csRGB",
",",
"clip",
"=",
"None",
",",
"alpha",
"=",
"True",
")",
":",
"return",
"doc",
"[",
"pno",
"]",
".",
"getPixmap",
"(",
"matrix",
"=",
"mat... | Create pixmap of document page by page number.
Notes:
Convenience function calling page.getPixmap.
Args:
pno: (int) page number
matrix: Matrix for transformation (default: Identity).
colorspace: (str/Colorspace) rgb, rgb, gray - case ignored, default csRGB.
clip: (irect-like) restrict rendering to this area.
alpha: (bool) include alpha channel | [
"Create",
"pixmap",
"of",
"document",
"page",
"by",
"page",
"number",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L438-L452 | train | 223,907 |
pymupdf/PyMuPDF | fitz/utils.py | getToC | def getToC(doc, simple = True):
"""Create a table of contents.
Args:
simple: a bool to control output. Returns a list, where each entry consists of outline level, title, page number and link destination (if simple = False). For details see PyMuPDF's documentation.
"""
def recurse(olItem, liste, lvl):
'''Recursively follow the outline item chain and record item information in a list.'''
while olItem:
if olItem.title:
title = olItem.title
else:
title = " "
if not olItem.isExternal:
if olItem.uri:
page = olItem.page + 1
else:
page = -1
else:
page = -1
if not simple:
link = getLinkDict(olItem)
liste.append([lvl, title, page, link])
else:
liste.append([lvl, title, page])
if olItem.down:
liste = recurse(olItem.down, liste, lvl+1)
olItem = olItem.next
return liste
# check if document is open and not encrypted
if doc.isClosed:
raise ValueError("illegal operation on closed document")
olItem = doc.outline
if not olItem: return []
lvl = 1
liste = []
return recurse(olItem, liste, lvl) | python | def getToC(doc, simple = True):
"""Create a table of contents.
Args:
simple: a bool to control output. Returns a list, where each entry consists of outline level, title, page number and link destination (if simple = False). For details see PyMuPDF's documentation.
"""
def recurse(olItem, liste, lvl):
'''Recursively follow the outline item chain and record item information in a list.'''
while olItem:
if olItem.title:
title = olItem.title
else:
title = " "
if not olItem.isExternal:
if olItem.uri:
page = olItem.page + 1
else:
page = -1
else:
page = -1
if not simple:
link = getLinkDict(olItem)
liste.append([lvl, title, page, link])
else:
liste.append([lvl, title, page])
if olItem.down:
liste = recurse(olItem.down, liste, lvl+1)
olItem = olItem.next
return liste
# check if document is open and not encrypted
if doc.isClosed:
raise ValueError("illegal operation on closed document")
olItem = doc.outline
if not olItem: return []
lvl = 1
liste = []
return recurse(olItem, liste, lvl) | [
"def",
"getToC",
"(",
"doc",
",",
"simple",
"=",
"True",
")",
":",
"def",
"recurse",
"(",
"olItem",
",",
"liste",
",",
"lvl",
")",
":",
"'''Recursively follow the outline item chain and record item information in a list.'''",
"while",
"olItem",
":",
"if",
"olItem",
... | Create a table of contents.
Args:
simple: a bool to control output. Returns a list, where each entry consists of outline level, title, page number and link destination (if simple = False). For details see PyMuPDF's documentation. | [
"Create",
"a",
"table",
"of",
"contents",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L528-L571 | train | 223,908 |
pymupdf/PyMuPDF | fitz/utils.py | updateLink | def updateLink(page, lnk):
""" Update a link on the current page. """
CheckParent(page)
annot = getLinkText(page, lnk)
if annot == "":
raise ValueError("link kind not supported")
page.parent._updateObject(lnk["xref"], annot, page = page)
return | python | def updateLink(page, lnk):
""" Update a link on the current page. """
CheckParent(page)
annot = getLinkText(page, lnk)
if annot == "":
raise ValueError("link kind not supported")
page.parent._updateObject(lnk["xref"], annot, page = page)
return | [
"def",
"updateLink",
"(",
"page",
",",
"lnk",
")",
":",
"CheckParent",
"(",
"page",
")",
"annot",
"=",
"getLinkText",
"(",
"page",
",",
"lnk",
")",
"if",
"annot",
"==",
"\"\"",
":",
"raise",
"ValueError",
"(",
"\"link kind not supported\"",
")",
"page",
... | Update a link on the current page. | [
"Update",
"a",
"link",
"on",
"the",
"current",
"page",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L990-L998 | train | 223,909 |
pymupdf/PyMuPDF | fitz/utils.py | insertLink | def insertLink(page, lnk, mark = True):
""" Insert a new link for the current page. """
CheckParent(page)
annot = getLinkText(page, lnk)
if annot == "":
raise ValueError("link kind not supported")
page._addAnnot_FromString([annot])
return | python | def insertLink(page, lnk, mark = True):
""" Insert a new link for the current page. """
CheckParent(page)
annot = getLinkText(page, lnk)
if annot == "":
raise ValueError("link kind not supported")
page._addAnnot_FromString([annot])
return | [
"def",
"insertLink",
"(",
"page",
",",
"lnk",
",",
"mark",
"=",
"True",
")",
":",
"CheckParent",
"(",
"page",
")",
"annot",
"=",
"getLinkText",
"(",
"page",
",",
"lnk",
")",
"if",
"annot",
"==",
"\"\"",
":",
"raise",
"ValueError",
"(",
"\"link kind not... | Insert a new link for the current page. | [
"Insert",
"a",
"new",
"link",
"for",
"the",
"current",
"page",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L1000-L1008 | train | 223,910 |
pymupdf/PyMuPDF | fitz/utils.py | newPage | def newPage(doc, pno=-1, width=595, height=842):
"""Create and return a new page object.
"""
doc._newPage(pno, width=width, height=height)
return doc[pno] | python | def newPage(doc, pno=-1, width=595, height=842):
"""Create and return a new page object.
"""
doc._newPage(pno, width=width, height=height)
return doc[pno] | [
"def",
"newPage",
"(",
"doc",
",",
"pno",
"=",
"-",
"1",
",",
"width",
"=",
"595",
",",
"height",
"=",
"842",
")",
":",
"doc",
".",
"_newPage",
"(",
"pno",
",",
"width",
"=",
"width",
",",
"height",
"=",
"height",
")",
"return",
"doc",
"[",
"pn... | Create and return a new page object. | [
"Create",
"and",
"return",
"a",
"new",
"page",
"object",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L1094-L1098 | train | 223,911 |
pymupdf/PyMuPDF | fitz/utils.py | insertPage | def insertPage(
doc,
pno,
text=None,
fontsize=11,
width=595,
height=842,
fontname="helv",
fontfile=None,
color=None,
):
""" Create a new PDF page and insert some text.
Notes:
Function combining Document.newPage() and Page.insertText().
For parameter details see these methods.
"""
page = doc.newPage(pno=pno, width=width, height=height)
if not bool(text):
return 0
rc = page.insertText(
(50, 72),
text,
fontsize=fontsize,
fontname=fontname,
fontfile=fontfile,
color=color,
)
return rc | python | def insertPage(
doc,
pno,
text=None,
fontsize=11,
width=595,
height=842,
fontname="helv",
fontfile=None,
color=None,
):
""" Create a new PDF page and insert some text.
Notes:
Function combining Document.newPage() and Page.insertText().
For parameter details see these methods.
"""
page = doc.newPage(pno=pno, width=width, height=height)
if not bool(text):
return 0
rc = page.insertText(
(50, 72),
text,
fontsize=fontsize,
fontname=fontname,
fontfile=fontfile,
color=color,
)
return rc | [
"def",
"insertPage",
"(",
"doc",
",",
"pno",
",",
"text",
"=",
"None",
",",
"fontsize",
"=",
"11",
",",
"width",
"=",
"595",
",",
"height",
"=",
"842",
",",
"fontname",
"=",
"\"helv\"",
",",
"fontfile",
"=",
"None",
",",
"color",
"=",
"None",
",",
... | Create a new PDF page and insert some text.
Notes:
Function combining Document.newPage() and Page.insertText().
For parameter details see these methods. | [
"Create",
"a",
"new",
"PDF",
"page",
"and",
"insert",
"some",
"text",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L1100-L1128 | train | 223,912 |
pymupdf/PyMuPDF | fitz/utils.py | drawSquiggle | def drawSquiggle(page, p1, p2, breadth = 2, color=None, dashes=None,
width=1, roundCap=False, overlay=True, morph=None):
"""Draw a squiggly line from point p1 to point p2.
"""
img = page.newShape()
p = img.drawSquiggle(Point(p1), Point(p2), breadth = breadth)
img.finish(color=color, dashes=dashes, width=width, closePath=False,
roundCap=roundCap, morph=morph)
img.commit(overlay)
return p | python | def drawSquiggle(page, p1, p2, breadth = 2, color=None, dashes=None,
width=1, roundCap=False, overlay=True, morph=None):
"""Draw a squiggly line from point p1 to point p2.
"""
img = page.newShape()
p = img.drawSquiggle(Point(p1), Point(p2), breadth = breadth)
img.finish(color=color, dashes=dashes, width=width, closePath=False,
roundCap=roundCap, morph=morph)
img.commit(overlay)
return p | [
"def",
"drawSquiggle",
"(",
"page",
",",
"p1",
",",
"p2",
",",
"breadth",
"=",
"2",
",",
"color",
"=",
"None",
",",
"dashes",
"=",
"None",
",",
"width",
"=",
"1",
",",
"roundCap",
"=",
"False",
",",
"overlay",
"=",
"True",
",",
"morph",
"=",
"Non... | Draw a squiggly line from point p1 to point p2. | [
"Draw",
"a",
"squiggly",
"line",
"from",
"point",
"p1",
"to",
"point",
"p2",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L1141-L1151 | train | 223,913 |
pymupdf/PyMuPDF | fitz/utils.py | drawQuad | 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=roundCap, morph=morph)
img.commit(overlay)
return Q | python | 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=roundCap, morph=morph)
img.commit(overlay)
return Q | [
"def",
"drawQuad",
"(",
"page",
",",
"quad",
",",
"color",
"=",
"None",
",",
"fill",
"=",
"None",
",",
"dashes",
"=",
"None",
",",
"width",
"=",
"1",
",",
"roundCap",
"=",
"False",
",",
"morph",
"=",
"None",
",",
"overlay",
"=",
"True",
")",
":",... | Draw a quadrilateral. | [
"Draw",
"a",
"quadrilateral",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L1177-L1187 | train | 223,914 |
pymupdf/PyMuPDF | fitz/utils.py | drawPolyline | 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, dashes=dashes, width=width,
roundCap=roundCap, morph=morph, closePath=closePath)
img.commit(overlay)
return Q | python | 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, dashes=dashes, width=width,
roundCap=roundCap, morph=morph, closePath=closePath)
img.commit(overlay)
return Q | [
"def",
"drawPolyline",
"(",
"page",
",",
"points",
",",
"color",
"=",
"None",
",",
"fill",
"=",
"None",
",",
"dashes",
"=",
"None",
",",
"width",
"=",
"1",
",",
"morph",
"=",
"None",
",",
"roundCap",
"=",
"False",
",",
"overlay",
"=",
"True",
",",
... | Draw multiple connected line segments. | [
"Draw",
"multiple",
"connected",
"line",
"segments",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L1189-L1200 | train | 223,915 |
pymupdf/PyMuPDF | fitz/utils.py | drawBezier | 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(Point(p1), Point(p2), Point(p3), Point(p4))
img.finish(color=color, fill=fill, dashes=dashes, width=width,
roundCap=roundCap, morph=morph, closePath=closePath)
img.commit(overlay)
return Q | python | 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(Point(p1), Point(p2), Point(p3), Point(p4))
img.finish(color=color, fill=fill, dashes=dashes, width=width,
roundCap=roundCap, morph=morph, closePath=closePath)
img.commit(overlay)
return Q | [
"def",
"drawBezier",
"(",
"page",
",",
"p1",
",",
"p2",
",",
"p3",
",",
"p4",
",",
"color",
"=",
"None",
",",
"fill",
"=",
"None",
",",
"dashes",
"=",
"None",
",",
"width",
"=",
"1",
",",
"morph",
"=",
"None",
",",
"closePath",
"=",
"False",
",... | Draw a general cubic Bezier curve from p1 to p4 using control points p2 and p3. | [
"Draw",
"a",
"general",
"cubic",
"Bezier",
"curve",
"from",
"p1",
"to",
"p4",
"using",
"control",
"points",
"p2",
"and",
"p3",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L1240-L1251 | train | 223,916 |
pymupdf/PyMuPDF | fitz/utils.py | getColor | 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.)
except:
return (1, 1, 1) | python | 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.)
except:
return (1, 1, 1) | [
"def",
"getColor",
"(",
"name",
")",
":",
"try",
":",
"c",
"=",
"getColorInfoList",
"(",
")",
"[",
"getColorList",
"(",
")",
".",
"index",
"(",
"name",
".",
"upper",
"(",
")",
")",
"]",
"return",
"(",
"c",
"[",
"1",
"]",
"/",
"255.",
",",
"c",
... | 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. | [
"Retrieve",
"RGB",
"color",
"in",
"PDF",
"format",
"by",
"name",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L1848-L1858 | train | 223,917 |
pymupdf/PyMuPDF | fitz/utils.py | getColorHSV | 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)
r = x[1] / 255.
g = x[2] / 255.
b = x[3] / 255.
cmax = max(r, g, b)
V = round(cmax * 100, 1)
cmin = min(r, g, b)
delta = cmax - cmin
if delta == 0:
hue = 0
elif cmax == r:
hue = 60. * (((g - b)/delta) % 6)
elif cmax == g:
hue = 60. * (((b - r)/delta) + 2)
else:
hue = 60. * (((r - g)/delta) + 4)
H = int(round(hue))
if cmax == 0:
sat = 0
else:
sat = delta / cmax
S = int(round(sat * 100))
return (H, S, V) | python | 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)
r = x[1] / 255.
g = x[2] / 255.
b = x[3] / 255.
cmax = max(r, g, b)
V = round(cmax * 100, 1)
cmin = min(r, g, b)
delta = cmax - cmin
if delta == 0:
hue = 0
elif cmax == r:
hue = 60. * (((g - b)/delta) % 6)
elif cmax == g:
hue = 60. * (((b - r)/delta) + 2)
else:
hue = 60. * (((r - g)/delta) + 4)
H = int(round(hue))
if cmax == 0:
sat = 0
else:
sat = delta / cmax
S = int(round(sat * 100))
return (H, S, V) | [
"def",
"getColorHSV",
"(",
"name",
")",
":",
"try",
":",
"x",
"=",
"getColorInfoList",
"(",
")",
"[",
"getColorList",
"(",
")",
".",
"index",
"(",
"name",
".",
"upper",
"(",
")",
")",
"]",
"except",
":",
"return",
"(",
"-",
"1",
",",
"-",
"1",
... | Retrieve the hue, saturation, value triple of a color name.
Returns:
a triple (degree, percent, percent). If not found (-1, -1, -1) is returned. | [
"Retrieve",
"the",
"hue",
"saturation",
"value",
"triple",
"of",
"a",
"color",
"name",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L1860-L1895 | train | 223,918 |
pymupdf/PyMuPDF | fitz/utils.py | Shape.horizontal_angle | 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 vector 'C' -> 'P'
alfa = math.asin(abs(S.y)) # absolute angle from horizontal
if S.x < 0: # make arcsin result unique
if S.y <= 0: # bottom-left
alfa = -(math.pi - alfa)
else: # top-left
alfa = math.pi - alfa
else:
if S.y >= 0: # top-right
pass
else: # bottom-right
alfa = - alfa
return alfa | python | 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 vector 'C' -> 'P'
alfa = math.asin(abs(S.y)) # absolute angle from horizontal
if S.x < 0: # make arcsin result unique
if S.y <= 0: # bottom-left
alfa = -(math.pi - alfa)
else: # top-left
alfa = math.pi - alfa
else:
if S.y >= 0: # top-right
pass
else: # bottom-right
alfa = - alfa
return alfa | [
"def",
"horizontal_angle",
"(",
"C",
",",
"P",
")",
":",
"S",
"=",
"Point",
"(",
"P",
"-",
"C",
")",
".",
"unit",
"# unit vector 'C' -> 'P'",
"alfa",
"=",
"math",
".",
"asin",
"(",
"abs",
"(",
"S",
".",
"y",
")",
")",
"# absolute angle from horizontal"... | 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. | [
"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",
"quad... | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L1986-L2003 | train | 223,919 |
pymupdf/PyMuPDF | fitz/utils.py | Shape.drawLine | 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_cont += "%g %g l\n" % JM_TUPLE(p2 * self.ipctm)
self.updateRect(p2)
self.lastPoint = p2
return self.lastPoint | python | 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_cont += "%g %g l\n" % JM_TUPLE(p2 * self.ipctm)
self.updateRect(p2)
self.lastPoint = p2
return self.lastPoint | [
"def",
"drawLine",
"(",
"self",
",",
"p1",
",",
"p2",
")",
":",
"p1",
"=",
"Point",
"(",
"p1",
")",
"p2",
"=",
"Point",
"(",
"p2",
")",
"if",
"not",
"(",
"self",
".",
"lastPoint",
"==",
"p1",
")",
":",
"self",
".",
"draw_cont",
"+=",
"\"%g %g m... | Draw a line between two points. | [
"Draw",
"a",
"line",
"between",
"two",
"points",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L2042-L2055 | train | 223,920 |
pymupdf/PyMuPDF | fitz/utils.py | Shape.drawPolyline | 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.lastPoint = Point(p)
else:
self.draw_cont += "%g %g l\n" % JM_TUPLE(Point(p) * self.ipctm)
self.updateRect(p)
self.lastPoint = Point(points[-1])
return self.lastPoint | python | 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.lastPoint = Point(p)
else:
self.draw_cont += "%g %g l\n" % JM_TUPLE(Point(p) * self.ipctm)
self.updateRect(p)
self.lastPoint = Point(points[-1])
return self.lastPoint | [
"def",
"drawPolyline",
"(",
"self",
",",
"points",
")",
":",
"for",
"i",
",",
"p",
"in",
"enumerate",
"(",
"points",
")",
":",
"if",
"i",
"==",
"0",
":",
"if",
"not",
"(",
"self",
".",
"lastPoint",
"==",
"Point",
"(",
"p",
")",
")",
":",
"self"... | Draw several connected line segments. | [
"Draw",
"several",
"connected",
"line",
"segments",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L2057-L2070 | train | 223,921 |
pymupdf/PyMuPDF | fitz/utils.py | Shape.drawBezier | 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 += "%g %g %g %g %g %g c\n" % JM_TUPLE(list(p2 * self.ipctm) + \
list(p3 * self.ipctm) + \
list(p4 * self.ipctm))
self.updateRect(p1)
self.updateRect(p2)
self.updateRect(p3)
self.updateRect(p4)
self.lastPoint = p4
return self.lastPoint | python | 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 += "%g %g %g %g %g %g c\n" % JM_TUPLE(list(p2 * self.ipctm) + \
list(p3 * self.ipctm) + \
list(p4 * self.ipctm))
self.updateRect(p1)
self.updateRect(p2)
self.updateRect(p3)
self.updateRect(p4)
self.lastPoint = p4
return self.lastPoint | [
"def",
"drawBezier",
"(",
"self",
",",
"p1",
",",
"p2",
",",
"p3",
",",
"p4",
")",
":",
"p1",
"=",
"Point",
"(",
"p1",
")",
"p2",
"=",
"Point",
"(",
"p2",
")",
"p3",
"=",
"Point",
"(",
"p3",
")",
"p4",
"=",
"Point",
"(",
"p4",
")",
"if",
... | Draw a standard cubic Bezier curve. | [
"Draw",
"a",
"standard",
"cubic",
"Bezier",
"curve",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L2072-L2089 | train | 223,922 |
pymupdf/PyMuPDF | fitz/utils.py | Shape.drawOval | 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.5
mr = q.ur + (q.lr - q.ur) * 0.5
mb = q.ll + (q.lr - q.ll) * 0.5
ml = q.ul + (q.ll - q.ul) * 0.5
if not (self.lastPoint == ml):
self.draw_cont += "%g %g m\n" % JM_TUPLE(ml * self.ipctm)
self.lastPoint = ml
self.drawCurve(ml, q.ll, mb)
self.drawCurve(mb, q.lr, mr)
self.drawCurve(mr, q.ur, mt)
self.drawCurve(mt, q.ul, ml)
self.updateRect(q.rect)
self.lastPoint = ml
return self.lastPoint | python | 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.5
mr = q.ur + (q.lr - q.ur) * 0.5
mb = q.ll + (q.lr - q.ll) * 0.5
ml = q.ul + (q.ll - q.ul) * 0.5
if not (self.lastPoint == ml):
self.draw_cont += "%g %g m\n" % JM_TUPLE(ml * self.ipctm)
self.lastPoint = ml
self.drawCurve(ml, q.ll, mb)
self.drawCurve(mb, q.lr, mr)
self.drawCurve(mr, q.ur, mt)
self.drawCurve(mt, q.ul, ml)
self.updateRect(q.rect)
self.lastPoint = ml
return self.lastPoint | [
"def",
"drawOval",
"(",
"self",
",",
"tetra",
")",
":",
"if",
"len",
"(",
"tetra",
")",
"!=",
"4",
":",
"raise",
"ValueError",
"(",
"\"invalid arg length\"",
")",
"if",
"hasattr",
"(",
"tetra",
"[",
"0",
"]",
",",
"\"__float__\"",
")",
":",
"q",
"=",... | Draw an ellipse inside a tetrapod. | [
"Draw",
"an",
"ellipse",
"inside",
"a",
"tetrapod",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L2091-L2114 | train | 223,923 |
pymupdf/PyMuPDF | fitz/utils.py | Shape.drawCurve | 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, k2, p3) | python | 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, k2, p3) | [
"def",
"drawCurve",
"(",
"self",
",",
"p1",
",",
"p2",
",",
"p3",
")",
":",
"kappa",
"=",
"0.55228474983",
"p1",
"=",
"Point",
"(",
"p1",
")",
"p2",
"=",
"Point",
"(",
"p2",
")",
"p3",
"=",
"Point",
"(",
"p3",
")",
"k1",
"=",
"p1",
"+",
"(",
... | Draw a curve between points using one control point. | [
"Draw",
"a",
"curve",
"between",
"points",
"using",
"one",
"control",
"point",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L2125-L2134 | train | 223,924 |
pymupdf/PyMuPDF | fitz/utils.py | Shape.drawQuad | def drawQuad(self, quad):
"""Draw a Quad.
"""
q = Quad(quad)
return self.drawPolyline([q.ul, q.ll, q.lr, q.ur, q.ul]) | python | def drawQuad(self, quad):
"""Draw a Quad.
"""
q = Quad(quad)
return self.drawPolyline([q.ul, q.ll, q.lr, q.ur, q.ul]) | [
"def",
"drawQuad",
"(",
"self",
",",
"quad",
")",
":",
"q",
"=",
"Quad",
"(",
"quad",
")",
"return",
"self",
".",
"drawPolyline",
"(",
"[",
"q",
".",
"ul",
",",
"q",
".",
"ll",
",",
"q",
".",
"lr",
",",
"q",
".",
"ur",
",",
"q",
".",
"ul",
... | Draw a Quad. | [
"Draw",
"a",
"Quad",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L2215-L2219 | train | 223,925 |
pymupdf/PyMuPDF | fitz/utils.py | Shape.drawZigzag | 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 / (4 * breadth), 0)) # always take full phases
if cnt < 4:
raise ValueError("points too close")
mb = rad / cnt # revised breadth
matrix = TOOLS._hor_matrix(p1, p2) # normalize line to x-axis
i_mat = ~matrix # get original position
points = [] # stores edges
for i in range (1, cnt):
if i % 4 == 1: # point "above" connection
p = Point(i, -1) * mb
elif i % 4 == 3: # point "below" connection
p = Point(i, 1) * mb
else: # ignore others
continue
points.append(p * i_mat)
self.drawPolyline([p1] + points + [p2]) # add start and end points
return p2 | python | 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 / (4 * breadth), 0)) # always take full phases
if cnt < 4:
raise ValueError("points too close")
mb = rad / cnt # revised breadth
matrix = TOOLS._hor_matrix(p1, p2) # normalize line to x-axis
i_mat = ~matrix # get original position
points = [] # stores edges
for i in range (1, cnt):
if i % 4 == 1: # point "above" connection
p = Point(i, -1) * mb
elif i % 4 == 3: # point "below" connection
p = Point(i, 1) * mb
else: # ignore others
continue
points.append(p * i_mat)
self.drawPolyline([p1] + points + [p2]) # add start and end points
return p2 | [
"def",
"drawZigzag",
"(",
"self",
",",
"p1",
",",
"p2",
",",
"breadth",
"=",
"2",
")",
":",
"p1",
"=",
"Point",
"(",
"p1",
")",
"p2",
"=",
"Point",
"(",
"p2",
")",
"S",
"=",
"p2",
"-",
"p1",
"# vector start - end",
"rad",
"=",
"abs",
"(",
"S",
... | Draw a zig-zagged line from p1 to p2. | [
"Draw",
"a",
"zig",
"-",
"zagged",
"line",
"from",
"p1",
"to",
"p2",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L2221-L2244 | train | 223,926 |
pymupdf/PyMuPDF | fitz/utils.py | Shape.drawSquiggle | 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 / (4 * breadth), 0)) # always take full phases
if cnt < 4:
raise ValueError("points too close")
mb = rad / cnt # revised breadth
matrix = TOOLS._hor_matrix(p1, p2) # normalize line to x-axis
i_mat = ~matrix # get original position
k = 2.4142135623765633 # y of drawCurve helper point
points = [] # stores edges
for i in range (1, cnt):
if i % 4 == 1: # point "above" connection
p = Point(i, -k) * mb
elif i % 4 == 3: # point "below" connection
p = Point(i, k) * mb
else: # else on connection line
p = Point(i, 0) * mb
points.append(p * i_mat)
points = [p1] + points + [p2]
cnt = len(points)
i = 0
while i + 2 < cnt:
self.drawCurve(points[i], points[i+1], points[i+2])
i += 2
return p2 | python | 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 / (4 * breadth), 0)) # always take full phases
if cnt < 4:
raise ValueError("points too close")
mb = rad / cnt # revised breadth
matrix = TOOLS._hor_matrix(p1, p2) # normalize line to x-axis
i_mat = ~matrix # get original position
k = 2.4142135623765633 # y of drawCurve helper point
points = [] # stores edges
for i in range (1, cnt):
if i % 4 == 1: # point "above" connection
p = Point(i, -k) * mb
elif i % 4 == 3: # point "below" connection
p = Point(i, k) * mb
else: # else on connection line
p = Point(i, 0) * mb
points.append(p * i_mat)
points = [p1] + points + [p2]
cnt = len(points)
i = 0
while i + 2 < cnt:
self.drawCurve(points[i], points[i+1], points[i+2])
i += 2
return p2 | [
"def",
"drawSquiggle",
"(",
"self",
",",
"p1",
",",
"p2",
",",
"breadth",
"=",
"2",
")",
":",
"p1",
"=",
"Point",
"(",
"p1",
")",
"p2",
"=",
"Point",
"(",
"p2",
")",
"S",
"=",
"p2",
"-",
"p1",
"# vector start - end",
"rad",
"=",
"abs",
"(",
"S"... | Draw a squiggly line from p1 to p2. | [
"Draw",
"a",
"squiggly",
"line",
"from",
"p1",
"to",
"p2",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L2246-L2277 | train | 223,927 |
pymupdf/PyMuPDF | fitz/utils.py | Shape.finish | 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:
Apply stroke and fill colors, dashes, line style and width, or
morphing. Also determines whether any open path should be closed
by a connecting line to its start point.
"""
if self.draw_cont == "": # treat empty contents as no-op
return
color_str = ColorCode(color, "c") # ensure proper color string
fill_str = ColorCode(fill, "f") # ensure proper fill string
if width != 1:
self.draw_cont += "%g w\n" % width
if roundCap:
self.draw_cont += "%i J %i j\n" % (roundCap, roundCap)
if dashes is not None and len(dashes) > 0:
self.draw_cont += "%s d\n" % dashes
if closePath:
self.draw_cont += "h\n"
self.lastPoint = None
if color is not None:
self.draw_cont += color_str
if fill is not None:
self.draw_cont += fill_str
if not even_odd:
self.draw_cont += "B\n"
else:
self.draw_cont += "B*\n"
else:
self.draw_cont += "S\n"
if CheckMorph(morph):
m1 = Matrix(1, 0, 0, 1, morph[0].x + self.x,
self.height - morph[0].y - self.y)
mat = ~m1 * morph[1] * m1
self.draw_cont = "%g %g %g %g %g %g cm\n" % JM_TUPLE(mat) + self.draw_cont
self.totalcont += "\nq\n" + self.draw_cont + "Q\n"
self.draw_cont = ""
self.lastPoint = None
return | python | 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:
Apply stroke and fill colors, dashes, line style and width, or
morphing. Also determines whether any open path should be closed
by a connecting line to its start point.
"""
if self.draw_cont == "": # treat empty contents as no-op
return
color_str = ColorCode(color, "c") # ensure proper color string
fill_str = ColorCode(fill, "f") # ensure proper fill string
if width != 1:
self.draw_cont += "%g w\n" % width
if roundCap:
self.draw_cont += "%i J %i j\n" % (roundCap, roundCap)
if dashes is not None and len(dashes) > 0:
self.draw_cont += "%s d\n" % dashes
if closePath:
self.draw_cont += "h\n"
self.lastPoint = None
if color is not None:
self.draw_cont += color_str
if fill is not None:
self.draw_cont += fill_str
if not even_odd:
self.draw_cont += "B\n"
else:
self.draw_cont += "B*\n"
else:
self.draw_cont += "S\n"
if CheckMorph(morph):
m1 = Matrix(1, 0, 0, 1, morph[0].x + self.x,
self.height - morph[0].y - self.y)
mat = ~m1 * morph[1] * m1
self.draw_cont = "%g %g %g %g %g %g cm\n" % JM_TUPLE(mat) + self.draw_cont
self.totalcont += "\nq\n" + self.draw_cont + "Q\n"
self.draw_cont = ""
self.lastPoint = None
return | [
"def",
"finish",
"(",
"self",
",",
"width",
"=",
"1",
",",
"color",
"=",
"None",
",",
"fill",
"=",
"None",
",",
"roundCap",
"=",
"False",
",",
"dashes",
"=",
"None",
",",
"even_odd",
"=",
"False",
",",
"morph",
"=",
"None",
",",
"closePath",
"=",
... | Finish the current drawing segment.
Notes:
Apply stroke and fill colors, dashes, line style and width, or
morphing. Also determines whether any open path should be closed
by a connecting line to its start point. | [
"Finish",
"the",
"current",
"drawing",
"segment",
"."
] | 917f2d83482510e26ba0ff01fd2392c26f3a8e90 | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L2709-L2767 | train | 223,928 |
stitchfix/pyxley | pyxley/charts/mg/mg.py | OptionHelper.set_float | 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):
raise TypeError("Value must be a float")
self.options[option] = value | python | 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):
raise TypeError("Value must be a float")
self.options[option] = value | [
"def",
"set_float",
"(",
"self",
",",
"option",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"float",
")",
":",
"raise",
"TypeError",
"(",
"\"Value must be a float\"",
")",
"self",
".",
"options",
"[",
"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. | [
"Set",
"a",
"float",
"option",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/mg/mg.py#L29-L41 | train | 223,929 |
stitchfix/pyxley | pyxley/charts/mg/mg.py | OptionHelper.set_integer | 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)
except ValueError as err:
print(err.args)
self.options[option] = value | python | 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)
except ValueError as err:
print(err.args)
self.options[option] = value | [
"def",
"set_integer",
"(",
"self",
",",
"option",
",",
"value",
")",
":",
"try",
":",
"int_value",
"=",
"int",
"(",
"value",
")",
"except",
"ValueError",
"as",
"err",
":",
"print",
"(",
"err",
".",
"args",
")",
"self",
".",
"options",
"[",
"option",
... | Set an integer option.
Args:
option (str): name of option.
value (int): value of the option.
Raises:
ValueError: Value must be an integer. | [
"Set",
"an",
"integer",
"option",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/mg/mg.py#L43-L58 | train | 223,930 |
stitchfix/pyxley | pyxley/charts/mg/mg.py | OptionHelper.set_boolean | 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):
raise TypeError("%s must be a boolean" % option)
self.options[option] = str(value).lower() | python | 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):
raise TypeError("%s must be a boolean" % option)
self.options[option] = str(value).lower() | [
"def",
"set_boolean",
"(",
"self",
",",
"option",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"%s must be a boolean\"",
"%",
"option",
")",
"self",
".",
"options",
"[",
"option",
"]... | Set a boolean option.
Args:
option (str): name of option.
value (bool): value of the option.
Raises:
TypeError: Value must be a boolean. | [
"Set",
"a",
"boolean",
"option",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/mg/mg.py#L60-L73 | train | 223,931 |
stitchfix/pyxley | pyxley/charts/mg/mg.py | OptionHelper.set_string | 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):
raise TypeError("%s must be a string" % option)
self.options[option] = value | python | 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):
raise TypeError("%s must be a string" % option)
self.options[option] = value | [
"def",
"set_string",
"(",
"self",
",",
"option",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"%s must be a string\"",
"%",
"option",
")",
"self",
".",
"options",
"[",
"option",
"]",
... | Set a string option.
Args:
option (str): name of option.
value (str): value of the option.
Raises:
TypeError: Value must be a string. | [
"Set",
"a",
"string",
"option",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/mg/mg.py#L75-L88 | train | 223,932 |
stitchfix/pyxley | pyxley/charts/mg/graphic.py | Graphic.custom_line_color_map | 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("custom_line_color_map must be a list")
self.options["custom_line_color_map"] = values | python | 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("custom_line_color_map must be a list")
self.options["custom_line_color_map"] = values | [
"def",
"custom_line_color_map",
"(",
"self",
",",
"values",
")",
":",
"if",
"not",
"isinstance",
"(",
"values",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"custom_line_color_map must be a list\"",
")",
"self",
".",
"options",
"[",
"\"custom_line_color_map... | Set the custom line color map.
Args:
values (list): list of colors.
Raises:
TypeError: Custom line color map must be a list. | [
"Set",
"the",
"custom",
"line",
"color",
"map",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/mg/graphic.py#L89-L101 | train | 223,933 |
stitchfix/pyxley | pyxley/charts/mg/graphic.py | Graphic.legend | 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 labels")
self.options["legend"] = values | python | 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 labels")
self.options["legend"] = values | [
"def",
"legend",
"(",
"self",
",",
"values",
")",
":",
"if",
"not",
"isinstance",
"(",
"values",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"legend must be a list of labels\"",
")",
"self",
".",
"options",
"[",
"\"legend\"",
"]",
"=",
"values"
] | Set the legend labels.
Args:
values (list): list of labels.
Raises:
ValueError: legend must be a list of labels. | [
"Set",
"the",
"legend",
"labels",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/mg/graphic.py#L164-L176 | train | 223,934 |
stitchfix/pyxley | pyxley/charts/mg/graphic.py | Graphic.markers | 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 objects")
self.options["markers"] = values | python | 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 objects")
self.options["markers"] = values | [
"def",
"markers",
"(",
"self",
",",
"values",
")",
":",
"if",
"not",
"isinstance",
"(",
"values",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"Markers must be a list of objects\"",
")",
"self",
".",
"options",
"[",
"\"markers\"",
"]",
"=",
"values"
] | Set the markers.
Args:
values (list): list of marker objects.
Raises:
ValueError: Markers must be a list of objects. | [
"Set",
"the",
"markers",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/mg/graphic.py#L194-L206 | train | 223,935 |
stitchfix/pyxley | pyxley/charts/mg/graphic.py | Graphic.get | def get(self):
"""Get graphics options."""
return {k:v for k,v in list(self.options.items()) if k in self._allowed_graphics} | python | def get(self):
"""Get graphics options."""
return {k:v for k,v in list(self.options.items()) if k in self._allowed_graphics} | [
"def",
"get",
"(",
"self",
")",
":",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"self",
".",
"options",
".",
"items",
"(",
")",
")",
"if",
"k",
"in",
"self",
".",
"_allowed_graphics",
"}"
] | Get graphics options. | [
"Get",
"graphics",
"options",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/mg/graphic.py#L260-L262 | train | 223,936 |
stitchfix/pyxley | pyxley/charts/charts.py | Chart.apply_filters | 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 | 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] | [
"def",
"apply_filters",
"(",
"df",
",",
"filters",
")",
":",
"idx",
"=",
"pd",
".",
"Series",
"(",
"[",
"True",
"]",
"*",
"df",
".",
"shape",
"[",
"0",
"]",
")",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"filters",
".",
"items",
"(",
")",
")",... | Basic filtering for a dataframe. | [
"Basic",
"filtering",
"for",
"a",
"dataframe",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/charts.py#L10-L18 | train | 223,937 |
stitchfix/pyxley | pyxley/charts/datatables/datatable.py | DataTable.format_row | 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[c]
row[c] = [b["min"],row[b["lower"]], row[b["upper"]], b["max"]]
return row | python | 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[c]
row[c] = [b["min"],row[b["lower"]], row[b["upper"]], b["max"]]
return row | [
"def",
"format_row",
"(",
"row",
",",
"bounds",
",",
"columns",
")",
":",
"for",
"c",
"in",
"columns",
":",
"if",
"c",
"not",
"in",
"row",
":",
"continue",
"if",
"\"format\"",
"in",
"columns",
"[",
"c",
"]",
":",
"row",
"[",
"c",
"]",
"=",
"colum... | Formats a single row of the dataframe | [
"Formats",
"a",
"single",
"row",
"of",
"the",
"dataframe"
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/datatables/datatable.py#L70-L83 | train | 223,938 |
stitchfix/pyxley | pyxley/charts/datatables/datatable.py | DataTable.to_json | 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[c] = {
"min": df[confidence[c]["lower"]].min(),
"max": df[confidence[c]["upper"]].max(),
"lower": confidence[c]["lower"],
"upper": confidence[c]["upper"]
}
labels = {}
for c in display_cols:
if "label" in columns[c]:
labels[c] = columns[c]["label"]
else:
labels[c] = c
for i, row in df.iterrows():
row_ = DataTable.format_row(row, bounds, columns)
records.append({labels[c]: row_[c] for c in display_cols})
return {
"data": records,
"columns": [{"data": labels[c]} for c in display_cols]
} | python | 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[c] = {
"min": df[confidence[c]["lower"]].min(),
"max": df[confidence[c]["upper"]].max(),
"lower": confidence[c]["lower"],
"upper": confidence[c]["upper"]
}
labels = {}
for c in display_cols:
if "label" in columns[c]:
labels[c] = columns[c]["label"]
else:
labels[c] = c
for i, row in df.iterrows():
row_ = DataTable.format_row(row, bounds, columns)
records.append({labels[c]: row_[c] for c in display_cols})
return {
"data": records,
"columns": [{"data": labels[c]} for c in display_cols]
} | [
"def",
"to_json",
"(",
"df",
",",
"columns",
",",
"confidence",
"=",
"{",
"}",
")",
":",
"records",
"=",
"[",
"]",
"display_cols",
"=",
"list",
"(",
"columns",
".",
"keys",
"(",
")",
")",
"if",
"not",
"display_cols",
":",
"display_cols",
"=",
"list",... | Transforms dataframe to properly formatted json response | [
"Transforms",
"dataframe",
"to",
"properly",
"formatted",
"json",
"response"
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/datatables/datatable.py#L86-L117 | train | 223,939 |
stitchfix/pyxley | pyxley/charts/mg/figure.py | Figure.get | 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 | 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 | [
"def",
"get",
"(",
"self",
")",
":",
"options",
"=",
"{",
"}",
"for",
"x",
"in",
"[",
"self",
".",
"axes",
",",
"self",
".",
"graphics",
",",
"self",
".",
"layout",
"]",
":",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"x",
".",
"get",
"(",
")... | Return axes, graphics, and layout options. | [
"Return",
"axes",
"graphics",
"and",
"layout",
"options",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/mg/figure.py#L22-L29 | train | 223,940 |
stitchfix/pyxley | pyxley/charts/mg/layout.py | Layout.set_margin | 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.
right (int): size of right margin in pixels.
buffer_size (int): buffer size in pixels between the chart and margins.
"""
self.set_integer("top", top)
self.set_integer("bottom", bottom)
self.set_integer("left", left)
self.set_integer("right", right)
self.set_integer("buffer", buffer_size) | python | 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.
right (int): size of right margin in pixels.
buffer_size (int): buffer size in pixels between the chart and margins.
"""
self.set_integer("top", top)
self.set_integer("bottom", bottom)
self.set_integer("left", left)
self.set_integer("right", right)
self.set_integer("buffer", buffer_size) | [
"def",
"set_margin",
"(",
"self",
",",
"top",
"=",
"40",
",",
"bottom",
"=",
"30",
",",
"left",
"=",
"50",
",",
"right",
"=",
"10",
",",
"buffer_size",
"=",
"8",
")",
":",
"self",
".",
"set_integer",
"(",
"\"top\"",
",",
"top",
")",
"self",
".",
... | 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.
right (int): size of right margin in pixels.
buffer_size (int): buffer size in pixels between the chart and margins. | [
"Set",
"margin",
"of",
"the",
"chart",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/mg/layout.py#L20-L35 | train | 223,941 |
stitchfix/pyxley | pyxley/charts/mg/layout.py | Layout.set_size | 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 threshold in pixels
width_threshold (int): width threshold in pixesls
"""
self.set_integer("height", height)
self.set_integer("width", width)
self.set_integer("small_height_threshold", height_threshold)
self.set_integer("small_width_threshold", width_threshold) | python | 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 threshold in pixels
width_threshold (int): width threshold in pixesls
"""
self.set_integer("height", height)
self.set_integer("width", width)
self.set_integer("small_height_threshold", height_threshold)
self.set_integer("small_width_threshold", width_threshold) | [
"def",
"set_size",
"(",
"self",
",",
"height",
"=",
"220",
",",
"width",
"=",
"350",
",",
"height_threshold",
"=",
"120",
",",
"width_threshold",
"=",
"160",
")",
":",
"self",
".",
"set_integer",
"(",
"\"height\"",
",",
"height",
")",
"self",
".",
"set... | Set the size of the chart.
Args:
height (int): height in pixels.
width (int): width in pixels.
height_threshold (int): height threshold in pixels
width_threshold (int): width threshold in pixesls | [
"Set",
"the",
"size",
"of",
"the",
"chart",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/mg/layout.py#L37-L52 | train | 223,942 |
stitchfix/pyxley | pyxley/charts/mg/layout.py | Layout.get | def get(self):
"""Get layout options."""
return {k:v for k,v in list(self.options.items()) if k in self._allowed_layout} | python | def get(self):
"""Get layout options."""
return {k:v for k,v in list(self.options.items()) if k in self._allowed_layout} | [
"def",
"get",
"(",
"self",
")",
":",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"self",
".",
"options",
".",
"items",
"(",
")",
")",
"if",
"k",
"in",
"self",
".",
"_allowed_layout",
"}"
] | Get layout options. | [
"Get",
"layout",
"options",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/mg/layout.py#L54-L56 | train | 223,943 |
stitchfix/pyxley | pyxley/react_template.py | format_props | 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 props to be fed to the React template.
"""
vars_ = []
props_ = []
for k, v in list(props.items()):
vars_.append(Template("var {{k}} = {{v}};").render(k=k,v=json.dumps(v)))
props_.append(Template(prop_template).render(k=k, v=k))
return "\n".join(vars_), delim.join(props_) | python | 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 props to be fed to the React template.
"""
vars_ = []
props_ = []
for k, v in list(props.items()):
vars_.append(Template("var {{k}} = {{v}};").render(k=k,v=json.dumps(v)))
props_.append(Template(prop_template).render(k=k, v=k))
return "\n".join(vars_), delim.join(props_) | [
"def",
"format_props",
"(",
"props",
",",
"prop_template",
"=",
"\"{{k}} = { {{v}} }\"",
",",
"delim",
"=",
"\"\\n\"",
")",
":",
"vars_",
"=",
"[",
"]",
"props_",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"props",
".",
"items",
"(",
")"... | 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 props to be fed to the React template. | [
"Formats",
"props",
"for",
"the",
"React",
"template",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/react_template.py#L35-L51 | train | 223,944 |
stitchfix/pyxley | pyxley/ui.py | register_layouts | 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): address of props; default is /api/props/
"""
def props(name):
if name not in layouts:
# cast as list for python3
name = list(layouts.keys())[0]
return jsonify({"layouts": layouts[name]["layout"]})
def apps():
paths = []
for i, k in enumerate(layouts.keys()):
if i == 0:
paths.append({
"path": "/",
"label": layouts[k].get("title", k)
})
paths.append({
"path": "/"+k,
"label": layouts[k].get("title", k)
})
return jsonify({"brand": brand, "navlinks": paths})
app.add_url_rule(url+"<string:name>/", view_func=props)
app.add_url_rule(url, view_func=apps) | python | 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): address of props; default is /api/props/
"""
def props(name):
if name not in layouts:
# cast as list for python3
name = list(layouts.keys())[0]
return jsonify({"layouts": layouts[name]["layout"]})
def apps():
paths = []
for i, k in enumerate(layouts.keys()):
if i == 0:
paths.append({
"path": "/",
"label": layouts[k].get("title", k)
})
paths.append({
"path": "/"+k,
"label": layouts[k].get("title", k)
})
return jsonify({"brand": brand, "navlinks": paths})
app.add_url_rule(url+"<string:name>/", view_func=props)
app.add_url_rule(url, view_func=apps) | [
"def",
"register_layouts",
"(",
"layouts",
",",
"app",
",",
"url",
"=",
"\"/api/props/\"",
",",
"brand",
"=",
"\"Pyxley\"",
")",
":",
"def",
"props",
"(",
"name",
")",
":",
"if",
"name",
"not",
"in",
"layouts",
":",
"# cast as list for python3",
"name",
"=... | 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): address of props; default is /api/props/ | [
"register",
"UILayout",
"with",
"the",
"flask",
"app"
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/ui.py#L5-L38 | train | 223,945 |
stitchfix/pyxley | pyxley/ui.py | UIComponent.register_route | 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 supplied")
app.add_url_rule(self.params["options"]["url"],
self.params["options"]["url"],
self.route_func) | python | 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 supplied")
app.add_url_rule(self.params["options"]["url"],
self.params["options"]["url"],
self.route_func) | [
"def",
"register_route",
"(",
"self",
",",
"app",
")",
":",
"if",
"\"url\"",
"not",
"in",
"self",
".",
"params",
"[",
"\"options\"",
"]",
":",
"raise",
"Exception",
"(",
"\"Component does not have a URL property\"",
")",
"if",
"not",
"hasattr",
"(",
"self",
... | Register the api route function with the app. | [
"Register",
"the",
"api",
"route",
"function",
"with",
"the",
"app",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/ui.py#L61-L71 | train | 223,946 |
stitchfix/pyxley | pyxley/ui.py | SimpleComponent.render | 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 | 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) | [
"def",
"render",
"(",
"self",
",",
"path",
")",
":",
"return",
"ReactComponent",
"(",
"self",
".",
"layout",
",",
"self",
".",
"src_file",
",",
"self",
".",
"component_id",
",",
"props",
"=",
"self",
".",
"props",
",",
"static_path",
"=",
"path",
")"
] | Render the component to a javascript file. | [
"Render",
"the",
"component",
"to",
"a",
"javascript",
"file",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/ui.py#L93-L100 | train | 223,947 |
stitchfix/pyxley | pyxley/ui.py | UILayout.add_filter | 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] = []
self.filters[filter_group].append(component) | python | 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] = []
self.filters[filter_group].append(component) | [
"def",
"add_filter",
"(",
"self",
",",
"component",
",",
"filter_group",
"=",
"\"pyxley-filter\"",
")",
":",
"if",
"getattr",
"(",
"component",
",",
"\"name\"",
")",
"!=",
"\"Filter\"",
":",
"raise",
"Exception",
"(",
"\"Component is not an instance of Filter\"",
... | Add a filter to the layout. | [
"Add",
"a",
"filter",
"to",
"the",
"layout",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/ui.py#L128-L134 | train | 223,948 |
stitchfix/pyxley | pyxley/ui.py | UILayout.add_chart | 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 | 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) | [
"def",
"add_chart",
"(",
"self",
",",
"component",
")",
":",
"if",
"getattr",
"(",
"component",
",",
"\"name\"",
")",
"!=",
"\"Chart\"",
":",
"raise",
"Exception",
"(",
"\"Component is not an instance of Chart\"",
")",
"self",
".",
"charts",
".",
"append",
"("... | Add a chart to the layout. | [
"Add",
"a",
"chart",
"to",
"the",
"layout",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/ui.py#L136-L140 | train | 223,949 |
stitchfix/pyxley | pyxley/ui.py | UILayout.build_props | 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.params for c in self.charts]
props["type"] = self.layout
return props | python | 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.params for c in self.charts]
props["type"] = self.layout
return props | [
"def",
"build_props",
"(",
"self",
")",
":",
"props",
"=",
"{",
"}",
"if",
"self",
".",
"filters",
":",
"props",
"[",
"\"filters\"",
"]",
"=",
"{",
"}",
"for",
"grp",
"in",
"self",
".",
"filters",
":",
"props",
"[",
"\"filters\"",
"]",
"[",
"grp",
... | Build the props dictionary. | [
"Build",
"the",
"props",
"dictionary",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/ui.py#L142-L153 | train | 223,950 |
stitchfix/pyxley | pyxley/ui.py | UILayout.assign_routes | 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 | 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) | [
"def",
"assign_routes",
"(",
"self",
",",
"app",
")",
":",
"for",
"grp",
"in",
"self",
".",
"filters",
":",
"for",
"f",
"in",
"self",
".",
"filters",
"[",
"grp",
"]",
":",
"if",
"f",
".",
"route_func",
":",
"f",
".",
"register_route",
"(",
"app",
... | Register routes with the app. | [
"Register",
"routes",
"with",
"the",
"app",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/ui.py#L155-L164 | train | 223,951 |
stitchfix/pyxley | pyxley/ui.py | UILayout.render_layout | 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 | 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) | [
"def",
"render_layout",
"(",
"self",
",",
"app",
",",
"path",
",",
"alias",
"=",
"None",
")",
":",
"self",
".",
"assign_routes",
"(",
"app",
")",
"return",
"ReactComponent",
"(",
"self",
".",
"layout",
",",
"self",
".",
"src_file",
",",
"self",
".",
... | Write to javascript. | [
"Write",
"to",
"javascript",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/ui.py#L166-L175 | train | 223,952 |
stitchfix/pyxley | pyxley/utils/flask_helper.py | default_static_path | 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 | 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/')) | [
"def",
"default_static_path",
"(",
")",
":",
"fdir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"fdir",
",",
"'../assets/'",
")",
")"
] | Return the path to the javascript bundle | [
"Return",
"the",
"path",
"to",
"the",
"javascript",
"bundle"
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/utils/flask_helper.py#L31-L36 | train | 223,953 |
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 | train | 223,954 |
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",
"Value... | 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 | train | 223,955 |
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",
"Value... | 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 | train | 223,956 |
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 | train | 223,957 |
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\"",
":",
"[",
"]",
",",
"\"m... | 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 | train | 223,958 |
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",
"]",
".",
"... | 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 | train | 223,959 |
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",
"]",
"]",
"=",
"... | 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 | train | 223,960 |
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 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 | train | 223,961 |
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",
... | 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 | train | 223,962 |
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",
"=",
"srcAWSSecretA... | 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 | train | 223,963 |
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",
"(",
")",
"... | 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 | train | 223,964 |
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",
"(",
"'Inva... | 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 | train | 223,965 |
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 | train | 223,966 |
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",
".",
"stopStableConnec... | 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 | train | 223,967 |
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",
"(",
"... | 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 | train | 223,968 |
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",
"(",
"topi... | 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 | train | 223,969 |
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",
"(",
"'Inv... | 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 | train | 223,970 |
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",
"... | 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 | train | 223,971 |
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\""... | 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 | train | 223,972 |
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 | train | 223,973 |
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",
"(",
"'... | Install Setuptools. | [
"Install",
"Setuptools",
"."
] | f3ab7e1740d37d585ffab0154edb4cb664afe4a9 | https://github.com/martinblech/xmltodict/blob/f3ab7e1740d37d585ffab0154edb4cb664afe4a9/ez_setup.py#L57-L66 | train | 223,974 |
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",
"... | Build Setuptools egg. | [
"Build",
"Setuptools",
"egg",
"."
] | f3ab7e1740d37d585ffab0154edb4cb664afe4a9 | https://github.com/martinblech/xmltodict/blob/f3ab7e1740d37d585ffab0154edb4cb664afe4a9/ez_setup.py#L69-L78 | train | 223,975 |
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}.eg... | Download Setuptools. | [
"Download",
"Setuptools",
"."
] | f3ab7e1740d37d585ffab0154edb4cb664afe4a9 | https://github.com/martinblech/xmltodict/blob/f3ab7e1740d37d585ffab0154edb4cb664afe4a9/ez_setup.py#L132-L149 | train | 223,976 |
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",
")... | 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 | train | 223,977 |
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 instal... | 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 | train | 223,978 |
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",
"(",
")",
"# Wr... | 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 | train | 223,979 |
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",
... | 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 | train | 223,980 |
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 | train | 223,981 |
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.createCon... | 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 | train | 223,982 |
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... | logs error messages | [
"logs",
"error",
"messages"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L269-L286 | train | 223,983 |
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",
"."... | 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 | train | 223,984 |
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 fro... | handles contractDetails and contractDetailsEnd | [
"handles",
"contractDetails",
"and",
"contractDetailsEnd"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L411-L487 | train | 223,985 |
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",
")",
"... | handle positions changes | [
"handle",
"positions",
"changes"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L553-L579 | train | 223,986 |
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",
")",
... | handle portfolio updates | [
"handle",
"portfolio",
"updates"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L600-L630 | train | 223,987 |
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\"",
... | handle order open & status | [
"handle",
"order",
"open",
"&",
"status"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L655-L727 | train | 223,988 |
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",
",",
... | adds order to triggerable list | [
"adds",
"order",
"to",
"triggerable",
"list"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1101-L1118 | train | 223,989 |
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",
",",
"*",
"*",
"... | 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 | train | 223,990 |
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",
"(",
")",
":",
"o... | modify stop order | [
"modify",
"stop",
"order"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1140-L1154 | train | 223,991 |
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",
"... | software-based trailing stop | [
"software",
"-",
"based",
"trailing",
"stop"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1157-L1214 | train | 223,992 |
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",
... | trigger waiting trailing stops | [
"trigger",
"waiting",
"trailing",
"stops"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1217-L1299 | train | 223,993 |
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",
"(",
"sy... | 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 | train | 223,994 |
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... | Creates TARGET order | [
"Creates",
"TARGET",
"order"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1598-L1612 | train | 223,995 |
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",
... | Creates STOP order | [
"Creates",
"STOP",
"order"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1615-L1657 | train | 223,996 |
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",
"paren... | 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 | train | 223,997 |
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",
"=",
... | Place order on IB TWS | [
"Place",
"order",
"on",
"IB",
"TWS"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1750-L1778 | train | 223,998 |
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 | train | 223,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.