INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Modeled after http:// msdn. microsoft. com/ en - us/ library/ ms649016%28VS. 85%29. aspx #_win32_Copying_Information_to_the_Clipboard
def SetClipboardData(type, content): """ Modeled after http://msdn.microsoft.com /en-us/library/ms649016%28VS.85%29.aspx #_win32_Copying_Information_to_the_Clipboard """ allocators = { clipboard.CF_TEXT: ctypes.create_string_buffer, clipboard.CF_UNICODETEXT: ctypes.create_unicode_buffer, clipboard.CF_HTML: ...
The main ( cli ) interface for the pylint runner.
def main(output=None, error=None, verbose=False): """ The main (cli) interface for the pylint runner. """ runner = Runner(args=["--verbose"] if verbose is not False else None) runner.run(output, error)
Parses any supplied command - line args and provides help text.
def _parse_args(self, args): """Parses any supplied command-line args and provides help text. """ parser = ArgumentParser(description="Runs pylint recursively on a directory") parser.add_argument( "-v", "--verbose", dest="verbose", action="store_...
Parse the ignores setting from the pylintrc file if available.
def _parse_ignores(self): """ Parse the ignores setting from the pylintrc file if available. """ error_message = ( colorama.Fore.RED + "{} does not appear to be a valid pylintrc file".format(self.rcfile) + colorama.Fore.RESET ) if not os.path.isfile(...
Recursively walk through a directory and get all python files and then walk through any potential directories that are found off current directory so long as not within self. IGNORE_FOLDERS: return: all python files that were found off current_dir
def get_files_from_dir(self, current_dir): """ Recursively walk through a directory and get all python files and then walk through any potential directories that are found off current directory, so long as not within self.IGNORE_FOLDERS :return: all python files that were found o...
Runs pylint on all python files in the current directory
def run(self, output=None, error=None): """ Runs pylint on all python files in the current directory """ pylint_output = output if output is not None else sys.stdout pylint_error = error if error is not None else sys.stderr savedout, savederr = sys.__stdout__, sys.__stderr__ sys...
Decorator type check production rule output
def strict(*types): """Decorator, type check production rule output""" def decorate(func): @wraps(func) def wrapper(self, p): func(self, p) if not isinstance(p[0], types): raise YAMLStrictTypeError(p[0], types, func) wrapper.co_firstlineno = func...
Get cursor position based on previous newline
def find_column(t): """Get cursor position, based on previous newline""" pos = t.lexer.lexpos data = t.lexer.lexdata last_cr = data.rfind('\n', 0, pos) if last_cr < 0: last_cr = -1 column = pos - last_cr return column
: param payload: a key/ value object containing the scimeta you want to store e. g. { weather: sunny temperature: 80C }: return: empty ( 200 status code )
def custom(self, payload): """ :param payload: a key/value object containing the scimeta you want to store e.g. {"weather": "sunny", "temperature": "80C" } :return: empty (200 status code) """ url = "{url_base}/resource/{pid}/scimeta/...
: param payload: a key/ value object containing the scimeta you want to store e. g. { weather: sunny temperature: 80C }: return: empty ( 200 status code )
def get(self): """ :param payload: a key/value object containing the scimeta you want to store e.g. {"weather": "sunny", "temperature": "80C" } :return: empty (200 status code) """ url = "{url_base}/resource/{pid}/scimeta/custom/".for...
: return: array of file objects ( 200 status code )
def all(self): """ :return: array of file objects (200 status code) """ url = "{url_base}/resource/{pid}/files/".format(url_base=self.hs.url_base, pid=self.pid) r = self.hs._request('GET', url) ...
: params: title: string keywords: array extra_metadata: array temporal_coverage: coverage object spatial_coverage: coverage object: return: file metadata object ( 200 status code )
def metadata(self, file_path, params=None): """ :params: title: string keywords: array extra_metadata: array temporal_coverage: coverage object spatial_coverage: coverage object :return: file metadata object (200 ...
Unzips a file: param payload: zip_with_rel_path: string remove_original_zip: boolean: return: ( object ) unzipped_path: string
def unzip(self, payload): """ Unzips a file :param payload: zip_with_rel_path: string remove_original_zip: boolean :return: (object) unzipped_path: string """ zip_with_rel_path = payload.pop('zip_with_rel_path') ur...
Sets a file to a specific HydroShare file type ( e. g. NetCDF GeoRaster GeoFeature etc ): param payload: file_path: string ( relative path of the file to be set to a specific file type ) hs_file_type: string ( one of the supported files types: SingleFile NetCDF GeoRaster RefTimeseries TimeSeries and GeoFeature ): retur...
def set_file_type(self, payload): """ Sets a file to a specific HydroShare file type (e.g. NetCDF, GeoRaster, GeoFeature etc) :param payload: file_path: string (relative path of the file to be set to a specific file type) hs_file_type: string (one of the supported ...
Set a single flag on a resource.: param payload: t: can be one of make_public make_private make_shareable make_not_shareable make_discoverable make_not_discoverable: return: empty but with 202 status_code
def flag(self, payload): """Set a single flag on a resource. :param payload: t: can be one of make_public, make_private, make_shareable, make_not_shareable, make_discoverable, make_not_discoverable :return: empty but with 202 status_code """ ...
Upload a file to a hydroshare resource.: param payload: file: File object to upload to server folder: folder path to upload the file to: return: json object resource_id: string resource id file_name: string name of file
def files(self, payload): """Upload a file to a hydroshare resource. :param payload: file: File object to upload to server folder: folder path to upload the file to :return: json object resource_id: string resource id, file_name: string na...
Pass through helper function for flag function.
def public(self, boolean): """Pass through helper function for flag function.""" if(boolean): r = self.flag({ "flag": "make_public" }) else: r = self.flag({ "flag": "make_private" }) return r
Pass through helper function for flag function.
def discoverable(self, boolean): """Pass through helper function for flag function.""" if(boolean): r = self.flag({ "flag": "make_discoverable" }) else: r = self.flag({ "flag": "make_not_discoverable" }) ...
Pass through helper function for flag function.
def shareable(self, boolean): """Pass through helper function for flag function.""" if(boolean): r = self.flag({ "flag": "make_shareable" }) else: r = self.flag({ "flag": "make_not_shareable" }) r...
Context that prevents the computer from going to sleep.
def no_sleep(): """ Context that prevents the computer from going to sleep. """ mode = power.ES.continuous | power.ES.system_required handle_nonzero_success(power.SetThreadExecutionState(mode)) try: yield finally: handle_nonzero_success(power.SetThreadExecutionState(power.ES.continuous))
Install update and set up selfoss.
def selfoss(reset_password=False): '''Install, update and set up selfoss. This selfoss installation uses sqlite (selfoss-default), php5-fpm and nginx. The connection is https-only and secured by a letsencrypt certificate. This certificate must be created separately with task setup.server_letsencrypt....
get file path
def get_cache_path(filename): """ get file path """ cwd = os.path.dirname(os.path.realpath(__file__)) return os.path.join(cwd, filename)
parameter: file_path - path to cache file return: data after parsing json file
def read(filename='cache'): """ parameter: file_path - path to cache file return: data after parsing json file""" cache_path = get_cache_path(filename) if not os.path.exists(cache_path) or os.stat(cache_path).st_size == 0: return None with open(cache_path, 'r') as file: return json.load(file)
write data to cache file parameters: cache_path - path to cache file content - a data structure to save into cache file
def write(content, filename='cache'): """ write data to cache file parameters: cache_path - path to cache file content - a data structure to save into cache file""" cache_path = get_cache_path(filename) with open(cache_path, 'w') as file: if content is not None: json.dump(content, file, indent=3, sort_keys...
Return a SECURITY_ATTRIBUTES structure with the SID set to the specified user ( uses current user if none is specified ).
def get_security_attributes_for_user(user=None): """ Return a SECURITY_ATTRIBUTES structure with the SID set to the specified user (uses current user if none is specified). """ if user is None: user = get_current_user() assert isinstance(user, security.TOKEN_USER), ( "user must be TOKEN_USER instance") SD ...
Get the current process token
def get_process_token(): """ Get the current process token """ token = wintypes.HANDLE() res = process.OpenProcessToken( process.GetCurrentProcess(), process.TOKEN_ALL_ACCESS, token) if not res > 0: raise RuntimeError("Couldn't get process token") return token
Get the LUID for the SeCreateSymbolicLinkPrivilege
def get_symlink_luid(): """ Get the LUID for the SeCreateSymbolicLinkPrivilege """ symlink_luid = privilege.LUID() res = privilege.LookupPrivilegeValue( None, "SeCreateSymbolicLinkPrivilege", symlink_luid) if not res > 0: raise RuntimeError("Couldn't lookup privilege value") return symlink_luid
Get all privileges associated with the current process.
def get_privilege_information(): """ Get all privileges associated with the current process. """ # first call with zero length to determine what size buffer we need return_length = wintypes.DWORD() params = [ get_process_token(), privilege.TOKEN_INFORMATION_CLASS.TokenPrivileges, None, 0, return_length...
Try to assign the symlink privilege to the current process token. Return True if the assignment is successful.
def enable_symlink_privilege(): """ Try to assign the symlink privilege to the current process token. Return True if the assignment is successful. """ # create a space in memory for a TOKEN_PRIVILEGES structure # with one element size = ctypes.sizeof(privilege.TOKEN_PRIVILEGES) size += ctypes.sizeof(privilege....
Grant the create symlink privilege to who.
def grant_symlink_privilege(who, machine=''): """ Grant the 'create symlink' privilege to who. Based on http://support.microsoft.com/kb/132958 """ flags = security.POLICY_CREATE_ACCOUNT | security.POLICY_LOOKUP_NAMES policy = OpenPolicy(machine, flags) return policy
Return a base - module ( e. g. theno ) or a sub - module ( e. g. theno. service. raccoon ) from the dict addon_modules given by param module_name.
def get_or_create_module_r(module_name, base_module=None): '''Return a base-module (e.g. 'theno') or a sub-module (e.g. 'theno.service.raccoon') from the dict addon_modules given by param 'module_name'. If the highest module (e.g. 'theno') not exists, an empty module will be created. This will be ...
Recursively iterate through package_module and add every fabric task to the addon_module keeping the task hierarchy.
def add_tasks_r(addon_module, package_module, package_name): '''Recursively iterate through 'package_module' and add every fabric task to the 'addon_module' keeping the task hierarchy. Args: addon_module(types.ModuleType) package_module(types.ModuleType) package_name(str): Required,...
Load an fabsetup addon given by package_name and hook it in the base task namespace username.
def load_addon(username, package_name, _globals): '''Load an fabsetup addon given by 'package_name' and hook it in the base task namespace 'username'. Args: username(str) package_name(str) _globals(dict): the globals() namespace of the fabric script. Return: None ''' ad...
Load all known fabsetup addons which are installed as pypi pip - packages.
def load_pip_addons(_globals): '''Load all known fabsetup addons which are installed as pypi pip-packages. Args: _globals(dict): the globals() namespace of the fabric script. Return: None ''' for package_name in known_pip_addons: _, username = package_username(package_name) ...
>>> package_user ( fabsetup - theno - termdown ) ( termdown theno )
def package_username(repo): ''' >>> package_user('fabsetup-theno-termdown') (termdown, theno) ''' package = repo.replace('-', '_') username = repo.split('-')[1] return package, username
Load all fabsetup addons which are stored under ~/. fabsetup - addon - repos as git repositories.
def load_repo_addons(_globals): '''Load all fabsetup addons which are stored under ~/.fabsetup-addon-repos as git repositories. Args: _globals(dict): the globals() namespace of the fabric script. Return: None ''' repos_dir = os.path.expanduser('~/.fabsetup-addon-repos') if os.path....
Put custom commands at ~/ bin/
def users_bin_dir(): '''Put custom commands at '~/bin/' For the conversion of diagrams into the pdf format: * dia2pdf, ep2svg, svg2pdf * alldia2pdf, allep2svg, alldia2pdf ''' # circumvent circular import, cf. http://stackoverflow.com/a/18486863 from fabfile.setup import pencil2 pencil2(...
r \ n \ s *
def t_ignore_INDENT(self, t): r'\n\s*' indent_status, curr_depth, next_depth = self.get_indent_status(t) if indent_status == 'NODENT': return if indent_status == 'INDENT': # note: also set by # * t_B_SEQUENCE_COMPACT_START # * t_B_MA...
r ( ?<! \\ )
def t_begin_singlequote(self, t): r"(?<!\\)'" t.lexer.push_state('singlequote') # t.lexer.begin('singlequote') t.type = 'CAST_TYPE' t.type = 'SINGLEQUOTE_START' return t
r \ n + \ *
def t_fold_end(self, t): r'\n+\ *' column = find_column(t) indent = self.indent_stack[-1] if column < indent: rollback_lexpos(t) if column <= indent: t.lexer.pop_state() t.type = 'B_FOLD_END' if column > indent: t.type = 'SC...
r \ - \ + ( ? = - \ ) # ^ ^ sequence indicator | \ - \ + ( ? = [ \ { \ [] \ | [ ^: \ n ] *: \ s ) # ^ ^ ^^^ map indicator # ^ ^ flow indicator
def t_B_SEQUENCE_COMPACT_START(self, t): r""" \-\ + (?= -\ ) # ^ ^ sequence indicator | \-\ + (?= [\{\[]\ | [^:\n]*:\s ) # ^ ^ ^^^ map indicator # ^ ^ flow indicator """ indent_status, curr_depth, n...
r Find the DLL for a given library.
def find_lib(lib): r""" Find the DLL for a given library. Accepts a string or loaded module >>> print(find_lib('kernel32').lower()) c:\windows\system32\kernel32.dll """ if isinstance(lib, str): lib = getattr(ctypes.windll, lib) size = 1024 result = ctypes.create_unicode_buffer(size) library.GetModuleFile...
Get science metadata for a resource in XML + RDF format
def getScienceMetadataRDF(self, pid): """ Get science metadata for a resource in XML+RDF format :param pid: The HydroShare ID of the resource :raises: HydroShareNotAuthorized if the user is not authorized to view the metadata. :raises: HydroShareNotFound if the resource was not found. ...
Get a resource in BagIt format
def getResource(self, pid, destination=None, unzip=False, wait_for_bag_creation=True): """ Get a resource in BagIt format :param pid: The HydroShare ID of the resource :param destination: String representing the directory to save bag to. Bag will be saved to file named $(PID).zip in...
Get the list of resource types supported by the HydroShare server
def getResourceTypes(self): """ Get the list of resource types supported by the HydroShare server :return: A set of strings representing the HydroShare resource types :raises: HydroShareHTTPException to signal an HTTP error """ url = "{url_base}/resource/types".format(url_base=...
Create a new resource.
def createResource(self, resource_type, title, resource_file=None, resource_filename=None, abstract=None, keywords=None, edit_users=None, view_users=None, edit_groups=None, view_groups=None, metadata=None, extra_metadata=None, progress_callback=None):...
Delete a resource.
def deleteResource(self, pid): """ Delete a resource. :param pid: The HydroShare ID of the resource """ url = "{url_base}/resource/{pid}/".format(url_base=self.url_base, pid=pid) r = self._request('DELETE', url) ...
Set access rules for a resource. Current only allows for setting the public or private setting.
def setAccessRules(self, pid, public=False): """ Set access rules for a resource. Current only allows for setting the public or private setting. :param pid: The HydroShare ID of the resource :param public: True if the resource should be made public. """ url = "{url_base...
Add a new file to an existing resource
def addResourceFile(self, pid, resource_file, resource_filename=None, progress_callback=None): """ Add a new file to an existing resource :param pid: The HydroShare ID of the resource :param resource_file: a read-only binary file-like object (i.e. opened with the flag 'rb') or a string ...
Get a file within a resource.
def getResourceFile(self, pid, filename, destination=None): """ Get a file within a resource. :param pid: The HydroShare ID of the resource :param filename: String representing the name of the resource file to get. :param destination: String representing the directory to save the resour...
Delete a resource file
def deleteResourceFile(self, pid, filename): """ Delete a resource file :param pid: The HydroShare ID of the resource :param filename: String representing the name of the resource file to delete :return: Dictionary containing 'resource_id' the ID of the resource from which the ...
Get a listing of files within a resource.
def getResourceFileList(self, pid): """ Get a listing of files within a resource. :param pid: The HydroShare ID of the resource whose resource files are to be listed. :raises: HydroShareArgumentException if any parameters are invalid. :raises: HydroShareNotAuthorized if user is not aut...
Get a listing of files and folders for a resource at the specified path ( * pathname * )
def getResourceFolderContents(self, pid, pathname): """ Get a listing of files and folders for a resource at the specified path (*pathname*) :param pid: The HydroShare ID of the resource whose folder contents to be listed :param pathname: Folder path for which contents (files and folders) need ...
Create a Referenced Content File (. url ): param pid: The HydroShare ID of the resource for which the file should be created: param name: Filename for the referenced file: param ref_url: url to be used in the referenced file: param path: Optional defaults to contents directory if not provided. Folder path for the file ...
def createReferenceURL(self, pid, name, ref_url, path="", validate=True): """Create a Referenced Content File (.url) :param pid: The HydroShare ID of the resource for which the file should be created :param name: Filename for the referenced file ...
Update a Referenced Content File (. url )
def updateReferenceURL(self, pid, name, ref_url, path=""): """Update a Referenced Content File (.url) :param pid: The HydroShare ID of the resource for which the file should be updated :param name: Filename for the referenced file :param r...
Deprecated use updateReferenceURL. Update a Referenced Content File (. url )
def updateReferencedFile(self, pid, path, name, ref_url): """Deprecated, use updateReferenceURL. Update a Referenced Content File (.url) :param pid: The HydroShare ID of the resource for which the file should be updated :param path: Folder path for the file to be updated in ...
Query the GET/ hsapi/ userInfo/ REST end point of the HydroShare server.
def getUserInfo(self): """ Query the GET /hsapi/userInfo/ REST end point of the HydroShare server. :raises: HydroShareHTTPException to signal an HTTP error :return: A JSON object representing user info, for example: { "username": "username", "first_name...
Get the decrypted value of an SSM parameter
def get_ssm_parameter(parameter_name): ''' Get the decrypted value of an SSM parameter Args: parameter_name - the name of the stored parameter of interest Return: Value if allowed and present else None ''' try: response = boto3.client('ssm').get_parameters( ...
Automatically find/ download setuptools and make it available on sys. path
def use_setuptools( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15 ): """Automatically find/download setuptools and make it available on sys.path `version` should be a valid setuptools version number that is available as an egg for download under the `downlo...
Install and set up powerline for vim bash tmux and i3.
def powerline(): '''Install and set up powerline for vim, bash, tmux, and i3. It uses pip (python2) and the most up to date powerline version (trunk) from the github repository. More infos: https://github.com/powerline/powerline https://powerline.readthedocs.io/en/latest/installation.html ...
More infos: https:// powerline. readthedocs. io/ en/ latest/ installation/ linux. html#fonts - installation https:// wiki. archlinux. org/ index. php/ Font_configuration $XDG_CONFIG_HOME: http:// superuser. com/ a/ 365918
def install_special_glyphs(): ''' More infos: https://powerline.readthedocs.io/en/latest/installation/linux.html#fonts-installation https://wiki.archlinux.org/index.php/Font_configuration $XDG_CONFIG_HOME: http://superuser.com/a/365918 ''' from_dir = '~/repos/powerline/font' run('...
More infos: https:// powerline. readthedocs. io/ en/ latest/ installation. html#pip - installation
def install_upgrade_powerline(): ''' More infos: https://powerline.readthedocs.io/en/latest/installation.html#pip-installation ''' checkup_git_repo_legacy('https://github.com/powerline/powerline.git') path_to_powerline = os.path.expanduser('~/repos/powerline') run(flo('pip install --user -...
Set up the bash extension of powerline or powerline_shell ( another task ).
def powerline_for_bash_or_powerline_shell(bindings_dir): '''Set up the bash extension of powerline or powerline_shell (another task). ''' question = '\nSet up powerline-shell instead of powerline bash extension?' if query_yes_no(question, default='yes'): from setup import powerline_shell ...
Returns the contents of the tag if the provided path consitutes the base of the current pages path.
def ifancestor(parser, token): """ Returns the contents of the tag if the provided path consitutes the base of the current pages path. There are two ways to provide arguments to this tag. Firstly one may provide a single argument that starts with a forward slash. e.g. {% ifancestor '/path/...
Print ping exit statistics
def exit_statistics(hostname, start_time, count_sent, count_received, min_time, avg_time, max_time, deviation): """ Print ping exit statistics """ end_time = datetime.datetime.now() duration = end_time - start_time duration_sec = float(duration.seconds * 1000) duration_ms = float(duration.mi...
static method that calls os. walk but filters out anything that doesn t match the filter
def _filtered_walk(path, file_filter): """ static method that calls os.walk, but filters out anything that doesn't match the filter """ for root, dirs, files in os.walk(path): log.debug('looking in %s', root) log.debug('files is %s', files) file_filter.set_root(root) files = filter(file_filter, fi...
Set the appropriate Cache - Control and Expires headers for the given number of hours.
def cache_control_expires(num_hours): """ Set the appropriate Cache-Control and Expires headers for the given number of hours. """ num_seconds = int(num_hours * 60 * 60) def decorator(func): @wraps(func) def inner(request, *args, **kwargs): response = func(request, *...
The main event of the utility. Create or update a Cloud Formation stack. Injecting properties where needed
def upsert(self): """ The main event of the utility. Create or update a Cloud Formation stack. Injecting properties where needed Args: None Returns: True if the stack create/update is started successfully else False if the start goes off in t...
List the existing stacks in the indicated region
def list(self): """ List the existing stacks in the indicated region Args: None Returns: True if True Todo: Figure out what could go wrong and take steps to hanlde problems. """ self._initialize_list() int...
Smash the given stack
def smash(self): """ Smash the given stack Args: None Returns: True if True Todo: Figure out what could go wrong and take steps to hanlde problems. """ self._initialize_smash() try: stack_name ...
The utililty requires boto3 clients to Cloud Formation and S3. Here is where we make them.
def _init_boto3_clients(self): """ The utililty requires boto3 clients to Cloud Formation and S3. Here is where we make them. Args: None Returns: Good or Bad; True or False """ try: profile = self._config.get('environment', {}...
Get parameters from Simple Systems Manager
def _get_ssm_parameter(self, p): """ Get parameters from Simple Systems Manager Args: p - a parameter name Returns: a value, decrypted if needed, if successful or None if things go sideways. """ try: response = self._ssm.g...
Fill in the _parameters dict from the properties file.
def _fill_parameters(self): """ Fill in the _parameters dict from the properties file. Args: None Returns: True Todo: Figure out what could go wrong and at least acknowledge the the fact that Murphy was an optimist. """ ...
Fill in the _tags dict from the tags file.
def _read_tags(self): """ Fill in the _tags dict from the tags file. Args: None Returns: True Todo: Figure what could go wrong and at least acknowledge the the fact that Murphy was an optimist. """ tags = self._co...
Determine if we are creating a new stack or updating and existing one. The update member is set as you would expect at the end of this query.
def _set_update(self): """ Determine if we are creating a new stack or updating and existing one. The update member is set as you would expect at the end of this query. Args: None Returns: True """ try: self._updateStack = Fal...
Cloud Formation likes to take the template from S3 so here we put the template into S3. We also store the parameters file that was used in this run. Note: you can pass anything as the version string but you should at least consider a version control tag or git commit hash as the version.
def _archive_elements(self): """ Cloud Formation likes to take the template from S3 so here we put the template into S3. We also store the parameters file that was used in this run. Note: you can pass anything as the version string but you should at least consider a version contr...
We are putting stuff into S3 were supplied the bucket. Here we craft the key of the elements we are putting up there in the internet clouds.
def _craft_s3_keys(self): """ We are putting stuff into S3, were supplied the bucket. Here we craft the key of the elements we are putting up there in the internet clouds. Args: None Returns: a tuple of teplate file key and property file key ...
Spin in a loop while the Cloud Formation process either fails or succeeds
def poll_stack(self): """ Spin in a loop while the Cloud Formation process either fails or succeeds Args: None Returns: Good or bad; True or False """ logging.info('polling stack status, POLL_INTERVAL={}'.format(POLL_INTERVAL)) time.sleep...
Run setup tasks to set up a nicely configured desktop pc.
def setup_desktop(): '''Run setup tasks to set up a nicely configured desktop pc. This is highly biased on my personal preference. The task is defined in file fabsetup_custom/fabfile_addtitions/__init__.py and could be customized by Your own needs. More info: README.md ''' run('sudo apt-get u...
Run setup tasks to set up a nicely configured webserver.
def setup_webserver(): '''Run setup tasks to set up a nicely configured webserver. Features: * owncloud service * fdroid repository * certificates via letsencrypt * and more The task is defined in file fabsetup_custom/fabfile_addtitions/__init__.py and could be customized by Your o...
Open a server on Unix Domain Socket
def start_recv(sockfile=None): '''Open a server on Unix Domain Socket''' if sockfile is not None: SOCKFILE = sockfile else: # default sockfile SOCKFILE = "/tmp/snort_alert" if os.path.exists(SOCKFILE): os.unlink(SOCKFILE) unsock = socket.socket(socket.AF_UNIX, socke...
Dump object to a file like object or string.
def dump(obj, fp=None, indent=None, sort_keys=False, **kw): """ Dump object to a file like object or string. :param obj: :param fp: Open file like object :param int indent: Indent size, default 2 :param bool sort_keys: Optionally sort dictionary keys. :return: Yaml serialized data. """ ...
Dump string.
def dumps(obj, indent=None, default=None, sort_keys=False, **kw): """Dump string.""" return YAMLEncoder(indent=indent, default=default, sort_keys=sort_keys, **kw).encode(obj)
Load yaml file
def load(s, **kwargs): """Load yaml file""" try: return loads(s, **kwargs) except TypeError: return loads(s.read(), **kwargs)
Load string
def loads(s, cls=None, **kwargs): """Load string""" if not isinstance(s, string_types): raise TypeError('the YAML object must be str, not {0!r}'.format(s.__class__.__name__)) cls = cls or YAMLDecoder return cls(**kwargs).decode(s)
The address in big - endian
def address(self): "The address in big-endian" _ = struct.pack('L', self.address_num) return struct.unpack('!L', _)[0]
add to ~/. bashrc: Export of $NVM env variable and load nvm command.
def enable_nvm(): '''add to ~/.bashrc: Export of $NVM env variable and load nvm command.''' bash_snippet = '~/.bashrc_nvm' install_file_legacy(path=bash_snippet) prefix = flo('if [ -f {bash_snippet} ]; ') enabler = flo('if [ -f {bash_snippet} ]; then source {bash_snippet}; fi') if env.host == '...
Getting started with nvm ( cf. https:// github. com/ creationix/ nvm#usage ).
def nvm_primer(): '''Getting started with nvm (cf. https://github.com/creationix/nvm#usage). ''' print('\nDownload, compile and install the latest release of node:\n\n' + cyan(' nvm install node')) print('\nAnd then in any new shell:\n\n' + cyan(' nvm use node') + ' # use the...
some validation checks before doing anything
def validate_currency(*currencies): """ some validation checks before doing anything """ validated_currency = [] if not currencies: raise CurrencyException('My function need something to run, duh') for currency in currencies: currency = currency.upper() if not isinstance(currency, str): raise TypeError('Cu...
validation checks for price argument
def validate_price(price): """ validation checks for price argument """ if isinstance(price, str): try: price = int(price) except ValueError: # fallback if convert to int failed price = float(price) if not isinstance(price, (int, float)): raise TypeError('Price should be a number: ' + repr(price)) retur...
return name of currency
def name(currency, *, plural=False): """ return name of currency """ currency = validate_currency(currency) if plural: return _currencies[currency]['name_plural'] return _currencies[currency]['name']
return symbol of currency
def symbol(currency, *, native=True): """ return symbol of currency """ currency = validate_currency(currency) if native: return _currencies[currency]['symbol_native'] return _currencies[currency]['symbol']
rounding currency value based on its max decimal digits
def rounding(price, currency): """ rounding currency value based on its max decimal digits """ currency = validate_currency(currency) price = validate_price(price) if decimals(currency) == 0: return round(int(price), decimals(currency)) return round(price, decimals(currency))
return format price with symbol. Example format ( 100 USD ) return $100 pretty ( price currency abbrev = True trim = False ) abbrev: True: print value + symbol. Symbol can either be placed before or after value False: print value + currency code. currency code is placed behind value trim: True: trim float value to the ...
def pretty(price, currency, *, abbrev=True, trim=True): """ return format price with symbol. Example format(100, 'USD') return '$100' pretty(price, currency, abbrev=True, trim=False) abbrev: True: print value + symbol. Symbol can either be placed before or after value False: print value + currency code. currency...
check if last update is over 30 mins ago. if so return True to update else False
def check_update(from_currency, to_currency): """ check if last update is over 30 mins ago. if so return True to update, else False """ if from_currency not in ccache: # if currency never get converted before ccache[from_currency] = {} if ccache[from_currency].get(to_currency) is None: ccache[from_currency][to_c...
update from_currency to_currency pair in cache if last update for that pair is over 30 minutes ago by request API info
def update_cache(from_currency, to_currency): """ update from_currency to_currency pair in cache if last update for that pair is over 30 minutes ago by request API info """ if check_update(from_currency, to_currency) is True: ccache[from_currency][to_currency]['value'] = convert_using_api(from_currency, to_currenc...
convert from from_currency to to_currency by requesting API
def convert_using_api(from_currency, to_currency): """ convert from from_currency to to_currency by requesting API """ convert_str = from_currency + '_' + to_currency options = {'compact': 'ultra', 'q': convert_str} api_url = 'https://free.currencyconverterapi.com/api/v5/convert' result = requests.get(api_url, par...
convert from from_currency to to_currency using cached info
def convert(from_currency, to_currency, from_currency_price=1): """ convert from from_currency to to_currency using cached info """ get_cache() from_currency, to_currency = validate_currency(from_currency, to_currency) update_cache(from_currency, to_currency) return ccache[from_currency][to_currency]['value'] * fr...
wait for the signal ; return after the signal has occurred or the timeout in seconds elapses.
def wait_for_signal(self, timeout=None): """ wait for the signal; return after the signal has occurred or the timeout in seconds elapses. """ timeout_ms = int(timeout * 1000) if timeout else win32event.INFINITE win32event.WaitForSingleObject(self.signal_event, timeout_ms)
发送站内消息
def send_message(self, recipient_list, subject, body): """发送站内消息 :param recipient_list: 收件人列表 :param subject: 标题 :param body: 内容(不能超过 1024 个字符) """ url = 'http://www.shanbay.com/api/v1/message/' recipient = ','.join(recipient_list) data = { 'r...