repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
bitesofcode/projexui
projexui/widgets/xlabel.py
XLabel.acceptEdit
def acceptEdit(self): """ Accepts the current edit for this label. """ if not self._lineEdit: return self.setText(self._lineEdit.text()) self._lineEdit.hide() if not self.signalsBlocked(): self.editingFinished.emit(self._lineEdit.text())
python
def acceptEdit(self): """ Accepts the current edit for this label. """ if not self._lineEdit: return self.setText(self._lineEdit.text()) self._lineEdit.hide() if not self.signalsBlocked(): self.editingFinished.emit(self._lineEdit.text())
[ "def", "acceptEdit", "(", "self", ")", ":", "if", "not", "self", ".", "_lineEdit", ":", "return", "self", ".", "setText", "(", "self", ".", "_lineEdit", ".", "text", "(", ")", ")", "self", ".", "_lineEdit", ".", "hide", "(", ")", "if", "not", "self", ".", "signalsBlocked", "(", ")", ":", "self", ".", "editingFinished", ".", "emit", "(", "self", ".", "_lineEdit", ".", "text", "(", ")", ")" ]
Accepts the current edit for this label.
[ "Accepts", "the", "current", "edit", "for", "this", "label", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xlabel.py#L32-L43
train
bitesofcode/projexui
projexui/widgets/xlabel.py
XLabel.beginEdit
def beginEdit(self): """ Begins editing for the label. """ if not self._lineEdit: return self.aboutToEdit.emit() self._lineEdit.setText(self.editText()) self._lineEdit.show() self._lineEdit.selectAll() self._lineEdit.setFocus()
python
def beginEdit(self): """ Begins editing for the label. """ if not self._lineEdit: return self.aboutToEdit.emit() self._lineEdit.setText(self.editText()) self._lineEdit.show() self._lineEdit.selectAll() self._lineEdit.setFocus()
[ "def", "beginEdit", "(", "self", ")", ":", "if", "not", "self", ".", "_lineEdit", ":", "return", "self", ".", "aboutToEdit", ".", "emit", "(", ")", "self", ".", "_lineEdit", ".", "setText", "(", "self", ".", "editText", "(", ")", ")", "self", ".", "_lineEdit", ".", "show", "(", ")", "self", ".", "_lineEdit", ".", "selectAll", "(", ")", "self", ".", "_lineEdit", ".", "setFocus", "(", ")" ]
Begins editing for the label.
[ "Begins", "editing", "for", "the", "label", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xlabel.py#L45-L57
train
bitesofcode/projexui
projexui/widgets/xlabel.py
XLabel.rejectEdit
def rejectEdit(self): """ Cancels the edit for this label. """ if self._lineEdit: self._lineEdit.hide() self.editingCancelled.emit()
python
def rejectEdit(self): """ Cancels the edit for this label. """ if self._lineEdit: self._lineEdit.hide() self.editingCancelled.emit()
[ "def", "rejectEdit", "(", "self", ")", ":", "if", "self", ".", "_lineEdit", ":", "self", ".", "_lineEdit", ".", "hide", "(", ")", "self", ".", "editingCancelled", ".", "emit", "(", ")" ]
Cancels the edit for this label.
[ "Cancels", "the", "edit", "for", "this", "label", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xlabel.py#L122-L128
train
Gbps/fastlog
fastlog/term.py
typeseq
def typeseq(types): """ Returns an escape for a terminal text formatting type, or a list of types. Valid types are: * 'i' for 'italic' * 'b' for 'bold' * 'u' for 'underline' * 'r' for 'reverse' """ ret = "" for t in types: ret += termcap.get(fmttypes[t]) return ret
python
def typeseq(types): """ Returns an escape for a terminal text formatting type, or a list of types. Valid types are: * 'i' for 'italic' * 'b' for 'bold' * 'u' for 'underline' * 'r' for 'reverse' """ ret = "" for t in types: ret += termcap.get(fmttypes[t]) return ret
[ "def", "typeseq", "(", "types", ")", ":", "ret", "=", "\"\"", "for", "t", "in", "types", ":", "ret", "+=", "termcap", ".", "get", "(", "fmttypes", "[", "t", "]", ")", "return", "ret" ]
Returns an escape for a terminal text formatting type, or a list of types. Valid types are: * 'i' for 'italic' * 'b' for 'bold' * 'u' for 'underline' * 'r' for 'reverse'
[ "Returns", "an", "escape", "for", "a", "terminal", "text", "formatting", "type", "or", "a", "list", "of", "types", "." ]
8edb2327d72191510302c4654ffaa1691fe31277
https://github.com/Gbps/fastlog/blob/8edb2327d72191510302c4654ffaa1691fe31277/fastlog/term.py#L117-L131
train
Gbps/fastlog
fastlog/term.py
nametonum
def nametonum(name): """ Returns a color code number given the color name. """ code = colorcodes.get(name) if code is None: raise ValueError("%s is not a valid color name." % name) else: return code
python
def nametonum(name): """ Returns a color code number given the color name. """ code = colorcodes.get(name) if code is None: raise ValueError("%s is not a valid color name." % name) else: return code
[ "def", "nametonum", "(", "name", ")", ":", "code", "=", "colorcodes", ".", "get", "(", "name", ")", "if", "code", "is", "None", ":", "raise", "ValueError", "(", "\"%s is not a valid color name.\"", "%", "name", ")", "else", ":", "return", "code" ]
Returns a color code number given the color name.
[ "Returns", "a", "color", "code", "number", "given", "the", "color", "name", "." ]
8edb2327d72191510302c4654ffaa1691fe31277
https://github.com/Gbps/fastlog/blob/8edb2327d72191510302c4654ffaa1691fe31277/fastlog/term.py#L133-L141
train
Gbps/fastlog
fastlog/term.py
fgseq
def fgseq(code): """ Returns the forground color terminal escape sequence for the given color code number or color name. """ if isinstance(code, str): code = nametonum(code) if code == -1: return "" s = termcap.get('setaf', code) or termcap.get('setf', code) return s
python
def fgseq(code): """ Returns the forground color terminal escape sequence for the given color code number or color name. """ if isinstance(code, str): code = nametonum(code) if code == -1: return "" s = termcap.get('setaf', code) or termcap.get('setf', code) return s
[ "def", "fgseq", "(", "code", ")", ":", "if", "isinstance", "(", "code", ",", "str", ")", ":", "code", "=", "nametonum", "(", "code", ")", "if", "code", "==", "-", "1", ":", "return", "\"\"", "s", "=", "termcap", ".", "get", "(", "'setaf'", ",", "code", ")", "or", "termcap", ".", "get", "(", "'setf'", ",", "code", ")", "return", "s" ]
Returns the forground color terminal escape sequence for the given color code number or color name.
[ "Returns", "the", "forground", "color", "terminal", "escape", "sequence", "for", "the", "given", "color", "code", "number", "or", "color", "name", "." ]
8edb2327d72191510302c4654ffaa1691fe31277
https://github.com/Gbps/fastlog/blob/8edb2327d72191510302c4654ffaa1691fe31277/fastlog/term.py#L143-L154
train
Gbps/fastlog
fastlog/term.py
bgseq
def bgseq(code): """ Returns the background color terminal escape sequence for the given color code number. """ if isinstance(code, str): code = nametonum(code) if code == -1: return "" s = termcap.get('setab', code) or termcap.get('setb', code) return s
python
def bgseq(code): """ Returns the background color terminal escape sequence for the given color code number. """ if isinstance(code, str): code = nametonum(code) if code == -1: return "" s = termcap.get('setab', code) or termcap.get('setb', code) return s
[ "def", "bgseq", "(", "code", ")", ":", "if", "isinstance", "(", "code", ",", "str", ")", ":", "code", "=", "nametonum", "(", "code", ")", "if", "code", "==", "-", "1", ":", "return", "\"\"", "s", "=", "termcap", ".", "get", "(", "'setab'", ",", "code", ")", "or", "termcap", ".", "get", "(", "'setb'", ",", "code", ")", "return", "s" ]
Returns the background color terminal escape sequence for the given color code number.
[ "Returns", "the", "background", "color", "terminal", "escape", "sequence", "for", "the", "given", "color", "code", "number", "." ]
8edb2327d72191510302c4654ffaa1691fe31277
https://github.com/Gbps/fastlog/blob/8edb2327d72191510302c4654ffaa1691fe31277/fastlog/term.py#L156-L167
train
Gbps/fastlog
fastlog/term.py
Style.parse
def parse(self, descriptor): """ Creates a text styling from a descriptor A descriptor is a dictionary containing any of the following keys: * fg: The foreground color (name or int) See `bgseq` * bg: The background color (name or int) See `fgseq` * fmt: The types of special text formatting (any combination of 'b', 'u', 'i', and 'r') See `typeseq` """ fg = descriptor.get('fg') bg = descriptor.get('bg') types = descriptor.get('fmt') ret = "" if fg: ret += fgseq(fg) if bg: ret += bgseq(bg) if types: t = typeseq(types) if t: ret += t # wew, strings and bytes, what's a guy to do! reset = resetseq() if not isinstance(reset, six.text_type): reset = reset.decode('utf-8') def ret_func(msg): if not isinstance(msg, six.text_type): msg = msg.decode('utf-8') return ret + msg + reset self.decorator = ret_func
python
def parse(self, descriptor): """ Creates a text styling from a descriptor A descriptor is a dictionary containing any of the following keys: * fg: The foreground color (name or int) See `bgseq` * bg: The background color (name or int) See `fgseq` * fmt: The types of special text formatting (any combination of 'b', 'u', 'i', and 'r') See `typeseq` """ fg = descriptor.get('fg') bg = descriptor.get('bg') types = descriptor.get('fmt') ret = "" if fg: ret += fgseq(fg) if bg: ret += bgseq(bg) if types: t = typeseq(types) if t: ret += t # wew, strings and bytes, what's a guy to do! reset = resetseq() if not isinstance(reset, six.text_type): reset = reset.decode('utf-8') def ret_func(msg): if not isinstance(msg, six.text_type): msg = msg.decode('utf-8') return ret + msg + reset self.decorator = ret_func
[ "def", "parse", "(", "self", ",", "descriptor", ")", ":", "fg", "=", "descriptor", ".", "get", "(", "'fg'", ")", "bg", "=", "descriptor", ".", "get", "(", "'bg'", ")", "types", "=", "descriptor", ".", "get", "(", "'fmt'", ")", "ret", "=", "\"\"", "if", "fg", ":", "ret", "+=", "fgseq", "(", "fg", ")", "if", "bg", ":", "ret", "+=", "bgseq", "(", "bg", ")", "if", "types", ":", "t", "=", "typeseq", "(", "types", ")", "if", "t", ":", "ret", "+=", "t", "# wew, strings and bytes, what's a guy to do!", "reset", "=", "resetseq", "(", ")", "if", "not", "isinstance", "(", "reset", ",", "six", ".", "text_type", ")", ":", "reset", "=", "reset", ".", "decode", "(", "'utf-8'", ")", "def", "ret_func", "(", "msg", ")", ":", "if", "not", "isinstance", "(", "msg", ",", "six", ".", "text_type", ")", ":", "msg", "=", "msg", ".", "decode", "(", "'utf-8'", ")", "return", "ret", "+", "msg", "+", "reset", "self", ".", "decorator", "=", "ret_func" ]
Creates a text styling from a descriptor A descriptor is a dictionary containing any of the following keys: * fg: The foreground color (name or int) See `bgseq` * bg: The background color (name or int) See `fgseq` * fmt: The types of special text formatting (any combination of 'b', 'u', 'i', and 'r') See `typeseq`
[ "Creates", "a", "text", "styling", "from", "a", "descriptor" ]
8edb2327d72191510302c4654ffaa1691fe31277
https://github.com/Gbps/fastlog/blob/8edb2327d72191510302c4654ffaa1691fe31277/fastlog/term.py#L78-L113
train
bitesofcode/projexui
projexui/widgets/xviewwidget/xviewprofiledialog.py
XViewProfileDialog.accept
def accept( self ): """ Saves the data to the profile before closing. """ if ( not self.uiNameTXT.text() ): QMessageBox.information(self, 'Invalid Name', 'You need to supply a name for your layout.') return prof = self.profile() if ( not prof ): prof = XViewProfile() prof.setName(nativestring(self.uiNameTXT.text())) prof.setVersion(self.uiVersionSPN.value()) prof.setDescription(nativestring(self.uiDescriptionTXT.toPlainText())) prof.setIcon(self.uiIconBTN.filepath()) super(XViewProfileDialog, self).accept()
python
def accept( self ): """ Saves the data to the profile before closing. """ if ( not self.uiNameTXT.text() ): QMessageBox.information(self, 'Invalid Name', 'You need to supply a name for your layout.') return prof = self.profile() if ( not prof ): prof = XViewProfile() prof.setName(nativestring(self.uiNameTXT.text())) prof.setVersion(self.uiVersionSPN.value()) prof.setDescription(nativestring(self.uiDescriptionTXT.toPlainText())) prof.setIcon(self.uiIconBTN.filepath()) super(XViewProfileDialog, self).accept()
[ "def", "accept", "(", "self", ")", ":", "if", "(", "not", "self", ".", "uiNameTXT", ".", "text", "(", ")", ")", ":", "QMessageBox", ".", "information", "(", "self", ",", "'Invalid Name'", ",", "'You need to supply a name for your layout.'", ")", "return", "prof", "=", "self", ".", "profile", "(", ")", "if", "(", "not", "prof", ")", ":", "prof", "=", "XViewProfile", "(", ")", "prof", ".", "setName", "(", "nativestring", "(", "self", ".", "uiNameTXT", ".", "text", "(", ")", ")", ")", "prof", ".", "setVersion", "(", "self", ".", "uiVersionSPN", ".", "value", "(", ")", ")", "prof", ".", "setDescription", "(", "nativestring", "(", "self", ".", "uiDescriptionTXT", ".", "toPlainText", "(", ")", ")", ")", "prof", ".", "setIcon", "(", "self", ".", "uiIconBTN", ".", "filepath", "(", ")", ")", "super", "(", "XViewProfileDialog", ",", "self", ")", ".", "accept", "(", ")" ]
Saves the data to the profile before closing.
[ "Saves", "the", "data", "to", "the", "profile", "before", "closing", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewprofiledialog.py#L35-L54
train
bitesofcode/projexui
projexui/widgets/xlocationwidget.py
XLocationWidget.browseMaps
def browseMaps( self ): """ Brings up a web browser with the address in a Google map. """ url = self.urlTemplate() params = urllib.urlencode({self.urlQueryKey(): self.location()}) url = url % {'params': params} webbrowser.open(url)
python
def browseMaps( self ): """ Brings up a web browser with the address in a Google map. """ url = self.urlTemplate() params = urllib.urlencode({self.urlQueryKey(): self.location()}) url = url % {'params': params} webbrowser.open(url)
[ "def", "browseMaps", "(", "self", ")", ":", "url", "=", "self", ".", "urlTemplate", "(", ")", "params", "=", "urllib", ".", "urlencode", "(", "{", "self", ".", "urlQueryKey", "(", ")", ":", "self", ".", "location", "(", ")", "}", ")", "url", "=", "url", "%", "{", "'params'", ":", "params", "}", "webbrowser", ".", "open", "(", "url", ")" ]
Brings up a web browser with the address in a Google map.
[ "Brings", "up", "a", "web", "browser", "with", "the", "address", "in", "a", "Google", "map", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xlocationwidget.py#L79-L87
train
Stryker0301/google-image-extractor
giextractor.py
GoogleImageExtractor._initialize_chrome_driver
def _initialize_chrome_driver(self): """Initializes chrome in headless mode""" try: print(colored('\nInitializing Headless Chrome...\n', 'yellow')) self._initialize_chrome_options() self._chromeDriver = webdriver.Chrome( chrome_options=self._chromeOptions) self._chromeDriver.maximize_window() print(colored('\nHeadless Chrome Initialized.', 'green')) except Exception as exception: print(colored('Error - Driver Initialization: ' + format(exception)), 'red')
python
def _initialize_chrome_driver(self): """Initializes chrome in headless mode""" try: print(colored('\nInitializing Headless Chrome...\n', 'yellow')) self._initialize_chrome_options() self._chromeDriver = webdriver.Chrome( chrome_options=self._chromeOptions) self._chromeDriver.maximize_window() print(colored('\nHeadless Chrome Initialized.', 'green')) except Exception as exception: print(colored('Error - Driver Initialization: ' + format(exception)), 'red')
[ "def", "_initialize_chrome_driver", "(", "self", ")", ":", "try", ":", "print", "(", "colored", "(", "'\\nInitializing Headless Chrome...\\n'", ",", "'yellow'", ")", ")", "self", ".", "_initialize_chrome_options", "(", ")", "self", ".", "_chromeDriver", "=", "webdriver", ".", "Chrome", "(", "chrome_options", "=", "self", ".", "_chromeOptions", ")", "self", ".", "_chromeDriver", ".", "maximize_window", "(", ")", "print", "(", "colored", "(", "'\\nHeadless Chrome Initialized.'", ",", "'green'", ")", ")", "except", "Exception", "as", "exception", ":", "print", "(", "colored", "(", "'Error - Driver Initialization: '", "+", "format", "(", "exception", ")", ")", ",", "'red'", ")" ]
Initializes chrome in headless mode
[ "Initializes", "chrome", "in", "headless", "mode" ]
bd227f3f77cc82603b9ad7798c9af9fed6724a05
https://github.com/Stryker0301/google-image-extractor/blob/bd227f3f77cc82603b9ad7798c9af9fed6724a05/giextractor.py#L72-L86
train
Stryker0301/google-image-extractor
giextractor.py
GoogleImageExtractor.extract_images
def extract_images(self, imageQuery, imageCount=100, destinationFolder='./', threadCount=4): """ Searches across Google Image Search with the specified image query and downloads the specified count of images Arguments: imageQuery {[str]} -- [Image Search Query] Keyword Arguments: imageCount {[int]} -- [Count of images that need to be downloaded] destinationFolder {[str]} -- [Download Destination Folder] threadCount {[int]} -- [Count of Threads, to parallelize download of images] """ # Initialize the chrome driver self._initialize_chrome_driver() # Initialize the image download parameters self._imageQuery = imageQuery self._imageCount = imageCount self._destinationFolder = destinationFolder self._threadCount = threadCount self._get_image_urls() self._create_storage_folder() self._download_images() # Print the final message specifying the total count of images downloaded print(colored('\n\nImages Downloaded: ' + str(self._imageCounter) + ' of ' + str(self._imageCount) + ' in ' + format_timespan(self._downloadProgressBar.data()['total_seconds_elapsed']) + '\n', 'green')) # Terminate the chrome instance self._chromeDriver.close() self._reset_helper_variables()
python
def extract_images(self, imageQuery, imageCount=100, destinationFolder='./', threadCount=4): """ Searches across Google Image Search with the specified image query and downloads the specified count of images Arguments: imageQuery {[str]} -- [Image Search Query] Keyword Arguments: imageCount {[int]} -- [Count of images that need to be downloaded] destinationFolder {[str]} -- [Download Destination Folder] threadCount {[int]} -- [Count of Threads, to parallelize download of images] """ # Initialize the chrome driver self._initialize_chrome_driver() # Initialize the image download parameters self._imageQuery = imageQuery self._imageCount = imageCount self._destinationFolder = destinationFolder self._threadCount = threadCount self._get_image_urls() self._create_storage_folder() self._download_images() # Print the final message specifying the total count of images downloaded print(colored('\n\nImages Downloaded: ' + str(self._imageCounter) + ' of ' + str(self._imageCount) + ' in ' + format_timespan(self._downloadProgressBar.data()['total_seconds_elapsed']) + '\n', 'green')) # Terminate the chrome instance self._chromeDriver.close() self._reset_helper_variables()
[ "def", "extract_images", "(", "self", ",", "imageQuery", ",", "imageCount", "=", "100", ",", "destinationFolder", "=", "'./'", ",", "threadCount", "=", "4", ")", ":", "# Initialize the chrome driver", "self", ".", "_initialize_chrome_driver", "(", ")", "# Initialize the image download parameters", "self", ".", "_imageQuery", "=", "imageQuery", "self", ".", "_imageCount", "=", "imageCount", "self", ".", "_destinationFolder", "=", "destinationFolder", "self", ".", "_threadCount", "=", "threadCount", "self", ".", "_get_image_urls", "(", ")", "self", ".", "_create_storage_folder", "(", ")", "self", ".", "_download_images", "(", ")", "# Print the final message specifying the total count of images downloaded", "print", "(", "colored", "(", "'\\n\\nImages Downloaded: '", "+", "str", "(", "self", ".", "_imageCounter", ")", "+", "' of '", "+", "str", "(", "self", ".", "_imageCount", ")", "+", "' in '", "+", "format_timespan", "(", "self", ".", "_downloadProgressBar", ".", "data", "(", ")", "[", "'total_seconds_elapsed'", "]", ")", "+", "'\\n'", ",", "'green'", ")", ")", "# Terminate the chrome instance", "self", ".", "_chromeDriver", ".", "close", "(", ")", "self", ".", "_reset_helper_variables", "(", ")" ]
Searches across Google Image Search with the specified image query and downloads the specified count of images Arguments: imageQuery {[str]} -- [Image Search Query] Keyword Arguments: imageCount {[int]} -- [Count of images that need to be downloaded] destinationFolder {[str]} -- [Download Destination Folder] threadCount {[int]} -- [Count of Threads, to parallelize download of images]
[ "Searches", "across", "Google", "Image", "Search", "with", "the", "specified", "image", "query", "and", "downloads", "the", "specified", "count", "of", "images" ]
bd227f3f77cc82603b9ad7798c9af9fed6724a05
https://github.com/Stryker0301/google-image-extractor/blob/bd227f3f77cc82603b9ad7798c9af9fed6724a05/giextractor.py#L129-L164
train
Stryker0301/google-image-extractor
giextractor.py
GoogleImageExtractor._get_image_urls
def _get_image_urls(self): """Retrieves the image URLS corresponding to the image query""" print(colored('\nRetrieving Image URLs...', 'yellow')) _imageQuery = self._imageQuery.replace(' ', '+') self._chromeDriver.get('https://www.google.co.in/search?q=' + _imageQuery + '&newwindow=1&source=lnms&tbm=isch') while self._imageURLsExtractedCount <= self._imageCount: self._extract_image_urls() self._page_scroll_down() # Slice the list of image URLs to contain the exact number of image # URLs that have been requested # self._imageURLs = self._imageURLs[:self._imageCount] print(colored('Image URLs retrieved.', 'green'))
python
def _get_image_urls(self): """Retrieves the image URLS corresponding to the image query""" print(colored('\nRetrieving Image URLs...', 'yellow')) _imageQuery = self._imageQuery.replace(' ', '+') self._chromeDriver.get('https://www.google.co.in/search?q=' + _imageQuery + '&newwindow=1&source=lnms&tbm=isch') while self._imageURLsExtractedCount <= self._imageCount: self._extract_image_urls() self._page_scroll_down() # Slice the list of image URLs to contain the exact number of image # URLs that have been requested # self._imageURLs = self._imageURLs[:self._imageCount] print(colored('Image URLs retrieved.', 'green'))
[ "def", "_get_image_urls", "(", "self", ")", ":", "print", "(", "colored", "(", "'\\nRetrieving Image URLs...'", ",", "'yellow'", ")", ")", "_imageQuery", "=", "self", ".", "_imageQuery", ".", "replace", "(", "' '", ",", "'+'", ")", "self", ".", "_chromeDriver", ".", "get", "(", "'https://www.google.co.in/search?q='", "+", "_imageQuery", "+", "'&newwindow=1&source=lnms&tbm=isch'", ")", "while", "self", ".", "_imageURLsExtractedCount", "<=", "self", ".", "_imageCount", ":", "self", ".", "_extract_image_urls", "(", ")", "self", ".", "_page_scroll_down", "(", ")", "# Slice the list of image URLs to contain the exact number of image", "# URLs that have been requested", "# self._imageURLs = self._imageURLs[:self._imageCount]", "print", "(", "colored", "(", "'Image URLs retrieved.'", ",", "'green'", ")", ")" ]
Retrieves the image URLS corresponding to the image query
[ "Retrieves", "the", "image", "URLS", "corresponding", "to", "the", "image", "query" ]
bd227f3f77cc82603b9ad7798c9af9fed6724a05
https://github.com/Stryker0301/google-image-extractor/blob/bd227f3f77cc82603b9ad7798c9af9fed6724a05/giextractor.py#L177-L195
train
Stryker0301/google-image-extractor
giextractor.py
GoogleImageExtractor._extract_image_urls
def _extract_image_urls(self): """Retrieves image URLs from the current page""" resultsPage = self._chromeDriver.page_source resultsPageSoup = BeautifulSoup(resultsPage, 'html.parser') images = resultsPageSoup.find_all('div', class_='rg_meta') images = [json.loads(image.contents[0]) for image in images] [self._imageURLs.append(image['ou']) for image in images] self._imageURLsExtractedCount += len(images)
python
def _extract_image_urls(self): """Retrieves image URLs from the current page""" resultsPage = self._chromeDriver.page_source resultsPageSoup = BeautifulSoup(resultsPage, 'html.parser') images = resultsPageSoup.find_all('div', class_='rg_meta') images = [json.loads(image.contents[0]) for image in images] [self._imageURLs.append(image['ou']) for image in images] self._imageURLsExtractedCount += len(images)
[ "def", "_extract_image_urls", "(", "self", ")", ":", "resultsPage", "=", "self", ".", "_chromeDriver", ".", "page_source", "resultsPageSoup", "=", "BeautifulSoup", "(", "resultsPage", ",", "'html.parser'", ")", "images", "=", "resultsPageSoup", ".", "find_all", "(", "'div'", ",", "class_", "=", "'rg_meta'", ")", "images", "=", "[", "json", ".", "loads", "(", "image", ".", "contents", "[", "0", "]", ")", "for", "image", "in", "images", "]", "[", "self", ".", "_imageURLs", ".", "append", "(", "image", "[", "'ou'", "]", ")", "for", "image", "in", "images", "]", "self", ".", "_imageURLsExtractedCount", "+=", "len", "(", "images", ")" ]
Retrieves image URLs from the current page
[ "Retrieves", "image", "URLs", "from", "the", "current", "page" ]
bd227f3f77cc82603b9ad7798c9af9fed6724a05
https://github.com/Stryker0301/google-image-extractor/blob/bd227f3f77cc82603b9ad7798c9af9fed6724a05/giextractor.py#L197-L208
train
Stryker0301/google-image-extractor
giextractor.py
GoogleImageExtractor._page_scroll_down
def _page_scroll_down(self): """Scrolls down to get the next set of images""" # Scroll down to request the next set of images self._chromeDriver.execute_script( 'window.scroll(0, document.body.clientHeight)') # Wait for the images to load completely time.sleep(self.WAIT_TIME) # Check if the button - 'Show More Results' is visible # If yes, click it and request more messages # This step helps is avoiding duplicate image URLS from being captured try: self._chromeDriver.find_element_by_id('smb').click() except ElementNotVisibleException as error: pass
python
def _page_scroll_down(self): """Scrolls down to get the next set of images""" # Scroll down to request the next set of images self._chromeDriver.execute_script( 'window.scroll(0, document.body.clientHeight)') # Wait for the images to load completely time.sleep(self.WAIT_TIME) # Check if the button - 'Show More Results' is visible # If yes, click it and request more messages # This step helps is avoiding duplicate image URLS from being captured try: self._chromeDriver.find_element_by_id('smb').click() except ElementNotVisibleException as error: pass
[ "def", "_page_scroll_down", "(", "self", ")", ":", "# Scroll down to request the next set of images", "self", ".", "_chromeDriver", ".", "execute_script", "(", "'window.scroll(0, document.body.clientHeight)'", ")", "# Wait for the images to load completely", "time", ".", "sleep", "(", "self", ".", "WAIT_TIME", ")", "# Check if the button - 'Show More Results' is visible", "# If yes, click it and request more messages", "# This step helps is avoiding duplicate image URLS from being captured", "try", ":", "self", ".", "_chromeDriver", ".", "find_element_by_id", "(", "'smb'", ")", ".", "click", "(", ")", "except", "ElementNotVisibleException", "as", "error", ":", "pass" ]
Scrolls down to get the next set of images
[ "Scrolls", "down", "to", "get", "the", "next", "set", "of", "images" ]
bd227f3f77cc82603b9ad7798c9af9fed6724a05
https://github.com/Stryker0301/google-image-extractor/blob/bd227f3f77cc82603b9ad7798c9af9fed6724a05/giextractor.py#L210-L226
train
Stryker0301/google-image-extractor
giextractor.py
GoogleImageExtractor._download_images
def _download_images(self): """ Downloads the images from the retrieved image URLs and stores in the specified destination folder. Multiprocessing is being used to minimize the download time """ print('\nDownloading Images for the Query: ' + self._imageQuery) try: self._initialize_progress_bar() # Initialize and assign work to the threads in the threadpool threadPool = Pool(self._threadCount) threadPool.map(self._download_image, self._imageURLs) threadPool.close() threadPool.join() # Download each image individually # [self._download_image(imageURL) for imageURL in self._imageURLs] self._downloadProgressBar.finish() except Exception as exception: print('Error - Image Download: ' + format(exception))
python
def _download_images(self): """ Downloads the images from the retrieved image URLs and stores in the specified destination folder. Multiprocessing is being used to minimize the download time """ print('\nDownloading Images for the Query: ' + self._imageQuery) try: self._initialize_progress_bar() # Initialize and assign work to the threads in the threadpool threadPool = Pool(self._threadCount) threadPool.map(self._download_image, self._imageURLs) threadPool.close() threadPool.join() # Download each image individually # [self._download_image(imageURL) for imageURL in self._imageURLs] self._downloadProgressBar.finish() except Exception as exception: print('Error - Image Download: ' + format(exception))
[ "def", "_download_images", "(", "self", ")", ":", "print", "(", "'\\nDownloading Images for the Query: '", "+", "self", ".", "_imageQuery", ")", "try", ":", "self", ".", "_initialize_progress_bar", "(", ")", "# Initialize and assign work to the threads in the threadpool", "threadPool", "=", "Pool", "(", "self", ".", "_threadCount", ")", "threadPool", ".", "map", "(", "self", ".", "_download_image", ",", "self", ".", "_imageURLs", ")", "threadPool", ".", "close", "(", ")", "threadPool", ".", "join", "(", ")", "# Download each image individually", "# [self._download_image(imageURL) for imageURL in self._imageURLs]", "self", ".", "_downloadProgressBar", ".", "finish", "(", ")", "except", "Exception", "as", "exception", ":", "print", "(", "'Error - Image Download: '", "+", "format", "(", "exception", ")", ")" ]
Downloads the images from the retrieved image URLs and stores in the specified destination folder. Multiprocessing is being used to minimize the download time
[ "Downloads", "the", "images", "from", "the", "retrieved", "image", "URLs", "and", "stores", "in", "the", "specified", "destination", "folder", ".", "Multiprocessing", "is", "being", "used", "to", "minimize", "the", "download", "time" ]
bd227f3f77cc82603b9ad7798c9af9fed6724a05
https://github.com/Stryker0301/google-image-extractor/blob/bd227f3f77cc82603b9ad7798c9af9fed6724a05/giextractor.py#L228-L253
train
Stryker0301/google-image-extractor
giextractor.py
GoogleImageExtractor._initialize_progress_bar
def _initialize_progress_bar(self): """Initializes the progress bar""" widgets = ['Download: ', Percentage(), ' ', Bar(), ' ', AdaptiveETA(), ' ', FileTransferSpeed()] self._downloadProgressBar = ProgressBar( widgets=widgets, max_value=self._imageCount).start()
python
def _initialize_progress_bar(self): """Initializes the progress bar""" widgets = ['Download: ', Percentage(), ' ', Bar(), ' ', AdaptiveETA(), ' ', FileTransferSpeed()] self._downloadProgressBar = ProgressBar( widgets=widgets, max_value=self._imageCount).start()
[ "def", "_initialize_progress_bar", "(", "self", ")", ":", "widgets", "=", "[", "'Download: '", ",", "Percentage", "(", ")", ",", "' '", ",", "Bar", "(", ")", ",", "' '", ",", "AdaptiveETA", "(", ")", ",", "' '", ",", "FileTransferSpeed", "(", ")", "]", "self", ".", "_downloadProgressBar", "=", "ProgressBar", "(", "widgets", "=", "widgets", ",", "max_value", "=", "self", ".", "_imageCount", ")", ".", "start", "(", ")" ]
Initializes the progress bar
[ "Initializes", "the", "progress", "bar" ]
bd227f3f77cc82603b9ad7798c9af9fed6724a05
https://github.com/Stryker0301/google-image-extractor/blob/bd227f3f77cc82603b9ad7798c9af9fed6724a05/giextractor.py#L255-L262
train
Stryker0301/google-image-extractor
giextractor.py
GoogleImageExtractor._download_image
def _download_image(self, imageURL): """ Downloads an image file from the given image URL Arguments: imageURL {[str]} -- [Image URL] """ # If the required count of images have been download, # refrain from downloading the remainder of the images if(self._imageCounter >= self._imageCount): return try: imageResponse = requests.get(imageURL) # Generate image file name as <_imageQuery>_<_imageCounter>.<extension> imageType, imageEncoding = mimetypes.guess_type(imageURL) if imageType is not None: imageExtension = mimetypes.guess_extension(imageType) else: imageExtension = mimetypes.guess_extension( imageResponse.headers['Content-Type']) imageFileName = self._imageQuery.replace( ' ', '_') + '_' + str(self._imageCounter) + imageExtension imageFileName = os.path.join(self._storageFolder, imageFileName) image = Image.open(BytesIO(imageResponse.content)) image.save(imageFileName) self._imageCounter += 1 self._downloadProgressBar.update(self._imageCounter) except Exception as exception: pass
python
def _download_image(self, imageURL): """ Downloads an image file from the given image URL Arguments: imageURL {[str]} -- [Image URL] """ # If the required count of images have been download, # refrain from downloading the remainder of the images if(self._imageCounter >= self._imageCount): return try: imageResponse = requests.get(imageURL) # Generate image file name as <_imageQuery>_<_imageCounter>.<extension> imageType, imageEncoding = mimetypes.guess_type(imageURL) if imageType is not None: imageExtension = mimetypes.guess_extension(imageType) else: imageExtension = mimetypes.guess_extension( imageResponse.headers['Content-Type']) imageFileName = self._imageQuery.replace( ' ', '_') + '_' + str(self._imageCounter) + imageExtension imageFileName = os.path.join(self._storageFolder, imageFileName) image = Image.open(BytesIO(imageResponse.content)) image.save(imageFileName) self._imageCounter += 1 self._downloadProgressBar.update(self._imageCounter) except Exception as exception: pass
[ "def", "_download_image", "(", "self", ",", "imageURL", ")", ":", "# If the required count of images have been download,", "# refrain from downloading the remainder of the images", "if", "(", "self", ".", "_imageCounter", ">=", "self", ".", "_imageCount", ")", ":", "return", "try", ":", "imageResponse", "=", "requests", ".", "get", "(", "imageURL", ")", "# Generate image file name as <_imageQuery>_<_imageCounter>.<extension>", "imageType", ",", "imageEncoding", "=", "mimetypes", ".", "guess_type", "(", "imageURL", ")", "if", "imageType", "is", "not", "None", ":", "imageExtension", "=", "mimetypes", ".", "guess_extension", "(", "imageType", ")", "else", ":", "imageExtension", "=", "mimetypes", ".", "guess_extension", "(", "imageResponse", ".", "headers", "[", "'Content-Type'", "]", ")", "imageFileName", "=", "self", ".", "_imageQuery", ".", "replace", "(", "' '", ",", "'_'", ")", "+", "'_'", "+", "str", "(", "self", ".", "_imageCounter", ")", "+", "imageExtension", "imageFileName", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_storageFolder", ",", "imageFileName", ")", "image", "=", "Image", ".", "open", "(", "BytesIO", "(", "imageResponse", ".", "content", ")", ")", "image", ".", "save", "(", "imageFileName", ")", "self", ".", "_imageCounter", "+=", "1", "self", ".", "_downloadProgressBar", ".", "update", "(", "self", ".", "_imageCounter", ")", "except", "Exception", "as", "exception", ":", "pass" ]
Downloads an image file from the given image URL Arguments: imageURL {[str]} -- [Image URL]
[ "Downloads", "an", "image", "file", "from", "the", "given", "image", "URL" ]
bd227f3f77cc82603b9ad7798c9af9fed6724a05
https://github.com/Stryker0301/google-image-extractor/blob/bd227f3f77cc82603b9ad7798c9af9fed6724a05/giextractor.py#L264-L301
train
bitesofcode/projexui
projexui/widgets/xloaderwidget.py
XLoaderWidget.increment
def increment(self, amount=1): """ Increments the main progress bar by amount. """ self._primaryProgressBar.setValue(self.value() + amount) QApplication.instance().processEvents()
python
def increment(self, amount=1): """ Increments the main progress bar by amount. """ self._primaryProgressBar.setValue(self.value() + amount) QApplication.instance().processEvents()
[ "def", "increment", "(", "self", ",", "amount", "=", "1", ")", ":", "self", ".", "_primaryProgressBar", ".", "setValue", "(", "self", ".", "value", "(", ")", "+", "amount", ")", "QApplication", ".", "instance", "(", ")", ".", "processEvents", "(", ")" ]
Increments the main progress bar by amount.
[ "Increments", "the", "main", "progress", "bar", "by", "amount", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xloaderwidget.py#L195-L200
train
bitesofcode/projexui
projexui/widgets/xloaderwidget.py
XLoaderWidget.incrementSub
def incrementSub(self, amount=1): """ Increments the sub-progress bar by amount. """ self._subProgressBar.setValue(self.subValue() + amount) QApplication.instance().processEvents()
python
def incrementSub(self, amount=1): """ Increments the sub-progress bar by amount. """ self._subProgressBar.setValue(self.subValue() + amount) QApplication.instance().processEvents()
[ "def", "incrementSub", "(", "self", ",", "amount", "=", "1", ")", ":", "self", ".", "_subProgressBar", ".", "setValue", "(", "self", ".", "subValue", "(", ")", "+", "amount", ")", "QApplication", ".", "instance", "(", ")", ".", "processEvents", "(", ")" ]
Increments the sub-progress bar by amount.
[ "Increments", "the", "sub", "-", "progress", "bar", "by", "amount", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xloaderwidget.py#L202-L207
train
bitesofcode/projexui
projexui/widgets/xchart/xchart.py
XChart.assignRenderer
def assignRenderer(self, action): """ Assigns the renderer for this chart to the current selected renderer. """ name = nativestring(action.text()).split(' ')[0] self._renderer = XChartRenderer.plugin(name) self.uiTypeBTN.setDefaultAction(action) self.recalculate()
python
def assignRenderer(self, action): """ Assigns the renderer for this chart to the current selected renderer. """ name = nativestring(action.text()).split(' ')[0] self._renderer = XChartRenderer.plugin(name) self.uiTypeBTN.setDefaultAction(action) self.recalculate()
[ "def", "assignRenderer", "(", "self", ",", "action", ")", ":", "name", "=", "nativestring", "(", "action", ".", "text", "(", ")", ")", ".", "split", "(", "' '", ")", "[", "0", "]", "self", ".", "_renderer", "=", "XChartRenderer", ".", "plugin", "(", "name", ")", "self", ".", "uiTypeBTN", ".", "setDefaultAction", "(", "action", ")", "self", ".", "recalculate", "(", ")" ]
Assigns the renderer for this chart to the current selected renderer.
[ "Assigns", "the", "renderer", "for", "this", "chart", "to", "the", "current", "selected", "renderer", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xchart/xchart.py#L235-L243
train
bitesofcode/projexui
projexui/widgets/xchart/xchart.py
XChart.recalculate
def recalculate(self): """ Recalculates the information for this chart. """ if not (self.isVisible() and self.renderer()): return # update dynamic range if self._dataChanged: for axis in self.axes(): if axis.useDynamicRange(): axis.calculateRange(self.values(axis.name())) self._dataChanged = False # recalculate the main grid xaxis = self.horizontalAxis() yaxis = self.verticalAxis() renderer = self.renderer() xvisible = xaxis is not None and self.showXAxis() and renderer.showXAxis() yvisible = yaxis is not None and self.showYAxis() and renderer.showYAxis() self.uiXAxisVIEW.setVisible(xvisible) self.uiYAxisVIEW.setVisible(yvisible) # calculate the main view view = self.uiChartVIEW chart_scene = view.scene() chart_scene.setSceneRect(0, 0, view.width() - 2, view.height() - 2) rect = renderer.calculate(chart_scene, xaxis, yaxis) # recalculate the xaxis if xaxis and self.showXAxis() and renderer.showXAxis(): view = self.uiXAxisVIEW scene = view.scene() scene.setSceneRect(0, 0, rect.width(), view.height()) scene.invalidate() # render the yaxis if yaxis and self.showYAxis() and renderer.showYAxis(): view = self.uiYAxisVIEW scene = view.scene() scene.setSceneRect(0, 0, view.width(), rect.height()) scene.invalidate() # recalculate the items renderer.calculateDatasets(chart_scene, self.axes(), self.datasets()) chart_scene.invalidate()
python
def recalculate(self): """ Recalculates the information for this chart. """ if not (self.isVisible() and self.renderer()): return # update dynamic range if self._dataChanged: for axis in self.axes(): if axis.useDynamicRange(): axis.calculateRange(self.values(axis.name())) self._dataChanged = False # recalculate the main grid xaxis = self.horizontalAxis() yaxis = self.verticalAxis() renderer = self.renderer() xvisible = xaxis is not None and self.showXAxis() and renderer.showXAxis() yvisible = yaxis is not None and self.showYAxis() and renderer.showYAxis() self.uiXAxisVIEW.setVisible(xvisible) self.uiYAxisVIEW.setVisible(yvisible) # calculate the main view view = self.uiChartVIEW chart_scene = view.scene() chart_scene.setSceneRect(0, 0, view.width() - 2, view.height() - 2) rect = renderer.calculate(chart_scene, xaxis, yaxis) # recalculate the xaxis if xaxis and self.showXAxis() and renderer.showXAxis(): view = self.uiXAxisVIEW scene = view.scene() scene.setSceneRect(0, 0, rect.width(), view.height()) scene.invalidate() # render the yaxis if yaxis and self.showYAxis() and renderer.showYAxis(): view = self.uiYAxisVIEW scene = view.scene() scene.setSceneRect(0, 0, view.width(), rect.height()) scene.invalidate() # recalculate the items renderer.calculateDatasets(chart_scene, self.axes(), self.datasets()) chart_scene.invalidate()
[ "def", "recalculate", "(", "self", ")", ":", "if", "not", "(", "self", ".", "isVisible", "(", ")", "and", "self", ".", "renderer", "(", ")", ")", ":", "return", "# update dynamic range\r", "if", "self", ".", "_dataChanged", ":", "for", "axis", "in", "self", ".", "axes", "(", ")", ":", "if", "axis", ".", "useDynamicRange", "(", ")", ":", "axis", ".", "calculateRange", "(", "self", ".", "values", "(", "axis", ".", "name", "(", ")", ")", ")", "self", ".", "_dataChanged", "=", "False", "# recalculate the main grid\r", "xaxis", "=", "self", ".", "horizontalAxis", "(", ")", "yaxis", "=", "self", ".", "verticalAxis", "(", ")", "renderer", "=", "self", ".", "renderer", "(", ")", "xvisible", "=", "xaxis", "is", "not", "None", "and", "self", ".", "showXAxis", "(", ")", "and", "renderer", ".", "showXAxis", "(", ")", "yvisible", "=", "yaxis", "is", "not", "None", "and", "self", ".", "showYAxis", "(", ")", "and", "renderer", ".", "showYAxis", "(", ")", "self", ".", "uiXAxisVIEW", ".", "setVisible", "(", "xvisible", ")", "self", ".", "uiYAxisVIEW", ".", "setVisible", "(", "yvisible", ")", "# calculate the main view\r", "view", "=", "self", ".", "uiChartVIEW", "chart_scene", "=", "view", ".", "scene", "(", ")", "chart_scene", ".", "setSceneRect", "(", "0", ",", "0", ",", "view", ".", "width", "(", ")", "-", "2", ",", "view", ".", "height", "(", ")", "-", "2", ")", "rect", "=", "renderer", ".", "calculate", "(", "chart_scene", ",", "xaxis", ",", "yaxis", ")", "# recalculate the xaxis\r", "if", "xaxis", "and", "self", ".", "showXAxis", "(", ")", "and", "renderer", ".", "showXAxis", "(", ")", ":", "view", "=", "self", ".", "uiXAxisVIEW", "scene", "=", "view", ".", "scene", "(", ")", "scene", ".", "setSceneRect", "(", "0", ",", "0", ",", "rect", ".", "width", "(", ")", ",", "view", ".", "height", "(", ")", ")", "scene", ".", "invalidate", "(", ")", "# render the yaxis\r", "if", "yaxis", "and", "self", ".", "showYAxis", "(", ")", "and", "renderer", ".", "showYAxis", "(", ")", ":", "view", "=", "self", ".", "uiYAxisVIEW", "scene", "=", "view", ".", "scene", "(", ")", "scene", ".", "setSceneRect", "(", "0", ",", "0", ",", "view", ".", "width", "(", ")", ",", "rect", ".", "height", "(", ")", ")", "scene", ".", "invalidate", "(", ")", "# recalculate the items\r", "renderer", ".", "calculateDatasets", "(", "chart_scene", ",", "self", ".", "axes", "(", ")", ",", "self", ".", "datasets", "(", ")", ")", "chart_scene", ".", "invalidate", "(", ")" ]
Recalculates the information for this chart.
[ "Recalculates", "the", "information", "for", "this", "chart", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xchart/xchart.py#L369-L420
train
bitesofcode/projexui
projexui/widgets/xchart/xchart.py
XChart.syncScrollbars
def syncScrollbars(self): """ Synchronizes the various scrollbars within this chart. """ chart_hbar = self.uiChartVIEW.horizontalScrollBar() chart_vbar = self.uiChartVIEW.verticalScrollBar() x_hbar = self.uiXAxisVIEW.horizontalScrollBar() x_vbar = self.uiXAxisVIEW.verticalScrollBar() y_hbar = self.uiYAxisVIEW.horizontalScrollBar() y_vbar = self.uiYAxisVIEW.verticalScrollBar() x_hbar.setRange(chart_hbar.minimum(), chart_hbar.maximum()) x_hbar.setValue(chart_hbar.value()) x_vbar.setValue(0) chart_vbar.setRange(y_vbar.minimum(), y_vbar.maximum()) chart_vbar.setValue(y_vbar.value()) y_hbar.setValue(4)
python
def syncScrollbars(self): """ Synchronizes the various scrollbars within this chart. """ chart_hbar = self.uiChartVIEW.horizontalScrollBar() chart_vbar = self.uiChartVIEW.verticalScrollBar() x_hbar = self.uiXAxisVIEW.horizontalScrollBar() x_vbar = self.uiXAxisVIEW.verticalScrollBar() y_hbar = self.uiYAxisVIEW.horizontalScrollBar() y_vbar = self.uiYAxisVIEW.verticalScrollBar() x_hbar.setRange(chart_hbar.minimum(), chart_hbar.maximum()) x_hbar.setValue(chart_hbar.value()) x_vbar.setValue(0) chart_vbar.setRange(y_vbar.minimum(), y_vbar.maximum()) chart_vbar.setValue(y_vbar.value()) y_hbar.setValue(4)
[ "def", "syncScrollbars", "(", "self", ")", ":", "chart_hbar", "=", "self", ".", "uiChartVIEW", ".", "horizontalScrollBar", "(", ")", "chart_vbar", "=", "self", ".", "uiChartVIEW", ".", "verticalScrollBar", "(", ")", "x_hbar", "=", "self", ".", "uiXAxisVIEW", ".", "horizontalScrollBar", "(", ")", "x_vbar", "=", "self", ".", "uiXAxisVIEW", ".", "verticalScrollBar", "(", ")", "y_hbar", "=", "self", ".", "uiYAxisVIEW", ".", "horizontalScrollBar", "(", ")", "y_vbar", "=", "self", ".", "uiYAxisVIEW", ".", "verticalScrollBar", "(", ")", "x_hbar", ".", "setRange", "(", "chart_hbar", ".", "minimum", "(", ")", ",", "chart_hbar", ".", "maximum", "(", ")", ")", "x_hbar", ".", "setValue", "(", "chart_hbar", ".", "value", "(", ")", ")", "x_vbar", ".", "setValue", "(", "0", ")", "chart_vbar", ".", "setRange", "(", "y_vbar", ".", "minimum", "(", ")", ",", "y_vbar", ".", "maximum", "(", ")", ")", "chart_vbar", ".", "setValue", "(", "y_vbar", ".", "value", "(", ")", ")", "y_hbar", ".", "setValue", "(", "4", ")" ]
Synchronizes the various scrollbars within this chart.
[ "Synchronizes", "the", "various", "scrollbars", "within", "this", "chart", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xchart/xchart.py#L692-L712
train
johnnoone/aioconsul
aioconsul/client/catalog_endpoint.py
CatalogEndpoint.deregister
async def deregister(self, node, *, check=None, service=None, write_token=None): """Deregisters a node, service or check Parameters: node (Object or ObjectID): Node check (ObjectID): Check ID service (ObjectID): Service ID write_token (ObjectID): Token ID Returns: bool: ``True`` on success **Node** expects a body that look like one of the following:: { "Datacenter": "dc1", "Node": "foobar", } :: { "Datacenter": "dc1", "Node": "foobar", "CheckID": "service:redis1" } :: { "Datacenter": "dc1", "Node": "foobar", "ServiceID": "redis1", } The behavior of the endpoint depends on what keys are provided. The endpoint requires **Node** to be provided while **Datacenter** will be defaulted to match that of the agent. If only **Node** is provided, the node and all associated services and checks are deleted. If **CheckID** is provided, only that check is removed. If **ServiceID** is provided, the service and its associated health check (if any) are removed. An optional ACL token may be provided to perform the deregister action by adding a **WriteRequest** block in the query, like this:: { "WriteRequest": { "Token": "foo" } } """ entry = {} if isinstance(node, str): entry["Node"] = node else: for k in ("Datacenter", "Node", "CheckID", "ServiceID", "WriteRequest"): if k in node: entry[k] = node[k] service_id = extract_attr(service, keys=["ServiceID", "ID"]) check_id = extract_attr(check, keys=["CheckID", "ID"]) if service_id and not check_id: entry["ServiceID"] = service_id elif service_id and check_id: entry["CheckID"] = "%s:%s" % (service_id, check_id) elif not service_id and check_id: entry["CheckID"] = check_id if write_token: entry["WriteRequest"] = { "Token": extract_attr(write_token, keys=["ID"]) } response = await self._api.put("/v1/catalog/deregister", data=entry) return response.status == 200
python
async def deregister(self, node, *, check=None, service=None, write_token=None): """Deregisters a node, service or check Parameters: node (Object or ObjectID): Node check (ObjectID): Check ID service (ObjectID): Service ID write_token (ObjectID): Token ID Returns: bool: ``True`` on success **Node** expects a body that look like one of the following:: { "Datacenter": "dc1", "Node": "foobar", } :: { "Datacenter": "dc1", "Node": "foobar", "CheckID": "service:redis1" } :: { "Datacenter": "dc1", "Node": "foobar", "ServiceID": "redis1", } The behavior of the endpoint depends on what keys are provided. The endpoint requires **Node** to be provided while **Datacenter** will be defaulted to match that of the agent. If only **Node** is provided, the node and all associated services and checks are deleted. If **CheckID** is provided, only that check is removed. If **ServiceID** is provided, the service and its associated health check (if any) are removed. An optional ACL token may be provided to perform the deregister action by adding a **WriteRequest** block in the query, like this:: { "WriteRequest": { "Token": "foo" } } """ entry = {} if isinstance(node, str): entry["Node"] = node else: for k in ("Datacenter", "Node", "CheckID", "ServiceID", "WriteRequest"): if k in node: entry[k] = node[k] service_id = extract_attr(service, keys=["ServiceID", "ID"]) check_id = extract_attr(check, keys=["CheckID", "ID"]) if service_id and not check_id: entry["ServiceID"] = service_id elif service_id and check_id: entry["CheckID"] = "%s:%s" % (service_id, check_id) elif not service_id and check_id: entry["CheckID"] = check_id if write_token: entry["WriteRequest"] = { "Token": extract_attr(write_token, keys=["ID"]) } response = await self._api.put("/v1/catalog/deregister", data=entry) return response.status == 200
[ "async", "def", "deregister", "(", "self", ",", "node", ",", "*", ",", "check", "=", "None", ",", "service", "=", "None", ",", "write_token", "=", "None", ")", ":", "entry", "=", "{", "}", "if", "isinstance", "(", "node", ",", "str", ")", ":", "entry", "[", "\"Node\"", "]", "=", "node", "else", ":", "for", "k", "in", "(", "\"Datacenter\"", ",", "\"Node\"", ",", "\"CheckID\"", ",", "\"ServiceID\"", ",", "\"WriteRequest\"", ")", ":", "if", "k", "in", "node", ":", "entry", "[", "k", "]", "=", "node", "[", "k", "]", "service_id", "=", "extract_attr", "(", "service", ",", "keys", "=", "[", "\"ServiceID\"", ",", "\"ID\"", "]", ")", "check_id", "=", "extract_attr", "(", "check", ",", "keys", "=", "[", "\"CheckID\"", ",", "\"ID\"", "]", ")", "if", "service_id", "and", "not", "check_id", ":", "entry", "[", "\"ServiceID\"", "]", "=", "service_id", "elif", "service_id", "and", "check_id", ":", "entry", "[", "\"CheckID\"", "]", "=", "\"%s:%s\"", "%", "(", "service_id", ",", "check_id", ")", "elif", "not", "service_id", "and", "check_id", ":", "entry", "[", "\"CheckID\"", "]", "=", "check_id", "if", "write_token", ":", "entry", "[", "\"WriteRequest\"", "]", "=", "{", "\"Token\"", ":", "extract_attr", "(", "write_token", ",", "keys", "=", "[", "\"ID\"", "]", ")", "}", "response", "=", "await", "self", ".", "_api", ".", "put", "(", "\"/v1/catalog/deregister\"", ",", "data", "=", "entry", ")", "return", "response", ".", "status", "==", "200" ]
Deregisters a node, service or check Parameters: node (Object or ObjectID): Node check (ObjectID): Check ID service (ObjectID): Service ID write_token (ObjectID): Token ID Returns: bool: ``True`` on success **Node** expects a body that look like one of the following:: { "Datacenter": "dc1", "Node": "foobar", } :: { "Datacenter": "dc1", "Node": "foobar", "CheckID": "service:redis1" } :: { "Datacenter": "dc1", "Node": "foobar", "ServiceID": "redis1", } The behavior of the endpoint depends on what keys are provided. The endpoint requires **Node** to be provided while **Datacenter** will be defaulted to match that of the agent. If only **Node** is provided, the node and all associated services and checks are deleted. If **CheckID** is provided, only that check is removed. If **ServiceID** is provided, the service and its associated health check (if any) are removed. An optional ACL token may be provided to perform the deregister action by adding a **WriteRequest** block in the query, like this:: { "WriteRequest": { "Token": "foo" } }
[ "Deregisters", "a", "node", "service", "or", "check" ]
02f7a529d7dc2e49bed942111067aa5faf320e90
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/catalog_endpoint.py#L193-L266
train
johnnoone/aioconsul
aioconsul/client/catalog_endpoint.py
CatalogEndpoint.nodes
async def nodes(self, *, dc=None, near=None, watch=None, consistency=None): """Lists nodes in a given DC Parameters: dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. near (str): Sort the node list in ascending order based on the estimated round trip time from that node. watch (Blocking): Do a blocking query consistency (Consistency): Force consistency Returns: CollectionMeta: where value is a list It returns a body like this:: [ { "Node": "baz", "Address": "10.1.10.11", "TaggedAddresses": { "lan": "10.1.10.11", "wan": "10.1.10.11" } }, { "Node": "foobar", "Address": "10.1.10.12", "TaggedAddresses": { "lan": "10.1.10.11", "wan": "10.1.10.12" } } ] """ params = {"dc": dc, "near": near} response = await self._api.get("/v1/catalog/nodes", params=params, watch=watch, consistency=consistency) return consul(response)
python
async def nodes(self, *, dc=None, near=None, watch=None, consistency=None): """Lists nodes in a given DC Parameters: dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. near (str): Sort the node list in ascending order based on the estimated round trip time from that node. watch (Blocking): Do a blocking query consistency (Consistency): Force consistency Returns: CollectionMeta: where value is a list It returns a body like this:: [ { "Node": "baz", "Address": "10.1.10.11", "TaggedAddresses": { "lan": "10.1.10.11", "wan": "10.1.10.11" } }, { "Node": "foobar", "Address": "10.1.10.12", "TaggedAddresses": { "lan": "10.1.10.11", "wan": "10.1.10.12" } } ] """ params = {"dc": dc, "near": near} response = await self._api.get("/v1/catalog/nodes", params=params, watch=watch, consistency=consistency) return consul(response)
[ "async", "def", "nodes", "(", "self", ",", "*", ",", "dc", "=", "None", ",", "near", "=", "None", ",", "watch", "=", "None", ",", "consistency", "=", "None", ")", ":", "params", "=", "{", "\"dc\"", ":", "dc", ",", "\"near\"", ":", "near", "}", "response", "=", "await", "self", ".", "_api", ".", "get", "(", "\"/v1/catalog/nodes\"", ",", "params", "=", "params", ",", "watch", "=", "watch", ",", "consistency", "=", "consistency", ")", "return", "consul", "(", "response", ")" ]
Lists nodes in a given DC Parameters: dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. near (str): Sort the node list in ascending order based on the estimated round trip time from that node. watch (Blocking): Do a blocking query consistency (Consistency): Force consistency Returns: CollectionMeta: where value is a list It returns a body like this:: [ { "Node": "baz", "Address": "10.1.10.11", "TaggedAddresses": { "lan": "10.1.10.11", "wan": "10.1.10.11" } }, { "Node": "foobar", "Address": "10.1.10.12", "TaggedAddresses": { "lan": "10.1.10.11", "wan": "10.1.10.12" } } ]
[ "Lists", "nodes", "in", "a", "given", "DC" ]
02f7a529d7dc2e49bed942111067aa5faf320e90
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/catalog_endpoint.py#L288-L328
train
johnnoone/aioconsul
aioconsul/client/catalog_endpoint.py
CatalogEndpoint.services
async def services(self, *, dc=None, watch=None, consistency=None): """Lists services in a given DC Parameters: dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. watch (Blocking): Do a blocking query consistency (Consistency): Force consistency Returns: ObjectMeta: where value is a dict It returns a JSON body like this:: { "consul": [], "redis": [], "postgresql": [ "master", "slave" ] } The keys are the service names, and the array values provide all known tags for a given service. """ params = {"dc": dc} response = await self._api.get("/v1/catalog/services", params=params, watch=watch, consistency=consistency) return consul(response)
python
async def services(self, *, dc=None, watch=None, consistency=None): """Lists services in a given DC Parameters: dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. watch (Blocking): Do a blocking query consistency (Consistency): Force consistency Returns: ObjectMeta: where value is a dict It returns a JSON body like this:: { "consul": [], "redis": [], "postgresql": [ "master", "slave" ] } The keys are the service names, and the array values provide all known tags for a given service. """ params = {"dc": dc} response = await self._api.get("/v1/catalog/services", params=params, watch=watch, consistency=consistency) return consul(response)
[ "async", "def", "services", "(", "self", ",", "*", ",", "dc", "=", "None", ",", "watch", "=", "None", ",", "consistency", "=", "None", ")", ":", "params", "=", "{", "\"dc\"", ":", "dc", "}", "response", "=", "await", "self", ".", "_api", ".", "get", "(", "\"/v1/catalog/services\"", ",", "params", "=", "params", ",", "watch", "=", "watch", ",", "consistency", "=", "consistency", ")", "return", "consul", "(", "response", ")" ]
Lists services in a given DC Parameters: dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. watch (Blocking): Do a blocking query consistency (Consistency): Force consistency Returns: ObjectMeta: where value is a dict It returns a JSON body like this:: { "consul": [], "redis": [], "postgresql": [ "master", "slave" ] } The keys are the service names, and the array values provide all known tags for a given service.
[ "Lists", "services", "in", "a", "given", "DC" ]
02f7a529d7dc2e49bed942111067aa5faf320e90
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/catalog_endpoint.py#L330-L360
train
bitesofcode/projexui
projexui/widgets/xviewwidget/xviewprofiletoolbar.py
XViewProfileToolBar.createProfile
def createProfile(self, profile=None, clearLayout=True): """ Prompts the user to create a new profile. """ if profile: prof = profile elif not self.viewWidget() or clearLayout: prof = XViewProfile() else: prof = self.viewWidget().saveProfile() blocked = self.signalsBlocked() self.blockSignals(False) changed = self.editProfile(prof) self.blockSignals(blocked) if not changed: return act = self.addProfile(prof) act.setChecked(True) # update the interface if self.viewWidget() and (profile or clearLayout): self.viewWidget().restoreProfile(prof) if not self.signalsBlocked(): self.profileCreated.emit(prof) self.profilesChanged.emit()
python
def createProfile(self, profile=None, clearLayout=True): """ Prompts the user to create a new profile. """ if profile: prof = profile elif not self.viewWidget() or clearLayout: prof = XViewProfile() else: prof = self.viewWidget().saveProfile() blocked = self.signalsBlocked() self.blockSignals(False) changed = self.editProfile(prof) self.blockSignals(blocked) if not changed: return act = self.addProfile(prof) act.setChecked(True) # update the interface if self.viewWidget() and (profile or clearLayout): self.viewWidget().restoreProfile(prof) if not self.signalsBlocked(): self.profileCreated.emit(prof) self.profilesChanged.emit()
[ "def", "createProfile", "(", "self", ",", "profile", "=", "None", ",", "clearLayout", "=", "True", ")", ":", "if", "profile", ":", "prof", "=", "profile", "elif", "not", "self", ".", "viewWidget", "(", ")", "or", "clearLayout", ":", "prof", "=", "XViewProfile", "(", ")", "else", ":", "prof", "=", "self", ".", "viewWidget", "(", ")", ".", "saveProfile", "(", ")", "blocked", "=", "self", ".", "signalsBlocked", "(", ")", "self", ".", "blockSignals", "(", "False", ")", "changed", "=", "self", ".", "editProfile", "(", "prof", ")", "self", ".", "blockSignals", "(", "blocked", ")", "if", "not", "changed", ":", "return", "act", "=", "self", ".", "addProfile", "(", "prof", ")", "act", ".", "setChecked", "(", "True", ")", "# update the interface\r", "if", "self", ".", "viewWidget", "(", ")", "and", "(", "profile", "or", "clearLayout", ")", ":", "self", ".", "viewWidget", "(", ")", ".", "restoreProfile", "(", "prof", ")", "if", "not", "self", ".", "signalsBlocked", "(", ")", ":", "self", ".", "profileCreated", ".", "emit", "(", "prof", ")", "self", ".", "profilesChanged", ".", "emit", "(", ")" ]
Prompts the user to create a new profile.
[ "Prompts", "the", "user", "to", "create", "a", "new", "profile", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewprofiletoolbar.py#L164-L192
train
bitesofcode/projexui
projexui/widgets/xquerybuilderwidget/xquerybuilderwidget.py
XQueryBuilderWidget.updateRemoveEnabled
def updateRemoveEnabled( self ): """ Updates the remove enabled baesd on the current number of line widgets. """ lineWidgets = self.lineWidgets() count = len(lineWidgets) state = self.minimumCount() < count for widget in lineWidgets: widget.setRemoveEnabled(state)
python
def updateRemoveEnabled( self ): """ Updates the remove enabled baesd on the current number of line widgets. """ lineWidgets = self.lineWidgets() count = len(lineWidgets) state = self.minimumCount() < count for widget in lineWidgets: widget.setRemoveEnabled(state)
[ "def", "updateRemoveEnabled", "(", "self", ")", ":", "lineWidgets", "=", "self", ".", "lineWidgets", "(", ")", "count", "=", "len", "(", "lineWidgets", ")", "state", "=", "self", ".", "minimumCount", "(", ")", "<", "count", "for", "widget", "in", "lineWidgets", ":", "widget", ".", "setRemoveEnabled", "(", "state", ")" ]
Updates the remove enabled baesd on the current number of line widgets.
[ "Updates", "the", "remove", "enabled", "baesd", "on", "the", "current", "number", "of", "line", "widgets", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xquerybuilderwidget/xquerybuilderwidget.py#L289-L298
train
bitesofcode/projexui
projexui/widgets/xquerybuilderwidget/xquerybuilderwidget.py
XQueryBuilderWidget.updateRules
def updateRules( self ): """ Updates the query line items to match the latest rule options. """ terms = sorted(self._rules.keys()) for child in self.lineWidgets(): child.setTerms(terms)
python
def updateRules( self ): """ Updates the query line items to match the latest rule options. """ terms = sorted(self._rules.keys()) for child in self.lineWidgets(): child.setTerms(terms)
[ "def", "updateRules", "(", "self", ")", ":", "terms", "=", "sorted", "(", "self", ".", "_rules", ".", "keys", "(", ")", ")", "for", "child", "in", "self", ".", "lineWidgets", "(", ")", ":", "child", ".", "setTerms", "(", "terms", ")" ]
Updates the query line items to match the latest rule options.
[ "Updates", "the", "query", "line", "items", "to", "match", "the", "latest", "rule", "options", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xquerybuilderwidget/xquerybuilderwidget.py#L300-L306
train
bitesofcode/projexui
projexui/widgets/xviewwidget/xviewprofilemanager.py
XViewProfileManager.handleProfileChange
def handleProfileChange(self): """ Emits that the current profile has changed. """ # restore the profile settings prof = self.currentProfile() vwidget = self.viewWidget() if vwidget: prof.restore(vwidget) if not self.signalsBlocked(): self.currentProfileChanged.emit(self.currentProfile())
python
def handleProfileChange(self): """ Emits that the current profile has changed. """ # restore the profile settings prof = self.currentProfile() vwidget = self.viewWidget() if vwidget: prof.restore(vwidget) if not self.signalsBlocked(): self.currentProfileChanged.emit(self.currentProfile())
[ "def", "handleProfileChange", "(", "self", ")", ":", "# restore the profile settings", "prof", "=", "self", ".", "currentProfile", "(", ")", "vwidget", "=", "self", ".", "viewWidget", "(", ")", "if", "vwidget", ":", "prof", ".", "restore", "(", "vwidget", ")", "if", "not", "self", ".", "signalsBlocked", "(", ")", ":", "self", ".", "currentProfileChanged", ".", "emit", "(", "self", ".", "currentProfile", "(", ")", ")" ]
Emits that the current profile has changed.
[ "Emits", "that", "the", "current", "profile", "has", "changed", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewprofilemanager.py#L89-L100
train
bitesofcode/projexui
projexui/widgets/xviewwidget/xviewprofilemanager.py
XViewProfileManager.showOptionsMenu
def showOptionsMenu(self): """ Displays the options menu. If the option menu policy is set to CustomContextMenu, then the optionMenuRequested signal will be emitted, otherwise the default context menu will be displayed. """ point = QPoint(0, self._optionsButton.height()) global_point = self._optionsButton.mapToGlobal(point) # prompt the custom context menu if self.optionsMenuPolicy() == Qt.CustomContextMenu: if not self.signalsBlocked(): self.optionsMenuRequested.emit(global_point) return # use the default context menu menu = XViewProfileManagerMenu(self) menu.exec_(global_point)
python
def showOptionsMenu(self): """ Displays the options menu. If the option menu policy is set to CustomContextMenu, then the optionMenuRequested signal will be emitted, otherwise the default context menu will be displayed. """ point = QPoint(0, self._optionsButton.height()) global_point = self._optionsButton.mapToGlobal(point) # prompt the custom context menu if self.optionsMenuPolicy() == Qt.CustomContextMenu: if not self.signalsBlocked(): self.optionsMenuRequested.emit(global_point) return # use the default context menu menu = XViewProfileManagerMenu(self) menu.exec_(global_point)
[ "def", "showOptionsMenu", "(", "self", ")", ":", "point", "=", "QPoint", "(", "0", ",", "self", ".", "_optionsButton", ".", "height", "(", ")", ")", "global_point", "=", "self", ".", "_optionsButton", ".", "mapToGlobal", "(", "point", ")", "# prompt the custom context menu", "if", "self", ".", "optionsMenuPolicy", "(", ")", "==", "Qt", ".", "CustomContextMenu", ":", "if", "not", "self", ".", "signalsBlocked", "(", ")", ":", "self", ".", "optionsMenuRequested", ".", "emit", "(", "global_point", ")", "return", "# use the default context menu", "menu", "=", "XViewProfileManagerMenu", "(", "self", ")", "menu", ".", "exec_", "(", "global_point", ")" ]
Displays the options menu. If the option menu policy is set to CustomContextMenu, then the optionMenuRequested signal will be emitted, otherwise the default context menu will be displayed.
[ "Displays", "the", "options", "menu", ".", "If", "the", "option", "menu", "policy", "is", "set", "to", "CustomContextMenu", "then", "the", "optionMenuRequested", "signal", "will", "be", "emitted", "otherwise", "the", "default", "context", "menu", "will", "be", "displayed", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewprofilemanager.py#L235-L252
train
bitesofcode/projexui
projexui/widgets/xsnapshotwidget.py
XSnapshotWidget.accept
def accept(self): """ Prompts the user for the filepath to save and then saves the image. """ filetypes = 'PNG Files (*.png);;JPG Files (*.jpg);;All Files (*.*)' filename = QFileDialog.getSaveFileName(None, 'Save Snapshot', self.filepath(), filetypes) if type(filename) == tuple: filename = filename[0] filename = nativestring(filename) if not filename: self.reject() else: self.setFilepath(filename) self.save()
python
def accept(self): """ Prompts the user for the filepath to save and then saves the image. """ filetypes = 'PNG Files (*.png);;JPG Files (*.jpg);;All Files (*.*)' filename = QFileDialog.getSaveFileName(None, 'Save Snapshot', self.filepath(), filetypes) if type(filename) == tuple: filename = filename[0] filename = nativestring(filename) if not filename: self.reject() else: self.setFilepath(filename) self.save()
[ "def", "accept", "(", "self", ")", ":", "filetypes", "=", "'PNG Files (*.png);;JPG Files (*.jpg);;All Files (*.*)'", "filename", "=", "QFileDialog", ".", "getSaveFileName", "(", "None", ",", "'Save Snapshot'", ",", "self", ".", "filepath", "(", ")", ",", "filetypes", ")", "if", "type", "(", "filename", ")", "==", "tuple", ":", "filename", "=", "filename", "[", "0", "]", "filename", "=", "nativestring", "(", "filename", ")", "if", "not", "filename", ":", "self", ".", "reject", "(", ")", "else", ":", "self", ".", "setFilepath", "(", "filename", ")", "self", ".", "save", "(", ")" ]
Prompts the user for the filepath to save and then saves the image.
[ "Prompts", "the", "user", "for", "the", "filepath", "to", "save", "and", "then", "saves", "the", "image", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xsnapshotwidget.py#L46-L64
train
bitesofcode/projexui
projexui/widgets/xsnapshotwidget.py
XSnapshotWidget.reject
def reject(self): """ Rejects the snapshot and closes the widget. """ if self.hideWindow(): self.hideWindow().show() self.close() self.deleteLater()
python
def reject(self): """ Rejects the snapshot and closes the widget. """ if self.hideWindow(): self.hideWindow().show() self.close() self.deleteLater()
[ "def", "reject", "(", "self", ")", ":", "if", "self", ".", "hideWindow", "(", ")", ":", "self", ".", "hideWindow", "(", ")", ".", "show", "(", ")", "self", ".", "close", "(", ")", "self", ".", "deleteLater", "(", ")" ]
Rejects the snapshot and closes the widget.
[ "Rejects", "the", "snapshot", "and", "closes", "the", "widget", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xsnapshotwidget.py#L144-L152
train
bitesofcode/projexui
projexui/widgets/xsnapshotwidget.py
XSnapshotWidget.save
def save(self): """ Saves the snapshot based on the current region. """ # close down the snapshot widget if self.hideWindow(): self.hideWindow().hide() self.hide() QApplication.processEvents() time.sleep(1) # create the pixmap to save wid = QApplication.desktop().winId() if not self._region.isNull(): x = self._region.x() y = self._region.y() w = self._region.width() h = self._region.height() else: x = self.x() y = self.y() w = self.width() h = self.height() pixmap = QPixmap.grabWindow(wid, x, y, w, h) pixmap.save(self.filepath()) self.close() self.deleteLater() if self.hideWindow(): self.hideWindow().show()
python
def save(self): """ Saves the snapshot based on the current region. """ # close down the snapshot widget if self.hideWindow(): self.hideWindow().hide() self.hide() QApplication.processEvents() time.sleep(1) # create the pixmap to save wid = QApplication.desktop().winId() if not self._region.isNull(): x = self._region.x() y = self._region.y() w = self._region.width() h = self._region.height() else: x = self.x() y = self.y() w = self.width() h = self.height() pixmap = QPixmap.grabWindow(wid, x, y, w, h) pixmap.save(self.filepath()) self.close() self.deleteLater() if self.hideWindow(): self.hideWindow().show()
[ "def", "save", "(", "self", ")", ":", "# close down the snapshot widget\r", "if", "self", ".", "hideWindow", "(", ")", ":", "self", ".", "hideWindow", "(", ")", ".", "hide", "(", ")", "self", ".", "hide", "(", ")", "QApplication", ".", "processEvents", "(", ")", "time", ".", "sleep", "(", "1", ")", "# create the pixmap to save\r", "wid", "=", "QApplication", ".", "desktop", "(", ")", ".", "winId", "(", ")", "if", "not", "self", ".", "_region", ".", "isNull", "(", ")", ":", "x", "=", "self", ".", "_region", ".", "x", "(", ")", "y", "=", "self", ".", "_region", ".", "y", "(", ")", "w", "=", "self", ".", "_region", ".", "width", "(", ")", "h", "=", "self", ".", "_region", ".", "height", "(", ")", "else", ":", "x", "=", "self", ".", "x", "(", ")", "y", "=", "self", ".", "y", "(", ")", "w", "=", "self", ".", "width", "(", ")", "h", "=", "self", ".", "height", "(", ")", "pixmap", "=", "QPixmap", ".", "grabWindow", "(", "wid", ",", "x", ",", "y", ",", "w", ",", "h", ")", "pixmap", ".", "save", "(", "self", ".", "filepath", "(", ")", ")", "self", ".", "close", "(", ")", "self", ".", "deleteLater", "(", ")", "if", "self", ".", "hideWindow", "(", ")", ":", "self", ".", "hideWindow", "(", ")", ".", "show", "(", ")" ]
Saves the snapshot based on the current region.
[ "Saves", "the", "snapshot", "based", "on", "the", "current", "region", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xsnapshotwidget.py#L162-L194
train
bitesofcode/projexui
projexui/widgets/xsnapshotwidget.py
XSnapshotWidget.show
def show(self): """ Shows this widget and hides the specified window if necessary. """ super(XSnapshotWidget, self).show() if self.hideWindow(): self.hideWindow().hide() QApplication.processEvents()
python
def show(self): """ Shows this widget and hides the specified window if necessary. """ super(XSnapshotWidget, self).show() if self.hideWindow(): self.hideWindow().hide() QApplication.processEvents()
[ "def", "show", "(", "self", ")", ":", "super", "(", "XSnapshotWidget", ",", "self", ")", ".", "show", "(", ")", "if", "self", ".", "hideWindow", "(", ")", ":", "self", ".", "hideWindow", "(", ")", ".", "hide", "(", ")", "QApplication", ".", "processEvents", "(", ")" ]
Shows this widget and hides the specified window if necessary.
[ "Shows", "this", "widget", "and", "hides", "the", "specified", "window", "if", "necessary", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xsnapshotwidget.py#L196-L204
train
mikhaildubov/AST-text-analysis
east/applications.py
keyphrases_table
def keyphrases_table(keyphrases, texts, similarity_measure=None, synonimizer=None, language=consts.Language.ENGLISH): """ Constructs the keyphrases table, containing their matching scores in a set of texts. The resulting table is stored as a dictionary of dictionaries, where the entry table["keyphrase"]["text"] corresponds to the matching score (0 <= score <= 1) of keyphrase "keyphrase" in the text named "text". :param keyphrases: list of strings :param texts: dictionary of form {text_name: text} :param similarity_measure: similarity measure to use :param synonimizer: SynonymExtractor object to be used :param language: Language of the text collection / keyphrases :returns: dictionary of dictionaries, having keyphrases on its first level and texts on the second level. """ similarity_measure = similarity_measure or relevance.ASTRelevanceMeasure() text_titles = texts.keys() text_collection = texts.values() similarity_measure.set_text_collection(text_collection, language) i = 0 keyphrases_prepared = {keyphrase: utils.prepare_text(keyphrase) for keyphrase in keyphrases} total_keyphrases = len(keyphrases) total_scores = len(text_collection) * total_keyphrases res = {} for keyphrase in keyphrases: if not keyphrase: continue res[keyphrase] = {} for j in xrange(len(text_collection)): i += 1 logging.progress("Calculating matching scores", i, total_scores) res[keyphrase][text_titles[j]] = similarity_measure.relevance( keyphrases_prepared[keyphrase], text=j, synonimizer=synonimizer) logging.clear() return res
python
def keyphrases_table(keyphrases, texts, similarity_measure=None, synonimizer=None, language=consts.Language.ENGLISH): """ Constructs the keyphrases table, containing their matching scores in a set of texts. The resulting table is stored as a dictionary of dictionaries, where the entry table["keyphrase"]["text"] corresponds to the matching score (0 <= score <= 1) of keyphrase "keyphrase" in the text named "text". :param keyphrases: list of strings :param texts: dictionary of form {text_name: text} :param similarity_measure: similarity measure to use :param synonimizer: SynonymExtractor object to be used :param language: Language of the text collection / keyphrases :returns: dictionary of dictionaries, having keyphrases on its first level and texts on the second level. """ similarity_measure = similarity_measure or relevance.ASTRelevanceMeasure() text_titles = texts.keys() text_collection = texts.values() similarity_measure.set_text_collection(text_collection, language) i = 0 keyphrases_prepared = {keyphrase: utils.prepare_text(keyphrase) for keyphrase in keyphrases} total_keyphrases = len(keyphrases) total_scores = len(text_collection) * total_keyphrases res = {} for keyphrase in keyphrases: if not keyphrase: continue res[keyphrase] = {} for j in xrange(len(text_collection)): i += 1 logging.progress("Calculating matching scores", i, total_scores) res[keyphrase][text_titles[j]] = similarity_measure.relevance( keyphrases_prepared[keyphrase], text=j, synonimizer=synonimizer) logging.clear() return res
[ "def", "keyphrases_table", "(", "keyphrases", ",", "texts", ",", "similarity_measure", "=", "None", ",", "synonimizer", "=", "None", ",", "language", "=", "consts", ".", "Language", ".", "ENGLISH", ")", ":", "similarity_measure", "=", "similarity_measure", "or", "relevance", ".", "ASTRelevanceMeasure", "(", ")", "text_titles", "=", "texts", ".", "keys", "(", ")", "text_collection", "=", "texts", ".", "values", "(", ")", "similarity_measure", ".", "set_text_collection", "(", "text_collection", ",", "language", ")", "i", "=", "0", "keyphrases_prepared", "=", "{", "keyphrase", ":", "utils", ".", "prepare_text", "(", "keyphrase", ")", "for", "keyphrase", "in", "keyphrases", "}", "total_keyphrases", "=", "len", "(", "keyphrases", ")", "total_scores", "=", "len", "(", "text_collection", ")", "*", "total_keyphrases", "res", "=", "{", "}", "for", "keyphrase", "in", "keyphrases", ":", "if", "not", "keyphrase", ":", "continue", "res", "[", "keyphrase", "]", "=", "{", "}", "for", "j", "in", "xrange", "(", "len", "(", "text_collection", ")", ")", ":", "i", "+=", "1", "logging", ".", "progress", "(", "\"Calculating matching scores\"", ",", "i", ",", "total_scores", ")", "res", "[", "keyphrase", "]", "[", "text_titles", "[", "j", "]", "]", "=", "similarity_measure", ".", "relevance", "(", "keyphrases_prepared", "[", "keyphrase", "]", ",", "text", "=", "j", ",", "synonimizer", "=", "synonimizer", ")", "logging", ".", "clear", "(", ")", "return", "res" ]
Constructs the keyphrases table, containing their matching scores in a set of texts. The resulting table is stored as a dictionary of dictionaries, where the entry table["keyphrase"]["text"] corresponds to the matching score (0 <= score <= 1) of keyphrase "keyphrase" in the text named "text". :param keyphrases: list of strings :param texts: dictionary of form {text_name: text} :param similarity_measure: similarity measure to use :param synonimizer: SynonymExtractor object to be used :param language: Language of the text collection / keyphrases :returns: dictionary of dictionaries, having keyphrases on its first level and texts on the second level.
[ "Constructs", "the", "keyphrases", "table", "containing", "their", "matching", "scores", "in", "a", "set", "of", "texts", "." ]
055ad8d2492c100bbbaa25309ec1074bdf1dfaa5
https://github.com/mikhaildubov/AST-text-analysis/blob/055ad8d2492c100bbbaa25309ec1074bdf1dfaa5/east/applications.py#L11-L56
train
mikhaildubov/AST-text-analysis
east/applications.py
keyphrases_graph
def keyphrases_graph(keyphrases, texts, referral_confidence=0.6, relevance_threshold=0.25, support_threshold=1, similarity_measure=None, synonimizer=None, language=consts.Language.ENGLISH): """ Constructs the keyphrases relation graph based on the given texts corpus. The graph construction algorithm is based on the analysis of co-occurrences of key phrases in the text corpus. A key phrase is considered to imply another one if that second phrase occurs frequently enough in the same texts as the first one (that frequency is controlled by the referral_confidence). A keyphrase counts as occuring in a text if its matching score for that text ecxeeds some threshold (Mirkin, Chernyak, & Chugunova, 2012). :param keyphrases: list of unicode strings :param texts: dictionary of form {text_name: text} :param referral_confidence: significance level of the graph in [0; 1], 0.6 by default :param relevance_threshold: threshold for the matching score in [0; 1] where a keyphrase starts to be considered as occuring in the corresponding text; the defaul value is 0.25 :param support_threshold: threshold for the support of a node (the number of documents containing the corresponding keyphrase) such that it can be included into the graph :param similarity_measure: Similarity measure to use :param synonimizer: SynonymExtractor object to be used :param language: Language of the text collection / keyphrases :returns: graph dictionary in a the following format: { "nodes": [ { "id": <id>, "label": "keyphrase", "support": <# of documents containing the keyphrase> }, ... ] "edges": [ { "source": "node_id", "target": "node_id", "confidence": <confidence_level> }, ... ] } """ similarity_measure = similarity_measure or relevance.ASTRelevanceMeasure() # Keyphrases table table = keyphrases_table(keyphrases, texts, similarity_measure, synonimizer, language) # Dictionary { "keyphrase" => set(names of texts containing "keyphrase") } keyphrase_texts = {keyphrase: set([text for text in texts if table[keyphrase][text] >= relevance_threshold]) for keyphrase in keyphrases} # Initializing the graph object with nodes graph = { "nodes": [ { "id": i, "label": keyphrase, "support": len(keyphrase_texts[keyphrase]) } for i, keyphrase in enumerate(keyphrases) ], "edges": [], "referral_confidence": referral_confidence, "relevance_threshold": relevance_threshold, "support_threshold": support_threshold } # Removing nodes with small support after we've numbered all nodes graph["nodes"] = [n for n in graph["nodes"] if len(keyphrase_texts[n["label"]]) >= support_threshold] # Creating edges # NOTE(msdubov): permutations(), unlike combinations(), treats (1,2) and (2,1) as different for i1, i2 in itertools.permutations(range(len(graph["nodes"])), 2): node1 = graph["nodes"][i1] node2 = graph["nodes"][i2] confidence = (float(len(keyphrase_texts[node1["label"]] & keyphrase_texts[node2["label"]])) / max(len(keyphrase_texts[node1["label"]]), 1)) if confidence >= referral_confidence: graph["edges"].append({ "source": node1["id"], "target": node2["id"], "confidence": confidence }) return graph
python
def keyphrases_graph(keyphrases, texts, referral_confidence=0.6, relevance_threshold=0.25, support_threshold=1, similarity_measure=None, synonimizer=None, language=consts.Language.ENGLISH): """ Constructs the keyphrases relation graph based on the given texts corpus. The graph construction algorithm is based on the analysis of co-occurrences of key phrases in the text corpus. A key phrase is considered to imply another one if that second phrase occurs frequently enough in the same texts as the first one (that frequency is controlled by the referral_confidence). A keyphrase counts as occuring in a text if its matching score for that text ecxeeds some threshold (Mirkin, Chernyak, & Chugunova, 2012). :param keyphrases: list of unicode strings :param texts: dictionary of form {text_name: text} :param referral_confidence: significance level of the graph in [0; 1], 0.6 by default :param relevance_threshold: threshold for the matching score in [0; 1] where a keyphrase starts to be considered as occuring in the corresponding text; the defaul value is 0.25 :param support_threshold: threshold for the support of a node (the number of documents containing the corresponding keyphrase) such that it can be included into the graph :param similarity_measure: Similarity measure to use :param synonimizer: SynonymExtractor object to be used :param language: Language of the text collection / keyphrases :returns: graph dictionary in a the following format: { "nodes": [ { "id": <id>, "label": "keyphrase", "support": <# of documents containing the keyphrase> }, ... ] "edges": [ { "source": "node_id", "target": "node_id", "confidence": <confidence_level> }, ... ] } """ similarity_measure = similarity_measure or relevance.ASTRelevanceMeasure() # Keyphrases table table = keyphrases_table(keyphrases, texts, similarity_measure, synonimizer, language) # Dictionary { "keyphrase" => set(names of texts containing "keyphrase") } keyphrase_texts = {keyphrase: set([text for text in texts if table[keyphrase][text] >= relevance_threshold]) for keyphrase in keyphrases} # Initializing the graph object with nodes graph = { "nodes": [ { "id": i, "label": keyphrase, "support": len(keyphrase_texts[keyphrase]) } for i, keyphrase in enumerate(keyphrases) ], "edges": [], "referral_confidence": referral_confidence, "relevance_threshold": relevance_threshold, "support_threshold": support_threshold } # Removing nodes with small support after we've numbered all nodes graph["nodes"] = [n for n in graph["nodes"] if len(keyphrase_texts[n["label"]]) >= support_threshold] # Creating edges # NOTE(msdubov): permutations(), unlike combinations(), treats (1,2) and (2,1) as different for i1, i2 in itertools.permutations(range(len(graph["nodes"])), 2): node1 = graph["nodes"][i1] node2 = graph["nodes"][i2] confidence = (float(len(keyphrase_texts[node1["label"]] & keyphrase_texts[node2["label"]])) / max(len(keyphrase_texts[node1["label"]]), 1)) if confidence >= referral_confidence: graph["edges"].append({ "source": node1["id"], "target": node2["id"], "confidence": confidence }) return graph
[ "def", "keyphrases_graph", "(", "keyphrases", ",", "texts", ",", "referral_confidence", "=", "0.6", ",", "relevance_threshold", "=", "0.25", ",", "support_threshold", "=", "1", ",", "similarity_measure", "=", "None", ",", "synonimizer", "=", "None", ",", "language", "=", "consts", ".", "Language", ".", "ENGLISH", ")", ":", "similarity_measure", "=", "similarity_measure", "or", "relevance", ".", "ASTRelevanceMeasure", "(", ")", "# Keyphrases table", "table", "=", "keyphrases_table", "(", "keyphrases", ",", "texts", ",", "similarity_measure", ",", "synonimizer", ",", "language", ")", "# Dictionary { \"keyphrase\" => set(names of texts containing \"keyphrase\") }", "keyphrase_texts", "=", "{", "keyphrase", ":", "set", "(", "[", "text", "for", "text", "in", "texts", "if", "table", "[", "keyphrase", "]", "[", "text", "]", ">=", "relevance_threshold", "]", ")", "for", "keyphrase", "in", "keyphrases", "}", "# Initializing the graph object with nodes", "graph", "=", "{", "\"nodes\"", ":", "[", "{", "\"id\"", ":", "i", ",", "\"label\"", ":", "keyphrase", ",", "\"support\"", ":", "len", "(", "keyphrase_texts", "[", "keyphrase", "]", ")", "}", "for", "i", ",", "keyphrase", "in", "enumerate", "(", "keyphrases", ")", "]", ",", "\"edges\"", ":", "[", "]", ",", "\"referral_confidence\"", ":", "referral_confidence", ",", "\"relevance_threshold\"", ":", "relevance_threshold", ",", "\"support_threshold\"", ":", "support_threshold", "}", "# Removing nodes with small support after we've numbered all nodes", "graph", "[", "\"nodes\"", "]", "=", "[", "n", "for", "n", "in", "graph", "[", "\"nodes\"", "]", "if", "len", "(", "keyphrase_texts", "[", "n", "[", "\"label\"", "]", "]", ")", ">=", "support_threshold", "]", "# Creating edges", "# NOTE(msdubov): permutations(), unlike combinations(), treats (1,2) and (2,1) as different", "for", "i1", ",", "i2", "in", "itertools", ".", "permutations", "(", "range", "(", "len", "(", "graph", "[", "\"nodes\"", "]", ")", ")", ",", "2", ")", ":", "node1", "=", "graph", "[", "\"nodes\"", "]", "[", "i1", "]", "node2", "=", "graph", "[", "\"nodes\"", "]", "[", "i2", "]", "confidence", "=", "(", "float", "(", "len", "(", "keyphrase_texts", "[", "node1", "[", "\"label\"", "]", "]", "&", "keyphrase_texts", "[", "node2", "[", "\"label\"", "]", "]", ")", ")", "/", "max", "(", "len", "(", "keyphrase_texts", "[", "node1", "[", "\"label\"", "]", "]", ")", ",", "1", ")", ")", "if", "confidence", ">=", "referral_confidence", ":", "graph", "[", "\"edges\"", "]", ".", "append", "(", "{", "\"source\"", ":", "node1", "[", "\"id\"", "]", ",", "\"target\"", ":", "node2", "[", "\"id\"", "]", ",", "\"confidence\"", ":", "confidence", "}", ")", "return", "graph" ]
Constructs the keyphrases relation graph based on the given texts corpus. The graph construction algorithm is based on the analysis of co-occurrences of key phrases in the text corpus. A key phrase is considered to imply another one if that second phrase occurs frequently enough in the same texts as the first one (that frequency is controlled by the referral_confidence). A keyphrase counts as occuring in a text if its matching score for that text ecxeeds some threshold (Mirkin, Chernyak, & Chugunova, 2012). :param keyphrases: list of unicode strings :param texts: dictionary of form {text_name: text} :param referral_confidence: significance level of the graph in [0; 1], 0.6 by default :param relevance_threshold: threshold for the matching score in [0; 1] where a keyphrase starts to be considered as occuring in the corresponding text; the defaul value is 0.25 :param support_threshold: threshold for the support of a node (the number of documents containing the corresponding keyphrase) such that it can be included into the graph :param similarity_measure: Similarity measure to use :param synonimizer: SynonymExtractor object to be used :param language: Language of the text collection / keyphrases :returns: graph dictionary in a the following format: { "nodes": [ { "id": <id>, "label": "keyphrase", "support": <# of documents containing the keyphrase> }, ... ] "edges": [ { "source": "node_id", "target": "node_id", "confidence": <confidence_level> }, ... ] }
[ "Constructs", "the", "keyphrases", "relation", "graph", "based", "on", "the", "given", "texts", "corpus", "." ]
055ad8d2492c100bbbaa25309ec1074bdf1dfaa5
https://github.com/mikhaildubov/AST-text-analysis/blob/055ad8d2492c100bbbaa25309ec1074bdf1dfaa5/east/applications.py#L59-L149
train
core/uricore
uricore/wkz_internal.py
_decode_unicode
def _decode_unicode(value, charset, errors): """Like the regular decode function but this one raises an `HTTPUnicodeError` if errors is `strict`.""" fallback = None if errors.startswith('fallback:'): fallback = errors[9:] errors = 'strict' try: return value.decode(charset, errors) except UnicodeError, e: if fallback is not None: return value.decode(fallback, 'replace') from werkzeug.exceptions import HTTPUnicodeError raise HTTPUnicodeError(str(e))
python
def _decode_unicode(value, charset, errors): """Like the regular decode function but this one raises an `HTTPUnicodeError` if errors is `strict`.""" fallback = None if errors.startswith('fallback:'): fallback = errors[9:] errors = 'strict' try: return value.decode(charset, errors) except UnicodeError, e: if fallback is not None: return value.decode(fallback, 'replace') from werkzeug.exceptions import HTTPUnicodeError raise HTTPUnicodeError(str(e))
[ "def", "_decode_unicode", "(", "value", ",", "charset", ",", "errors", ")", ":", "fallback", "=", "None", "if", "errors", ".", "startswith", "(", "'fallback:'", ")", ":", "fallback", "=", "errors", "[", "9", ":", "]", "errors", "=", "'strict'", "try", ":", "return", "value", ".", "decode", "(", "charset", ",", "errors", ")", "except", "UnicodeError", ",", "e", ":", "if", "fallback", "is", "not", "None", ":", "return", "value", ".", "decode", "(", "fallback", ",", "'replace'", ")", "from", "werkzeug", ".", "exceptions", "import", "HTTPUnicodeError", "raise", "HTTPUnicodeError", "(", "str", "(", "e", ")", ")" ]
Like the regular decode function but this one raises an `HTTPUnicodeError` if errors is `strict`.
[ "Like", "the", "regular", "decode", "function", "but", "this", "one", "raises", "an", "HTTPUnicodeError", "if", "errors", "is", "strict", "." ]
dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a
https://github.com/core/uricore/blob/dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a/uricore/wkz_internal.py#L12-L25
train
bitesofcode/projexui
projexui/widgets/xiconbutton.py
XIconButton.dropEvent
def dropEvent( self, event ): """ Handles a drop event. """ url = event.mimeData().urls()[0] url_path = nativestring(url.toString()) # download an icon from the web if ( not url_path.startswith('file:') ): filename = os.path.basename(url_path) temp_path = os.path.join(nativestring(QDir.tempPath()), filename) try: urllib.urlretrieve(url_path, temp_path) except IOError: return self.setFilepath(temp_path) else: self.setFilepath(url_path.replace('file://', ''))
python
def dropEvent( self, event ): """ Handles a drop event. """ url = event.mimeData().urls()[0] url_path = nativestring(url.toString()) # download an icon from the web if ( not url_path.startswith('file:') ): filename = os.path.basename(url_path) temp_path = os.path.join(nativestring(QDir.tempPath()), filename) try: urllib.urlretrieve(url_path, temp_path) except IOError: return self.setFilepath(temp_path) else: self.setFilepath(url_path.replace('file://', ''))
[ "def", "dropEvent", "(", "self", ",", "event", ")", ":", "url", "=", "event", ".", "mimeData", "(", ")", ".", "urls", "(", ")", "[", "0", "]", "url_path", "=", "nativestring", "(", "url", ".", "toString", "(", ")", ")", "# download an icon from the web\r", "if", "(", "not", "url_path", ".", "startswith", "(", "'file:'", ")", ")", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "url_path", ")", "temp_path", "=", "os", ".", "path", ".", "join", "(", "nativestring", "(", "QDir", ".", "tempPath", "(", ")", ")", ",", "filename", ")", "try", ":", "urllib", ".", "urlretrieve", "(", "url_path", ",", "temp_path", ")", "except", "IOError", ":", "return", "self", ".", "setFilepath", "(", "temp_path", ")", "else", ":", "self", ".", "setFilepath", "(", "url_path", ".", "replace", "(", "'file://'", ",", "''", ")", ")" ]
Handles a drop event.
[ "Handles", "a", "drop", "event", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xiconbutton.py#L90-L109
train
bitesofcode/projexui
projexui/widgets/xiconbutton.py
XIconButton.pickFilepath
def pickFilepath( self ): """ Picks the image file to use for this icon path. """ filepath = QFileDialog.getOpenFileName( self, 'Select Image File', QDir.currentPath(), self.fileTypes()) if type(filepath) == tuple: filepath = nativestring(filepath[0]) if ( filepath ): self.setFilepath(filepath)
python
def pickFilepath( self ): """ Picks the image file to use for this icon path. """ filepath = QFileDialog.getOpenFileName( self, 'Select Image File', QDir.currentPath(), self.fileTypes()) if type(filepath) == tuple: filepath = nativestring(filepath[0]) if ( filepath ): self.setFilepath(filepath)
[ "def", "pickFilepath", "(", "self", ")", ":", "filepath", "=", "QFileDialog", ".", "getOpenFileName", "(", "self", ",", "'Select Image File'", ",", "QDir", ".", "currentPath", "(", ")", ",", "self", ".", "fileTypes", "(", ")", ")", "if", "type", "(", "filepath", ")", "==", "tuple", ":", "filepath", "=", "nativestring", "(", "filepath", "[", "0", "]", ")", "if", "(", "filepath", ")", ":", "self", ".", "setFilepath", "(", "filepath", ")" ]
Picks the image file to use for this icon path.
[ "Picks", "the", "image", "file", "to", "use", "for", "this", "icon", "path", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xiconbutton.py#L111-L124
train
johnnoone/aioconsul
aioconsul/client/event_endpoint.py
EventEndpoint.fire
async def fire(self, name, payload=None, *, dc=None, node=None, service=None, tag=None): """Fires a new event Parameters: name (str): Event name payload (Payload): Opaque data node (Filter): Regular expression to filter by node name service (Filter): Regular expression to filter by service tag (Filter): Regular expression to filter by service tags dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. Returns: Object: where value is event ID The return body is like:: { "ID": "b54fe110-7af5-cafc-d1fb-afc8ba432b1c", "Name": "deploy", "Payload": None, "NodeFilter": re.compile("node-\d+"), "ServiceFilter": "", "TagFilter": "", "Version": 1, "LTime": 0 } The **ID** field uniquely identifies the newly fired event. """ params = { "dc": dc, "node": extract_pattern(node), "service": extract_pattern(service), "tag": extract_pattern(tag) } payload = encode_value(payload) if payload else None response = await self._api.put( "/v1/event/fire", name, data=payload, params=params, headers={"Content-Type": "application/octet-stream"}) result = format_event(response.body) return result
python
async def fire(self, name, payload=None, *, dc=None, node=None, service=None, tag=None): """Fires a new event Parameters: name (str): Event name payload (Payload): Opaque data node (Filter): Regular expression to filter by node name service (Filter): Regular expression to filter by service tag (Filter): Regular expression to filter by service tags dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. Returns: Object: where value is event ID The return body is like:: { "ID": "b54fe110-7af5-cafc-d1fb-afc8ba432b1c", "Name": "deploy", "Payload": None, "NodeFilter": re.compile("node-\d+"), "ServiceFilter": "", "TagFilter": "", "Version": 1, "LTime": 0 } The **ID** field uniquely identifies the newly fired event. """ params = { "dc": dc, "node": extract_pattern(node), "service": extract_pattern(service), "tag": extract_pattern(tag) } payload = encode_value(payload) if payload else None response = await self._api.put( "/v1/event/fire", name, data=payload, params=params, headers={"Content-Type": "application/octet-stream"}) result = format_event(response.body) return result
[ "async", "def", "fire", "(", "self", ",", "name", ",", "payload", "=", "None", ",", "*", ",", "dc", "=", "None", ",", "node", "=", "None", ",", "service", "=", "None", ",", "tag", "=", "None", ")", ":", "params", "=", "{", "\"dc\"", ":", "dc", ",", "\"node\"", ":", "extract_pattern", "(", "node", ")", ",", "\"service\"", ":", "extract_pattern", "(", "service", ")", ",", "\"tag\"", ":", "extract_pattern", "(", "tag", ")", "}", "payload", "=", "encode_value", "(", "payload", ")", "if", "payload", "else", "None", "response", "=", "await", "self", ".", "_api", ".", "put", "(", "\"/v1/event/fire\"", ",", "name", ",", "data", "=", "payload", ",", "params", "=", "params", ",", "headers", "=", "{", "\"Content-Type\"", ":", "\"application/octet-stream\"", "}", ")", "result", "=", "format_event", "(", "response", ".", "body", ")", "return", "result" ]
Fires a new event Parameters: name (str): Event name payload (Payload): Opaque data node (Filter): Regular expression to filter by node name service (Filter): Regular expression to filter by service tag (Filter): Regular expression to filter by service tags dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. Returns: Object: where value is event ID The return body is like:: { "ID": "b54fe110-7af5-cafc-d1fb-afc8ba432b1c", "Name": "deploy", "Payload": None, "NodeFilter": re.compile("node-\d+"), "ServiceFilter": "", "TagFilter": "", "Version": 1, "LTime": 0 } The **ID** field uniquely identifies the newly fired event.
[ "Fires", "a", "new", "event" ]
02f7a529d7dc2e49bed942111067aa5faf320e90
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/event_endpoint.py#L10-L53
train
johnnoone/aioconsul
aioconsul/client/event_endpoint.py
EventEndpoint.items
async def items(self, name=None, *, watch=None): """Lists the most recent events an agent has seen Parameters: name (str): Filter events by name. watch (Blocking): Do a blocking query Returns: CollectionMeta: where value is a list of events It returns a JSON body like this:: [ { "ID": "b54fe110-7af5-cafc-d1fb-afc8ba432b1c", "Name": "deploy", "Payload": bytes("abcd"), "NodeFilter": re.compile("node-\d+"), "ServiceFilter": "", "TagFilter": "", "Version": 1, "LTime": 19 }, ... ] """ path = "/v1/event/list" params = {"name": name} response = await self._api.get(path, params=params, watch=watch) results = [format_event(data) for data in response.body] return consul(results, meta=extract_meta(response.headers))
python
async def items(self, name=None, *, watch=None): """Lists the most recent events an agent has seen Parameters: name (str): Filter events by name. watch (Blocking): Do a blocking query Returns: CollectionMeta: where value is a list of events It returns a JSON body like this:: [ { "ID": "b54fe110-7af5-cafc-d1fb-afc8ba432b1c", "Name": "deploy", "Payload": bytes("abcd"), "NodeFilter": re.compile("node-\d+"), "ServiceFilter": "", "TagFilter": "", "Version": 1, "LTime": 19 }, ... ] """ path = "/v1/event/list" params = {"name": name} response = await self._api.get(path, params=params, watch=watch) results = [format_event(data) for data in response.body] return consul(results, meta=extract_meta(response.headers))
[ "async", "def", "items", "(", "self", ",", "name", "=", "None", ",", "*", ",", "watch", "=", "None", ")", ":", "path", "=", "\"/v1/event/list\"", "params", "=", "{", "\"name\"", ":", "name", "}", "response", "=", "await", "self", ".", "_api", ".", "get", "(", "path", ",", "params", "=", "params", ",", "watch", "=", "watch", ")", "results", "=", "[", "format_event", "(", "data", ")", "for", "data", "in", "response", ".", "body", "]", "return", "consul", "(", "results", ",", "meta", "=", "extract_meta", "(", "response", ".", "headers", ")", ")" ]
Lists the most recent events an agent has seen Parameters: name (str): Filter events by name. watch (Blocking): Do a blocking query Returns: CollectionMeta: where value is a list of events It returns a JSON body like this:: [ { "ID": "b54fe110-7af5-cafc-d1fb-afc8ba432b1c", "Name": "deploy", "Payload": bytes("abcd"), "NodeFilter": re.compile("node-\d+"), "ServiceFilter": "", "TagFilter": "", "Version": 1, "LTime": 19 }, ... ]
[ "Lists", "the", "most", "recent", "events", "an", "agent", "has", "seen" ]
02f7a529d7dc2e49bed942111067aa5faf320e90
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/event_endpoint.py#L55-L84
train
bitesofcode/projexui
projexui/widgets/xorbtreewidget/xorbrecorditem.py
XOrbRecordItem.updateRecordValues
def updateRecordValues(self): """ Updates the ui to show the latest record values. """ record = self.record() if not record: return # update the record information tree = self.treeWidget() if not isinstance(tree, XTreeWidget): return for column in record.schema().columns(): c = tree.column(column.displayName()) if c == -1: continue elif tree.isColumnHidden(c): continue else: val = record.recordValue(column.name()) self.updateColumnValue(column, val, c) # update the record state information if not record.isRecord(): self.addRecordState(XOrbRecordItem.State.New) elif record.isModified(): self.addRecordState(XOrbRecordItem.State.Modified)
python
def updateRecordValues(self): """ Updates the ui to show the latest record values. """ record = self.record() if not record: return # update the record information tree = self.treeWidget() if not isinstance(tree, XTreeWidget): return for column in record.schema().columns(): c = tree.column(column.displayName()) if c == -1: continue elif tree.isColumnHidden(c): continue else: val = record.recordValue(column.name()) self.updateColumnValue(column, val, c) # update the record state information if not record.isRecord(): self.addRecordState(XOrbRecordItem.State.New) elif record.isModified(): self.addRecordState(XOrbRecordItem.State.Modified)
[ "def", "updateRecordValues", "(", "self", ")", ":", "record", "=", "self", ".", "record", "(", ")", "if", "not", "record", ":", "return", "# update the record information\r", "tree", "=", "self", ".", "treeWidget", "(", ")", "if", "not", "isinstance", "(", "tree", ",", "XTreeWidget", ")", ":", "return", "for", "column", "in", "record", ".", "schema", "(", ")", ".", "columns", "(", ")", ":", "c", "=", "tree", ".", "column", "(", "column", ".", "displayName", "(", ")", ")", "if", "c", "==", "-", "1", ":", "continue", "elif", "tree", ".", "isColumnHidden", "(", "c", ")", ":", "continue", "else", ":", "val", "=", "record", ".", "recordValue", "(", "column", ".", "name", "(", ")", ")", "self", ".", "updateColumnValue", "(", "column", ",", "val", ",", "c", ")", "# update the record state information\r", "if", "not", "record", ".", "isRecord", "(", ")", ":", "self", ".", "addRecordState", "(", "XOrbRecordItem", ".", "State", ".", "New", ")", "elif", "record", ".", "isModified", "(", ")", ":", "self", ".", "addRecordState", "(", "XOrbRecordItem", ".", "State", ".", "Modified", ")" ]
Updates the ui to show the latest record values.
[ "Updates", "the", "ui", "to", "show", "the", "latest", "record", "values", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbtreewidget/xorbrecorditem.py#L288-L318
train
andylockran/heatmiserV3
heatmiserV3/heatmiser.py
CRC16.extract_bits
def extract_bits(self, val): """Extras the 4 bits, XORS the message data, and does table lookups.""" # Step one, extract the Most significant 4 bits of the CRC register thisval = self.high >> 4 # XOR in the Message Data into the extracted bits thisval = thisval ^ val # Shift the CRC Register left 4 bits self.high = (self.high << 4) | (self.low >> 4) self.high = self.high & constants.BYTEMASK # force char self.low = self.low << 4 self.low = self.low & constants.BYTEMASK # force char # Do the table lookups and XOR the result into the CRC tables self.high = self.high ^ self.LookupHigh[thisval] self.high = self.high & constants.BYTEMASK # force char self.low = self.low ^ self.LookupLow[thisval] self.low = self.low & constants.BYTEMASK
python
def extract_bits(self, val): """Extras the 4 bits, XORS the message data, and does table lookups.""" # Step one, extract the Most significant 4 bits of the CRC register thisval = self.high >> 4 # XOR in the Message Data into the extracted bits thisval = thisval ^ val # Shift the CRC Register left 4 bits self.high = (self.high << 4) | (self.low >> 4) self.high = self.high & constants.BYTEMASK # force char self.low = self.low << 4 self.low = self.low & constants.BYTEMASK # force char # Do the table lookups and XOR the result into the CRC tables self.high = self.high ^ self.LookupHigh[thisval] self.high = self.high & constants.BYTEMASK # force char self.low = self.low ^ self.LookupLow[thisval] self.low = self.low & constants.BYTEMASK
[ "def", "extract_bits", "(", "self", ",", "val", ")", ":", "# Step one, extract the Most significant 4 bits of the CRC register\r", "thisval", "=", "self", ".", "high", ">>", "4", "# XOR in the Message Data into the extracted bits\r", "thisval", "=", "thisval", "^", "val", "# Shift the CRC Register left 4 bits\r", "self", ".", "high", "=", "(", "self", ".", "high", "<<", "4", ")", "|", "(", "self", ".", "low", ">>", "4", ")", "self", ".", "high", "=", "self", ".", "high", "&", "constants", ".", "BYTEMASK", "# force char\r", "self", ".", "low", "=", "self", ".", "low", "<<", "4", "self", ".", "low", "=", "self", ".", "low", "&", "constants", ".", "BYTEMASK", "# force char\r", "# Do the table lookups and XOR the result into the CRC tables\r", "self", ".", "high", "=", "self", ".", "high", "^", "self", ".", "LookupHigh", "[", "thisval", "]", "self", ".", "high", "=", "self", ".", "high", "&", "constants", ".", "BYTEMASK", "# force char\r", "self", ".", "low", "=", "self", ".", "low", "^", "self", ".", "LookupLow", "[", "thisval", "]", "self", ".", "low", "=", "self", ".", "low", "&", "constants", ".", "BYTEMASK" ]
Extras the 4 bits, XORS the message data, and does table lookups.
[ "Extras", "the", "4", "bits", "XORS", "the", "message", "data", "and", "does", "table", "lookups", "." ]
bd8638f5fd1f85d16c908020252f58a0cc4f6ac0
https://github.com/andylockran/heatmiserV3/blob/bd8638f5fd1f85d16c908020252f58a0cc4f6ac0/heatmiserV3/heatmiser.py#L37-L52
train
andylockran/heatmiserV3
heatmiserV3/heatmiser.py
CRC16.run
def run(self, message): """Calculates a CRC""" for value in message: self.update(value) return [self.low, self.high]
python
def run(self, message): """Calculates a CRC""" for value in message: self.update(value) return [self.low, self.high]
[ "def", "run", "(", "self", ",", "message", ")", ":", "for", "value", "in", "message", ":", "self", ".", "update", "(", "value", ")", "return", "[", "self", ".", "low", ",", "self", ".", "high", "]" ]
Calculates a CRC
[ "Calculates", "a", "CRC" ]
bd8638f5fd1f85d16c908020252f58a0cc4f6ac0
https://github.com/andylockran/heatmiserV3/blob/bd8638f5fd1f85d16c908020252f58a0cc4f6ac0/heatmiserV3/heatmiser.py#L59-L63
train
andylockran/heatmiserV3
heatmiserV3/heatmiser.py
HeatmiserThermostat._hm_form_message
def _hm_form_message( self, thermostat_id, protocol, source, function, start, payload ): """Forms a message payload, excluding CRC""" if protocol == constants.HMV3_ID: start_low = (start & constants.BYTEMASK) start_high = (start >> 8) & constants.BYTEMASK if function == constants.FUNC_READ: payload_length = 0 length_low = (constants.RW_LENGTH_ALL & constants.BYTEMASK) length_high = (constants.RW_LENGTH_ALL >> 8) & constants.BYTEMASK else: payload_length = len(payload) length_low = (payload_length & constants.BYTEMASK) length_high = (payload_length >> 8) & constants.BYTEMASK msg = [ thermostat_id, 10 + payload_length, source, function, start_low, start_high, length_low, length_high ] if function == constants.FUNC_WRITE: msg = msg + payload type(msg) return msg else: assert 0, "Un-supported protocol found %s" % protocol
python
def _hm_form_message( self, thermostat_id, protocol, source, function, start, payload ): """Forms a message payload, excluding CRC""" if protocol == constants.HMV3_ID: start_low = (start & constants.BYTEMASK) start_high = (start >> 8) & constants.BYTEMASK if function == constants.FUNC_READ: payload_length = 0 length_low = (constants.RW_LENGTH_ALL & constants.BYTEMASK) length_high = (constants.RW_LENGTH_ALL >> 8) & constants.BYTEMASK else: payload_length = len(payload) length_low = (payload_length & constants.BYTEMASK) length_high = (payload_length >> 8) & constants.BYTEMASK msg = [ thermostat_id, 10 + payload_length, source, function, start_low, start_high, length_low, length_high ] if function == constants.FUNC_WRITE: msg = msg + payload type(msg) return msg else: assert 0, "Un-supported protocol found %s" % protocol
[ "def", "_hm_form_message", "(", "self", ",", "thermostat_id", ",", "protocol", ",", "source", ",", "function", ",", "start", ",", "payload", ")", ":", "if", "protocol", "==", "constants", ".", "HMV3_ID", ":", "start_low", "=", "(", "start", "&", "constants", ".", "BYTEMASK", ")", "start_high", "=", "(", "start", ">>", "8", ")", "&", "constants", ".", "BYTEMASK", "if", "function", "==", "constants", ".", "FUNC_READ", ":", "payload_length", "=", "0", "length_low", "=", "(", "constants", ".", "RW_LENGTH_ALL", "&", "constants", ".", "BYTEMASK", ")", "length_high", "=", "(", "constants", ".", "RW_LENGTH_ALL", ">>", "8", ")", "&", "constants", ".", "BYTEMASK", "else", ":", "payload_length", "=", "len", "(", "payload", ")", "length_low", "=", "(", "payload_length", "&", "constants", ".", "BYTEMASK", ")", "length_high", "=", "(", "payload_length", ">>", "8", ")", "&", "constants", ".", "BYTEMASK", "msg", "=", "[", "thermostat_id", ",", "10", "+", "payload_length", ",", "source", ",", "function", ",", "start_low", ",", "start_high", ",", "length_low", ",", "length_high", "]", "if", "function", "==", "constants", ".", "FUNC_WRITE", ":", "msg", "=", "msg", "+", "payload", "type", "(", "msg", ")", "return", "msg", "else", ":", "assert", "0", ",", "\"Un-supported protocol found %s\"", "%", "protocol" ]
Forms a message payload, excluding CRC
[ "Forms", "a", "message", "payload", "excluding", "CRC" ]
bd8638f5fd1f85d16c908020252f58a0cc4f6ac0
https://github.com/andylockran/heatmiserV3/blob/bd8638f5fd1f85d16c908020252f58a0cc4f6ac0/heatmiserV3/heatmiser.py#L80-L117
train
andylockran/heatmiserV3
heatmiserV3/heatmiser.py
HeatmiserThermostat._hm_form_message_crc
def _hm_form_message_crc( self, thermostat_id, protocol, source, function, start, payload ): """Forms a message payload, including CRC""" data = self._hm_form_message( thermostat_id, protocol, source, function, start, payload) crc = CRC16() data = data + crc.run(data) return data
python
def _hm_form_message_crc( self, thermostat_id, protocol, source, function, start, payload ): """Forms a message payload, including CRC""" data = self._hm_form_message( thermostat_id, protocol, source, function, start, payload) crc = CRC16() data = data + crc.run(data) return data
[ "def", "_hm_form_message_crc", "(", "self", ",", "thermostat_id", ",", "protocol", ",", "source", ",", "function", ",", "start", ",", "payload", ")", ":", "data", "=", "self", ".", "_hm_form_message", "(", "thermostat_id", ",", "protocol", ",", "source", ",", "function", ",", "start", ",", "payload", ")", "crc", "=", "CRC16", "(", ")", "data", "=", "data", "+", "crc", ".", "run", "(", "data", ")", "return", "data" ]
Forms a message payload, including CRC
[ "Forms", "a", "message", "payload", "including", "CRC" ]
bd8638f5fd1f85d16c908020252f58a0cc4f6ac0
https://github.com/andylockran/heatmiserV3/blob/bd8638f5fd1f85d16c908020252f58a0cc4f6ac0/heatmiserV3/heatmiser.py#L119-L133
train
andylockran/heatmiserV3
heatmiserV3/heatmiser.py
HeatmiserThermostat._hm_verify_message_crc_uk
def _hm_verify_message_crc_uk( self, thermostat_id, protocol, source, expectedFunction, expectedLength, datal ): """Verifies message appears legal""" # expectedLength only used for read msgs as always 7 for write badresponse = 0 if protocol == constants.HMV3_ID: checksum = datal[len(datal) - 2:] rxmsg = datal[:len(datal) - 2] crc = CRC16() # Initialises the CRC expectedchecksum = crc.run(rxmsg) if expectedchecksum == checksum: logging.info("CRC is correct") else: logging.error("CRC is INCORRECT") serror = "Incorrect CRC" sys.stderr.write(serror) badresponse += 1 dest_addr = datal[0] frame_len_l = datal[1] frame_len_h = datal[2] frame_len = (frame_len_h << 8) | frame_len_l source_addr = datal[3] func_code = datal[4] if (dest_addr != 129 and dest_addr != 160): logging.info("dest_addr is ILLEGAL") serror = "Illegal Dest Addr: %s\n" % (dest_addr) sys.stderr.write(serror) badresponse += 1 if dest_addr != thermostat_id: logging.info("dest_addr is INCORRECT") serror = "Incorrect Dest Addr: %s\n" % (dest_addr) sys.stderr.write(serror) badresponse += 1 if (source_addr < 1 or source_addr > 32): logging.info("source_addr is ILLEGAL") serror = "Illegal Src Addr: %s\n" % (source_addr) sys.stderr.write(serror) badresponse += 1 if source_addr != source: logging.info("source addr is INCORRECT") serror = "Incorrect Src Addr: %s\n" % (source_addr) sys.stderr.write(serror) badresponse += 1 if ( func_code != constants.FUNC_WRITE and func_code != constants.FUNC_READ ): logging.info("Func Code is UNKNWON") serror = "Unknown Func Code: %s\n" % (func_code) sys.stderr.write(serror) badresponse += 1 if func_code != expectedFunction: logging.info("Func Code is UNEXPECTED") serror = "Unexpected Func Code: %s\n" % (func_code) sys.stderr.write(serror) badresponse += 1 if ( func_code == constants.FUNC_WRITE and frame_len != 7 ): # Reply to Write is always 7 long logging.info("response length is INCORRECT") serror = "Incorrect length: %s\n" % (frame_len) sys.stderr.write(serror) badresponse += 1 if len(datal) != frame_len: logging.info("response length MISMATCHES header") serror = "Mismatch length: %s %s\n" % (len(datal), frame_len) sys.stderr.write(serror) badresponse += 1 # if (func_code == constants.FUNC_READ and # expectedLength !=len(datal) ): # # Read response length is wrong # logging.info("response length # not EXPECTED value") # logging.info("Got %s when expecting %s", # len(datal), expectedLength) # logging.info("Data is:\n %s", datal) # s = "Incorrect length: %s\n" % (frame_len) # sys.stderr.write(s) # badresponse += 1 if (badresponse == 0): return True else: return False else: assert 0, "Un-supported protocol found %s" % protocol
python
def _hm_verify_message_crc_uk( self, thermostat_id, protocol, source, expectedFunction, expectedLength, datal ): """Verifies message appears legal""" # expectedLength only used for read msgs as always 7 for write badresponse = 0 if protocol == constants.HMV3_ID: checksum = datal[len(datal) - 2:] rxmsg = datal[:len(datal) - 2] crc = CRC16() # Initialises the CRC expectedchecksum = crc.run(rxmsg) if expectedchecksum == checksum: logging.info("CRC is correct") else: logging.error("CRC is INCORRECT") serror = "Incorrect CRC" sys.stderr.write(serror) badresponse += 1 dest_addr = datal[0] frame_len_l = datal[1] frame_len_h = datal[2] frame_len = (frame_len_h << 8) | frame_len_l source_addr = datal[3] func_code = datal[4] if (dest_addr != 129 and dest_addr != 160): logging.info("dest_addr is ILLEGAL") serror = "Illegal Dest Addr: %s\n" % (dest_addr) sys.stderr.write(serror) badresponse += 1 if dest_addr != thermostat_id: logging.info("dest_addr is INCORRECT") serror = "Incorrect Dest Addr: %s\n" % (dest_addr) sys.stderr.write(serror) badresponse += 1 if (source_addr < 1 or source_addr > 32): logging.info("source_addr is ILLEGAL") serror = "Illegal Src Addr: %s\n" % (source_addr) sys.stderr.write(serror) badresponse += 1 if source_addr != source: logging.info("source addr is INCORRECT") serror = "Incorrect Src Addr: %s\n" % (source_addr) sys.stderr.write(serror) badresponse += 1 if ( func_code != constants.FUNC_WRITE and func_code != constants.FUNC_READ ): logging.info("Func Code is UNKNWON") serror = "Unknown Func Code: %s\n" % (func_code) sys.stderr.write(serror) badresponse += 1 if func_code != expectedFunction: logging.info("Func Code is UNEXPECTED") serror = "Unexpected Func Code: %s\n" % (func_code) sys.stderr.write(serror) badresponse += 1 if ( func_code == constants.FUNC_WRITE and frame_len != 7 ): # Reply to Write is always 7 long logging.info("response length is INCORRECT") serror = "Incorrect length: %s\n" % (frame_len) sys.stderr.write(serror) badresponse += 1 if len(datal) != frame_len: logging.info("response length MISMATCHES header") serror = "Mismatch length: %s %s\n" % (len(datal), frame_len) sys.stderr.write(serror) badresponse += 1 # if (func_code == constants.FUNC_READ and # expectedLength !=len(datal) ): # # Read response length is wrong # logging.info("response length # not EXPECTED value") # logging.info("Got %s when expecting %s", # len(datal), expectedLength) # logging.info("Data is:\n %s", datal) # s = "Incorrect length: %s\n" % (frame_len) # sys.stderr.write(s) # badresponse += 1 if (badresponse == 0): return True else: return False else: assert 0, "Un-supported protocol found %s" % protocol
[ "def", "_hm_verify_message_crc_uk", "(", "self", ",", "thermostat_id", ",", "protocol", ",", "source", ",", "expectedFunction", ",", "expectedLength", ",", "datal", ")", ":", "# expectedLength only used for read msgs as always 7 for write\r", "badresponse", "=", "0", "if", "protocol", "==", "constants", ".", "HMV3_ID", ":", "checksum", "=", "datal", "[", "len", "(", "datal", ")", "-", "2", ":", "]", "rxmsg", "=", "datal", "[", ":", "len", "(", "datal", ")", "-", "2", "]", "crc", "=", "CRC16", "(", ")", "# Initialises the CRC\r", "expectedchecksum", "=", "crc", ".", "run", "(", "rxmsg", ")", "if", "expectedchecksum", "==", "checksum", ":", "logging", ".", "info", "(", "\"CRC is correct\"", ")", "else", ":", "logging", ".", "error", "(", "\"CRC is INCORRECT\"", ")", "serror", "=", "\"Incorrect CRC\"", "sys", ".", "stderr", ".", "write", "(", "serror", ")", "badresponse", "+=", "1", "dest_addr", "=", "datal", "[", "0", "]", "frame_len_l", "=", "datal", "[", "1", "]", "frame_len_h", "=", "datal", "[", "2", "]", "frame_len", "=", "(", "frame_len_h", "<<", "8", ")", "|", "frame_len_l", "source_addr", "=", "datal", "[", "3", "]", "func_code", "=", "datal", "[", "4", "]", "if", "(", "dest_addr", "!=", "129", "and", "dest_addr", "!=", "160", ")", ":", "logging", ".", "info", "(", "\"dest_addr is ILLEGAL\"", ")", "serror", "=", "\"Illegal Dest Addr: %s\\n\"", "%", "(", "dest_addr", ")", "sys", ".", "stderr", ".", "write", "(", "serror", ")", "badresponse", "+=", "1", "if", "dest_addr", "!=", "thermostat_id", ":", "logging", ".", "info", "(", "\"dest_addr is INCORRECT\"", ")", "serror", "=", "\"Incorrect Dest Addr: %s\\n\"", "%", "(", "dest_addr", ")", "sys", ".", "stderr", ".", "write", "(", "serror", ")", "badresponse", "+=", "1", "if", "(", "source_addr", "<", "1", "or", "source_addr", ">", "32", ")", ":", "logging", ".", "info", "(", "\"source_addr is ILLEGAL\"", ")", "serror", "=", "\"Illegal Src Addr: %s\\n\"", "%", "(", "source_addr", ")", "sys", ".", "stderr", ".", "write", "(", "serror", ")", "badresponse", "+=", "1", "if", "source_addr", "!=", "source", ":", "logging", ".", "info", "(", "\"source addr is INCORRECT\"", ")", "serror", "=", "\"Incorrect Src Addr: %s\\n\"", "%", "(", "source_addr", ")", "sys", ".", "stderr", ".", "write", "(", "serror", ")", "badresponse", "+=", "1", "if", "(", "func_code", "!=", "constants", ".", "FUNC_WRITE", "and", "func_code", "!=", "constants", ".", "FUNC_READ", ")", ":", "logging", ".", "info", "(", "\"Func Code is UNKNWON\"", ")", "serror", "=", "\"Unknown Func Code: %s\\n\"", "%", "(", "func_code", ")", "sys", ".", "stderr", ".", "write", "(", "serror", ")", "badresponse", "+=", "1", "if", "func_code", "!=", "expectedFunction", ":", "logging", ".", "info", "(", "\"Func Code is UNEXPECTED\"", ")", "serror", "=", "\"Unexpected Func Code: %s\\n\"", "%", "(", "func_code", ")", "sys", ".", "stderr", ".", "write", "(", "serror", ")", "badresponse", "+=", "1", "if", "(", "func_code", "==", "constants", ".", "FUNC_WRITE", "and", "frame_len", "!=", "7", ")", ":", "# Reply to Write is always 7 long\r", "logging", ".", "info", "(", "\"response length is INCORRECT\"", ")", "serror", "=", "\"Incorrect length: %s\\n\"", "%", "(", "frame_len", ")", "sys", ".", "stderr", ".", "write", "(", "serror", ")", "badresponse", "+=", "1", "if", "len", "(", "datal", ")", "!=", "frame_len", ":", "logging", ".", "info", "(", "\"response length MISMATCHES header\"", ")", "serror", "=", "\"Mismatch length: %s %s\\n\"", "%", "(", "len", "(", "datal", ")", ",", "frame_len", ")", "sys", ".", "stderr", ".", "write", "(", "serror", ")", "badresponse", "+=", "1", "# if (func_code == constants.FUNC_READ and\r", "# expectedLength !=len(datal) ):\r", "# # Read response length is wrong\r", "# logging.info(\"response length\r", "# not EXPECTED value\")\r", "# logging.info(\"Got %s when expecting %s\",\r", "# len(datal), expectedLength)\r", "# logging.info(\"Data is:\\n %s\", datal)\r", "# s = \"Incorrect length: %s\\n\" % (frame_len)\r", "# sys.stderr.write(s)\r", "# badresponse += 1\r", "if", "(", "badresponse", "==", "0", ")", ":", "return", "True", "else", ":", "return", "False", "else", ":", "assert", "0", ",", "\"Un-supported protocol found %s\"", "%", "protocol" ]
Verifies message appears legal
[ "Verifies", "message", "appears", "legal" ]
bd8638f5fd1f85d16c908020252f58a0cc4f6ac0
https://github.com/andylockran/heatmiserV3/blob/bd8638f5fd1f85d16c908020252f58a0cc4f6ac0/heatmiserV3/heatmiser.py#L135-L238
train
andylockran/heatmiserV3
heatmiserV3/heatmiser.py
HeatmiserThermostat._hm_send_msg
def _hm_send_msg(self, message): """This is the only interface to the serial connection.""" try: serial_message = message self.conn.write(serial_message) # Write a string except serial.SerialTimeoutException: serror = "Write timeout error: \n" sys.stderr.write(serror) # Now wait for reply byteread = self.conn.read(159) # NB max return is 75 in 5/2 mode or 159 in 7day mode datal = list(byteread) return datal
python
def _hm_send_msg(self, message): """This is the only interface to the serial connection.""" try: serial_message = message self.conn.write(serial_message) # Write a string except serial.SerialTimeoutException: serror = "Write timeout error: \n" sys.stderr.write(serror) # Now wait for reply byteread = self.conn.read(159) # NB max return is 75 in 5/2 mode or 159 in 7day mode datal = list(byteread) return datal
[ "def", "_hm_send_msg", "(", "self", ",", "message", ")", ":", "try", ":", "serial_message", "=", "message", "self", ".", "conn", ".", "write", "(", "serial_message", ")", "# Write a string\r", "except", "serial", ".", "SerialTimeoutException", ":", "serror", "=", "\"Write timeout error: \\n\"", "sys", ".", "stderr", ".", "write", "(", "serror", ")", "# Now wait for reply\r", "byteread", "=", "self", ".", "conn", ".", "read", "(", "159", ")", "# NB max return is 75 in 5/2 mode or 159 in 7day mode\r", "datal", "=", "list", "(", "byteread", ")", "return", "datal" ]
This is the only interface to the serial connection.
[ "This", "is", "the", "only", "interface", "to", "the", "serial", "connection", "." ]
bd8638f5fd1f85d16c908020252f58a0cc4f6ac0
https://github.com/andylockran/heatmiserV3/blob/bd8638f5fd1f85d16c908020252f58a0cc4f6ac0/heatmiserV3/heatmiser.py#L240-L252
train
andylockran/heatmiserV3
heatmiserV3/heatmiser.py
HeatmiserThermostat._hm_read_address
def _hm_read_address(self): """Reads from the DCB and maps to yaml config file.""" response = self._hm_send_address(self.address, 0, 0, 0) lookup = self.config['keys'] offset = self.config['offset'] keydata = {} for i in lookup: try: kdata = lookup[i] ddata = response[i + offset] keydata[i] = { 'label': kdata, 'value': ddata } except IndexError: logging.info("Finished processing at %d", i) return keydata
python
def _hm_read_address(self): """Reads from the DCB and maps to yaml config file.""" response = self._hm_send_address(self.address, 0, 0, 0) lookup = self.config['keys'] offset = self.config['offset'] keydata = {} for i in lookup: try: kdata = lookup[i] ddata = response[i + offset] keydata[i] = { 'label': kdata, 'value': ddata } except IndexError: logging.info("Finished processing at %d", i) return keydata
[ "def", "_hm_read_address", "(", "self", ")", ":", "response", "=", "self", ".", "_hm_send_address", "(", "self", ".", "address", ",", "0", ",", "0", ",", "0", ")", "lookup", "=", "self", ".", "config", "[", "'keys'", "]", "offset", "=", "self", ".", "config", "[", "'offset'", "]", "keydata", "=", "{", "}", "for", "i", "in", "lookup", ":", "try", ":", "kdata", "=", "lookup", "[", "i", "]", "ddata", "=", "response", "[", "i", "+", "offset", "]", "keydata", "[", "i", "]", "=", "{", "'label'", ":", "kdata", ",", "'value'", ":", "ddata", "}", "except", "IndexError", ":", "logging", ".", "info", "(", "\"Finished processing at %d\"", ",", "i", ")", "return", "keydata" ]
Reads from the DCB and maps to yaml config file.
[ "Reads", "from", "the", "DCB", "and", "maps", "to", "yaml", "config", "file", "." ]
bd8638f5fd1f85d16c908020252f58a0cc4f6ac0
https://github.com/andylockran/heatmiserV3/blob/bd8638f5fd1f85d16c908020252f58a0cc4f6ac0/heatmiserV3/heatmiser.py#L284-L300
train
andylockran/heatmiserV3
heatmiserV3/heatmiser.py
HeatmiserThermostat.read_dcb
def read_dcb(self): """ Returns the full DCB, only use for non read-only operations Use self.dcb for read-only operations. """ logging.info("Getting latest data from DCB....") self.dcb = self._hm_read_address() return self.dcb
python
def read_dcb(self): """ Returns the full DCB, only use for non read-only operations Use self.dcb for read-only operations. """ logging.info("Getting latest data from DCB....") self.dcb = self._hm_read_address() return self.dcb
[ "def", "read_dcb", "(", "self", ")", ":", "logging", ".", "info", "(", "\"Getting latest data from DCB....\"", ")", "self", ".", "dcb", "=", "self", ".", "_hm_read_address", "(", ")", "return", "self", ".", "dcb" ]
Returns the full DCB, only use for non read-only operations Use self.dcb for read-only operations.
[ "Returns", "the", "full", "DCB", "only", "use", "for", "non", "read", "-", "only", "operations", "Use", "self", ".", "dcb", "for", "read", "-", "only", "operations", "." ]
bd8638f5fd1f85d16c908020252f58a0cc4f6ac0
https://github.com/andylockran/heatmiserV3/blob/bd8638f5fd1f85d16c908020252f58a0cc4f6ac0/heatmiserV3/heatmiser.py#L302-L309
train
andylockran/heatmiserV3
heatmiserV3/heatmiser.py
HeatmiserThermostat.set_target_temp
def set_target_temp(self, temperature): """ Sets the target temperature, to the requested int """ if 35 < temperature < 5: logging.info("Refusing to set temp outside of allowed range") return False else: self._hm_send_address(self.address, 18, temperature, 1) return True
python
def set_target_temp(self, temperature): """ Sets the target temperature, to the requested int """ if 35 < temperature < 5: logging.info("Refusing to set temp outside of allowed range") return False else: self._hm_send_address(self.address, 18, temperature, 1) return True
[ "def", "set_target_temp", "(", "self", ",", "temperature", ")", ":", "if", "35", "<", "temperature", "<", "5", ":", "logging", ".", "info", "(", "\"Refusing to set temp outside of allowed range\"", ")", "return", "False", "else", ":", "self", ".", "_hm_send_address", "(", "self", ".", "address", ",", "18", ",", "temperature", ",", "1", ")", "return", "True" ]
Sets the target temperature, to the requested int
[ "Sets", "the", "target", "temperature", "to", "the", "requested", "int" ]
bd8638f5fd1f85d16c908020252f58a0cc4f6ac0
https://github.com/andylockran/heatmiserV3/blob/bd8638f5fd1f85d16c908020252f58a0cc4f6ac0/heatmiserV3/heatmiser.py#L384-L393
train
johnnoone/aioconsul
aioconsul/client/health_endpoint.py
HealthEndpoint.node
async def node(self, node, *, dc=None, watch=None, consistency=None): """Returns the health info of a node. Parameters: node (ObjectID): Node ID dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. watch (Blocking): Do a blocking query consistency (Consistency): Force consistency Returns: CollectionMeta: where value is a list of checks returns the checks specific of a node. It returns a body like this:: [ { "Node": "foobar", "CheckID": "serfHealth", "Name": "Serf Health Status", "Status": "passing", "Notes": "", "Output": "", "ServiceID": "", "ServiceName": "" }, { "Node": "foobar", "CheckID": "service:redis", "Name": "Service 'redis' check", "Status": "passing", "Notes": "", "Output": "", "ServiceID": "redis", "ServiceName": "redis" } ] In this case, we can see there is a system level check (that is, a check with no associated ``ServiceID``) as well as a service check for Redis. The "serfHealth" check is special in that it is automatically present on every node. When a node joins the Consul cluster, it is part of a distributed failure detection provided by Serf. If a node fails, it is detected and the status is automatically changed to ``critical``. """ node_id = extract_attr(node, keys=["Node", "ID"]) params = {"dc": dc} response = await self._api.get("/v1/health/node", node_id, params=params, watch=watch, consistency=consistency) return consul(response)
python
async def node(self, node, *, dc=None, watch=None, consistency=None): """Returns the health info of a node. Parameters: node (ObjectID): Node ID dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. watch (Blocking): Do a blocking query consistency (Consistency): Force consistency Returns: CollectionMeta: where value is a list of checks returns the checks specific of a node. It returns a body like this:: [ { "Node": "foobar", "CheckID": "serfHealth", "Name": "Serf Health Status", "Status": "passing", "Notes": "", "Output": "", "ServiceID": "", "ServiceName": "" }, { "Node": "foobar", "CheckID": "service:redis", "Name": "Service 'redis' check", "Status": "passing", "Notes": "", "Output": "", "ServiceID": "redis", "ServiceName": "redis" } ] In this case, we can see there is a system level check (that is, a check with no associated ``ServiceID``) as well as a service check for Redis. The "serfHealth" check is special in that it is automatically present on every node. When a node joins the Consul cluster, it is part of a distributed failure detection provided by Serf. If a node fails, it is detected and the status is automatically changed to ``critical``. """ node_id = extract_attr(node, keys=["Node", "ID"]) params = {"dc": dc} response = await self._api.get("/v1/health/node", node_id, params=params, watch=watch, consistency=consistency) return consul(response)
[ "async", "def", "node", "(", "self", ",", "node", ",", "*", ",", "dc", "=", "None", ",", "watch", "=", "None", ",", "consistency", "=", "None", ")", ":", "node_id", "=", "extract_attr", "(", "node", ",", "keys", "=", "[", "\"Node\"", ",", "\"ID\"", "]", ")", "params", "=", "{", "\"dc\"", ":", "dc", "}", "response", "=", "await", "self", ".", "_api", ".", "get", "(", "\"/v1/health/node\"", ",", "node_id", ",", "params", "=", "params", ",", "watch", "=", "watch", ",", "consistency", "=", "consistency", ")", "return", "consul", "(", "response", ")" ]
Returns the health info of a node. Parameters: node (ObjectID): Node ID dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. watch (Blocking): Do a blocking query consistency (Consistency): Force consistency Returns: CollectionMeta: where value is a list of checks returns the checks specific of a node. It returns a body like this:: [ { "Node": "foobar", "CheckID": "serfHealth", "Name": "Serf Health Status", "Status": "passing", "Notes": "", "Output": "", "ServiceID": "", "ServiceName": "" }, { "Node": "foobar", "CheckID": "service:redis", "Name": "Service 'redis' check", "Status": "passing", "Notes": "", "Output": "", "ServiceID": "redis", "ServiceName": "redis" } ] In this case, we can see there is a system level check (that is, a check with no associated ``ServiceID``) as well as a service check for Redis. The "serfHealth" check is special in that it is automatically present on every node. When a node joins the Consul cluster, it is part of a distributed failure detection provided by Serf. If a node fails, it is detected and the status is automatically changed to ``critical``.
[ "Returns", "the", "health", "info", "of", "a", "node", "." ]
02f7a529d7dc2e49bed942111067aa5faf320e90
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/health_endpoint.py#L16-L69
train
johnnoone/aioconsul
aioconsul/client/health_endpoint.py
HealthEndpoint.checks
async def checks(self, service, *, dc=None, near=None, watch=None, consistency=None): """Returns the checks of a service Parameters: dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. near (str): With a node name will sort the node list in ascending order based on the estimated round trip time from that node watch (Blocking): Do a blocking query consistency (Consistency): Force consistency Returns: CollectionMeta: where value is a list of checks """ service_id = extract_attr(service, keys=["ServiceID", "ID"]) params = {"dc": dc, "near": near} response = await self._api.get("/v1/health/checks", service_id, params=params, watch=watch, consistency=consistency) return consul(response)
python
async def checks(self, service, *, dc=None, near=None, watch=None, consistency=None): """Returns the checks of a service Parameters: dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. near (str): With a node name will sort the node list in ascending order based on the estimated round trip time from that node watch (Blocking): Do a blocking query consistency (Consistency): Force consistency Returns: CollectionMeta: where value is a list of checks """ service_id = extract_attr(service, keys=["ServiceID", "ID"]) params = {"dc": dc, "near": near} response = await self._api.get("/v1/health/checks", service_id, params=params, watch=watch, consistency=consistency) return consul(response)
[ "async", "def", "checks", "(", "self", ",", "service", ",", "*", ",", "dc", "=", "None", ",", "near", "=", "None", ",", "watch", "=", "None", ",", "consistency", "=", "None", ")", ":", "service_id", "=", "extract_attr", "(", "service", ",", "keys", "=", "[", "\"ServiceID\"", ",", "\"ID\"", "]", ")", "params", "=", "{", "\"dc\"", ":", "dc", ",", "\"near\"", ":", "near", "}", "response", "=", "await", "self", ".", "_api", ".", "get", "(", "\"/v1/health/checks\"", ",", "service_id", ",", "params", "=", "params", ",", "watch", "=", "watch", ",", "consistency", "=", "consistency", ")", "return", "consul", "(", "response", ")" ]
Returns the checks of a service Parameters: dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. near (str): With a node name will sort the node list in ascending order based on the estimated round trip time from that node watch (Blocking): Do a blocking query consistency (Consistency): Force consistency Returns: CollectionMeta: where value is a list of checks
[ "Returns", "the", "checks", "of", "a", "service" ]
02f7a529d7dc2e49bed942111067aa5faf320e90
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/health_endpoint.py#L71-L92
train
core/uricore
uricore/wkz_wsgi.py
make_limited_stream
def make_limited_stream(stream, limit): """Makes a stream limited.""" if not isinstance(stream, LimitedStream): if limit is None: raise TypeError('stream not limited and no limit provided.') stream = LimitedStream(stream, limit) return stream
python
def make_limited_stream(stream, limit): """Makes a stream limited.""" if not isinstance(stream, LimitedStream): if limit is None: raise TypeError('stream not limited and no limit provided.') stream = LimitedStream(stream, limit) return stream
[ "def", "make_limited_stream", "(", "stream", ",", "limit", ")", ":", "if", "not", "isinstance", "(", "stream", ",", "LimitedStream", ")", ":", "if", "limit", "is", "None", ":", "raise", "TypeError", "(", "'stream not limited and no limit provided.'", ")", "stream", "=", "LimitedStream", "(", "stream", ",", "limit", ")", "return", "stream" ]
Makes a stream limited.
[ "Makes", "a", "stream", "limited", "." ]
dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a
https://github.com/core/uricore/blob/dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a/uricore/wkz_wsgi.py#L172-L178
train
core/uricore
uricore/wkz_wsgi.py
LimitedStream.exhaust
def exhaust(self, chunk_size=1024 * 16): """Exhaust the stream. This consumes all the data left until the limit is reached. :param chunk_size: the size for a chunk. It will read the chunk until the stream is exhausted and throw away the results. """ to_read = self.limit - self._pos chunk = chunk_size while to_read > 0: chunk = min(to_read, chunk) self.read(chunk) to_read -= chunk
python
def exhaust(self, chunk_size=1024 * 16): """Exhaust the stream. This consumes all the data left until the limit is reached. :param chunk_size: the size for a chunk. It will read the chunk until the stream is exhausted and throw away the results. """ to_read = self.limit - self._pos chunk = chunk_size while to_read > 0: chunk = min(to_read, chunk) self.read(chunk) to_read -= chunk
[ "def", "exhaust", "(", "self", ",", "chunk_size", "=", "1024", "*", "16", ")", ":", "to_read", "=", "self", ".", "limit", "-", "self", ".", "_pos", "chunk", "=", "chunk_size", "while", "to_read", ">", "0", ":", "chunk", "=", "min", "(", "to_read", ",", "chunk", ")", "self", ".", "read", "(", "chunk", ")", "to_read", "-=", "chunk" ]
Exhaust the stream. This consumes all the data left until the limit is reached. :param chunk_size: the size for a chunk. It will read the chunk until the stream is exhausted and throw away the results.
[ "Exhaust", "the", "stream", ".", "This", "consumes", "all", "the", "data", "left", "until", "the", "limit", "is", "reached", "." ]
dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a
https://github.com/core/uricore/blob/dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a/uricore/wkz_wsgi.py#L85-L98
train
core/uricore
uricore/wkz_wsgi.py
LimitedStream.read
def read(self, size=None): """Read `size` bytes or if size is not provided everything is read. :param size: the number of bytes read. """ if self._pos >= self.limit: return self.on_exhausted() if size is None or size == -1: # -1 is for consistence with file size = self.limit to_read = min(self.limit - self._pos, size) try: read = self._read(to_read) except (IOError, ValueError): return self.on_disconnect() if to_read and len(read) != to_read: return self.on_disconnect() self._pos += len(read) return read
python
def read(self, size=None): """Read `size` bytes or if size is not provided everything is read. :param size: the number of bytes read. """ if self._pos >= self.limit: return self.on_exhausted() if size is None or size == -1: # -1 is for consistence with file size = self.limit to_read = min(self.limit - self._pos, size) try: read = self._read(to_read) except (IOError, ValueError): return self.on_disconnect() if to_read and len(read) != to_read: return self.on_disconnect() self._pos += len(read) return read
[ "def", "read", "(", "self", ",", "size", "=", "None", ")", ":", "if", "self", ".", "_pos", ">=", "self", ".", "limit", ":", "return", "self", ".", "on_exhausted", "(", ")", "if", "size", "is", "None", "or", "size", "==", "-", "1", ":", "# -1 is for consistence with file", "size", "=", "self", ".", "limit", "to_read", "=", "min", "(", "self", ".", "limit", "-", "self", ".", "_pos", ",", "size", ")", "try", ":", "read", "=", "self", ".", "_read", "(", "to_read", ")", "except", "(", "IOError", ",", "ValueError", ")", ":", "return", "self", ".", "on_disconnect", "(", ")", "if", "to_read", "and", "len", "(", "read", ")", "!=", "to_read", ":", "return", "self", ".", "on_disconnect", "(", ")", "self", ".", "_pos", "+=", "len", "(", "read", ")", "return", "read" ]
Read `size` bytes or if size is not provided everything is read. :param size: the number of bytes read.
[ "Read", "size", "bytes", "or", "if", "size", "is", "not", "provided", "everything", "is", "read", "." ]
dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a
https://github.com/core/uricore/blob/dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a/uricore/wkz_wsgi.py#L100-L117
train
core/uricore
uricore/wkz_wsgi.py
LimitedStream.readline
def readline(self, size=None): """Reads one line from the stream.""" if self._pos >= self.limit: return self.on_exhausted() if size is None: size = self.limit - self._pos else: size = min(size, self.limit - self._pos) try: line = self._readline(size) except (ValueError, IOError): return self.on_disconnect() if size and not line: return self.on_disconnect() self._pos += len(line) return line
python
def readline(self, size=None): """Reads one line from the stream.""" if self._pos >= self.limit: return self.on_exhausted() if size is None: size = self.limit - self._pos else: size = min(size, self.limit - self._pos) try: line = self._readline(size) except (ValueError, IOError): return self.on_disconnect() if size and not line: return self.on_disconnect() self._pos += len(line) return line
[ "def", "readline", "(", "self", ",", "size", "=", "None", ")", ":", "if", "self", ".", "_pos", ">=", "self", ".", "limit", ":", "return", "self", ".", "on_exhausted", "(", ")", "if", "size", "is", "None", ":", "size", "=", "self", ".", "limit", "-", "self", ".", "_pos", "else", ":", "size", "=", "min", "(", "size", ",", "self", ".", "limit", "-", "self", ".", "_pos", ")", "try", ":", "line", "=", "self", ".", "_readline", "(", "size", ")", "except", "(", "ValueError", ",", "IOError", ")", ":", "return", "self", ".", "on_disconnect", "(", ")", "if", "size", "and", "not", "line", ":", "return", "self", ".", "on_disconnect", "(", ")", "self", ".", "_pos", "+=", "len", "(", "line", ")", "return", "line" ]
Reads one line from the stream.
[ "Reads", "one", "line", "from", "the", "stream", "." ]
dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a
https://github.com/core/uricore/blob/dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a/uricore/wkz_wsgi.py#L119-L134
train
bitesofcode/projexui
projexui/widgets/xcalendarwidget/xcalendaritem.py
XCalendarItem.rebuild
def rebuild( self ): """ Rebuilds the current item in the scene. """ self.markForRebuild(False) self._textData = [] if ( self.rebuildBlocked() ): return scene = self.scene() if ( not scene ): return # rebuild a month look if ( scene.currentMode() == scene.Mode.Month ): self.rebuildMonth() elif ( scene.currentMode() in (scene.Mode.Day, scene.Mode.Week) ): self.rebuildDay()
python
def rebuild( self ): """ Rebuilds the current item in the scene. """ self.markForRebuild(False) self._textData = [] if ( self.rebuildBlocked() ): return scene = self.scene() if ( not scene ): return # rebuild a month look if ( scene.currentMode() == scene.Mode.Month ): self.rebuildMonth() elif ( scene.currentMode() in (scene.Mode.Day, scene.Mode.Week) ): self.rebuildDay()
[ "def", "rebuild", "(", "self", ")", ":", "self", ".", "markForRebuild", "(", "False", ")", "self", ".", "_textData", "=", "[", "]", "if", "(", "self", ".", "rebuildBlocked", "(", ")", ")", ":", "return", "scene", "=", "self", ".", "scene", "(", ")", "if", "(", "not", "scene", ")", ":", "return", "# rebuild a month look\r", "if", "(", "scene", ".", "currentMode", "(", ")", "==", "scene", ".", "Mode", ".", "Month", ")", ":", "self", ".", "rebuildMonth", "(", ")", "elif", "(", "scene", ".", "currentMode", "(", ")", "in", "(", "scene", ".", "Mode", ".", "Day", ",", "scene", ".", "Mode", ".", "Week", ")", ")", ":", "self", ".", "rebuildDay", "(", ")" ]
Rebuilds the current item in the scene.
[ "Rebuilds", "the", "current", "item", "in", "the", "scene", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xcalendarwidget/xcalendaritem.py#L240-L259
train
bitesofcode/projexui
projexui/widgets/xcalendarwidget/xcalendaritem.py
XCalendarItem.rebuildDay
def rebuildDay( self ): """ Rebuilds the current item in day mode. """ scene = self.scene() if ( not scene ): return # calculate the base information start_date = self.dateStart() end_date = self.dateEnd() min_date = scene.minimumDate() max_date = scene.maximumDate() # make sure our item is visible if ( not (min_date <= end_date and start_date <= max_date)): self.hide() self.setPath(QPainterPath()) return # make sure we have valid range information if ( start_date < min_date ): start_date = min_date start_inrange = False else: start_inrange = True if ( max_date < end_date ): end_date = max_date end_inrange = False else: end_inrange = True # rebuild the path path = QPainterPath() self.setPos(0, 0) pad = 2 offset = 18 height = 16 # rebuild a timed item if ( not self.isAllDay() ): start_dtime = QDateTime(self.dateStart(), self.timeStart()) end_dtime = QDateTime(self.dateStart(), self.timeEnd().addSecs(-30*60)) start_rect = scene.dateTimeRect(start_dtime) end_rect = scene.dateTimeRect(end_dtime) left = start_rect.left() + pad top = start_rect.top() + pad right = start_rect.right() - pad bottom = end_rect.bottom() - pad path.moveTo(left, top) path.lineTo(right, top) path.lineTo(right, bottom) path.lineTo(left, bottom) path.lineTo(left, top) data = (left + 6, top + 6, right - left - 12, bottom - top - 12, Qt.AlignTop | Qt.AlignLeft, '%s - %s\n(%s)' % (self.timeStart().toString('h:mmap')[:-1], self.timeEnd().toString('h:mmap'), self.title())) self._textData.append(data) self.setPath(path) self.show()
python
def rebuildDay( self ): """ Rebuilds the current item in day mode. """ scene = self.scene() if ( not scene ): return # calculate the base information start_date = self.dateStart() end_date = self.dateEnd() min_date = scene.minimumDate() max_date = scene.maximumDate() # make sure our item is visible if ( not (min_date <= end_date and start_date <= max_date)): self.hide() self.setPath(QPainterPath()) return # make sure we have valid range information if ( start_date < min_date ): start_date = min_date start_inrange = False else: start_inrange = True if ( max_date < end_date ): end_date = max_date end_inrange = False else: end_inrange = True # rebuild the path path = QPainterPath() self.setPos(0, 0) pad = 2 offset = 18 height = 16 # rebuild a timed item if ( not self.isAllDay() ): start_dtime = QDateTime(self.dateStart(), self.timeStart()) end_dtime = QDateTime(self.dateStart(), self.timeEnd().addSecs(-30*60)) start_rect = scene.dateTimeRect(start_dtime) end_rect = scene.dateTimeRect(end_dtime) left = start_rect.left() + pad top = start_rect.top() + pad right = start_rect.right() - pad bottom = end_rect.bottom() - pad path.moveTo(left, top) path.lineTo(right, top) path.lineTo(right, bottom) path.lineTo(left, bottom) path.lineTo(left, top) data = (left + 6, top + 6, right - left - 12, bottom - top - 12, Qt.AlignTop | Qt.AlignLeft, '%s - %s\n(%s)' % (self.timeStart().toString('h:mmap')[:-1], self.timeEnd().toString('h:mmap'), self.title())) self._textData.append(data) self.setPath(path) self.show()
[ "def", "rebuildDay", "(", "self", ")", ":", "scene", "=", "self", ".", "scene", "(", ")", "if", "(", "not", "scene", ")", ":", "return", "# calculate the base information\r", "start_date", "=", "self", ".", "dateStart", "(", ")", "end_date", "=", "self", ".", "dateEnd", "(", ")", "min_date", "=", "scene", ".", "minimumDate", "(", ")", "max_date", "=", "scene", ".", "maximumDate", "(", ")", "# make sure our item is visible\r", "if", "(", "not", "(", "min_date", "<=", "end_date", "and", "start_date", "<=", "max_date", ")", ")", ":", "self", ".", "hide", "(", ")", "self", ".", "setPath", "(", "QPainterPath", "(", ")", ")", "return", "# make sure we have valid range information\r", "if", "(", "start_date", "<", "min_date", ")", ":", "start_date", "=", "min_date", "start_inrange", "=", "False", "else", ":", "start_inrange", "=", "True", "if", "(", "max_date", "<", "end_date", ")", ":", "end_date", "=", "max_date", "end_inrange", "=", "False", "else", ":", "end_inrange", "=", "True", "# rebuild the path\r", "path", "=", "QPainterPath", "(", ")", "self", ".", "setPos", "(", "0", ",", "0", ")", "pad", "=", "2", "offset", "=", "18", "height", "=", "16", "# rebuild a timed item\r", "if", "(", "not", "self", ".", "isAllDay", "(", ")", ")", ":", "start_dtime", "=", "QDateTime", "(", "self", ".", "dateStart", "(", ")", ",", "self", ".", "timeStart", "(", ")", ")", "end_dtime", "=", "QDateTime", "(", "self", ".", "dateStart", "(", ")", ",", "self", ".", "timeEnd", "(", ")", ".", "addSecs", "(", "-", "30", "*", "60", ")", ")", "start_rect", "=", "scene", ".", "dateTimeRect", "(", "start_dtime", ")", "end_rect", "=", "scene", ".", "dateTimeRect", "(", "end_dtime", ")", "left", "=", "start_rect", ".", "left", "(", ")", "+", "pad", "top", "=", "start_rect", ".", "top", "(", ")", "+", "pad", "right", "=", "start_rect", ".", "right", "(", ")", "-", "pad", "bottom", "=", "end_rect", ".", "bottom", "(", ")", "-", "pad", "path", ".", "moveTo", "(", "left", ",", "top", ")", "path", ".", "lineTo", "(", "right", ",", "top", ")", "path", ".", "lineTo", "(", "right", ",", "bottom", ")", "path", ".", "lineTo", "(", "left", ",", "bottom", ")", "path", ".", "lineTo", "(", "left", ",", "top", ")", "data", "=", "(", "left", "+", "6", ",", "top", "+", "6", ",", "right", "-", "left", "-", "12", ",", "bottom", "-", "top", "-", "12", ",", "Qt", ".", "AlignTop", "|", "Qt", ".", "AlignLeft", ",", "'%s - %s\\n(%s)'", "%", "(", "self", ".", "timeStart", "(", ")", ".", "toString", "(", "'h:mmap'", ")", "[", ":", "-", "1", "]", ",", "self", ".", "timeEnd", "(", ")", ".", "toString", "(", "'h:mmap'", ")", ",", "self", ".", "title", "(", ")", ")", ")", "self", ".", "_textData", ".", "append", "(", "data", ")", "self", ".", "setPath", "(", "path", ")", "self", ".", "show", "(", ")" ]
Rebuilds the current item in day mode.
[ "Rebuilds", "the", "current", "item", "in", "day", "mode", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xcalendarwidget/xcalendaritem.py#L261-L334
train
bitesofcode/projexui
projexui/wizards/xscaffoldwizard/xscaffoldwizard.py
XScaffoldPropertiesPage.validatePage
def validatePage(self): """ Validates the page against the scaffold information, setting the values along the way. """ widgets = self.propertyWidgetMap() failed = '' for prop, widget in widgets.items(): val, success = projexui.widgetValue(widget) if success: # ensure we have the required values if not val and not (prop.type == 'bool' and val is False): if prop.default: val = prop.default elif prop.required: msg = '{0} is a required value'.format(prop.label) failed = msg break # ensure the values match the required expression elif prop.regex and not re.match(prop.regex, nativestring(val)): msg = '{0} needs to be in the format {1}'.format(prop.label, prop.regex) failed = msg break prop.value = val else: msg = 'Failed to get a proper value for {0}'.format(prop.label) failed = msg break if failed: QtGui.QMessageBox.warning(None, 'Properties Failed', failed) return False return True
python
def validatePage(self): """ Validates the page against the scaffold information, setting the values along the way. """ widgets = self.propertyWidgetMap() failed = '' for prop, widget in widgets.items(): val, success = projexui.widgetValue(widget) if success: # ensure we have the required values if not val and not (prop.type == 'bool' and val is False): if prop.default: val = prop.default elif prop.required: msg = '{0} is a required value'.format(prop.label) failed = msg break # ensure the values match the required expression elif prop.regex and not re.match(prop.regex, nativestring(val)): msg = '{0} needs to be in the format {1}'.format(prop.label, prop.regex) failed = msg break prop.value = val else: msg = 'Failed to get a proper value for {0}'.format(prop.label) failed = msg break if failed: QtGui.QMessageBox.warning(None, 'Properties Failed', failed) return False return True
[ "def", "validatePage", "(", "self", ")", ":", "widgets", "=", "self", ".", "propertyWidgetMap", "(", ")", "failed", "=", "''", "for", "prop", ",", "widget", "in", "widgets", ".", "items", "(", ")", ":", "val", ",", "success", "=", "projexui", ".", "widgetValue", "(", "widget", ")", "if", "success", ":", "# ensure we have the required values\r", "if", "not", "val", "and", "not", "(", "prop", ".", "type", "==", "'bool'", "and", "val", "is", "False", ")", ":", "if", "prop", ".", "default", ":", "val", "=", "prop", ".", "default", "elif", "prop", ".", "required", ":", "msg", "=", "'{0} is a required value'", ".", "format", "(", "prop", ".", "label", ")", "failed", "=", "msg", "break", "# ensure the values match the required expression\r", "elif", "prop", ".", "regex", "and", "not", "re", ".", "match", "(", "prop", ".", "regex", ",", "nativestring", "(", "val", ")", ")", ":", "msg", "=", "'{0} needs to be in the format {1}'", ".", "format", "(", "prop", ".", "label", ",", "prop", ".", "regex", ")", "failed", "=", "msg", "break", "prop", ".", "value", "=", "val", "else", ":", "msg", "=", "'Failed to get a proper value for {0}'", ".", "format", "(", "prop", ".", "label", ")", "failed", "=", "msg", "break", "if", "failed", ":", "QtGui", ".", "QMessageBox", ".", "warning", "(", "None", ",", "'Properties Failed'", ",", "failed", ")", "return", "False", "return", "True" ]
Validates the page against the scaffold information, setting the values along the way.
[ "Validates", "the", "page", "against", "the", "scaffold", "information", "setting", "the", "values", "along", "the", "way", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/wizards/xscaffoldwizard/xscaffoldwizard.py#L166-L203
train
bitesofcode/projexui
projexui/wizards/xscaffoldwizard/xscaffoldwizard.py
XScaffoldElementItem.save
def save(self): """ Saves the state for this item to the scaffold. """ enabled = self.checkState(0) == QtCore.Qt.Checked self._element.set('name', nativestring(self.text(0))) self._element.set('enabled', nativestring(enabled)) for child in self.children(): child.save()
python
def save(self): """ Saves the state for this item to the scaffold. """ enabled = self.checkState(0) == QtCore.Qt.Checked self._element.set('name', nativestring(self.text(0))) self._element.set('enabled', nativestring(enabled)) for child in self.children(): child.save()
[ "def", "save", "(", "self", ")", ":", "enabled", "=", "self", ".", "checkState", "(", "0", ")", "==", "QtCore", ".", "Qt", ".", "Checked", "self", ".", "_element", ".", "set", "(", "'name'", ",", "nativestring", "(", "self", ".", "text", "(", "0", ")", ")", ")", "self", ".", "_element", ".", "set", "(", "'enabled'", ",", "nativestring", "(", "enabled", ")", ")", "for", "child", "in", "self", ".", "children", "(", ")", ":", "child", ".", "save", "(", ")" ]
Saves the state for this item to the scaffold.
[ "Saves", "the", "state", "for", "this", "item", "to", "the", "scaffold", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/wizards/xscaffoldwizard/xscaffoldwizard.py#L241-L250
train
bitesofcode/projexui
projexui/wizards/xscaffoldwizard/xscaffoldwizard.py
XScaffoldElementItem.update
def update(self, enabled=None): """ Updates this item based on the interface. """ if enabled is None: enabled = self.checkState(0) == QtCore.Qt.Checked elif not enabled or self._element.get('enabled', 'True') != 'True': self.setCheckState(0, QtCore.Qt.Unchecked) else: self.setCheckState(0, QtCore.Qt.Checked) if enabled: self.setForeground(0, QtGui.QBrush()) else: self.setForeground(0, QtGui.QBrush(QtGui.QColor('lightGray'))) for child in self.children(): child.update(enabled)
python
def update(self, enabled=None): """ Updates this item based on the interface. """ if enabled is None: enabled = self.checkState(0) == QtCore.Qt.Checked elif not enabled or self._element.get('enabled', 'True') != 'True': self.setCheckState(0, QtCore.Qt.Unchecked) else: self.setCheckState(0, QtCore.Qt.Checked) if enabled: self.setForeground(0, QtGui.QBrush()) else: self.setForeground(0, QtGui.QBrush(QtGui.QColor('lightGray'))) for child in self.children(): child.update(enabled)
[ "def", "update", "(", "self", ",", "enabled", "=", "None", ")", ":", "if", "enabled", "is", "None", ":", "enabled", "=", "self", ".", "checkState", "(", "0", ")", "==", "QtCore", ".", "Qt", ".", "Checked", "elif", "not", "enabled", "or", "self", ".", "_element", ".", "get", "(", "'enabled'", ",", "'True'", ")", "!=", "'True'", ":", "self", ".", "setCheckState", "(", "0", ",", "QtCore", ".", "Qt", ".", "Unchecked", ")", "else", ":", "self", ".", "setCheckState", "(", "0", ",", "QtCore", ".", "Qt", ".", "Checked", ")", "if", "enabled", ":", "self", ".", "setForeground", "(", "0", ",", "QtGui", ".", "QBrush", "(", ")", ")", "else", ":", "self", ".", "setForeground", "(", "0", ",", "QtGui", ".", "QBrush", "(", "QtGui", ".", "QColor", "(", "'lightGray'", ")", ")", ")", "for", "child", "in", "self", ".", "children", "(", ")", ":", "child", ".", "update", "(", "enabled", ")" ]
Updates this item based on the interface.
[ "Updates", "this", "item", "based", "on", "the", "interface", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/wizards/xscaffoldwizard/xscaffoldwizard.py#L252-L269
train
bitesofcode/projexui
projexui/wizards/xscaffoldwizard/xscaffoldwizard.py
XScaffoldStructurePage.initializePage
def initializePage(self): """ Initializes the page based on the current structure information. """ tree = self.uiStructureTREE tree.blockSignals(True) tree.setUpdatesEnabled(False) self.uiStructureTREE.clear() xstruct = self.scaffold().structure() self._structure = xstruct for xentry in xstruct: XScaffoldElementItem(tree, xentry) tree.blockSignals(False) tree.setUpdatesEnabled(True)
python
def initializePage(self): """ Initializes the page based on the current structure information. """ tree = self.uiStructureTREE tree.blockSignals(True) tree.setUpdatesEnabled(False) self.uiStructureTREE.clear() xstruct = self.scaffold().structure() self._structure = xstruct for xentry in xstruct: XScaffoldElementItem(tree, xentry) tree.blockSignals(False) tree.setUpdatesEnabled(True)
[ "def", "initializePage", "(", "self", ")", ":", "tree", "=", "self", ".", "uiStructureTREE", "tree", ".", "blockSignals", "(", "True", ")", "tree", ".", "setUpdatesEnabled", "(", "False", ")", "self", ".", "uiStructureTREE", ".", "clear", "(", ")", "xstruct", "=", "self", ".", "scaffold", "(", ")", ".", "structure", "(", ")", "self", ".", "_structure", "=", "xstruct", "for", "xentry", "in", "xstruct", ":", "XScaffoldElementItem", "(", "tree", ",", "xentry", ")", "tree", ".", "blockSignals", "(", "False", ")", "tree", ".", "setUpdatesEnabled", "(", "True", ")" ]
Initializes the page based on the current structure information.
[ "Initializes", "the", "page", "based", "on", "the", "current", "structure", "information", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/wizards/xscaffoldwizard/xscaffoldwizard.py#L290-L305
train
bitesofcode/projexui
projexui/wizards/xscaffoldwizard/xscaffoldwizard.py
XScaffoldStructurePage.validatePage
def validatePage(self): """ Finishes up the structure information for this wizard by building the scaffold. """ path = self.uiOutputPATH.filepath() for item in self.uiStructureTREE.topLevelItems(): item.save() try: self.scaffold().build(path, self._structure) except Exception, err: QtGui.QMessageBox.critical(None, 'Error Occurred', nativestring(err)) return False return True
python
def validatePage(self): """ Finishes up the structure information for this wizard by building the scaffold. """ path = self.uiOutputPATH.filepath() for item in self.uiStructureTREE.topLevelItems(): item.save() try: self.scaffold().build(path, self._structure) except Exception, err: QtGui.QMessageBox.critical(None, 'Error Occurred', nativestring(err)) return False return True
[ "def", "validatePage", "(", "self", ")", ":", "path", "=", "self", ".", "uiOutputPATH", ".", "filepath", "(", ")", "for", "item", "in", "self", ".", "uiStructureTREE", ".", "topLevelItems", "(", ")", ":", "item", ".", "save", "(", ")", "try", ":", "self", ".", "scaffold", "(", ")", ".", "build", "(", "path", ",", "self", ".", "_structure", ")", "except", "Exception", ",", "err", ":", "QtGui", ".", "QMessageBox", ".", "critical", "(", "None", ",", "'Error Occurred'", ",", "nativestring", "(", "err", ")", ")", "return", "False", "return", "True" ]
Finishes up the structure information for this wizard by building the scaffold.
[ "Finishes", "up", "the", "structure", "information", "for", "this", "wizard", "by", "building", "the", "scaffold", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/wizards/xscaffoldwizard/xscaffoldwizard.py#L315-L331
train
bitesofcode/projexui
projexui/widgets/xorbcolumnedit/xorbcolumnedit.py
XOrbColumnEdit.rebuild
def rebuild( self ): """ Clears out all the child widgets from this widget and creates the widget that best matches the column properties for this edit. """ plugins.init() self.blockSignals(True) self.setUpdatesEnabled(False) # clear the old editor if ( self._editor ): self._editor.close() self._editor.setParent(None) self._editor.deleteLater() self._editor = None # create a new widget plugin_class = plugins.widgets.get(self._columnType) if ( plugin_class ): self._editor = plugin_class(self) self.layout().addWidget(self._editor) self.blockSignals(False) self.setUpdatesEnabled(True)
python
def rebuild( self ): """ Clears out all the child widgets from this widget and creates the widget that best matches the column properties for this edit. """ plugins.init() self.blockSignals(True) self.setUpdatesEnabled(False) # clear the old editor if ( self._editor ): self._editor.close() self._editor.setParent(None) self._editor.deleteLater() self._editor = None # create a new widget plugin_class = plugins.widgets.get(self._columnType) if ( plugin_class ): self._editor = plugin_class(self) self.layout().addWidget(self._editor) self.blockSignals(False) self.setUpdatesEnabled(True)
[ "def", "rebuild", "(", "self", ")", ":", "plugins", ".", "init", "(", ")", "self", ".", "blockSignals", "(", "True", ")", "self", ".", "setUpdatesEnabled", "(", "False", ")", "# clear the old editor\r", "if", "(", "self", ".", "_editor", ")", ":", "self", ".", "_editor", ".", "close", "(", ")", "self", ".", "_editor", ".", "setParent", "(", "None", ")", "self", ".", "_editor", ".", "deleteLater", "(", ")", "self", ".", "_editor", "=", "None", "# create a new widget\r", "plugin_class", "=", "plugins", ".", "widgets", ".", "get", "(", "self", ".", "_columnType", ")", "if", "(", "plugin_class", ")", ":", "self", ".", "_editor", "=", "plugin_class", "(", "self", ")", "self", ".", "layout", "(", ")", ".", "addWidget", "(", "self", ".", "_editor", ")", "self", ".", "blockSignals", "(", "False", ")", "self", ".", "setUpdatesEnabled", "(", "True", ")" ]
Clears out all the child widgets from this widget and creates the widget that best matches the column properties for this edit.
[ "Clears", "out", "all", "the", "child", "widgets", "from", "this", "widget", "and", "creates", "the", "widget", "that", "best", "matches", "the", "column", "properties", "for", "this", "edit", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbcolumnedit/xorbcolumnedit.py#L120-L144
train
bitesofcode/projexui
projexui/windows/xdkwindow/xdkwindow.py
XdkWindow.closeContentsWidget
def closeContentsWidget( self ): """ Closes the current contents widget. """ widget = self.currentContentsWidget() if ( not widget ): return widget.close() widget.setParent(None) widget.deleteLater()
python
def closeContentsWidget( self ): """ Closes the current contents widget. """ widget = self.currentContentsWidget() if ( not widget ): return widget.close() widget.setParent(None) widget.deleteLater()
[ "def", "closeContentsWidget", "(", "self", ")", ":", "widget", "=", "self", ".", "currentContentsWidget", "(", ")", "if", "(", "not", "widget", ")", ":", "return", "widget", ".", "close", "(", ")", "widget", ".", "setParent", "(", "None", ")", "widget", ".", "deleteLater", "(", ")" ]
Closes the current contents widget.
[ "Closes", "the", "current", "contents", "widget", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/windows/xdkwindow/xdkwindow.py#L246-L256
train
bitesofcode/projexui
projexui/windows/xdkwindow/xdkwindow.py
XdkWindow.copyText
def copyText( self ): """ Copies the selected text to the clipboard. """ view = self.currentWebView() QApplication.clipboard().setText(view.page().selectedText())
python
def copyText( self ): """ Copies the selected text to the clipboard. """ view = self.currentWebView() QApplication.clipboard().setText(view.page().selectedText())
[ "def", "copyText", "(", "self", ")", ":", "view", "=", "self", ".", "currentWebView", "(", ")", "QApplication", ".", "clipboard", "(", ")", ".", "setText", "(", "view", ".", "page", "(", ")", ".", "selectedText", "(", ")", ")" ]
Copies the selected text to the clipboard.
[ "Copies", "the", "selected", "text", "to", "the", "clipboard", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/windows/xdkwindow/xdkwindow.py#L258-L263
train
bitesofcode/projexui
projexui/windows/xdkwindow/xdkwindow.py
XdkWindow.findPrev
def findPrev( self ): """ Looks for the previous occurance of the current search text. """ text = self.uiFindTXT.text() view = self.currentWebView() options = QWebPage.FindWrapsAroundDocument options |= QWebPage.FindBackward if ( self.uiCaseSensitiveCHK.isChecked() ): options |= QWebPage.FindCaseSensitively view.page().findText(text, options)
python
def findPrev( self ): """ Looks for the previous occurance of the current search text. """ text = self.uiFindTXT.text() view = self.currentWebView() options = QWebPage.FindWrapsAroundDocument options |= QWebPage.FindBackward if ( self.uiCaseSensitiveCHK.isChecked() ): options |= QWebPage.FindCaseSensitively view.page().findText(text, options)
[ "def", "findPrev", "(", "self", ")", ":", "text", "=", "self", ".", "uiFindTXT", ".", "text", "(", ")", "view", "=", "self", ".", "currentWebView", "(", ")", "options", "=", "QWebPage", ".", "FindWrapsAroundDocument", "options", "|=", "QWebPage", ".", "FindBackward", "if", "(", "self", ".", "uiCaseSensitiveCHK", ".", "isChecked", "(", ")", ")", ":", "options", "|=", "QWebPage", ".", "FindCaseSensitively", "view", ".", "page", "(", ")", ".", "findText", "(", "text", ",", "options", ")" ]
Looks for the previous occurance of the current search text.
[ "Looks", "for", "the", "previous", "occurance", "of", "the", "current", "search", "text", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/windows/xdkwindow/xdkwindow.py#L322-L335
train
bitesofcode/projexui
projexui/windows/xdkwindow/xdkwindow.py
XdkWindow.refreshFromIndex
def refreshFromIndex( self ): """ Refreshes the documentation from the selected index item. """ item = self.uiIndexTREE.currentItem() if ( not item ): return self.gotoUrl(item.toolTip(0))
python
def refreshFromIndex( self ): """ Refreshes the documentation from the selected index item. """ item = self.uiIndexTREE.currentItem() if ( not item ): return self.gotoUrl(item.toolTip(0))
[ "def", "refreshFromIndex", "(", "self", ")", ":", "item", "=", "self", ".", "uiIndexTREE", ".", "currentItem", "(", ")", "if", "(", "not", "item", ")", ":", "return", "self", ".", "gotoUrl", "(", "item", ".", "toolTip", "(", "0", ")", ")" ]
Refreshes the documentation from the selected index item.
[ "Refreshes", "the", "documentation", "from", "the", "selected", "index", "item", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/windows/xdkwindow/xdkwindow.py#L455-L463
train
bitesofcode/projexui
projexui/windows/xdkwindow/xdkwindow.py
XdkWindow.refreshContents
def refreshContents( self ): """ Refreshes the contents tab with the latest selection from the browser. """ item = self.uiContentsTREE.currentItem() if not isinstance(item, XdkEntryItem): return item.load() url = item.url() if url: self.gotoUrl(url)
python
def refreshContents( self ): """ Refreshes the contents tab with the latest selection from the browser. """ item = self.uiContentsTREE.currentItem() if not isinstance(item, XdkEntryItem): return item.load() url = item.url() if url: self.gotoUrl(url)
[ "def", "refreshContents", "(", "self", ")", ":", "item", "=", "self", ".", "uiContentsTREE", ".", "currentItem", "(", ")", "if", "not", "isinstance", "(", "item", ",", "XdkEntryItem", ")", ":", "return", "item", ".", "load", "(", ")", "url", "=", "item", ".", "url", "(", ")", "if", "url", ":", "self", ".", "gotoUrl", "(", "url", ")" ]
Refreshes the contents tab with the latest selection from the browser.
[ "Refreshes", "the", "contents", "tab", "with", "the", "latest", "selection", "from", "the", "browser", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/windows/xdkwindow/xdkwindow.py#L465-L476
train
bitesofcode/projexui
projexui/windows/xdkwindow/xdkwindow.py
XdkWindow.refreshUi
def refreshUi( self ): """ Refreshes the interface based on the current settings. """ widget = self.uiContentsTAB.currentWidget() is_content = isinstance(widget, QWebView) if is_content: self._currentContentsIndex = self.uiContentsTAB.currentIndex() history = widget.page().history() else: history = None self.uiBackACT.setEnabled(is_content and history.canGoBack()) self.uiForwardACT.setEnabled(is_content and history.canGoForward()) self.uiHomeACT.setEnabled(is_content) self.uiNewTabACT.setEnabled(is_content) self.uiCopyTextACT.setEnabled(is_content) self.uiCloseTabACT.setEnabled(is_content and self.uiContentsTAB.count() > 2) for i in range(1, self.uiContentsTAB.count()): widget = self.uiContentsTAB.widget(i) self.uiContentsTAB.setTabText(i, widget.title())
python
def refreshUi( self ): """ Refreshes the interface based on the current settings. """ widget = self.uiContentsTAB.currentWidget() is_content = isinstance(widget, QWebView) if is_content: self._currentContentsIndex = self.uiContentsTAB.currentIndex() history = widget.page().history() else: history = None self.uiBackACT.setEnabled(is_content and history.canGoBack()) self.uiForwardACT.setEnabled(is_content and history.canGoForward()) self.uiHomeACT.setEnabled(is_content) self.uiNewTabACT.setEnabled(is_content) self.uiCopyTextACT.setEnabled(is_content) self.uiCloseTabACT.setEnabled(is_content and self.uiContentsTAB.count() > 2) for i in range(1, self.uiContentsTAB.count()): widget = self.uiContentsTAB.widget(i) self.uiContentsTAB.setTabText(i, widget.title())
[ "def", "refreshUi", "(", "self", ")", ":", "widget", "=", "self", ".", "uiContentsTAB", ".", "currentWidget", "(", ")", "is_content", "=", "isinstance", "(", "widget", ",", "QWebView", ")", "if", "is_content", ":", "self", ".", "_currentContentsIndex", "=", "self", ".", "uiContentsTAB", ".", "currentIndex", "(", ")", "history", "=", "widget", ".", "page", "(", ")", ".", "history", "(", ")", "else", ":", "history", "=", "None", "self", ".", "uiBackACT", ".", "setEnabled", "(", "is_content", "and", "history", ".", "canGoBack", "(", ")", ")", "self", ".", "uiForwardACT", ".", "setEnabled", "(", "is_content", "and", "history", ".", "canGoForward", "(", ")", ")", "self", ".", "uiHomeACT", ".", "setEnabled", "(", "is_content", ")", "self", ".", "uiNewTabACT", ".", "setEnabled", "(", "is_content", ")", "self", ".", "uiCopyTextACT", ".", "setEnabled", "(", "is_content", ")", "self", ".", "uiCloseTabACT", ".", "setEnabled", "(", "is_content", "and", "self", ".", "uiContentsTAB", ".", "count", "(", ")", ">", "2", ")", "for", "i", "in", "range", "(", "1", ",", "self", ".", "uiContentsTAB", ".", "count", "(", ")", ")", ":", "widget", "=", "self", ".", "uiContentsTAB", ".", "widget", "(", "i", ")", "self", ".", "uiContentsTAB", ".", "setTabText", "(", "i", ",", "widget", ".", "title", "(", ")", ")" ]
Refreshes the interface based on the current settings.
[ "Refreshes", "the", "interface", "based", "on", "the", "current", "settings", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/windows/xdkwindow/xdkwindow.py#L478-L501
train
bitesofcode/projexui
projexui/windows/xdkwindow/xdkwindow.py
XdkWindow.search
def search( self ): """ Looks up the current search terms from the xdk files that are loaded. """ QApplication.instance().setOverrideCursor(Qt.WaitCursor) terms = nativestring(self.uiSearchTXT.text()) html = [] entry_html = '<a href="%(url)s">%(title)s</a><br/>'\ '<small>%(url)s</small>' for i in range(self.uiContentsTREE.topLevelItemCount()): item = self.uiContentsTREE.topLevelItem(i) results = item.search(terms) results.sort(lambda x, y: cmp(y['strength'], x['strength'])) for item in results: html.append( entry_html % item ) if ( not html ): html.append('<b>No results were found for %s</b>' % terms) self.uiSearchWEB.setHtml(SEARCH_HTML % '<br/><br/>'.join(html)) QApplication.instance().restoreOverrideCursor()
python
def search( self ): """ Looks up the current search terms from the xdk files that are loaded. """ QApplication.instance().setOverrideCursor(Qt.WaitCursor) terms = nativestring(self.uiSearchTXT.text()) html = [] entry_html = '<a href="%(url)s">%(title)s</a><br/>'\ '<small>%(url)s</small>' for i in range(self.uiContentsTREE.topLevelItemCount()): item = self.uiContentsTREE.topLevelItem(i) results = item.search(terms) results.sort(lambda x, y: cmp(y['strength'], x['strength'])) for item in results: html.append( entry_html % item ) if ( not html ): html.append('<b>No results were found for %s</b>' % terms) self.uiSearchWEB.setHtml(SEARCH_HTML % '<br/><br/>'.join(html)) QApplication.instance().restoreOverrideCursor()
[ "def", "search", "(", "self", ")", ":", "QApplication", ".", "instance", "(", ")", ".", "setOverrideCursor", "(", "Qt", ".", "WaitCursor", ")", "terms", "=", "nativestring", "(", "self", ".", "uiSearchTXT", ".", "text", "(", ")", ")", "html", "=", "[", "]", "entry_html", "=", "'<a href=\"%(url)s\">%(title)s</a><br/>'", "'<small>%(url)s</small>'", "for", "i", "in", "range", "(", "self", ".", "uiContentsTREE", ".", "topLevelItemCount", "(", ")", ")", ":", "item", "=", "self", ".", "uiContentsTREE", ".", "topLevelItem", "(", "i", ")", "results", "=", "item", ".", "search", "(", "terms", ")", "results", ".", "sort", "(", "lambda", "x", ",", "y", ":", "cmp", "(", "y", "[", "'strength'", "]", ",", "x", "[", "'strength'", "]", ")", ")", "for", "item", "in", "results", ":", "html", ".", "append", "(", "entry_html", "%", "item", ")", "if", "(", "not", "html", ")", ":", "html", ".", "append", "(", "'<b>No results were found for %s</b>'", "%", "terms", ")", "self", ".", "uiSearchWEB", ".", "setHtml", "(", "SEARCH_HTML", "%", "'<br/><br/>'", ".", "join", "(", "html", ")", ")", "QApplication", ".", "instance", "(", ")", ".", "restoreOverrideCursor", "(", ")" ]
Looks up the current search terms from the xdk files that are loaded.
[ "Looks", "up", "the", "current", "search", "terms", "from", "the", "xdk", "files", "that", "are", "loaded", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/windows/xdkwindow/xdkwindow.py#L503-L529
train
intelsdi-x/snap-plugin-lib-py
snap_plugin/v1/config_map.py
ConfigMap.clear
def clear(self): "Removes all entries from the config map" self._pb.IntMap.clear() self._pb.StringMap.clear() self._pb.FloatMap.clear() self._pb.BoolMap.clear()
python
def clear(self): "Removes all entries from the config map" self._pb.IntMap.clear() self._pb.StringMap.clear() self._pb.FloatMap.clear() self._pb.BoolMap.clear()
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_pb", ".", "IntMap", ".", "clear", "(", ")", "self", ".", "_pb", ".", "StringMap", ".", "clear", "(", ")", "self", ".", "_pb", ".", "FloatMap", ".", "clear", "(", ")", "self", ".", "_pb", ".", "BoolMap", ".", "clear", "(", ")" ]
Removes all entries from the config map
[ "Removes", "all", "entries", "from", "the", "config", "map" ]
8da5d00ac5f9d2b48a7239563ac7788209891ca4
https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/config_map.py#L129-L134
train
intelsdi-x/snap-plugin-lib-py
snap_plugin/v1/config_map.py
ConfigMap.keys
def keys(self): "Returns a list of ConfigMap keys." return (list(self._pb.IntMap.keys()) + list(self._pb.StringMap.keys()) + list(self._pb.FloatMap.keys()) + list(self._pb.BoolMap.keys()))
python
def keys(self): "Returns a list of ConfigMap keys." return (list(self._pb.IntMap.keys()) + list(self._pb.StringMap.keys()) + list(self._pb.FloatMap.keys()) + list(self._pb.BoolMap.keys()))
[ "def", "keys", "(", "self", ")", ":", "return", "(", "list", "(", "self", ".", "_pb", ".", "IntMap", ".", "keys", "(", ")", ")", "+", "list", "(", "self", ".", "_pb", ".", "StringMap", ".", "keys", "(", ")", ")", "+", "list", "(", "self", ".", "_pb", ".", "FloatMap", ".", "keys", "(", ")", ")", "+", "list", "(", "self", ".", "_pb", ".", "BoolMap", ".", "keys", "(", ")", ")", ")" ]
Returns a list of ConfigMap keys.
[ "Returns", "a", "list", "of", "ConfigMap", "keys", "." ]
8da5d00ac5f9d2b48a7239563ac7788209891ca4
https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/config_map.py#L159-L162
train
intelsdi-x/snap-plugin-lib-py
snap_plugin/v1/config_map.py
ConfigMap.values
def values(self): "Returns a list of ConfigMap values." return (list(self._pb.IntMap.values()) + list(self._pb.StringMap.values()) + list(self._pb.FloatMap.values()) + list(self._pb.BoolMap.values()))
python
def values(self): "Returns a list of ConfigMap values." return (list(self._pb.IntMap.values()) + list(self._pb.StringMap.values()) + list(self._pb.FloatMap.values()) + list(self._pb.BoolMap.values()))
[ "def", "values", "(", "self", ")", ":", "return", "(", "list", "(", "self", ".", "_pb", ".", "IntMap", ".", "values", "(", ")", ")", "+", "list", "(", "self", ".", "_pb", ".", "StringMap", ".", "values", "(", ")", ")", "+", "list", "(", "self", ".", "_pb", ".", "FloatMap", ".", "values", "(", ")", ")", "+", "list", "(", "self", ".", "_pb", ".", "BoolMap", ".", "values", "(", ")", ")", ")" ]
Returns a list of ConfigMap values.
[ "Returns", "a", "list", "of", "ConfigMap", "values", "." ]
8da5d00ac5f9d2b48a7239563ac7788209891ca4
https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/config_map.py#L164-L167
train
intelsdi-x/snap-plugin-lib-py
snap_plugin/v1/config_map.py
ConfigMap.iteritems
def iteritems(self): "Returns an iterator over the items of ConfigMap." return chain(self._pb.StringMap.items(), self._pb.IntMap.items(), self._pb.FloatMap.items(), self._pb.BoolMap.items())
python
def iteritems(self): "Returns an iterator over the items of ConfigMap." return chain(self._pb.StringMap.items(), self._pb.IntMap.items(), self._pb.FloatMap.items(), self._pb.BoolMap.items())
[ "def", "iteritems", "(", "self", ")", ":", "return", "chain", "(", "self", ".", "_pb", ".", "StringMap", ".", "items", "(", ")", ",", "self", ".", "_pb", ".", "IntMap", ".", "items", "(", ")", ",", "self", ".", "_pb", ".", "FloatMap", ".", "items", "(", ")", ",", "self", ".", "_pb", ".", "BoolMap", ".", "items", "(", ")", ")" ]
Returns an iterator over the items of ConfigMap.
[ "Returns", "an", "iterator", "over", "the", "items", "of", "ConfigMap", "." ]
8da5d00ac5f9d2b48a7239563ac7788209891ca4
https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/config_map.py#L169-L174
train
intelsdi-x/snap-plugin-lib-py
snap_plugin/v1/config_map.py
ConfigMap.itervalues
def itervalues(self): "Returns an iterator over the values of ConfigMap." return chain(self._pb.StringMap.values(), self._pb.IntMap.values(), self._pb.FloatMap.values(), self._pb.BoolMap.values())
python
def itervalues(self): "Returns an iterator over the values of ConfigMap." return chain(self._pb.StringMap.values(), self._pb.IntMap.values(), self._pb.FloatMap.values(), self._pb.BoolMap.values())
[ "def", "itervalues", "(", "self", ")", ":", "return", "chain", "(", "self", ".", "_pb", ".", "StringMap", ".", "values", "(", ")", ",", "self", ".", "_pb", ".", "IntMap", ".", "values", "(", ")", ",", "self", ".", "_pb", ".", "FloatMap", ".", "values", "(", ")", ",", "self", ".", "_pb", ".", "BoolMap", ".", "values", "(", ")", ")" ]
Returns an iterator over the values of ConfigMap.
[ "Returns", "an", "iterator", "over", "the", "values", "of", "ConfigMap", "." ]
8da5d00ac5f9d2b48a7239563ac7788209891ca4
https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/config_map.py#L176-L181
train
intelsdi-x/snap-plugin-lib-py
snap_plugin/v1/config_map.py
ConfigMap.iterkeys
def iterkeys(self): "Returns an iterator over the keys of ConfigMap." return chain(self._pb.StringMap.keys(), self._pb.IntMap.keys(), self._pb.FloatMap.keys(), self._pb.BoolMap.keys())
python
def iterkeys(self): "Returns an iterator over the keys of ConfigMap." return chain(self._pb.StringMap.keys(), self._pb.IntMap.keys(), self._pb.FloatMap.keys(), self._pb.BoolMap.keys())
[ "def", "iterkeys", "(", "self", ")", ":", "return", "chain", "(", "self", ".", "_pb", ".", "StringMap", ".", "keys", "(", ")", ",", "self", ".", "_pb", ".", "IntMap", ".", "keys", "(", ")", ",", "self", ".", "_pb", ".", "FloatMap", ".", "keys", "(", ")", ",", "self", ".", "_pb", ".", "BoolMap", ".", "keys", "(", ")", ")" ]
Returns an iterator over the keys of ConfigMap.
[ "Returns", "an", "iterator", "over", "the", "keys", "of", "ConfigMap", "." ]
8da5d00ac5f9d2b48a7239563ac7788209891ca4
https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/config_map.py#L183-L188
train
intelsdi-x/snap-plugin-lib-py
snap_plugin/v1/config_map.py
ConfigMap.pop
def pop(self, key, default=None): """Remove specified key and return the corresponding value. If key is not found, default is returned if given, otherwise KeyError is raised. """ if key not in self: if default is not None: return default raise KeyError(key) for map in [self._pb.IntMap, self._pb.FloatMap, self._pb.StringMap, self._pb.BoolMap]: if key in map.keys(): return map.pop(key)
python
def pop(self, key, default=None): """Remove specified key and return the corresponding value. If key is not found, default is returned if given, otherwise KeyError is raised. """ if key not in self: if default is not None: return default raise KeyError(key) for map in [self._pb.IntMap, self._pb.FloatMap, self._pb.StringMap, self._pb.BoolMap]: if key in map.keys(): return map.pop(key)
[ "def", "pop", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "if", "key", "not", "in", "self", ":", "if", "default", "is", "not", "None", ":", "return", "default", "raise", "KeyError", "(", "key", ")", "for", "map", "in", "[", "self", ".", "_pb", ".", "IntMap", ",", "self", ".", "_pb", ".", "FloatMap", ",", "self", ".", "_pb", ".", "StringMap", ",", "self", ".", "_pb", ".", "BoolMap", "]", ":", "if", "key", "in", "map", ".", "keys", "(", ")", ":", "return", "map", ".", "pop", "(", "key", ")" ]
Remove specified key and return the corresponding value. If key is not found, default is returned if given, otherwise KeyError is raised.
[ "Remove", "specified", "key", "and", "return", "the", "corresponding", "value", ".", "If", "key", "is", "not", "found", "default", "is", "returned", "if", "given", "otherwise", "KeyError", "is", "raised", "." ]
8da5d00ac5f9d2b48a7239563ac7788209891ca4
https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/config_map.py#L195-L207
train
bitesofcode/projexui
projexui/xorbworker.py
XOrbWorker.interrupt
def interrupt(self): """ Interrupts the current database from processing. """ if self._database and self._databaseThreadId: # support Orb 2 interruption capabilities try: self._database.interrupt(self._databaseThreadId) except AttributeError: pass self._database = None self._databaseThreadId = 0
python
def interrupt(self): """ Interrupts the current database from processing. """ if self._database and self._databaseThreadId: # support Orb 2 interruption capabilities try: self._database.interrupt(self._databaseThreadId) except AttributeError: pass self._database = None self._databaseThreadId = 0
[ "def", "interrupt", "(", "self", ")", ":", "if", "self", ".", "_database", "and", "self", ".", "_databaseThreadId", ":", "# support Orb 2 interruption capabilities\r", "try", ":", "self", ".", "_database", ".", "interrupt", "(", "self", ".", "_databaseThreadId", ")", "except", "AttributeError", ":", "pass", "self", ".", "_database", "=", "None", "self", ".", "_databaseThreadId", "=", "0" ]
Interrupts the current database from processing.
[ "Interrupts", "the", "current", "database", "from", "processing", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xorbworker.py#L121-L133
train
bitesofcode/projexui
projexui/xorbworker.py
XOrbWorker.waitUntilFinished
def waitUntilFinished(self): """ Processes the main thread until the loading process has finished. This is a way to force the main thread to be synchronous in its execution. """ QtCore.QCoreApplication.processEvents() while self.isLoading(): QtCore.QCoreApplication.processEvents()
python
def waitUntilFinished(self): """ Processes the main thread until the loading process has finished. This is a way to force the main thread to be synchronous in its execution. """ QtCore.QCoreApplication.processEvents() while self.isLoading(): QtCore.QCoreApplication.processEvents()
[ "def", "waitUntilFinished", "(", "self", ")", ":", "QtCore", ".", "QCoreApplication", ".", "processEvents", "(", ")", "while", "self", ".", "isLoading", "(", ")", ":", "QtCore", ".", "QCoreApplication", ".", "processEvents", "(", ")" ]
Processes the main thread until the loading process has finished. This is a way to force the main thread to be synchronous in its execution.
[ "Processes", "the", "main", "thread", "until", "the", "loading", "process", "has", "finished", ".", "This", "is", "a", "way", "to", "force", "the", "main", "thread", "to", "be", "synchronous", "in", "its", "execution", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xorbworker.py#L153-L160
train
bitesofcode/projexui
projexui/widgets/xrichtextedit/xrichtextedit.py
XRichTextEdit.assignAlignment
def assignAlignment(self, action): """ Sets the current alignment for the editor. """ if self._actions['align_left'] == action: self.setAlignment(Qt.AlignLeft) elif self._actions['align_right'] == action: self.setAlignment(Qt.AlignRight) elif self._actions['align_center'] == action: self.setAlignment(Qt.AlignHCenter) else: self.setAlignment(Qt.AlignJustify)
python
def assignAlignment(self, action): """ Sets the current alignment for the editor. """ if self._actions['align_left'] == action: self.setAlignment(Qt.AlignLeft) elif self._actions['align_right'] == action: self.setAlignment(Qt.AlignRight) elif self._actions['align_center'] == action: self.setAlignment(Qt.AlignHCenter) else: self.setAlignment(Qt.AlignJustify)
[ "def", "assignAlignment", "(", "self", ",", "action", ")", ":", "if", "self", ".", "_actions", "[", "'align_left'", "]", "==", "action", ":", "self", ".", "setAlignment", "(", "Qt", ".", "AlignLeft", ")", "elif", "self", ".", "_actions", "[", "'align_right'", "]", "==", "action", ":", "self", ".", "setAlignment", "(", "Qt", ".", "AlignRight", ")", "elif", "self", ".", "_actions", "[", "'align_center'", "]", "==", "action", ":", "self", ".", "setAlignment", "(", "Qt", ".", "AlignHCenter", ")", "else", ":", "self", ".", "setAlignment", "(", "Qt", ".", "AlignJustify", ")" ]
Sets the current alignment for the editor.
[ "Sets", "the", "current", "alignment", "for", "the", "editor", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xrichtextedit/xrichtextedit.py#L165-L176
train
bitesofcode/projexui
projexui/widgets/xrichtextedit/xrichtextedit.py
XRichTextEdit.assignFont
def assignFont(self): """ Assigns the font family and point size settings from the font picker widget. """ font = self.currentFont() font.setFamily(self._fontPickerWidget.currentFamily()) font.setPointSize(self._fontPickerWidget.pointSize()) self.setCurrentFont(font)
python
def assignFont(self): """ Assigns the font family and point size settings from the font picker widget. """ font = self.currentFont() font.setFamily(self._fontPickerWidget.currentFamily()) font.setPointSize(self._fontPickerWidget.pointSize()) self.setCurrentFont(font)
[ "def", "assignFont", "(", "self", ")", ":", "font", "=", "self", ".", "currentFont", "(", ")", "font", ".", "setFamily", "(", "self", ".", "_fontPickerWidget", ".", "currentFamily", "(", ")", ")", "font", ".", "setPointSize", "(", "self", ".", "_fontPickerWidget", ".", "pointSize", "(", ")", ")", "self", ".", "setCurrentFont", "(", "font", ")" ]
Assigns the font family and point size settings from the font picker widget.
[ "Assigns", "the", "font", "family", "and", "point", "size", "settings", "from", "the", "font", "picker", "widget", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xrichtextedit/xrichtextedit.py#L178-L186
train
bitesofcode/projexui
projexui/widgets/xrichtextedit/xrichtextedit.py
XRichTextEdit.refreshUi
def refreshUi(self): """ Matches the UI state to the current cursor positioning. """ font = self.currentFont() for name in ('underline', 'bold', 'italic', 'strikeOut'): getter = getattr(font, name) act = self._actions[name] act.blockSignals(True) act.setChecked(getter()) act.blockSignals(False)
python
def refreshUi(self): """ Matches the UI state to the current cursor positioning. """ font = self.currentFont() for name in ('underline', 'bold', 'italic', 'strikeOut'): getter = getattr(font, name) act = self._actions[name] act.blockSignals(True) act.setChecked(getter()) act.blockSignals(False)
[ "def", "refreshUi", "(", "self", ")", ":", "font", "=", "self", ".", "currentFont", "(", ")", "for", "name", "in", "(", "'underline'", ",", "'bold'", ",", "'italic'", ",", "'strikeOut'", ")", ":", "getter", "=", "getattr", "(", "font", ",", "name", ")", "act", "=", "self", ".", "_actions", "[", "name", "]", "act", ".", "blockSignals", "(", "True", ")", "act", ".", "setChecked", "(", "getter", "(", ")", ")", "act", ".", "blockSignals", "(", "False", ")" ]
Matches the UI state to the current cursor positioning.
[ "Matches", "the", "UI", "state", "to", "the", "current", "cursor", "positioning", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xrichtextedit/xrichtextedit.py#L465-L476
train
bitesofcode/projexui
projexui/widgets/xrichtextedit/xrichtextedit.py
XRichTextEdit.refreshAlignmentUi
def refreshAlignmentUi(self): """ Refreshes the alignment UI information. """ align = self.alignment() for name, value in (('align_left', Qt.AlignLeft), ('align_right', Qt.AlignRight), ('align_center', Qt.AlignHCenter), ('align_justify', Qt.AlignJustify)): act = self._actions[name] act.blockSignals(True) act.setChecked(value == align) act.blockSignals(False)
python
def refreshAlignmentUi(self): """ Refreshes the alignment UI information. """ align = self.alignment() for name, value in (('align_left', Qt.AlignLeft), ('align_right', Qt.AlignRight), ('align_center', Qt.AlignHCenter), ('align_justify', Qt.AlignJustify)): act = self._actions[name] act.blockSignals(True) act.setChecked(value == align) act.blockSignals(False)
[ "def", "refreshAlignmentUi", "(", "self", ")", ":", "align", "=", "self", ".", "alignment", "(", ")", "for", "name", ",", "value", "in", "(", "(", "'align_left'", ",", "Qt", ".", "AlignLeft", ")", ",", "(", "'align_right'", ",", "Qt", ".", "AlignRight", ")", ",", "(", "'align_center'", ",", "Qt", ".", "AlignHCenter", ")", ",", "(", "'align_justify'", ",", "Qt", ".", "AlignJustify", ")", ")", ":", "act", "=", "self", ".", "_actions", "[", "name", "]", "act", ".", "blockSignals", "(", "True", ")", "act", ".", "setChecked", "(", "value", "==", "align", ")", "act", ".", "blockSignals", "(", "False", ")" ]
Refreshes the alignment UI information.
[ "Refreshes", "the", "alignment", "UI", "information", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xrichtextedit/xrichtextedit.py#L478-L491
train
bitesofcode/projexui
projexui/widgets/xrichtextedit/xrichtextedit.py
XRichTextEdit.updateFontPicker
def updateFontPicker(self): """ Updates the font picker widget to the current font settings. """ font = self.currentFont() self._fontPickerWidget.setPointSize(font.pointSize()) self._fontPickerWidget.setCurrentFamily(font.family())
python
def updateFontPicker(self): """ Updates the font picker widget to the current font settings. """ font = self.currentFont() self._fontPickerWidget.setPointSize(font.pointSize()) self._fontPickerWidget.setCurrentFamily(font.family())
[ "def", "updateFontPicker", "(", "self", ")", ":", "font", "=", "self", ".", "currentFont", "(", ")", "self", ".", "_fontPickerWidget", ".", "setPointSize", "(", "font", ".", "pointSize", "(", ")", ")", "self", ".", "_fontPickerWidget", ".", "setCurrentFamily", "(", "font", ".", "family", "(", ")", ")" ]
Updates the font picker widget to the current font settings.
[ "Updates", "the", "font", "picker", "widget", "to", "the", "current", "font", "settings", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xrichtextedit/xrichtextedit.py#L708-L714
train
bitesofcode/projexui
projexui/widgets/xchartwidget/xchartwidgetitem.py
XChartWidgetItem.startDrag
def startDrag(self, data): """ Starts dragging information from this chart widget based on the dragData associated with this item. """ if not data: return widget = self.scene().chartWidget() drag = QDrag(widget) drag.setMimeData(data) drag.exec_()
python
def startDrag(self, data): """ Starts dragging information from this chart widget based on the dragData associated with this item. """ if not data: return widget = self.scene().chartWidget() drag = QDrag(widget) drag.setMimeData(data) drag.exec_()
[ "def", "startDrag", "(", "self", ",", "data", ")", ":", "if", "not", "data", ":", "return", "widget", "=", "self", ".", "scene", "(", ")", ".", "chartWidget", "(", ")", "drag", "=", "QDrag", "(", "widget", ")", "drag", ".", "setMimeData", "(", "data", ")", "drag", ".", "exec_", "(", ")" ]
Starts dragging information from this chart widget based on the dragData associated with this item.
[ "Starts", "dragging", "information", "from", "this", "chart", "widget", "based", "on", "the", "dragData", "associated", "with", "this", "item", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xchartwidget/xchartwidgetitem.py#L740-L751
train
bitesofcode/projexui
projexui/widgets/xoverlaywizard.py
XOverlayWizardPage.adjustMargins
def adjustMargins(self): """ Adjusts the margins to incorporate enough room for the widget's title and sub-title. """ y = 0 height = 0 if self._titleLabel.text(): height += self._titleLabel.height() + 3 y += height if self._subTitleLabel.text(): self._subTitleLabel.move(0, y) height += self._subTitleLabel.height() + 3 self.setContentsMargins(0, height, 0, 0)
python
def adjustMargins(self): """ Adjusts the margins to incorporate enough room for the widget's title and sub-title. """ y = 0 height = 0 if self._titleLabel.text(): height += self._titleLabel.height() + 3 y += height if self._subTitleLabel.text(): self._subTitleLabel.move(0, y) height += self._subTitleLabel.height() + 3 self.setContentsMargins(0, height, 0, 0)
[ "def", "adjustMargins", "(", "self", ")", ":", "y", "=", "0", "height", "=", "0", "if", "self", ".", "_titleLabel", ".", "text", "(", ")", ":", "height", "+=", "self", ".", "_titleLabel", ".", "height", "(", ")", "+", "3", "y", "+=", "height", "if", "self", ".", "_subTitleLabel", ".", "text", "(", ")", ":", "self", ".", "_subTitleLabel", ".", "move", "(", "0", ",", "y", ")", "height", "+=", "self", ".", "_subTitleLabel", ".", "height", "(", ")", "+", "3", "self", ".", "setContentsMargins", "(", "0", ",", "height", ",", "0", ",", "0", ")" ]
Adjusts the margins to incorporate enough room for the widget's title and sub-title.
[ "Adjusts", "the", "margins", "to", "incorporate", "enough", "room", "for", "the", "widget", "s", "title", "and", "sub", "-", "title", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywizard.py#L45-L59
train
bitesofcode/projexui
projexui/widgets/xoverlaywizard.py
XOverlayWizardPage.nextId
def nextId(self): """ Returns the next id for this page. By default, it will provide the next id from the wizard, but this method can be overloaded to create a custom path. If -1 is returned, then it will be considered the final page. :return <int> """ if self._nextId is not None: return self._nextId wizard = self.wizard() curr_id = wizard.currentId() all_ids = wizard.pageIds() try: return all_ids[all_ids.index(curr_id)+1] except IndexError: return -1
python
def nextId(self): """ Returns the next id for this page. By default, it will provide the next id from the wizard, but this method can be overloaded to create a custom path. If -1 is returned, then it will be considered the final page. :return <int> """ if self._nextId is not None: return self._nextId wizard = self.wizard() curr_id = wizard.currentId() all_ids = wizard.pageIds() try: return all_ids[all_ids.index(curr_id)+1] except IndexError: return -1
[ "def", "nextId", "(", "self", ")", ":", "if", "self", ".", "_nextId", "is", "not", "None", ":", "return", "self", ".", "_nextId", "wizard", "=", "self", ".", "wizard", "(", ")", "curr_id", "=", "wizard", ".", "currentId", "(", ")", "all_ids", "=", "wizard", ".", "pageIds", "(", ")", "try", ":", "return", "all_ids", "[", "all_ids", ".", "index", "(", "curr_id", ")", "+", "1", "]", "except", "IndexError", ":", "return", "-", "1" ]
Returns the next id for this page. By default, it will provide the next id from the wizard, but this method can be overloaded to create a custom path. If -1 is returned, then it will be considered the final page. :return <int>
[ "Returns", "the", "next", "id", "for", "this", "page", ".", "By", "default", "it", "will", "provide", "the", "next", "id", "from", "the", "wizard", "but", "this", "method", "can", "be", "overloaded", "to", "create", "a", "custom", "path", ".", "If", "-", "1", "is", "returned", "then", "it", "will", "be", "considered", "the", "final", "page", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywizard.py#L121-L138
train
bitesofcode/projexui
projexui/widgets/xoverlaywizard.py
XOverlayWizardPage.setSubTitle
def setSubTitle(self, title): """ Sets the sub-title for this page to the inputed title. :param title | <str> """ self._subTitleLabel.setText(title) self._subTitleLabel.adjustSize() self.adjustMargins()
python
def setSubTitle(self, title): """ Sets the sub-title for this page to the inputed title. :param title | <str> """ self._subTitleLabel.setText(title) self._subTitleLabel.adjustSize() self.adjustMargins()
[ "def", "setSubTitle", "(", "self", ",", "title", ")", ":", "self", ".", "_subTitleLabel", ".", "setText", "(", "title", ")", "self", ".", "_subTitleLabel", ".", "adjustSize", "(", ")", "self", ".", "adjustMargins", "(", ")" ]
Sets the sub-title for this page to the inputed title. :param title | <str>
[ "Sets", "the", "sub", "-", "title", "for", "this", "page", "to", "the", "inputed", "title", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywizard.py#L174-L182
train
bitesofcode/projexui
projexui/widgets/xoverlaywizard.py
XOverlayWizardPage.setTitle
def setTitle(self, title): """ Sets the title for this page to the inputed title. :param title | <str> """ self._titleLabel.setText(title) self._titleLabel.adjustSize() self.adjustMargins()
python
def setTitle(self, title): """ Sets the title for this page to the inputed title. :param title | <str> """ self._titleLabel.setText(title) self._titleLabel.adjustSize() self.adjustMargins()
[ "def", "setTitle", "(", "self", ",", "title", ")", ":", "self", ".", "_titleLabel", ".", "setText", "(", "title", ")", "self", ".", "_titleLabel", ".", "adjustSize", "(", ")", "self", ".", "adjustMargins", "(", ")" ]
Sets the title for this page to the inputed title. :param title | <str>
[ "Sets", "the", "title", "for", "this", "page", "to", "the", "inputed", "title", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywizard.py#L192-L200
train
bitesofcode/projexui
projexui/widgets/xoverlaywizard.py
XOverlayWizard.adjustSize
def adjustSize(self): """ Adjusts the size of this wizard and its page contents to the inputed size. :param size | <QtCore.QSize> """ super(XOverlayWizard, self).adjustSize() # adjust the page size page_size = self.pageSize() # resize the current page to the inputed size x = (self.width() - page_size.width()) / 2 y = (self.height() - page_size.height()) / 2 btn_height = max([btn.height() for btn in self._buttons.values()]) curr_page = self.currentPage() for page in self._pages.values(): page.resize(page_size.width(), page_size.height() - btn_height - 6) if page == curr_page: page.move(x, y) else: page.move(self.width(), y) # move the left most buttons y += page_size.height() - btn_height left_btns = (self._buttons[self.WizardButton.HelpButton], self._buttons[self.WizardButton.BackButton]) for btn in left_btns: if btn.isVisible(): btn.move(x, y) btn.raise_() x += btn.width() + 6 # move the right buttons x = self.width() - (self.width() - page_size.width()) / 2 for key in reversed(sorted(self._buttons.keys())): btn = self._buttons[key] if not btn.isVisible() or btn in left_btns: continue btn.move(x - btn.width(), y) btn.raise_() x -= btn.width() + 6
python
def adjustSize(self): """ Adjusts the size of this wizard and its page contents to the inputed size. :param size | <QtCore.QSize> """ super(XOverlayWizard, self).adjustSize() # adjust the page size page_size = self.pageSize() # resize the current page to the inputed size x = (self.width() - page_size.width()) / 2 y = (self.height() - page_size.height()) / 2 btn_height = max([btn.height() for btn in self._buttons.values()]) curr_page = self.currentPage() for page in self._pages.values(): page.resize(page_size.width(), page_size.height() - btn_height - 6) if page == curr_page: page.move(x, y) else: page.move(self.width(), y) # move the left most buttons y += page_size.height() - btn_height left_btns = (self._buttons[self.WizardButton.HelpButton], self._buttons[self.WizardButton.BackButton]) for btn in left_btns: if btn.isVisible(): btn.move(x, y) btn.raise_() x += btn.width() + 6 # move the right buttons x = self.width() - (self.width() - page_size.width()) / 2 for key in reversed(sorted(self._buttons.keys())): btn = self._buttons[key] if not btn.isVisible() or btn in left_btns: continue btn.move(x - btn.width(), y) btn.raise_() x -= btn.width() + 6
[ "def", "adjustSize", "(", "self", ")", ":", "super", "(", "XOverlayWizard", ",", "self", ")", ".", "adjustSize", "(", ")", "# adjust the page size", "page_size", "=", "self", ".", "pageSize", "(", ")", "# resize the current page to the inputed size", "x", "=", "(", "self", ".", "width", "(", ")", "-", "page_size", ".", "width", "(", ")", ")", "/", "2", "y", "=", "(", "self", ".", "height", "(", ")", "-", "page_size", ".", "height", "(", ")", ")", "/", "2", "btn_height", "=", "max", "(", "[", "btn", ".", "height", "(", ")", "for", "btn", "in", "self", ".", "_buttons", ".", "values", "(", ")", "]", ")", "curr_page", "=", "self", ".", "currentPage", "(", ")", "for", "page", "in", "self", ".", "_pages", ".", "values", "(", ")", ":", "page", ".", "resize", "(", "page_size", ".", "width", "(", ")", ",", "page_size", ".", "height", "(", ")", "-", "btn_height", "-", "6", ")", "if", "page", "==", "curr_page", ":", "page", ".", "move", "(", "x", ",", "y", ")", "else", ":", "page", ".", "move", "(", "self", ".", "width", "(", ")", ",", "y", ")", "# move the left most buttons", "y", "+=", "page_size", ".", "height", "(", ")", "-", "btn_height", "left_btns", "=", "(", "self", ".", "_buttons", "[", "self", ".", "WizardButton", ".", "HelpButton", "]", ",", "self", ".", "_buttons", "[", "self", ".", "WizardButton", ".", "BackButton", "]", ")", "for", "btn", "in", "left_btns", ":", "if", "btn", ".", "isVisible", "(", ")", ":", "btn", ".", "move", "(", "x", ",", "y", ")", "btn", ".", "raise_", "(", ")", "x", "+=", "btn", ".", "width", "(", ")", "+", "6", "# move the right buttons", "x", "=", "self", ".", "width", "(", ")", "-", "(", "self", ".", "width", "(", ")", "-", "page_size", ".", "width", "(", ")", ")", "/", "2", "for", "key", "in", "reversed", "(", "sorted", "(", "self", ".", "_buttons", ".", "keys", "(", ")", ")", ")", ":", "btn", "=", "self", ".", "_buttons", "[", "key", "]", "if", "not", "btn", ".", "isVisible", "(", ")", "or", "btn", "in", "left_btns", ":", "continue", "btn", ".", "move", "(", "x", "-", "btn", ".", "width", "(", ")", ",", "y", ")", "btn", ".", "raise_", "(", ")", "x", "-=", "btn", ".", "width", "(", ")", "+", "6" ]
Adjusts the size of this wizard and its page contents to the inputed size. :param size | <QtCore.QSize>
[ "Adjusts", "the", "size", "of", "this", "wizard", "and", "its", "page", "contents", "to", "the", "inputed", "size", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywizard.py#L319-L361
train
bitesofcode/projexui
projexui/widgets/xoverlaywizard.py
XOverlayWizard.canGoBack
def canGoBack(self): """ Returns whether or not this wizard can move forward. :return <bool> """ try: backId = self._navigation.index(self.currentId())-1 if backId >= 0: self._navigation[backId] else: return False except StandardError: return False else: return True
python
def canGoBack(self): """ Returns whether or not this wizard can move forward. :return <bool> """ try: backId = self._navigation.index(self.currentId())-1 if backId >= 0: self._navigation[backId] else: return False except StandardError: return False else: return True
[ "def", "canGoBack", "(", "self", ")", ":", "try", ":", "backId", "=", "self", ".", "_navigation", ".", "index", "(", "self", ".", "currentId", "(", ")", ")", "-", "1", "if", "backId", ">=", "0", ":", "self", ".", "_navigation", "[", "backId", "]", "else", ":", "return", "False", "except", "StandardError", ":", "return", "False", "else", ":", "return", "True" ]
Returns whether or not this wizard can move forward. :return <bool>
[ "Returns", "whether", "or", "not", "this", "wizard", "can", "move", "forward", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywizard.py#L448-L463
train
bitesofcode/projexui
projexui/widgets/xoverlaywizard.py
XOverlayWizard.pageSize
def pageSize(self): """ Returns the current page size for this wizard. :return <QtCore.QSize> """ # update the size based on the new size page_size = self.fixedPageSize() if page_size.isEmpty(): w = self.width() - 80 h = self.height() - 80 min_w = self.minimumPageSize().width() min_h = self.minimumPageSize().height() max_w = self.maximumPageSize().width() max_h = self.maximumPageSize().height() page_size = QtCore.QSize(min(max(min_w, w), max_w), min(max(min_h, h), max_h)) return page_size
python
def pageSize(self): """ Returns the current page size for this wizard. :return <QtCore.QSize> """ # update the size based on the new size page_size = self.fixedPageSize() if page_size.isEmpty(): w = self.width() - 80 h = self.height() - 80 min_w = self.minimumPageSize().width() min_h = self.minimumPageSize().height() max_w = self.maximumPageSize().width() max_h = self.maximumPageSize().height() page_size = QtCore.QSize(min(max(min_w, w), max_w), min(max(min_h, h), max_h)) return page_size
[ "def", "pageSize", "(", "self", ")", ":", "# update the size based on the new size", "page_size", "=", "self", ".", "fixedPageSize", "(", ")", "if", "page_size", ".", "isEmpty", "(", ")", ":", "w", "=", "self", ".", "width", "(", ")", "-", "80", "h", "=", "self", ".", "height", "(", ")", "-", "80", "min_w", "=", "self", ".", "minimumPageSize", "(", ")", ".", "width", "(", ")", "min_h", "=", "self", ".", "minimumPageSize", "(", ")", ".", "height", "(", ")", "max_w", "=", "self", ".", "maximumPageSize", "(", ")", ".", "width", "(", ")", "max_h", "=", "self", ".", "maximumPageSize", "(", ")", ".", "height", "(", ")", "page_size", "=", "QtCore", ".", "QSize", "(", "min", "(", "max", "(", "min_w", ",", "w", ")", ",", "max_w", ")", ",", "min", "(", "max", "(", "min_h", ",", "h", ")", ",", "max_h", ")", ")", "return", "page_size" ]
Returns the current page size for this wizard. :return <QtCore.QSize>
[ "Returns", "the", "current", "page", "size", "for", "this", "wizard", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywizard.py#L644-L663
train
bitesofcode/projexui
projexui/widgets/xoverlaywizard.py
XOverlayWizard.restart
def restart(self): """ Restarts the whole wizard from the beginning. """ # hide all of the pages for page in self._pages.values(): page.hide() pageId = self.startId() try: first_page = self._pages[pageId] except KeyError: return self._currentId = pageId self._navigation = [pageId] page_size = self.pageSize() x = (self.width() - page_size.width()) / 2 y = (self.height() - page_size.height()) / 2 first_page.move(self.width()+first_page.width(), y) first_page.show() # animate the current page out anim_out = QtCore.QPropertyAnimation(self) anim_out.setTargetObject(first_page) anim_out.setPropertyName('pos') anim_out.setStartValue(first_page.pos()) anim_out.setEndValue(QtCore.QPoint(x, y)) anim_out.setDuration(self.animationSpeed()) anim_out.setEasingCurve(QtCore.QEasingCurve.Linear) anim_out.finished.connect(anim_out.deleteLater) # update the button states self._buttons[self.WizardButton.BackButton].setVisible(False) self._buttons[self.WizardButton.NextButton].setVisible(self.canGoForward()) self._buttons[self.WizardButton.CommitButton].setVisible(first_page.isCommitPage()) self._buttons[self.WizardButton.FinishButton].setVisible(first_page.isFinalPage()) self.adjustSize() first_page.initializePage() self.currentIdChanged.emit(pageId) anim_out.start()
python
def restart(self): """ Restarts the whole wizard from the beginning. """ # hide all of the pages for page in self._pages.values(): page.hide() pageId = self.startId() try: first_page = self._pages[pageId] except KeyError: return self._currentId = pageId self._navigation = [pageId] page_size = self.pageSize() x = (self.width() - page_size.width()) / 2 y = (self.height() - page_size.height()) / 2 first_page.move(self.width()+first_page.width(), y) first_page.show() # animate the current page out anim_out = QtCore.QPropertyAnimation(self) anim_out.setTargetObject(first_page) anim_out.setPropertyName('pos') anim_out.setStartValue(first_page.pos()) anim_out.setEndValue(QtCore.QPoint(x, y)) anim_out.setDuration(self.animationSpeed()) anim_out.setEasingCurve(QtCore.QEasingCurve.Linear) anim_out.finished.connect(anim_out.deleteLater) # update the button states self._buttons[self.WizardButton.BackButton].setVisible(False) self._buttons[self.WizardButton.NextButton].setVisible(self.canGoForward()) self._buttons[self.WizardButton.CommitButton].setVisible(first_page.isCommitPage()) self._buttons[self.WizardButton.FinishButton].setVisible(first_page.isFinalPage()) self.adjustSize() first_page.initializePage() self.currentIdChanged.emit(pageId) anim_out.start()
[ "def", "restart", "(", "self", ")", ":", "# hide all of the pages", "for", "page", "in", "self", ".", "_pages", ".", "values", "(", ")", ":", "page", ".", "hide", "(", ")", "pageId", "=", "self", ".", "startId", "(", ")", "try", ":", "first_page", "=", "self", ".", "_pages", "[", "pageId", "]", "except", "KeyError", ":", "return", "self", ".", "_currentId", "=", "pageId", "self", ".", "_navigation", "=", "[", "pageId", "]", "page_size", "=", "self", ".", "pageSize", "(", ")", "x", "=", "(", "self", ".", "width", "(", ")", "-", "page_size", ".", "width", "(", ")", ")", "/", "2", "y", "=", "(", "self", ".", "height", "(", ")", "-", "page_size", ".", "height", "(", ")", ")", "/", "2", "first_page", ".", "move", "(", "self", ".", "width", "(", ")", "+", "first_page", ".", "width", "(", ")", ",", "y", ")", "first_page", ".", "show", "(", ")", "# animate the current page out", "anim_out", "=", "QtCore", ".", "QPropertyAnimation", "(", "self", ")", "anim_out", ".", "setTargetObject", "(", "first_page", ")", "anim_out", ".", "setPropertyName", "(", "'pos'", ")", "anim_out", ".", "setStartValue", "(", "first_page", ".", "pos", "(", ")", ")", "anim_out", ".", "setEndValue", "(", "QtCore", ".", "QPoint", "(", "x", ",", "y", ")", ")", "anim_out", ".", "setDuration", "(", "self", ".", "animationSpeed", "(", ")", ")", "anim_out", ".", "setEasingCurve", "(", "QtCore", ".", "QEasingCurve", ".", "Linear", ")", "anim_out", ".", "finished", ".", "connect", "(", "anim_out", ".", "deleteLater", ")", "# update the button states", "self", ".", "_buttons", "[", "self", ".", "WizardButton", ".", "BackButton", "]", ".", "setVisible", "(", "False", ")", "self", ".", "_buttons", "[", "self", ".", "WizardButton", ".", "NextButton", "]", ".", "setVisible", "(", "self", ".", "canGoForward", "(", ")", ")", "self", ".", "_buttons", "[", "self", ".", "WizardButton", ".", "CommitButton", "]", ".", "setVisible", "(", "first_page", ".", "isCommitPage", "(", ")", ")", "self", ".", "_buttons", "[", "self", ".", "WizardButton", ".", "FinishButton", "]", ".", "setVisible", "(", "first_page", ".", "isFinalPage", "(", ")", ")", "self", ".", "adjustSize", "(", ")", "first_page", ".", "initializePage", "(", ")", "self", ".", "currentIdChanged", ".", "emit", "(", "pageId", ")", "anim_out", ".", "start", "(", ")" ]
Restarts the whole wizard from the beginning.
[ "Restarts", "the", "whole", "wizard", "from", "the", "beginning", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywizard.py#L673-L716
train
bitesofcode/projexui
projexui/widgets/xoverlaywizard.py
XOverlayWizard.removePage
def removePage(self, pageId): """ Removes the inputed page from this wizard. :param pageId | <int> """ try: self._pages[pageId].deleteLater() del self._pages[pageId] except KeyError: pass
python
def removePage(self, pageId): """ Removes the inputed page from this wizard. :param pageId | <int> """ try: self._pages[pageId].deleteLater() del self._pages[pageId] except KeyError: pass
[ "def", "removePage", "(", "self", ",", "pageId", ")", ":", "try", ":", "self", ".", "_pages", "[", "pageId", "]", ".", "deleteLater", "(", ")", "del", "self", ".", "_pages", "[", "pageId", "]", "except", "KeyError", ":", "pass" ]
Removes the inputed page from this wizard. :param pageId | <int>
[ "Removes", "the", "inputed", "page", "from", "this", "wizard", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywizard.py#L718-L728
train
bitesofcode/projexui
projexui/widgets/xoverlaywizard.py
XOverlayWizard.setButton
def setButton(self, which, button): """ Sets the button for this wizard for the inputed type. :param which | <XOverlayWizard.WizardButton> button | <QtGui.QPushButton> """ try: self._buttons[which].deleteLater() except KeyError: pass button.setParent(self) self._buttons[which] = button
python
def setButton(self, which, button): """ Sets the button for this wizard for the inputed type. :param which | <XOverlayWizard.WizardButton> button | <QtGui.QPushButton> """ try: self._buttons[which].deleteLater() except KeyError: pass button.setParent(self) self._buttons[which] = button
[ "def", "setButton", "(", "self", ",", "which", ",", "button", ")", ":", "try", ":", "self", ".", "_buttons", "[", "which", "]", ".", "deleteLater", "(", ")", "except", "KeyError", ":", "pass", "button", ".", "setParent", "(", "self", ")", "self", ".", "_buttons", "[", "which", "]", "=", "button" ]
Sets the button for this wizard for the inputed type. :param which | <XOverlayWizard.WizardButton> button | <QtGui.QPushButton>
[ "Sets", "the", "button", "for", "this", "wizard", "for", "the", "inputed", "type", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywizard.py#L747-L760
train
bitesofcode/projexui
projexui/widgets/xoverlaywizard.py
XOverlayWizard.setButtonText
def setButtonText(self, which, text): """ Sets the display text for the inputed button to the given text. :param which | <XOverlayWizard.WizardButton> text | <str> """ try: self._buttons[which].setText(text) except KeyError: pass
python
def setButtonText(self, which, text): """ Sets the display text for the inputed button to the given text. :param which | <XOverlayWizard.WizardButton> text | <str> """ try: self._buttons[which].setText(text) except KeyError: pass
[ "def", "setButtonText", "(", "self", ",", "which", ",", "text", ")", ":", "try", ":", "self", ".", "_buttons", "[", "which", "]", ".", "setText", "(", "text", ")", "except", "KeyError", ":", "pass" ]
Sets the display text for the inputed button to the given text. :param which | <XOverlayWizard.WizardButton> text | <str>
[ "Sets", "the", "display", "text", "for", "the", "inputed", "button", "to", "the", "given", "text", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywizard.py#L762-L772
train
bitesofcode/projexui
projexui/widgets/xoverlaywizard.py
XOverlayWizard.setPage
def setPage(self, pageId, page): """ Sets the page and id for the given page vs. auto-constructing it. This will allow the developer to create a custom order for IDs. :param pageId | <int> page | <projexui.widgets.xoverlaywizard.XOverlayWizardPage> """ page.setParent(self) if self.property("useShadow") is not False: # create the drop shadow effect effect = QtGui.QGraphicsDropShadowEffect(page) effect.setColor(QtGui.QColor('black')) effect.setBlurRadius(50) effect.setOffset(0, 0) page.setGraphicsEffect(effect) self._pages[pageId] = page if self._startId == -1: self._startId = pageId
python
def setPage(self, pageId, page): """ Sets the page and id for the given page vs. auto-constructing it. This will allow the developer to create a custom order for IDs. :param pageId | <int> page | <projexui.widgets.xoverlaywizard.XOverlayWizardPage> """ page.setParent(self) if self.property("useShadow") is not False: # create the drop shadow effect effect = QtGui.QGraphicsDropShadowEffect(page) effect.setColor(QtGui.QColor('black')) effect.setBlurRadius(50) effect.setOffset(0, 0) page.setGraphicsEffect(effect) self._pages[pageId] = page if self._startId == -1: self._startId = pageId
[ "def", "setPage", "(", "self", ",", "pageId", ",", "page", ")", ":", "page", ".", "setParent", "(", "self", ")", "if", "self", ".", "property", "(", "\"useShadow\"", ")", "is", "not", "False", ":", "# create the drop shadow effect", "effect", "=", "QtGui", ".", "QGraphicsDropShadowEffect", "(", "page", ")", "effect", ".", "setColor", "(", "QtGui", ".", "QColor", "(", "'black'", ")", ")", "effect", ".", "setBlurRadius", "(", "50", ")", "effect", ".", "setOffset", "(", "0", ",", "0", ")", "page", ".", "setGraphicsEffect", "(", "effect", ")", "self", ".", "_pages", "[", "pageId", "]", "=", "page", "if", "self", ".", "_startId", "==", "-", "1", ":", "self", ".", "_startId", "=", "pageId" ]
Sets the page and id for the given page vs. auto-constructing it. This will allow the developer to create a custom order for IDs. :param pageId | <int> page | <projexui.widgets.xoverlaywizard.XOverlayWizardPage>
[ "Sets", "the", "page", "and", "id", "for", "the", "given", "page", "vs", ".", "auto", "-", "constructing", "it", ".", "This", "will", "allow", "the", "developer", "to", "create", "a", "custom", "order", "for", "IDs", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywizard.py#L816-L837
train