repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
xtream1101/web-wrapper
web_wrapper/selenium_utils.py
SeleniumUtils._get_site
python
def _get_site(self, url, headers, cookies, timeout, driver_args, driver_kwargs): try: # **TODO**: Find what exception this will throw and catch it and call # self.driver.execute_script("window.stop()") # Then still try and get the source from the page self.drive...
Try and return page content in the requested format using selenium
train
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/selenium_utils.py#L63-L101
null
class SeleniumUtils: def get_selenium_header(self): """ Return server response headers from selenium request Also includes the keys `status-code` and `status-text` """ javascript = """ function parseResponseHeaders( headerStr ){ va...
xtream1101/web-wrapper
web_wrapper/selenium_utils.py
SeleniumUtils.hover
python
def hover(self, element): javascript = """var evObj = document.createEvent('MouseEvents'); evObj.initMouseEvent(\"mouseover\", true, false, window, 0, 0, 0, 0, 0, \ false, false, false, false, 0, null); arguments[0].dispatchEvent(evObj);"""...
In selenium, move cursor over an element :element: Object found using driver.find_...("element_class/id/etc")
train
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/selenium_utils.py#L103-L114
null
class SeleniumUtils: def get_selenium_header(self): """ Return server response headers from selenium request Also includes the keys `status-code` and `status-text` """ javascript = """ function parseResponseHeaders( headerStr ){ va...
xtream1101/web-wrapper
web_wrapper/selenium_utils.py
SeleniumUtils.scroll_to_bottom
python
def scroll_to_bottom(self): if self.driver.selenium is not None: try: self.driver.selenium.execute_script("window.scrollTo(0, document.body.scrollHeight);") except WebDriverException: self.driver.selenium.execute_script("window.scrollTo(0, 50000);") ...
Scoll to the very bottom of the page TODO: add increment & delay options to scoll slowly down the whole page to let each section load in
train
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/selenium_utils.py#L126-L137
null
class SeleniumUtils: def get_selenium_header(self): """ Return server response headers from selenium request Also includes the keys `status-code` and `status-text` """ javascript = """ function parseResponseHeaders( headerStr ){ va...
xtream1101/web-wrapper
web_wrapper/selenium_utils.py
SeleniumUtils.chrome_fullpage_screenshot
python
def chrome_fullpage_screenshot(self, file, delay=0): total_width = self.driver.execute_script("return document.body.offsetWidth") total_height = self.driver.execute_script("return document.body.parentNode.scrollHeight") viewport_width = self.driver.execute_script("return document.body.clientWidt...
Fullscreen workaround for chrome Source: http://seleniumpythonqa.blogspot.com/2015/08/generate-full-page-screenshot-in-chrome.html
train
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/selenium_utils.py#L139-L204
null
class SeleniumUtils: def get_selenium_header(self): """ Return server response headers from selenium request Also includes the keys `status-code` and `status-text` """ javascript = """ function parseResponseHeaders( headerStr ){ va...
xtream1101/web-wrapper
web_wrapper/driver_selenium_phantomjs.py
DriverSeleniumPhantomJS.set_proxy
python
def set_proxy(self, proxy, update=True): update_web_driver = False if self.current_proxy != proxy: # Did we change proxies? update_web_driver = True self.current_proxy = proxy if proxy is None: self.driver_args['service_args'] = self.default_service_a...
Set proxy for requests session
train
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/driver_selenium_phantomjs.py#L63-L86
[ "def _update(self):\n \"\"\"\n Re create the web driver with the new proxy or header settings\n \"\"\"\n logger.debug(\"Update phantomjs web driver\")\n self.quit()\n self._create_session()\n" ]
class DriverSeleniumPhantomJS(Web, SeleniumUtils): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.driver_type = 'selenium_phantomjs' self.default_service_args = self.driver_args.get('service_args', []) self.driver_args['service_args'] = self.default_serv...
xtream1101/web-wrapper
web_wrapper/driver_selenium_phantomjs.py
DriverSeleniumPhantomJS._create_session
python
def _create_session(self): logger.debug("Create new phantomjs web driver") self.driver = webdriver.PhantomJS(desired_capabilities=self.dcap, **self.driver_args) self.set_cookies(self.current_cookies) self.driver.set_window_size(1920, 1080)
Creates a fresh session with no/default headers and proxies
train
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/driver_selenium_phantomjs.py#L92-L100
[ "def set_cookies(self, cookies):\n # TODO: Does not seem to actually set them correctly\n self.driver.delete_all_cookies()\n for cookie in cookies:\n print(cookie)\n self.driver.add_cookie({k: cookie[k] for k in ('name', 'value', 'path', 'expirationDate', 'expiry', 'domain') if k in cookie})\...
class DriverSeleniumPhantomJS(Web, SeleniumUtils): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.driver_type = 'selenium_phantomjs' self.default_service_args = self.driver_args.get('service_args', []) self.driver_args['service_args'] = self.default_serv...
xtream1101/web-wrapper
web_wrapper/driver_selenium_phantomjs.py
DriverSeleniumPhantomJS.reset
python
def reset(self): # Kill old connection self.quit() # Clear proxy data self.driver_args['service_args'] = self.default_service_args # Clear headers self.dcap = dict(webdriver.DesiredCapabilities.PHANTOMJS) # Create new web driver self._create_session()
Kills old session and creates a new one with no proxies or headers
train
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/driver_selenium_phantomjs.py#L110-L121
[ "def _create_session(self):\n \"\"\"\n Creates a fresh session with no/default headers and proxies\n \"\"\"\n logger.debug(\"Create new phantomjs web driver\")\n self.driver = webdriver.PhantomJS(desired_capabilities=self.dcap,\n **self.driver_args)\n self.set_...
class DriverSeleniumPhantomJS(Web, SeleniumUtils): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.driver_type = 'selenium_phantomjs' self.default_service_args = self.driver_args.get('service_args', []) self.driver_args['service_args'] = self.default_serv...
xtream1101/web-wrapper
web_wrapper/driver_selenium_chrome.py
DriverSeleniumChrome.set_proxy
python
def set_proxy(self, proxy, update=True): update_web_driver = False if self.current_proxy != proxy: # Did we change proxies? update_web_driver = True self.current_proxy = proxy if proxy is None: # TODO: Need to be able to remove a proxy if one is set ...
Set proxy for chrome session
train
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/driver_selenium_chrome.py#L46-L71
[ "def _update(self):\n \"\"\"\n Re create the web driver with the new proxy or header settings\n \"\"\"\n logger.debug(\"Update chrome web driver\")\n self.quit()\n self._create_session()\n", "def _proxy_extension(self, proxy_parts):\n \"\"\"\n Creates a chrome extension for the proxy\n ...
class DriverSeleniumChrome(Web, SeleniumUtils): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.driver_type = 'selenium_chrome' self.opts = webdriver.ChromeOptions() self.update_headers(self.current_headers, update=False) self.set_proxy(self.curre...
xtream1101/web-wrapper
web_wrapper/driver_selenium_chrome.py
DriverSeleniumChrome._create_session
python
def _create_session(self): self.driver = webdriver.Chrome(chrome_options=self.opts, **self.driver_args) self.driver.set_window_size(1920, 1080)
Creates a fresh session with no/default headers and proxies
train
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/driver_selenium_chrome.py#L73-L78
null
class DriverSeleniumChrome(Web, SeleniumUtils): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.driver_type = 'selenium_chrome' self.opts = webdriver.ChromeOptions() self.update_headers(self.current_headers, update=False) self.set_proxy(self.curre...
xtream1101/web-wrapper
web_wrapper/driver_selenium_chrome.py
DriverSeleniumChrome.reset
python
def reset(self): # Kill old connection self.quit() # Clear chrome configs self.opts = webdriver.ChromeOptions() # Create new web driver self._create_session()
Kills old session and creates a new one with no proxies or headers
train
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/driver_selenium_chrome.py#L88-L97
[ "def _create_session(self):\n \"\"\"\n Creates a fresh session with no/default headers and proxies\n \"\"\"\n self.driver = webdriver.Chrome(chrome_options=self.opts, **self.driver_args)\n self.driver.set_window_size(1920, 1080)\n", "def quit(self):\n \"\"\"\n Generic function to close distro...
class DriverSeleniumChrome(Web, SeleniumUtils): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.driver_type = 'selenium_chrome' self.opts = webdriver.ChromeOptions() self.update_headers(self.current_headers, update=False) self.set_proxy(self.curre...
xtream1101/web-wrapper
web_wrapper/driver_selenium_chrome.py
DriverSeleniumChrome._proxy_extension
python
def _proxy_extension(self, proxy_parts): import zipfile manifest_json = """ { "version": "1.0.0", "manifest_version": 2, "name": "Chrome Proxy", "permissions": [ ...
Creates a chrome extension for the proxy Only need to be done this way when using a proxy with auth
train
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/driver_selenium_chrome.py#L110-L173
null
class DriverSeleniumChrome(Web, SeleniumUtils): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.driver_type = 'selenium_chrome' self.opts = webdriver.ChromeOptions() self.update_headers(self.current_headers, update=False) self.set_proxy(self.curre...
xtream1101/web-wrapper
web_wrapper/driver_selenium_chrome.py
DriverSeleniumChrome._header_extension
python
def _header_extension(self, remove_headers=[], add_or_modify_headers={}): import string import zipfile plugin_file = 'custom_headers_plugin.zip' if remove_headers is None: remove_headers = [] if add_or_modify_headers is None: add_or_modify_headers = {} ...
Create modheaders extension Source: https://vimmaniac.com/blog/bangal/modify-and-add-custom-headers-in-selenium-chrome-driver/ kwargs: remove_headers (list): headers name to remove add_or_modify_headers (dict): ie. {"Header-Name": "Header Value"} return str -> plugin p...
train
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/driver_selenium_chrome.py#L175-L279
null
class DriverSeleniumChrome(Web, SeleniumUtils): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.driver_type = 'selenium_chrome' self.opts = webdriver.ChromeOptions() self.update_headers(self.current_headers, update=False) self.set_proxy(self.curre...
xtream1101/web-wrapper
web_wrapper/driver_requests.py
DriverRequests.set_proxy
python
def set_proxy(self, proxy): # TODO: Validate proxy url format if proxy is None: self.driver.proxies = {'http': None, 'https': None } else: self.driver.proxies = {'http': proxy, ...
Set proxy for requests session
train
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/driver_requests.py#L54-L69
null
class DriverRequests(Web): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.driver_type = 'requests' self._create_session() # Headers Set/Get def get_headers(self): return self.driver.headers def set_headers(self, headers): self.driv...
xtream1101/web-wrapper
web_wrapper/driver_requests.py
DriverRequests._create_session
python
def _create_session(self): self.driver = requests.Session(**self.driver_args) # Set default headers self.update_headers(self.current_headers) self.update_cookies(self.current_cookies) self.set_proxy(self.current_proxy)
Creates a fresh session with the default header (random UA)
train
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/driver_requests.py#L75-L83
[ "def update_headers(self, headers):\n self.driver.headers.update(headers)\n", "def update_cookies(self, cookies):\n for cookie in self._clean_cookies(cookies):\n self.driver.cookies.update(cookie)\n", "def set_proxy(self, proxy):\n \"\"\"\n Set proxy for requests session\n \"\"\"\n # TO...
class DriverRequests(Web): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.driver_type = 'requests' self._create_session() # Headers Set/Get def get_headers(self): return self.driver.headers def set_headers(self, headers): self.driv...
xtream1101/web-wrapper
web_wrapper/driver_requests.py
DriverRequests._get_site
python
def _get_site(self, url, headers, cookies, timeout, driver_args, driver_kwargs): try: # Headers and cookies are combined to the ones stored in the requests session # Ones passed in here will override the ones in the session if they are the same key response = self.driver.get...
Try and return page content in the requested format using requests
train
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/driver_requests.py#L99-L125
null
class DriverRequests(Web): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.driver_type = 'requests' self._create_session() # Headers Set/Get def get_headers(self): return self.driver.headers def set_headers(self, headers): self.driv...
MacHu-GWU/windtalker-project
windtalker/asymmetric.py
AsymmetricCipher.newkeys
python
def newkeys(nbits=1024): pubkey, privkey = rsa.newkeys(nbits, poolsize=1) return pubkey, privkey
Create a new pair of public and private key pair to use.
train
https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/asymmetric.py#L48-L53
null
class AsymmetricCipher(BaseCipher): """ A asymmetric encryption algorithm utility class helps you easily encrypt/decrypt text and files. :param my_pubkey: your public key :param my_privkey: your private key :param his_pubkey: other's public key you use to encrypt message **中文文档** 非对称加...
MacHu-GWU/windtalker-project
windtalker/asymmetric.py
AsymmetricCipher.encrypt
python
def encrypt(self, binary, use_sign=True): token = rsa.encrypt(binary, self.his_pubkey) # encrypt it if use_sign: self.sign = rsa.sign(binary, self.my_privkey, "SHA-1") # sign it return token
Encrypt binary data. **中文文档** - 发送消息时只需要对方的pubkey - 如需使用签名, 则双方都需要持有对方的pubkey
train
https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/asymmetric.py#L55-L67
null
class AsymmetricCipher(BaseCipher): """ A asymmetric encryption algorithm utility class helps you easily encrypt/decrypt text and files. :param my_pubkey: your public key :param my_privkey: your private key :param his_pubkey: other's public key you use to encrypt message **中文文档** 非对称加...
MacHu-GWU/windtalker-project
windtalker/asymmetric.py
AsymmetricCipher.decrypt
python
def decrypt(self, token, signature=None): binary = rsa.decrypt(token, self.my_privkey) if signature: rsa.verify(binary, signature, self.his_pubkey) return binary
Decrypt binary data. **中文文档** - 接收消息时只需要自己的privkey - 如需使用签名, 则双方都需要持有对方的pubkey
train
https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/asymmetric.py#L69-L81
null
class AsymmetricCipher(BaseCipher): """ A asymmetric encryption algorithm utility class helps you easily encrypt/decrypt text and files. :param my_pubkey: your public key :param my_privkey: your private key :param his_pubkey: other's public key you use to encrypt message **中文文档** 非对称加...
MacHu-GWU/windtalker-project
windtalker/asymmetric.py
AsymmetricCipher.encrypt_file
python
def encrypt_file(self, path, output_path=None, overwrite=False, enable_verbose=True): path, output_path = files.process_dst_overwrite_args( src=path, dst=output_path, overwrite=overwrite, src_to_dst_func=...
Encrypt a file using rsa. RSA for big file encryption is very slow. For big file, I recommend to use symmetric encryption and use RSA to encrypt the password.
train
https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/asymmetric.py#L83-L100
[ "def process_dst_overwrite_args(src,\n dst=None,\n overwrite=True,\n src_to_dst_func=None):\n src = os.path.abspath(src)\n\n if dst is None:\n dst = src_to_dst_func(src)\n\n if not overwrite:\n if os.pat...
class AsymmetricCipher(BaseCipher): """ A asymmetric encryption algorithm utility class helps you easily encrypt/decrypt text and files. :param my_pubkey: your public key :param my_privkey: your private key :param his_pubkey: other's public key you use to encrypt message **中文文档** 非对称加...
MacHu-GWU/windtalker-project
windtalker/asymmetric.py
AsymmetricCipher.decrypt_file
python
def decrypt_file(self, path, output_path=None, overwrite=False, enable_verbose=True): path, output_path = files.process_dst_overwrite_args( src=path, dst=output_path, overwrite=overwrite, src_to_dst_func=...
Decrypt a file using rsa.
train
https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/asymmetric.py#L102-L116
[ "def process_dst_overwrite_args(src,\n dst=None,\n overwrite=True,\n src_to_dst_func=None):\n src = os.path.abspath(src)\n\n if dst is None:\n dst = src_to_dst_func(src)\n\n if not overwrite:\n if os.pat...
class AsymmetricCipher(BaseCipher): """ A asymmetric encryption algorithm utility class helps you easily encrypt/decrypt text and files. :param my_pubkey: your public key :param my_privkey: your private key :param his_pubkey: other's public key you use to encrypt message **中文文档** 非对称加...
MacHu-GWU/windtalker-project
windtalker/cipher.py
BaseCipher.encrypt_binary
python
def encrypt_binary(self, binary, *args, **kwargs): return self.encrypt(binary, *args, **kwargs)
input: bytes, output: bytes
train
https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/cipher.py#L55-L59
[ "def encrypt(self, binary, *args, **kwargs):\n \"\"\"\n Overwrite this method using your encrypt algorithm.\n\n :param binary: binary data you need to encrypt\n :return: encrypted_binary, encrypted binary data\n \"\"\"\n raise NotImplementedError\n" ]
class BaseCipher(object): """ Base cipher class. Any cipher utility class that using any encryption algorithm can be inherited from this base class. The only method you need to implement is :meth:`BaseCipher.encrypt` and :meth:`BaseCipher.decrypt`. Because once you can encrypt binary data, then...
MacHu-GWU/windtalker-project
windtalker/cipher.py
BaseCipher.decrypt_binary
python
def decrypt_binary(self, binary, *args, **kwargs): return self.decrypt(binary, *args, **kwargs)
input: bytes, output: bytes
train
https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/cipher.py#L61-L65
[ "def decrypt(self, binary, *args, **kwargs):\n \"\"\"\n Overwrite this method using your decrypt algorithm.\n\n :param binary: binary data you need to decrypt\n :return: decrypted_binary, decrypted binary data\n \"\"\"\n raise NotImplementedError\n" ]
class BaseCipher(object): """ Base cipher class. Any cipher utility class that using any encryption algorithm can be inherited from this base class. The only method you need to implement is :meth:`BaseCipher.encrypt` and :meth:`BaseCipher.decrypt`. Because once you can encrypt binary data, then...
MacHu-GWU/windtalker-project
windtalker/cipher.py
BaseCipher.encrypt_text
python
def encrypt_text(self, text, *args, **kwargs): b = text.encode("utf-8") token = self.encrypt(b, *args, **kwargs) return base64.b64encode(token).decode("utf-8")
Encrypt a string. input: unicode str, output: unicode str
train
https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/cipher.py#L67-L75
[ "def encrypt(self, binary, *args, **kwargs):\n \"\"\"\n Overwrite this method using your encrypt algorithm.\n\n :param binary: binary data you need to encrypt\n :return: encrypted_binary, encrypted binary data\n \"\"\"\n raise NotImplementedError\n" ]
class BaseCipher(object): """ Base cipher class. Any cipher utility class that using any encryption algorithm can be inherited from this base class. The only method you need to implement is :meth:`BaseCipher.encrypt` and :meth:`BaseCipher.decrypt`. Because once you can encrypt binary data, then...
MacHu-GWU/windtalker-project
windtalker/cipher.py
BaseCipher.decrypt_text
python
def decrypt_text(self, text, *args, **kwargs): b = text.encode("utf-8") token = base64.b64decode(b) return self.decrypt(token, *args, **kwargs).decode("utf-8")
Decrypt a string. input: unicode str, output: unicode str
train
https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/cipher.py#L77-L85
[ "def decrypt(self, binary, *args, **kwargs):\n \"\"\"\n Overwrite this method using your decrypt algorithm.\n\n :param binary: binary data you need to decrypt\n :return: decrypted_binary, decrypted binary data\n \"\"\"\n raise NotImplementedError\n" ]
class BaseCipher(object): """ Base cipher class. Any cipher utility class that using any encryption algorithm can be inherited from this base class. The only method you need to implement is :meth:`BaseCipher.encrypt` and :meth:`BaseCipher.decrypt`. Because once you can encrypt binary data, then...
MacHu-GWU/windtalker-project
windtalker/cipher.py
BaseCipher._show
python
def _show(self, message, indent=0, enable_verbose=True): # pragma: no cover if enable_verbose: print(" " * indent + message)
Message printer.
train
https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/cipher.py#L87-L91
null
class BaseCipher(object): """ Base cipher class. Any cipher utility class that using any encryption algorithm can be inherited from this base class. The only method you need to implement is :meth:`BaseCipher.encrypt` and :meth:`BaseCipher.decrypt`. Because once you can encrypt binary data, then...
MacHu-GWU/windtalker-project
windtalker/cipher.py
BaseCipher.encrypt_file
python
def encrypt_file(self, path, output_path=None, overwrite=False, stream=True, enable_verbose=True, **kwargs): path, output_path = files.process_dst_overwrite_args( src=path, d...
Encrypt a file. If output_path are not given, then try to use the path with a surfix appended. The default automatical file path handling is defined here :meth:`windtalker.files.get_encrypted_file_path` :param path: path of the file you need to encrypt :param output_path: encrypted file...
train
https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/cipher.py#L93-L125
[ "def process_dst_overwrite_args(src,\n dst=None,\n overwrite=True,\n src_to_dst_func=None):\n src = os.path.abspath(src)\n\n if dst is None:\n dst = src_to_dst_func(src)\n\n if not overwrite:\n if os.pat...
class BaseCipher(object): """ Base cipher class. Any cipher utility class that using any encryption algorithm can be inherited from this base class. The only method you need to implement is :meth:`BaseCipher.encrypt` and :meth:`BaseCipher.decrypt`. Because once you can encrypt binary data, then...
MacHu-GWU/windtalker-project
windtalker/cipher.py
BaseCipher.decrypt_file
python
def decrypt_file(self, path, output_path=None, overwrite=False, stream=True, enable_verbose=True, **kwargs): path, output_path = files.process_dst_overwrite_args( src=path, d...
Decrypt a file. If output_path are not given, then try to use the path with a surfix appended. The default automatical file path handling is defined here :meth:`windtalker.files.recover_path` :param path: path of the file you need to decrypt :param output_path: decrypted file output pat...
train
https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/cipher.py#L127-L159
[ "def process_dst_overwrite_args(src,\n dst=None,\n overwrite=True,\n src_to_dst_func=None):\n src = os.path.abspath(src)\n\n if dst is None:\n dst = src_to_dst_func(src)\n\n if not overwrite:\n if os.pat...
class BaseCipher(object): """ Base cipher class. Any cipher utility class that using any encryption algorithm can be inherited from this base class. The only method you need to implement is :meth:`BaseCipher.encrypt` and :meth:`BaseCipher.decrypt`. Because once you can encrypt binary data, then...
MacHu-GWU/windtalker-project
windtalker/cipher.py
BaseCipher.encrypt_dir
python
def encrypt_dir(self, path, output_path=None, overwrite=False, stream=True, enable_verbose=True): path, output_path = files.process_dst_overwrite_args( src=path, dst=output_path, overwrite=overwrite, ...
Encrypt everything in a directory. :param path: path of the dir you need to encrypt :param output_path: encrypted dir output path :param overwrite: if True, then silently overwrite output file if exists :param stream: if it is a very big file, stream mode can avoid using too m...
train
https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/cipher.py#L161-L198
[ "def process_dst_overwrite_args(src,\n dst=None,\n overwrite=True,\n src_to_dst_func=None):\n src = os.path.abspath(src)\n\n if dst is None:\n dst = src_to_dst_func(src)\n\n if not overwrite:\n if os.pat...
class BaseCipher(object): """ Base cipher class. Any cipher utility class that using any encryption algorithm can be inherited from this base class. The only method you need to implement is :meth:`BaseCipher.encrypt` and :meth:`BaseCipher.decrypt`. Because once you can encrypt binary data, then...
MacHu-GWU/windtalker-project
windtalker/symmetric.py
SymmetricCipher.any_text_to_fernet_key
python
def any_text_to_fernet_key(self, text): md5 = fingerprint.fingerprint.of_text(text) fernet_key = base64.b64encode(md5.encode("utf-8")) return fernet_key
Convert any text to a fernet key for encryption.
train
https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/symmetric.py#L56-L62
[ "def of_text(self, text, encoding=\"utf-8\"):\n \"\"\"Use default hash method to return hash value of a piece of string\n default setting use 'utf-8' encoding.\n \"\"\"\n m = self.hash_algo()\n m.update(text.encode(encoding))\n if self.return_int:\n return int(m.hexdigest(), 16)\n else:\...
class SymmetricCipher(Fernet, BaseCipher): """ A symmetric encryption algorithm utility class helps you easily encrypt/decrypt text, files and even a directory. :param password: The secret password you use to encrypt all your message. If you feel uncomfortable to put that in your code, you can le...
MacHu-GWU/windtalker-project
windtalker/files.py
get_encrpyted_path
python
def get_encrpyted_path(original_path, surfix=default_surfix): p = Path(original_path).absolute() encrypted_p = p.change(new_fname=p.fname + surfix) return encrypted_p.abspath
Find the output encrypted file /dir path (by adding a surfix). Example: - file: ``${home}/test.txt`` -> ``${home}/test-encrypted.txt`` - dir: ``${home}/Documents`` -> ``${home}/Documents-encrypted``
train
https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/files.py#L12-L23
null
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import os from pathlib_mate import Path default_surfix = "-encrypted" # windtalker secret def get_decrpyted_path(encrypted_path, surfix=default_surfix): """ Find the original path of encrypted file or dir. Example:...
MacHu-GWU/windtalker-project
windtalker/files.py
get_decrpyted_path
python
def get_decrpyted_path(encrypted_path, surfix=default_surfix): surfix_reversed = surfix[::-1] p = Path(encrypted_path).absolute() fname = p.fname fname_reversed = fname[::-1] new_fname = fname_reversed.replace(surfix_reversed, "", 1)[::-1] decrypted_p = p.change(new_fname=new_fname) return ...
Find the original path of encrypted file or dir. Example: - file: ``${home}/test-encrypted.txt`` -> ``${home}/test.txt`` - dir: ``${home}/Documents-encrypted`` -> ``${home}/Documents``
train
https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/files.py#L26-L42
null
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import os from pathlib_mate import Path default_surfix = "-encrypted" # windtalker secret def get_encrpyted_path(original_path, surfix=default_surfix): """ Find the output encrypted file /dir path (by adding a surfix). ...
MacHu-GWU/windtalker-project
windtalker/files.py
transform
python
def transform(src, dst, converter, overwrite=False, stream=True, chunksize=1024**2, **kwargs): if not overwrite: # pragma: no cover if Path(dst).exists(): raise EnvironmentError("'%s' already exists!" % dst) with open(src, "rb") as f_input: with open(dst, "wb") as f_o...
A file stream transform IO utility function. :param src: original file path :param dst: destination file path :param converter: binary content converter function :param overwrite: default False, :param stream: default True, if True, use stream IO mode, chunksize has to be specified. :para...
train
https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/files.py#L45-L79
[ "def encrypt(self, binary, *args, **kwargs):\n \"\"\"\n Overwrite this method using your encrypt algorithm.\n\n :param binary: binary data you need to encrypt\n :return: encrypted_binary, encrypted binary data\n \"\"\"\n raise NotImplementedError\n", "def decrypt(self, binary, *args, **kwargs):\...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import os from pathlib_mate import Path default_surfix = "-encrypted" # windtalker secret def get_encrpyted_path(original_path, surfix=default_surfix): """ Find the output encrypted file /dir path (by adding a surfix). ...
MacHu-GWU/windtalker-project
windtalker/fingerprint.py
FingerPrint.of_bytes
python
def of_bytes(self, py_bytes): m = self.hash_algo() m.update(py_bytes) if self.return_int: return int(m.hexdigest(), 16) else: return m.hexdigest()
Use default hash method to return hash value of bytes.
train
https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/fingerprint.py#L103-L111
null
class FingerPrint(object): """A hashlib wrapper class allow you to use one line to do hash as you wish. Usage:: >>> from fingerprint import fingerprint >>> print(fingerprint.of_bytes(bytes(123))) b1fec41621e338896e2d26f232a6b006 >>> print(fingerprint.of_text("message")) ...
MacHu-GWU/windtalker-project
windtalker/fingerprint.py
FingerPrint.of_text
python
def of_text(self, text, encoding="utf-8"): m = self.hash_algo() m.update(text.encode(encoding)) if self.return_int: return int(m.hexdigest(), 16) else: return m.hexdigest()
Use default hash method to return hash value of a piece of string default setting use 'utf-8' encoding.
train
https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/fingerprint.py#L113-L122
null
class FingerPrint(object): """A hashlib wrapper class allow you to use one line to do hash as you wish. Usage:: >>> from fingerprint import fingerprint >>> print(fingerprint.of_bytes(bytes(123))) b1fec41621e338896e2d26f232a6b006 >>> print(fingerprint.of_text("message")) ...
MacHu-GWU/windtalker-project
windtalker/fingerprint.py
FingerPrint.of_pyobj
python
def of_pyobj(self, pyobj): m = self.hash_algo() m.update(pickle.dumps(pyobj, protocol=self.pk_protocol)) if self.return_int: return int(m.hexdigest(), 16) else: return m.hexdigest()
Use default hash method to return hash value of a piece of Python picklable object.
train
https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/fingerprint.py#L124-L133
null
class FingerPrint(object): """A hashlib wrapper class allow you to use one line to do hash as you wish. Usage:: >>> from fingerprint import fingerprint >>> print(fingerprint.of_bytes(bytes(123))) b1fec41621e338896e2d26f232a6b006 >>> print(fingerprint.of_text("message")) ...
MaT1g3R/option
option/option_.py
Option.maybe
python
def maybe(cls, val: Optional[T]) -> 'Option[T]': return cast('Option[T]', NONE) if val is None else cls.Some(val)
Shortcut method to return ``Some`` or :py:data:`NONE` based on ``val``. Args: val: Some value. Returns: ``Some(val)`` if the ``val`` is not None, otherwise :py:data:`NONE`. Examples: >>> Option.maybe(0) Some(0) >>> Option.maybe(None)...
train
https://github.com/MaT1g3R/option/blob/37c954e6e74273d48649b3236bc881a1286107d6/option/option_.py#L85-L101
null
class Option(Generic[T]): """ :py:class:`Option` represents an optional value. Every :py:class:`Option` is either ``Some`` and contains a value, or :py:data:`NONE` and does not. To create a ``Some`` value, please use :py:meth:`Option.Some` or :py:func:`Some`. To create a :py:data:`NONE` value,...
MaT1g3R/option
option/option_.py
Option.expect
python
def expect(self, msg) -> T: if self._is_some: return self._val raise ValueError(msg)
Unwraps the option. Raises an exception if the value is :py:data:`NONE`. Args: msg: The exception message. Returns: The wrapped value. Raises: ``ValueError`` with message provided by ``msg`` if the value is :py:data:`NONE`. Examples: >>...
train
https://github.com/MaT1g3R/option/blob/37c954e6e74273d48649b3236bc881a1286107d6/option/option_.py#L144-L168
null
class Option(Generic[T]): """ :py:class:`Option` represents an optional value. Every :py:class:`Option` is either ``Some`` and contains a value, or :py:data:`NONE` and does not. To create a ``Some`` value, please use :py:meth:`Option.Some` or :py:func:`Some`. To create a :py:data:`NONE` value,...
MaT1g3R/option
option/option_.py
Option.unwrap_or
python
def unwrap_or(self, default: U) -> Union[T, U]: return self.unwrap_or_else(lambda: default)
Returns the contained value or ``default``. Args: default: The default value. Returns: The contained value if the :py:class:`Option` is ``Some``, otherwise ``default``. Notes: If you wish to use a result of a function call as the default, ...
train
https://github.com/MaT1g3R/option/blob/37c954e6e74273d48649b3236bc881a1286107d6/option/option_.py#L198-L219
null
class Option(Generic[T]): """ :py:class:`Option` represents an optional value. Every :py:class:`Option` is either ``Some`` and contains a value, or :py:data:`NONE` and does not. To create a ``Some`` value, please use :py:meth:`Option.Some` or :py:func:`Some`. To create a :py:data:`NONE` value,...
MaT1g3R/option
option/option_.py
Option.unwrap_or_else
python
def unwrap_or_else(self, callback: Callable[[], U]) -> Union[T, U]: return self._val if self._is_some else callback()
Returns the contained value or computes it from ``callback``. Args: callback: The the default callback. Returns: The contained value if the :py:class:`Option` is ``Some``, otherwise ``callback()``. Examples: >>> Some(0).unwrap_or_else(lambda: 11...
train
https://github.com/MaT1g3R/option/blob/37c954e6e74273d48649b3236bc881a1286107d6/option/option_.py#L221-L238
null
class Option(Generic[T]): """ :py:class:`Option` represents an optional value. Every :py:class:`Option` is either ``Some`` and contains a value, or :py:data:`NONE` and does not. To create a ``Some`` value, please use :py:meth:`Option.Some` or :py:func:`Some`. To create a :py:data:`NONE` value,...
MaT1g3R/option
option/option_.py
Option.map
python
def map(self, callback: Callable[[T], U]) -> 'Option[U]': return self._type.Some(callback(self._val)) if self._is_some else cast('Option[U]', NONE)
Applies the ``callback`` with the contained value as its argument or returns :py:data:`NONE`. Args: callback: The callback to apply to the contained value. Returns: The ``callback`` result wrapped in an :class:`Option` if the contained value is ``Some``, oth...
train
https://github.com/MaT1g3R/option/blob/37c954e6e74273d48649b3236bc881a1286107d6/option/option_.py#L240-L258
null
class Option(Generic[T]): """ :py:class:`Option` represents an optional value. Every :py:class:`Option` is either ``Some`` and contains a value, or :py:data:`NONE` and does not. To create a ``Some`` value, please use :py:meth:`Option.Some` or :py:func:`Some`. To create a :py:data:`NONE` value,...
MaT1g3R/option
option/option_.py
Option.map_or
python
def map_or(self, callback: Callable[[T], U], default: A) -> Union[U, A]: return callback(self._val) if self._is_some else default
Applies the ``callback`` to the contained value or returns ``default``. Args: callback: The callback to apply to the contained value. default: The default value. Returns: The ``callback`` result if the contained value is ``Some``, otherwise ``default``. ...
train
https://github.com/MaT1g3R/option/blob/37c954e6e74273d48649b3236bc881a1286107d6/option/option_.py#L260-L282
null
class Option(Generic[T]): """ :py:class:`Option` represents an optional value. Every :py:class:`Option` is either ``Some`` and contains a value, or :py:data:`NONE` and does not. To create a ``Some`` value, please use :py:meth:`Option.Some` or :py:func:`Some`. To create a :py:data:`NONE` value,...
MaT1g3R/option
option/option_.py
Option.flatmap
python
def flatmap(self, callback: 'Callable[[T], Option[U]]') -> 'Option[U]': return callback(self._val) if self._is_some else cast('Option[U]', NONE)
Applies the callback to the contained value if the option is not :py:data:`NONE`. This is different than :py:meth:`Option.map` because the result of the callback isn't wrapped in a new :py:class:`Option` Args: callback: The callback to apply to the contained value. ...
train
https://github.com/MaT1g3R/option/blob/37c954e6e74273d48649b3236bc881a1286107d6/option/option_.py#L305-L334
null
class Option(Generic[T]): """ :py:class:`Option` represents an optional value. Every :py:class:`Option` is either ``Some`` and contains a value, or :py:data:`NONE` and does not. To create a ``Some`` value, please use :py:meth:`Option.Some` or :py:func:`Some`. To create a :py:data:`NONE` value,...
MaT1g3R/option
option/option_.py
Option.filter
python
def filter(self, predicate: Callable[[T], bool]) -> 'Option[T]': if self._is_some and predicate(self._val): return self return cast('Option[T]', NONE)
Returns :py:data:`NONE` if the :py:class:`Option` is :py:data:`NONE`, otherwise filter the contained value by ``predicate``. Args: predicate: The fitler function. Returns: :py:data:`NONE` if the contained value is :py:data:`NONE`, otherwise: * The option...
train
https://github.com/MaT1g3R/option/blob/37c954e6e74273d48649b3236bc881a1286107d6/option/option_.py#L336-L359
null
class Option(Generic[T]): """ :py:class:`Option` represents an optional value. Every :py:class:`Option` is either ``Some`` and contains a value, or :py:data:`NONE` and does not. To create a ``Some`` value, please use :py:meth:`Option.Some` or :py:func:`Some`. To create a :py:data:`NONE` value,...
MaT1g3R/option
option/option_.py
Option.get
python
def get( self: 'Option[Mapping[K,V]]', key: K, default=None ) -> 'Option[V]': if self._is_some: return self._type.maybe(self._val.get(key, default)) return self._type.maybe(default)
Gets a mapping value by key in the contained value or returns ``default`` if the key doesn't exist. Args: key: The mapping key. default: The defauilt value. Returns: * ``Some`` variant of the mapping value if the key exists and the value is no...
train
https://github.com/MaT1g3R/option/blob/37c954e6e74273d48649b3236bc881a1286107d6/option/option_.py#L361-L392
null
class Option(Generic[T]): """ :py:class:`Option` represents an optional value. Every :py:class:`Option` is either ``Some`` and contains a value, or :py:data:`NONE` and does not. To create a ``Some`` value, please use :py:meth:`Option.Some` or :py:func:`Some`. To create a :py:data:`NONE` value,...
MaT1g3R/option
option/result.py
Result.ok
python
def ok(self) -> Option[T]: return Option.Some(cast(T, self._val)) if self._is_ok else cast(Option[T], NONE)
Converts from :class:`Result` [T, E] to :class:`option.option_.Option` [T]. Returns: :class:`Option` containing the success value if `self` is :meth:`Result.Ok`, otherwise :data:`option.option_.NONE`. Examples: >>> Ok(1).ok() Some(1) >>> Err(...
train
https://github.com/MaT1g3R/option/blob/37c954e6e74273d48649b3236bc881a1286107d6/option/result.py#L128-L142
null
class Result(Generic[T, E]): """ :class:`Result` is a type that either success (:meth:`Result.Ok`) or failure (:meth:`Result.Err`). To create an Ok value, use :meth:`Result.Ok` or :func:`Ok`. To create a Err value, use :meth:`Result.Err` or :func:`Err`. Calling the :class:`Result` constructor...
MaT1g3R/option
option/result.py
Result.err
python
def err(self) -> Option[E]: return cast(Option[E], NONE) if self._is_ok else Option.Some(cast(E, self._val))
Converts from :class:`Result` [T, E] to :class:`option.option_.Option` [E]. Returns: :class:`Option` containing the error value if `self` is :meth:`Result.Err`, otherwise :data:`option.option_.NONE`. Examples: >>> Ok(1).err() NONE >>> Err(1)....
train
https://github.com/MaT1g3R/option/blob/37c954e6e74273d48649b3236bc881a1286107d6/option/result.py#L144-L158
null
class Result(Generic[T, E]): """ :class:`Result` is a type that either success (:meth:`Result.Ok`) or failure (:meth:`Result.Err`). To create an Ok value, use :meth:`Result.Ok` or :func:`Ok`. To create a Err value, use :meth:`Result.Err` or :func:`Err`. Calling the :class:`Result` constructor...
MaT1g3R/option
option/result.py
Result.map
python
def map(self, op: Callable[[T], U]) -> 'Union[Result[U, E], Result[T, E]]': return self._type.Ok(op(cast(T, self._val))) if self._is_ok else self
Applies a function to the contained :meth:`Result.Ok` value. Args: op: The function to apply to the :meth:`Result.Ok` value. Returns: A :class:`Result` with its success value as the function result if `self` is an :meth:`Result.Ok` value, otherwise returns ...
train
https://github.com/MaT1g3R/option/blob/37c954e6e74273d48649b3236bc881a1286107d6/option/result.py#L160-L178
null
class Result(Generic[T, E]): """ :class:`Result` is a type that either success (:meth:`Result.Ok`) or failure (:meth:`Result.Err`). To create an Ok value, use :meth:`Result.Ok` or :func:`Ok`. To create a Err value, use :meth:`Result.Err` or :func:`Err`. Calling the :class:`Result` constructor...
MaT1g3R/option
option/result.py
Result.flatmap
python
def flatmap(self, op: 'Callable[[T], Result[U, E]]') -> 'Result[U, E]': return op(cast(T, self._val)) if self._is_ok else cast('Result[U, E]', self)
Applies a function to the contained :meth:`Result.Ok` value. This is different than :meth:`Result.map` because the function result is not wrapped in a new :class:`Result`. Args: op: The function to apply to the contained :meth:`Result.Ok` value. Returns: The re...
train
https://github.com/MaT1g3R/option/blob/37c954e6e74273d48649b3236bc881a1286107d6/option/result.py#L180-L206
null
class Result(Generic[T, E]): """ :class:`Result` is a type that either success (:meth:`Result.Ok`) or failure (:meth:`Result.Err`). To create an Ok value, use :meth:`Result.Ok` or :func:`Ok`. To create a Err value, use :meth:`Result.Err` or :func:`Err`. Calling the :class:`Result` constructor...
MaT1g3R/option
option/result.py
Result.map_err
python
def map_err(self, op: Callable[[E], F]) -> 'Union[Result[T, F], Result[T, E]]': return self if self._is_ok else cast( 'Result[T, F]', self._type.Err(op(cast(E, self._val))) )
Applies a function to the contained :meth:`Result.Err` value. Args: op: The function to apply to the :meth:`Result.Err` value. Returns: A :class:`Result` with its error value as the function result if `self` is a :meth:`Result.Err` value, otherwise returns ...
train
https://github.com/MaT1g3R/option/blob/37c954e6e74273d48649b3236bc881a1286107d6/option/result.py#L208-L229
null
class Result(Generic[T, E]): """ :class:`Result` is a type that either success (:meth:`Result.Ok`) or failure (:meth:`Result.Err`). To create an Ok value, use :meth:`Result.Ok` or :func:`Ok`. To create a Err value, use :meth:`Result.Err` or :func:`Err`. Calling the :class:`Result` constructor...
MaT1g3R/option
option/result.py
Result.unwrap
python
def unwrap(self) -> T: if self._is_ok: return cast(T, self._val) raise ValueError(self._val)
Returns the success value in the :class:`Result`. Returns: The success value in the :class:`Result`. Raises: ``ValueError`` with the message provided by the error value if the :class:`Result` is a :meth:`Result.Err` value. Examples: >>> Ok(1).u...
train
https://github.com/MaT1g3R/option/blob/37c954e6e74273d48649b3236bc881a1286107d6/option/result.py#L231-L253
null
class Result(Generic[T, E]): """ :class:`Result` is a type that either success (:meth:`Result.Ok`) or failure (:meth:`Result.Err`). To create an Ok value, use :meth:`Result.Ok` or :func:`Ok`. To create a Err value, use :meth:`Result.Err` or :func:`Err`. Calling the :class:`Result` constructor...
MaT1g3R/option
option/result.py
Result.unwrap_or
python
def unwrap_or(self, optb: T) -> T: return cast(T, self._val) if self._is_ok else optb
Returns the success value in the :class:`Result` or ``optb``. Args: optb: The default return value. Returns: The success value in the :class:`Result` if it is a :meth:`Result.Ok` value, otherwise ``optb``. Notes: If you wish to use a result of a...
train
https://github.com/MaT1g3R/option/blob/37c954e6e74273d48649b3236bc881a1286107d6/option/result.py#L255-L276
null
class Result(Generic[T, E]): """ :class:`Result` is a type that either success (:meth:`Result.Ok`) or failure (:meth:`Result.Err`). To create an Ok value, use :meth:`Result.Ok` or :func:`Ok`. To create a Err value, use :meth:`Result.Err` or :func:`Err`. Calling the :class:`Result` constructor...
MaT1g3R/option
option/result.py
Result.unwrap_or_else
python
def unwrap_or_else(self, op: Callable[[E], U]) -> Union[T, U]: return cast(T, self._val) if self._is_ok else op(cast(E, self._val))
Returns the sucess value in the :class:`Result` or computes a default from the error value. Args: op: The function to computes default with. Returns: The success value in the :class:`Result` if it is a :meth:`Result.Ok` value, otherwise ``op(E)``. ...
train
https://github.com/MaT1g3R/option/blob/37c954e6e74273d48649b3236bc881a1286107d6/option/result.py#L278-L296
null
class Result(Generic[T, E]): """ :class:`Result` is a type that either success (:meth:`Result.Ok`) or failure (:meth:`Result.Err`). To create an Ok value, use :meth:`Result.Ok` or :func:`Ok`. To create a Err value, use :meth:`Result.Err` or :func:`Err`. Calling the :class:`Result` constructor...
MaT1g3R/option
option/result.py
Result.expect
python
def expect(self, msg) -> T: if self._is_ok: return cast(T, self._val) raise ValueError(msg)
Returns the success value in the :class:`Result` or raises a ``ValueError`` with a provided message. Args: msg: The error message. Returns: The success value in the :class:`Result` if it is a :meth:`Result.Ok` value. Raises: ``ValueError...
train
https://github.com/MaT1g3R/option/blob/37c954e6e74273d48649b3236bc881a1286107d6/option/result.py#L298-L325
null
class Result(Generic[T, E]): """ :class:`Result` is a type that either success (:meth:`Result.Ok`) or failure (:meth:`Result.Err`). To create an Ok value, use :meth:`Result.Ok` or :func:`Ok`. To create a Err value, use :meth:`Result.Err` or :func:`Err`. Calling the :class:`Result` constructor...
MaT1g3R/option
option/result.py
Result.unwrap_err
python
def unwrap_err(self) -> E: if self._is_ok: raise ValueError(self._val) return cast(E, self._val)
Returns the error value in a :class:`Result`. Returns: The error value in the :class:`Result` if it is a :meth:`Result.Err` value. Raises: ``ValueError`` with the message provided by the success value if the :class:`Result` is a :meth:`Result.Ok` value....
train
https://github.com/MaT1g3R/option/blob/37c954e6e74273d48649b3236bc881a1286107d6/option/result.py#L327-L350
null
class Result(Generic[T, E]): """ :class:`Result` is a type that either success (:meth:`Result.Ok`) or failure (:meth:`Result.Err`). To create an Ok value, use :meth:`Result.Ok` or :func:`Ok`. To create a Err value, use :meth:`Result.Err` or :func:`Err`. Calling the :class:`Result` constructor...
MaT1g3R/option
option/result.py
Result.expect_err
python
def expect_err(self, msg) -> E: if self._is_ok: raise ValueError(msg) return cast(E, self._val)
Returns the error value in a :class:`Result`, or raises a ``ValueError`` with the provided message. Args: msg: The error message. Returns: The error value in the :class:`Result` if it is a :meth:`Result.Err` value. Raises: ``ValueError``...
train
https://github.com/MaT1g3R/option/blob/37c954e6e74273d48649b3236bc881a1286107d6/option/result.py#L352-L379
null
class Result(Generic[T, E]): """ :class:`Result` is a type that either success (:meth:`Result.Ok`) or failure (:meth:`Result.Err`). To create an Ok value, use :meth:`Result.Ok` or :func:`Ok`. To create a Err value, use :meth:`Result.Err` or :func:`Err`. Calling the :class:`Result` constructor...
tjomasc/snekbol
snekbol/document.py
Document.add_component_definition
python
def add_component_definition(self, definition): # definition.identity = self._to_uri_from_namespace(definition.identity) if definition.identity not in self._components.keys(): self._components[definition.identity] = definition else: raise ValueError("{} has already been d...
Add a ComponentDefinition to the document
train
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L79-L87
null
class Document(object): """ Provides a base for creating SBOL documents """ def __init__(self, namespace, validate=True): # Don't access directly: use function getter/setters self._components = {} self._sequences = {} self._namespaces = ...
tjomasc/snekbol
snekbol/document.py
Document.assemble_component
python
def assemble_component(self, into_component, using_components): if not isinstance(using_components, list) or len(using_components) == 0: raise Exception('Must supply list of ComponentDefinitions') components = [] sequence_annotations = [] seq_elements = '' for k, c ...
Assemble a list of already defined components into a structual hirearchy
train
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L114-L168
[ "def _add_sequence(self, sequence):\n \"\"\"\n Add a Sequence to the document\n \"\"\"\n if sequence.identity not in self._sequences.keys():\n self._sequences[sequence.identity] = sequence\n else:\n raise ValueError(\"{} has already been defined\".format(sequence.identity))\n" ]
class Document(object): """ Provides a base for creating SBOL documents """ def __init__(self, namespace, validate=True): # Don't access directly: use function getter/setters self._components = {} self._sequences = {} self._namespaces = ...
tjomasc/snekbol
snekbol/document.py
Document._add_sequence
python
def _add_sequence(self, sequence): if sequence.identity not in self._sequences.keys(): self._sequences[sequence.identity] = sequence else: raise ValueError("{} has already been defined".format(sequence.identity))
Add a Sequence to the document
train
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L170-L177
null
class Document(object): """ Provides a base for creating SBOL documents """ def __init__(self, namespace, validate=True): # Don't access directly: use function getter/setters self._components = {} self._sequences = {} self._namespaces = ...
tjomasc/snekbol
snekbol/document.py
Document.add_model
python
def add_model(self, model): if model.identity not in self._models.keys(): self._models[model.identity] = model else: raise ValueError("{} has already been defined".format(model.identity))
Add a model to the document
train
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L179-L186
null
class Document(object): """ Provides a base for creating SBOL documents """ def __init__(self, namespace, validate=True): # Don't access directly: use function getter/setters self._components = {} self._sequences = {} self._namespaces = ...
tjomasc/snekbol
snekbol/document.py
Document.add_module_definition
python
def add_module_definition(self, module_definition): if module_definition.identity not in self._module_definitions.keys(): self._module_definitions[module_definition.identity] = module_definition else: raise ValueError("{} has already been defined".format(module_definition.identit...
Add a ModuleDefinition to the document
train
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L203-L210
null
class Document(object): """ Provides a base for creating SBOL documents """ def __init__(self, namespace, validate=True): # Don't access directly: use function getter/setters self._components = {} self._sequences = {} self._namespaces = ...
tjomasc/snekbol
snekbol/document.py
Document.get_components
python
def get_components(self, uri): try: component_definition = self._components[uri] except KeyError: return False sorted_sequences = sorted(component_definition.sequence_annotations, key=attrgetter('first_location')) return [c.compo...
Get components from a component definition in order
train
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L233-L244
null
class Document(object): """ Provides a base for creating SBOL documents """ def __init__(self, namespace, validate=True): # Don't access directly: use function getter/setters self._components = {} self._sequences = {} self._namespaces = ...
tjomasc/snekbol
snekbol/document.py
Document.clear_document
python
def clear_document(self): self._components.clear() self._sequences.clear() self._namespaces.clear() self._models.clear() self._modules.clear() self._collections.clear() self._annotations.clear() self._functional_component_store.clear() self._collec...
Clears ALL items from document, reseting it to clean
train
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L246-L258
null
class Document(object): """ Provides a base for creating SBOL documents """ def __init__(self, namespace, validate=True): # Don't access directly: use function getter/setters self._components = {} self._sequences = {} self._namespaces = ...
tjomasc/snekbol
snekbol/document.py
Document._get_triplet_value
python
def _get_triplet_value(self, graph, identity, rdf_type): value = graph.value(subject=identity, predicate=rdf_type) return value.toPython() if value is not None else value
Get a value from an RDF triple
train
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L263-L268
null
class Document(object): """ Provides a base for creating SBOL documents """ def __init__(self, namespace, validate=True): # Don't access directly: use function getter/setters self._components = {} self._sequences = {} self._namespaces = ...
tjomasc/snekbol
snekbol/document.py
Document._get_triplet_value_list
python
def _get_triplet_value_list(self, graph, identity, rdf_type): values = [] for elem in graph.objects(identity, rdf_type): values.append(elem.toPython()) return values
Get a list of values from RDF triples when more than one may be present
train
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L270-L277
null
class Document(object): """ Provides a base for creating SBOL documents """ def __init__(self, namespace, validate=True): # Don't access directly: use function getter/setters self._components = {} self._sequences = {} self._namespaces = ...
tjomasc/snekbol
snekbol/document.py
Document._read_sequences
python
def _read_sequences(self, graph): for e in self._get_elements(graph, SBOL.Sequence): identity = e[0] c = self._get_rdf_identified(graph, identity) c['elements'] = self._get_triplet_value(graph, identity, SBOL.elements) c['encoding'] = self._get_triplet_value(graph...
Read graph and add sequences to document
train
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L306-L317
null
class Document(object): """ Provides a base for creating SBOL documents """ def __init__(self, namespace, validate=True): # Don't access directly: use function getter/setters self._components = {} self._sequences = {} self._namespaces = ...
tjomasc/snekbol
snekbol/document.py
Document._read_component_definitions
python
def _read_component_definitions(self, graph): for e in self._get_elements(graph, SBOL.ComponentDefinition): identity = e[0] # Store component values in dict c = self._get_rdf_identified(graph, identity) c['roles'] = self._get_triplet_value_list(graph, identity, SB...
Read graph and add component defintions to document
train
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L319-L331
null
class Document(object): """ Provides a base for creating SBOL documents """ def __init__(self, namespace, validate=True): # Don't access directly: use function getter/setters self._components = {} self._sequences = {} self._namespaces = ...
tjomasc/snekbol
snekbol/document.py
Document._extend_component_definitions
python
def _extend_component_definitions(self, graph): for def_uri, comp_def in self._components.items(): # Store created components indexed for later lookup component_index = {} identity = URIRef(def_uri) # Get components for comp in graph.triples((identity...
Read graph and update component definitions with related elements
train
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L333-L405
null
class Document(object): """ Provides a base for creating SBOL documents """ def __init__(self, namespace, validate=True): # Don't access directly: use function getter/setters self._components = {} self._sequences = {} self._namespaces = ...
tjomasc/snekbol
snekbol/document.py
Document._read_models
python
def _read_models(self, graph): for e in self._get_elements(graph, SBOL.Model): identity = e[0] m = self._get_rdf_identified(graph, identity) m['source'] = self._get_triplet_value(graph, identity, SBOL.source) m['language'] = self._get_triplet_value(graph, identity...
Read graph and add models to document
train
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L407-L419
null
class Document(object): """ Provides a base for creating SBOL documents """ def __init__(self, namespace, validate=True): # Don't access directly: use function getter/setters self._components = {} self._sequences = {} self._namespaces = ...
tjomasc/snekbol
snekbol/document.py
Document._read_module_definitions
python
def _read_module_definitions(self, graph): for e in self._get_elements(graph, SBOL.ModuleDefinition): identity = e[0] m = self._get_rdf_identified(graph, identity) m['roles'] = self._get_triplet_value_list(graph, identity, SBOL.role) functional_components = {} ...
Read graph and add module defintions to document
train
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L421-L458
null
class Document(object): """ Provides a base for creating SBOL documents """ def __init__(self, namespace, validate=True): # Don't access directly: use function getter/setters self._components = {} self._sequences = {} self._namespaces = ...
tjomasc/snekbol
snekbol/document.py
Document._extend_module_definitions
python
def _extend_module_definitions(self, graph): for mod_id in self._modules: mod_identity = self._get_triplet_value(graph, URIRef(mod_id), SBOL.module) modules = [] for mod in graph.triples((mod_identity, SBOL.module, None)): md = self._get_rdf_identified(graph, ...
Using collected module definitions extend linkages
train
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L460-L481
null
class Document(object): """ Provides a base for creating SBOL documents """ def __init__(self, namespace, validate=True): # Don't access directly: use function getter/setters self._components = {} self._sequences = {} self._namespaces = ...
tjomasc/snekbol
snekbol/document.py
Document._read_annotations
python
def _read_annotations(self, graph): flipped_namespaces = {v: k for k, v in self._namespaces.items()} for triple in graph.triples((None, RDF.type, None)): namespace, obj = split_uri(triple[2]) prefix = flipped_namespaces[namespace] as_string = '{}:{}'.format(prefix, ob...
Find any non-defined elements at TopLevel and create annotations
train
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L483-L499
null
class Document(object): """ Provides a base for creating SBOL documents """ def __init__(self, namespace, validate=True): # Don't access directly: use function getter/setters self._components = {} self._sequences = {} self._namespaces = ...
tjomasc/snekbol
snekbol/document.py
Document._read_collections
python
def _read_collections(self, graph): for e in self._get_elements(graph, SBOL.Collection): identity = e[0] c = self._get_rdf_identified(graph, identity) members = [] # Need to handle other non-standard TopLevel objects first for m in graph.triples((ident...
Read graph and add collections to document
train
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L501-L513
null
class Document(object): """ Provides a base for creating SBOL documents """ def __init__(self, namespace, validate=True): # Don't access directly: use function getter/setters self._components = {} self._sequences = {} self._namespaces = ...
tjomasc/snekbol
snekbol/document.py
Document.read
python
def read(self, f): self.clear_document() g = Graph() g.parse(f, format='xml') for n in g.namespaces(): ns = n[1].toPython() if not ns.endswith(('#', '/', ':')): ns = ns + '/' self._namespaces[n[0]] = ns # Extend the existi...
Read in an SBOL file, replacing current document contents
train
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L515-L540
[ "def clear_document(self):\n \"\"\"\n Clears ALL items from document, reseting it to clean\n \"\"\"\n self._components.clear()\n self._sequences.clear()\n self._namespaces.clear()\n self._models.clear()\n self._modules.clear()\n self._collections.clear()\n self._annotations.clear()\n ...
class Document(object): """ Provides a base for creating SBOL documents """ def __init__(self, namespace, validate=True): # Don't access directly: use function getter/setters self._components = {} self._sequences = {} self._namespaces = ...
tjomasc/snekbol
snekbol/document.py
Document.write
python
def write(self, f): rdf = ET.Element(NS('rdf', 'RDF'), nsmap=XML_NS) # TODO: TopLevel Annotations sequence_values = sorted(self._sequences.values(), key=lambda x: x.identity) self._add_to_root(rdf, sequence_values) component_values = sorted(self._components.values(), key=lambda ...
Write an SBOL file from current document contents
train
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L553-L576
[ "def NS(namespace, tag):\n \"\"\"\n Generate a namespaced tag for use in creation of an XML file\n \"\"\"\n return '{' + XML_NS[namespace] + '}' + tag\n", "def _add_to_root(self, root_node, elements):\n for item in elements:\n elem = item._as_rdf_xml(self.ns)\n root_node.append(elem)\...
class Document(object): """ Provides a base for creating SBOL documents """ def __init__(self, namespace, validate=True): # Don't access directly: use function getter/setters self._components = {} self._sequences = {} self._namespaces = ...
tjomasc/snekbol
snekbol/identified.py
Identified._as_rdf_xml
python
def _as_rdf_xml(self, ns): self.rdf_identity = self._get_identity(ns) elements = [] elements.append(ET.Element(NS('sbol', 'persistentIdentity'), attrib={NS('rdf', 'resource'): self._get_persistent_identitity(ns)})) ...
Return identity details for the element as XML nodes
train
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/identified.py#L68-L98
null
class Identified(object): """ Mixin to provide identity support to SBOL objects """ def __init__(self, identity, name = None, was_derived_from = None, version = None, description = None, display_id = No...
sveetch/py-css-styleguide
py_css_styleguide/parser.py
TinycssSourceParser.digest_prelude
python
def digest_prelude(self, rule): name = [] for token in rule.prelude: if token.type == 'ident': name.append(token.value) return "__".join(name)
Walk on rule prelude (aka CSS selector) tokens to return a string of the value name (from css selector). Actually only simple selector and selector with descendant combinator are supported. Using any other selector kind may leads to unexpected issues. Arguments: rul...
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/parser.py#L29-L52
null
class TinycssSourceParser(object): """ CSS parser using tinycss2 Since tinycss2 only return tokens, this parser is in charge to turn them to usable datas: a dict of properties for each selector. """ def digest_content(self, rule): """ Walk on rule content tokens to return a di...
sveetch/py-css-styleguide
py_css_styleguide/parser.py
TinycssSourceParser.digest_content
python
def digest_content(self, rule): data = OrderedDict() current_key = None for token in rule.content: # Assume first identity token is the property name if token.type == 'ident': # Ignore starting '-' from css variables name = token.value ...
Walk on rule content tokens to return a dict of properties. This is pretty naive and will choke/fail on everything that is more evolved than simple ``ident(string):value(string)`` Arguments: rule (tinycss2.ast.QualifiedRule): Qualified rule object as returned by ti...
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/parser.py#L54-L87
null
class TinycssSourceParser(object): """ CSS parser using tinycss2 Since tinycss2 only return tokens, this parser is in charge to turn them to usable datas: a dict of properties for each selector. """ def digest_prelude(self, rule): """ Walk on rule prelude (aka CSS selector) toke...
sveetch/py-css-styleguide
py_css_styleguide/parser.py
TinycssSourceParser.consume
python
def consume(self, source): manifest = OrderedDict() rules = parse_stylesheet( source, skip_comments=True, skip_whitespace=True, ) for rule in rules: # Gather rule selector+properties name = self.digest_prelude(rule) ...
Parse source and consume tokens from tinycss2. Arguments: source (string): Source content to parse. Returns: dict: Retrieved rules.
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/parser.py#L89-L118
[ "def digest_prelude(self, rule):\n \"\"\"\n Walk on rule prelude (aka CSS selector) tokens to return a string of\n the value name (from css selector).\n\n Actually only simple selector and selector with descendant combinator\n are supported. Using any other selector kind may leads to unexpected\n ...
class TinycssSourceParser(object): """ CSS parser using tinycss2 Since tinycss2 only return tokens, this parser is in charge to turn them to usable datas: a dict of properties for each selector. """ def digest_prelude(self, rule): """ Walk on rule prelude (aka CSS selector) toke...
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.validate_rule_name
python
def validate_rule_name(self, name): if not name: raise SerializerError("Rule name is empty".format(name)) if name[0] not in RULE_ALLOWED_START: msg = "Rule name '{}' must starts with a letter" raise SerializerError(msg.format(name)) for item in name: ...
Validate rule name. Arguments: name (string): Rule name. Returns: bool: ``True`` if rule name is valid.
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L46-L69
null
class ManifestSerializer(object): """ Serialize parsed CSS to data suitable to Manifest Raises: SerializerError: When there is an invalid syntax in datas. Attributes: _metas (collections.OrderedDict): Buffer to store serialized metas from parsed source. Default is an empty ...
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.validate_variable_name
python
def validate_variable_name(self, name): if not name: raise SerializerError("Variable name is empty".format(name)) if name[0] not in PROPERTY_ALLOWED_START: msg = "Variable name '{}' must starts with a letter" raise SerializerError(msg.format(name)) for item ...
Validate variable name. Arguments: name (string): Property name. Returns: bool: ``True`` if variable name is valid.
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L71-L94
null
class ManifestSerializer(object): """ Serialize parsed CSS to data suitable to Manifest Raises: SerializerError: When there is an invalid syntax in datas. Attributes: _metas (collections.OrderedDict): Buffer to store serialized metas from parsed source. Default is an empty ...
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.value_splitter
python
def value_splitter(self, reference, prop, value, mode): items = [] if mode == 'json-list': try: items = json.loads(value) except json.JSONDecodeError as e: print(value) msg = ("Reference '{ref}' raised JSON decoder error when " ...
Split a string into a list items. Default behavior is to split on white spaces. Arguments: reference (string): Reference name used when raising possible error. prop (string): Property name used when raising possible error. value (string): Property v...
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L96-L134
null
class ManifestSerializer(object): """ Serialize parsed CSS to data suitable to Manifest Raises: SerializerError: When there is an invalid syntax in datas. Attributes: _metas (collections.OrderedDict): Buffer to store serialized metas from parsed source. Default is an empty ...
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.serialize_to_json
python
def serialize_to_json(self, name, datas): data_object = datas.get('object', None) if data_object is None: msg = ("JSON reference '{}' lacks of required 'object' variable") raise SerializerError(msg.format(name)) try: content = json.loads(data_object, object_...
Serialize given datas to any object from assumed JSON string. Arguments: name (string): Name only used inside possible exception message. datas (dict): Datas to serialize. Returns: object: Object depending from JSON content.
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L136-L159
null
class ManifestSerializer(object): """ Serialize parsed CSS to data suitable to Manifest Raises: SerializerError: When there is an invalid syntax in datas. Attributes: _metas (collections.OrderedDict): Buffer to store serialized metas from parsed source. Default is an empty ...
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.serialize_to_nested
python
def serialize_to_nested(self, name, datas): keys = datas.get('keys', None) splitter = datas.get('splitter', self._DEFAULT_SPLITTER) if not keys: msg = ("Nested reference '{}' lacks of required 'keys' variable " "or is empty") raise SerializerError(msg....
Serialize given datas to a nested structure where each key create an item and each other variable is stored as a subitem with corresponding value (according to key index position). Arguments: name (string): Name only used inside possible exception message. datas (dict): ...
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L161-L205
[ "def value_splitter(self, reference, prop, value, mode):\n \"\"\"\n Split a string into a list items.\n\n Default behavior is to split on white spaces.\n\n\n Arguments:\n reference (string): Reference name used when raising possible\n error.\n prop (string): Property name used w...
class ManifestSerializer(object): """ Serialize parsed CSS to data suitable to Manifest Raises: SerializerError: When there is an invalid syntax in datas. Attributes: _metas (collections.OrderedDict): Buffer to store serialized metas from parsed source. Default is an empty ...
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.serialize_to_flat
python
def serialize_to_flat(self, name, datas): keys = datas.get('keys', None) values = datas.get('values', None) splitter = datas.get('splitter', self._DEFAULT_SPLITTER) if not keys: msg = ("Flat reference '{}' lacks of required 'keys' variable or " "is empty")...
Serialize given datas to a flat structure ``KEY:VALUE`` where ``KEY`` comes from ``keys`` variable and ``VALUE`` comes from ``values`` variable. This means both ``keys`` and ``values`` are required variable to be correctly filled (each one is a string of item separated with an empty ...
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L207-L247
[ "def value_splitter(self, reference, prop, value, mode):\n \"\"\"\n Split a string into a list items.\n\n Default behavior is to split on white spaces.\n\n\n Arguments:\n reference (string): Reference name used when raising possible\n error.\n prop (string): Property name used w...
class ManifestSerializer(object): """ Serialize parsed CSS to data suitable to Manifest Raises: SerializerError: When there is an invalid syntax in datas. Attributes: _metas (collections.OrderedDict): Buffer to store serialized metas from parsed source. Default is an empty ...
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.serialize_to_list
python
def serialize_to_list(self, name, datas): items = datas.get('items', None) splitter = datas.get('splitter', self._DEFAULT_SPLITTER) if items is None: msg = ("List reference '{}' lacks of required 'items' variable " "or is empty") raise SerializerError(...
Serialize given datas to a list structure. List structure is very simple and only require a variable ``--items`` which is a string of values separated with an empty space. Every other properties are ignored. Arguments: name (string): Name only used inside possible exception...
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L249-L274
[ "def value_splitter(self, reference, prop, value, mode):\n \"\"\"\n Split a string into a list items.\n\n Default behavior is to split on white spaces.\n\n\n Arguments:\n reference (string): Reference name used when raising possible\n error.\n prop (string): Property name used w...
class ManifestSerializer(object): """ Serialize parsed CSS to data suitable to Manifest Raises: SerializerError: When there is an invalid syntax in datas. Attributes: _metas (collections.OrderedDict): Buffer to store serialized metas from parsed source. Default is an empty ...
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.serialize_to_string
python
def serialize_to_string(self, name, datas): value = datas.get('value', None) if value is None: msg = ("String reference '{}' lacks of required 'value' variable " "or is empty") raise SerializerError(msg.format(name)) return value
Serialize given datas to a string. Simply return the value from required variable``value``. Arguments: name (string): Name only used inside possible exception message. datas (dict): Datas to serialize. Returns: string: Value.
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L276-L296
null
class ManifestSerializer(object): """ Serialize parsed CSS to data suitable to Manifest Raises: SerializerError: When there is an invalid syntax in datas. Attributes: _metas (collections.OrderedDict): Buffer to store serialized metas from parsed source. Default is an empty ...
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.get_meta_references
python
def get_meta_references(self, datas): rule = datas.get(RULE_META_REFERENCES, {}) if not rule: msg = "Manifest lacks of '.{}' or is empty" raise SerializerError(msg.format(RULE_META_REFERENCES)) else: if rule.get('names', None): names = rule.ge...
Get manifest enabled references declaration This required declaration is readed from ``styleguide-metas-references`` rule that require either a ``--names`` or ``--auto`` variable, each one define the mode to enable reference: Manually Using ``--names`` which define a list o...
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L298-L344
[ "def validate_rule_name(self, name):\n \"\"\"\n Validate rule name.\n\n Arguments:\n name (string): Rule name.\n\n Returns:\n bool: ``True`` if rule name is valid.\n \"\"\"\n if not name:\n raise SerializerError(\"Rule name is empty\".format(name))\n\n if name[0] not in RUL...
class ManifestSerializer(object): """ Serialize parsed CSS to data suitable to Manifest Raises: SerializerError: When there is an invalid syntax in datas. Attributes: _metas (collections.OrderedDict): Buffer to store serialized metas from parsed source. Default is an empty ...
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.get_reference
python
def get_reference(self, datas, name): rule_name = '-'.join((RULE_REFERENCE, name)) structure_mode = 'nested' if rule_name not in datas: msg = "Unable to find enabled reference '{}'" raise SerializerError(msg.format(name)) properties = datas.get(rule_name) ...
Get serialized reference datas Because every reference is turned to a dict (that stands on ``keys`` variable that is a list of key names), every variables must have the same exact length of word than the key name list. A reference name starts with 'styleguide-reference-' followed by ...
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L346-L410
[ "def validate_variable_name(self, name):\n \"\"\"\n Validate variable name.\n\n Arguments:\n name (string): Property name.\n\n Returns:\n bool: ``True`` if variable name is valid.\n \"\"\"\n if not name:\n raise SerializerError(\"Variable name is empty\".format(name))\n\n i...
class ManifestSerializer(object): """ Serialize parsed CSS to data suitable to Manifest Raises: SerializerError: When there is an invalid syntax in datas. Attributes: _metas (collections.OrderedDict): Buffer to store serialized metas from parsed source. Default is an empty ...
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.get_available_references
python
def get_available_references(self, datas): names = [] for k, v in datas.items(): if k.startswith(RULE_REFERENCE): names.append(k[len(RULE_REFERENCE)+1:]) return names
Get available manifest reference names. Every rules starting with prefix from ``nomenclature.RULE_REFERENCE`` are available references. Only name validation is performed on these references. Arguments: datas (dict): Data where to search for reference declarations. ...
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L412-L434
null
class ManifestSerializer(object): """ Serialize parsed CSS to data suitable to Manifest Raises: SerializerError: When there is an invalid syntax in datas. Attributes: _metas (collections.OrderedDict): Buffer to store serialized metas from parsed source. Default is an empty ...
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.get_enabled_references
python
def get_enabled_references(self, datas, meta_references): references = OrderedDict() for section in meta_references: references[section] = self.get_reference(datas, section) return references
Get enabled manifest references declarations. Enabled references are defined through meta references declaration, every other references are ignored. Arguments: datas (dict): Data where to search for reference declarations. This is commonly the fully parsed manifest...
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L436-L456
[ "def get_reference(self, datas, name):\n \"\"\"\n Get serialized reference datas\n\n Because every reference is turned to a dict (that stands on ``keys``\n variable that is a list of key names), every variables must have the\n same exact length of word than the key name list.\n\n A reference name ...
class ManifestSerializer(object): """ Serialize parsed CSS to data suitable to Manifest Raises: SerializerError: When there is an invalid syntax in datas. Attributes: _metas (collections.OrderedDict): Buffer to store serialized metas from parsed source. Default is an empty ...
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
ManifestSerializer.serialize
python
def serialize(self, datas): self._metas = OrderedDict({ 'references': self.get_meta_references(datas), }) return self.get_enabled_references(datas, self._metas['references'])
Serialize datas to manifest structure with metas and references. Only references are returned, metas are assigned to attribute ``ManifestSerializer._metas``. Arguments: datas (dict): Data where to search for reference declarations. This is commonly the fully parsed ...
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L458-L476
[ "def get_meta_references(self, datas):\n \"\"\"\n Get manifest enabled references declaration\n\n This required declaration is readed from\n ``styleguide-metas-references`` rule that require either a ``--names``\n or ``--auto`` variable, each one define the mode to enable reference:\n\n Manually\n...
class ManifestSerializer(object): """ Serialize parsed CSS to data suitable to Manifest Raises: SerializerError: When there is an invalid syntax in datas. Attributes: _metas (collections.OrderedDict): Buffer to store serialized metas from parsed source. Default is an empty ...
sveetch/py-css-styleguide
py_css_styleguide/model.py
Manifest.load
python
def load(self, source, filepath=None): # Set _path if source is a file-like object try: self._path = source.name except AttributeError: self._path = filepath # Get source content either it's a string or a file-like object try: source_content =...
Load source as manifest attributes Arguments: source (string or file-object): CSS source to parse and serialize to find metas and rules. It can be either a string or a file-like object (aka with a ``read()`` method which return string). Keywo...
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/model.py#L41-L87
[ "def set_rule(self, name, properties):\n \"\"\"\n Set a rules as object attribute.\n\n Arguments:\n name (string): Rule name to set as attribute name.\n properties (dict): Dictionnary of properties.\n \"\"\"\n self._rule_attrs.append(name)\n setattr(self, name, properties)\n", "def...
class Manifest(object): """ Manifest model During load process, every rule is stored as object attribute so you can reach them directly. Attributes: _path (string): Possible filepath for source if it has been given or finded from source file-object. _datas (dict): Dicti...
sveetch/py-css-styleguide
py_css_styleguide/model.py
Manifest.set_rule
python
def set_rule(self, name, properties): self._rule_attrs.append(name) setattr(self, name, properties)
Set a rules as object attribute. Arguments: name (string): Rule name to set as attribute name. properties (dict): Dictionnary of properties.
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/model.py#L89-L98
null
class Manifest(object): """ Manifest model During load process, every rule is stored as object attribute so you can reach them directly. Attributes: _path (string): Possible filepath for source if it has been given or finded from source file-object. _datas (dict): Dicti...
sveetch/py-css-styleguide
py_css_styleguide/model.py
Manifest.remove_rule
python
def remove_rule(self, name): self._rule_attrs.remove(name) delattr(self, name)
Remove a rule from attributes. Arguments: name (string): Rule name to remove.
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/model.py#L100-L108
null
class Manifest(object): """ Manifest model During load process, every rule is stored as object attribute so you can reach them directly. Attributes: _path (string): Possible filepath for source if it has been given or finded from source file-object. _datas (dict): Dicti...
sveetch/py-css-styleguide
py_css_styleguide/model.py
Manifest.to_json
python
def to_json(self, indent=4): agregate = { 'metas': self.metas, } agregate.update({k: getattr(self, k) for k in self._rule_attrs}) return json.dumps(agregate, indent=indent)
Serialize metas and reference attributes to a JSON string. Keyword Arguments: indent (int): Space indentation, default to ``4``. Returns: string: JSON datas.
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/model.py#L110-L126
null
class Manifest(object): """ Manifest model During load process, every rule is stored as object attribute so you can reach them directly. Attributes: _path (string): Possible filepath for source if it has been given or finded from source file-object. _datas (dict): Dicti...
rbarrois/confutils
confutils/configfile.py
ConfigLineList.find_lines
python
def find_lines(self, line): for other_line in self.lines: if other_line.match(line): yield other_line
Find all lines matching a given line.
train
https://github.com/rbarrois/confutils/blob/26bbb3f31c09a99ee2104263a9e97d6d3fc8e4f4/confutils/configfile.py#L110-L114
null
class ConfigLineList(object): """A list of ConfigLine.""" def __init__(self, *lines): self.lines = list(lines) def append(self, line): self.lines.append(line) def remove(self, line): old_len = len(self.lines) self.lines = [l for l in self.lines if not l.match(line)] ...
rbarrois/confutils
confutils/configfile.py
ConfigLineList.update
python
def update(self, old_line, new_line, once=False): nb = 0 for i, line in enumerate(self.lines): if line.match(old_line): self.lines[i] = new_line nb += 1 if once: return nb return nb
Replace all lines matching `old_line` with `new_line`. If ``once`` is set to True, remove only the first instance.
train
https://github.com/rbarrois/confutils/blob/26bbb3f31c09a99ee2104263a9e97d6d3fc8e4f4/confutils/configfile.py#L121-L133
null
class ConfigLineList(object): """A list of ConfigLine.""" def __init__(self, *lines): self.lines = list(lines) def append(self, line): self.lines.append(line) def find_lines(self, line): """Find all lines matching a given line.""" for other_line in self.lines: ...
rbarrois/confutils
confutils/configfile.py
Section.update
python
def update(self, old_line, new_line, once=False): nb = 0 for block in self.blocks: nb += block.update(old_line, new_line, once=once) if nb and once: return nb return nb
Replace all lines matching `old_line` with `new_line`. If ``once`` is set to True, remove only the first instance.
train
https://github.com/rbarrois/confutils/blob/26bbb3f31c09a99ee2104263a9e97d6d3fc8e4f4/confutils/configfile.py#L215-L225
null
class Section(object): """A section. A section has a ``name`` and lines spread around the file. """ def __init__(self, name): self.name = name self.blocks = [] self.extra_block = None def new_block(self, **kwargs): block = SectionBlock(self.name, **kwargs) s...
rbarrois/confutils
confutils/configfile.py
Section.remove
python
def remove(self, line): nb = 0 for block in self.blocks: nb += block.remove(line) return nb
Delete all lines matching the given line.
train
https://github.com/rbarrois/confutils/blob/26bbb3f31c09a99ee2104263a9e97d6d3fc8e4f4/confutils/configfile.py#L227-L233
null
class Section(object): """A section. A section has a ``name`` and lines spread around the file. """ def __init__(self, name): self.name = name self.blocks = [] self.extra_block = None def new_block(self, **kwargs): block = SectionBlock(self.name, **kwargs) s...
rbarrois/confutils
confutils/configfile.py
MultiValuedSectionView.add
python
def add(self, key, value): self.configfile.add(self.name, key, value)
Add a new value for a key. This differs from __setitem__ in adding a new value instead of updating the list of values, thus avoiding the need to fetch the previous list of values.
train
https://github.com/rbarrois/confutils/blob/26bbb3f31c09a99ee2104263a9e97d6d3fc8e4f4/confutils/configfile.py#L298-L305
null
class MultiValuedSectionView(BaseSectionView): """A SectionView where each key may have multiple values. Always provide the list of expected values when setting. """ def __getitem__(self, key): entries = list(self.configfile.get(self.name, key)) if not entries: raise KeyErro...