_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q263700
scanAllProcessesForCwd
validation
def scanAllProcessesForCwd(searchPortion, isExactMatch=False): ''' scanAllProcessesForCwd - Scans all processes on the system for a given search pattern. @param searchPortion <str> - Any portion of directory to search @param isExactMatch <bool> Default False - If match should be exact, otherwise a partial match is performed. @return - <dict> - A dictionary of pid -> cwdResults for each pid that matched the search pattern. For format of
python
{ "resource": "" }
q263701
scanProcessForMapping
validation
def scanProcessForMapping(pid, searchPortion, isExactMatch=False, ignoreCase=False): ''' scanProcessForMapping - Searches a given pid's mappings for a certain pattern. @param pid <int> - A running process ID on this system @param searchPortion <str> - A mapping for which to search, example: libc or python or libz.so.1. Give empty string to return all mappings. @param isExactMatch <bool> Default False - If match should be exact, otherwise a partial match is performed. @param ignoreCase <bool> Default False - If True, search will be performed case-insensitively @return <dict> - If result is found, the following dict is returned. If no match found on the given pid, or pid is not found running, None is returned. { 'searchPortion' : The passed search pattern 'pid' : The passed pid (as an integer) 'owner' : String of process owner, or uid if no mapping can be found, or "unknown" if neither could be determined. 'cmdline' : Commandline string 'matchedMappings' : All mappings likes that matched the given search pattern } ''' try: try: pid = int(pid) except ValueError as e: sys.stderr.write('Expected an integer, got %s for pid.\n' %(str(type(pid)),)) raise e with open('/proc/%d/maps' %(pid,), 'r') as f: contents = f.read() lines = contents.split('\n') matchedMappings = [] if isExactMatch is True: if ignoreCase is False: isMatch = lambda searchFor, searchIn : bool(searchFor == searchIn) else: isMatch = lambda searchFor, searchIn : bool(searchFor.lower() == searchIn.lower()) else:
python
{ "resource": "" }
q263702
scanAllProcessesForMapping
validation
def scanAllProcessesForMapping(searchPortion, isExactMatch=False, ignoreCase=False): ''' scanAllProcessesForMapping - Scans all processes on the system for a given search pattern. @param searchPortion <str> - A mapping for which to search, example: libc or python or libz.so.1. Give empty string to return all mappings. @param isExactMatch <bool> Default False - If match should be exact, otherwise a partial match is performed. @param ignoreCase <bool> Default False - If True, search will be performed case-insensitively @return - <dict> - A dictionary of pid -> mappingResults for each pid that matched the search pattern. For format of "mappingResults", @see scanProcessForMapping ''' pids = getAllRunningPids() # Since processes could disappear, we run
python
{ "resource": "" }
q263703
scanProcessForOpenFile
validation
def scanProcessForOpenFile(pid, searchPortion, isExactMatch=True, ignoreCase=False): ''' scanProcessForOpenFile - Scans open FDs for a given pid to see if any are the provided searchPortion @param searchPortion <str> - Filename to check @param isExactMatch <bool> Default True - If match should be exact, otherwise a partial match is performed. @param ignoreCase <bool> Default False - If True, search will be performed case-insensitively @return - If result is found, the following dict is returned. If no match found on the given pid, or the pid is not found running, None is returned. { 'searchPortion' : The search portion provided 'pid' : The passed pid (as an integer) 'owner' : String of process owner, or "unknown" if one could not be determined 'cmdline' : Commandline string 'fds' : List of file descriptors assigned to this file (could be mapped several times) 'filenames' : List of the filenames matched } ''' try: try: pid = int(pid) except ValueError as e: sys.stderr.write('Expected an integer, got %s for pid.\n' %(str(type(pid)),)) raise e prefixDir = "/proc/%d/fd" % (pid,) processFDs = os.listdir(prefixDir) matchedFDs = [] matchedFilenames = [] if isExactMatch is True: if ignoreCase is False: isMatch = lambda searchFor, totalPath : bool(searchFor == totalPath) else: isMatch = lambda searchFor, totalPath : bool(searchFor.lower() == totalPath.lower()) else: if ignoreCase is False: isMatch = lambda searchFor, totalPath : bool(searchFor in totalPath)
python
{ "resource": "" }
q263704
scanAllProcessesForOpenFile
validation
def scanAllProcessesForOpenFile(searchPortion, isExactMatch=True, ignoreCase=False): ''' scanAllProcessessForOpenFile - Scans all processes on the system for a given filename @param searchPortion <str> - Filename to check @param isExactMatch <bool> Default True - If match should be exact, otherwise a partial match is performed. @param ignoreCase <bool> Default False - If True, search will be performed case-insensitively
python
{ "resource": "" }
q263705
Hub.connect
validation
def connect(self): """Create and connect to socket for TCP communication with hub.""" try: self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._socket.settimeout(TIMEOUT_SECONDS) self._socket.connect((self._ip, self._port)) _LOGGER.debug("Successfully created Hub at %s:%s :)", self._ip,
python
{ "resource": "" }
q263706
Hub.send_command
validation
def send_command(self, command): """Send TCP command to hub and return response.""" # use lock to make TCP send/receive thread safe with self._lock: try: self._socket.send(command.encode("utf8")) result = self.receive() # hub may send "status"/"new" messages that should be ignored while result.startswith("S") or result.startswith("NEW"): _LOGGER.debug("!Got response: %s", result) result = self.receive()
python
{ "resource": "" }
q263707
Hub.receive
validation
def receive(self): """Receive TCP response, looping to get whole thing or timeout.""" try: buffer = self._socket.recv(BUFFER_SIZE) except socket.timeout as error: # Something is wrong, assume it's offline temporarily _LOGGER.error("Error receiving: %s", error) # self._socket.close() return "" # Read until a newline or timeout
python
{ "resource": "" }
q263708
Hub.get_data
validation
def get_data(self): """Get current light data as dictionary with light zids as keys.""" response = self.send_command(GET_LIGHTS_COMMAND) _LOGGER.debug("get_data response: %s", repr(response)) if not response: _LOGGER.debug("Empty response: %s", response) return {} response = response.strip() # Check string before splitting (avoid IndexError if malformed) if not (response.startswith("GLB") and response.endswith(";")): _LOGGER.debug("Invalid response: %s", repr(response)) return {}
python
{ "resource": "" }
q263709
Hub.get_lights
validation
def get_lights(self): """Get current light data, set and return as list of Bulb objects.""" # Throttle updates. Use cached data if within UPDATE_INTERVAL_SECONDS now = datetime.datetime.now() if (now - self._last_updated) < datetime.timedelta( seconds=UPDATE_INTERVAL_SECONDS): # _LOGGER.debug("Using cached light data") return self._bulbs else: self._last_updated = now light_data = self.get_data() _LOGGER.debug("got: %s", light_data) if not light_data: return [] if self._bulbs: # Bulbs already created, just update values for bulb in self._bulbs: # use the values for the bulb with the correct ID try:
python
{ "resource": "" }
q263710
Bulb.set_brightness
validation
def set_brightness(self, brightness): """Set brightness of bulb.""" command = "C {},,,,{},\r\n".format(self._zid, brightness) response = self._hub.send_command(command)
python
{ "resource": "" }
q263711
Bulb.set_all
validation
def set_all(self, red, green, blue, brightness): """Set color and brightness of bulb.""" command = "C {},{},{},{},{},\r\n".format(self._zid, red, green, blue,
python
{ "resource": "" }
q263712
Bulb.update
validation
def update(self): """Update light objects to their current values.""" bulbs = self._hub.get_lights() if not bulbs:
python
{ "resource": "" }
q263713
retrieve_document
validation
def retrieve_document(file_path, directory='sec_filings'): ''' This function takes a file path beginning with edgar and stores the form in a directory. The default directory is sec_filings but can be changed through a keyword argument. ''' ftp = FTP('ftp.sec.gov', timeout=None) ftp.login() name = file_path.replace('/', '_') if not os.path.exists(directory): os.makedirs(directory) with tempfile.TemporaryFile() as
python
{ "resource": "" }
q263714
readtxt
validation
def readtxt(filepath): """ read file as is""" with open(filepath, 'rt') as f:
python
{ "resource": "" }
q263715
_clean_up
validation
def _clean_up(paths): """ Clean up after ourselves, removing created files. @param {[String]} A list of file paths specifying the files we've created during run. Will all be deleted. @return {None} """ print('Cleaning up') #
python
{ "resource": "" }
q263716
_create_index_file
validation
def _create_index_file( root_dir, location, image_files, dirs, force_no_processing=False): """ Create an index file in the given location, supplying known lists of present image files and subdirectories. @param {String} root_dir - The root directory of the entire crawl. Used to ascertain whether the given location is the top level. @param {String} location - The current directory of the crawl. The index file will be created here. @param {[String]} image_files - A list of image file names in the location. These will be displayed in the index file's gallery. @param {[String]} dirs - The subdirectories of the location directory. These will be displayed as links further down the file structure. @param {Boolean=False} force_no_processing - If True, do not attempt to actually process thumbnails, PIL images or anything. Simply index <img> tags with original file src attributes. @return {String} The full path (location plus filename) of the newly created index file. Intended for usage cleaning up created files. """ # Put together HTML as a list of the lines we'll want to include # Issue #2 exists to do this better than HTML in-code header_text = \ 'imageMe: ' + location + ' [' + str(len(image_files)) + ' image(s)]' html = [ '<!DOCTYPE html>', '<html>', ' <head>', ' <title>imageMe</title>' ' <style>', ' html, body {margin: 0;padding: 0;}', ' .header {text-align: right;}', ' .content {', ' padding: 3em;', ' padding-left: 4em;', ' padding-right: 4em;', ' }', ' .image {max-width: 100%; border-radius: 0.3em;}', ' td {width: ' + str(100.0 / IMAGES_PER_ROW) + '%;}', ' </style>', ' </head>', ' <body>', ' <div class="content">', ' <h2 class="header">' + header_text + '</h2>' ] # Populate the present subdirectories - this includes '..' unless we're at # the top level directories = [] if root_dir != location: directories
python
{ "resource": "" }
q263717
_create_index_files
validation
def _create_index_files(root_dir, force_no_processing=False): """ Crawl the root directory downwards, generating an index HTML file in each directory on the way down. @param {String} root_dir - The top level directory to crawl down from. In normal usage, this will be '.'. @param {Boolean=False} force_no_processing - If True, do not attempt to actually process thumbnails, PIL images or anything. Simply index <img> tags with original file src attributes. @return {[String]} Full file paths of all created files. """ # Initialise list of created file paths to build up as we make them created_files = [] # Walk the root dir downwards, creating index files as we go for here, dirs, files in os.walk(root_dir): print('Processing %s' % here) # Sort the subdirectories by name
python
{ "resource": "" }
q263718
_get_image_from_file
validation
def _get_image_from_file(dir_path, image_file): """ Get an instance of PIL.Image from the given file. @param {String} dir_path - The directory containing the image file @param {String} image_file - The filename of the image file within dir_path @return {PIL.Image} An instance of the image file as a PIL Image, or None if the functionality is not available. This could be because PIL is not present, or because it can't process the given file type. """ # Save ourselves the effort if PIL is not present, and return None now if not PIL_ENABLED: return None #
python
{ "resource": "" }
q263719
_get_src_from_image
validation
def _get_src_from_image(img, fallback_image_file): """ Get base-64 encoded data as a string for the given image. Fallback to return fallback_image_file if cannot get the image data or img is None. @param {Image} img - The PIL Image to get src data for @param {String} fallback_image_file - The filename of the image file, to be used when image data capture fails @return {String} The base-64 encoded image data string, or path to the file itself if not supported. """ # If the image is None, then we can't process, so we should return the # path to the file itself if img is None: return fallback_image_file # Target format should be the same as the original image format, unless it's # a TIF/TIFF, which can't be displayed by most browsers; we convert these #
python
{ "resource": "" }
q263720
_get_thumbnail_image_from_file
validation
def _get_thumbnail_image_from_file(dir_path, image_file): """ Get a PIL.Image from the given image file which has been scaled down to THUMBNAIL_WIDTH wide. @param {String} dir_path - The directory containing the image file @param {String} image_file - The filename of the image file within dir_path @return {PIL.Image} An instance of the thumbnail as a PIL Image, or None if the functionality is not available. See _get_image_from_file for details. """ # Get image img = _get_image_from_file(dir_path, image_file) # If it's not supported, exit now if img is None: return None if img.format.lower() == 'gif': return None # Get image dimensions img_width, img_height = img.size # We need to perform a
python
{ "resource": "" }
q263721
_run_server
validation
def _run_server(): """ Run the image server. This is blocking. Will handle user KeyboardInterrupt and other exceptions appropriately and return control once the server is stopped. @return {None} """ # Get the port to run on port = _get_server_port() # Configure allow_reuse_address to make re-runs of the script less painful - # if this is not True then waiting for the address to be freed after the # last run can block a subsequent run SocketServer.TCPServer.allow_reuse_address = True # Create the server instance server = SocketServer.TCPServer(
python
{ "resource": "" }
q263722
serve_dir
validation
def serve_dir(dir_path): """ Generate indexes and run server from the given directory downwards. @param {String} dir_path - The directory path (absolute, or relative to CWD) @return {None} """ # Create index files, and store the list of their paths for cleanup later # This time, force no processing - this gives us a fast first-pass in terms # of page generation, but potentially slow serving for large image files print('Performing first pass index file generation') created_files = _create_index_files(dir_path, True) if (PIL_ENABLED): # If PIL is enabled, we'd like to process the HTML indexes to include # generated thumbnails - this slows down generation so we don't do it # first time around, but now we're serving
python
{ "resource": "" }
q263723
static
validation
def static(**kwargs): """ USE carefully ^^ """ def wrap(fn):
python
{ "resource": "" }
q263724
rand_blend_mask
validation
def rand_blend_mask(shape, rand=rand.uniform(-10, 10), **kwargs): """ random blending masks """ # batch, channel = shape[0], shape[3] z = rand(shape[0])
python
{ "resource": "" }
q263725
snoise2d
validation
def snoise2d(size, z=0.0, scale=0.05, octaves=1, persistence=0.25, lacunarity=2.0): """ z value as like a seed """ import noise data = np.empty(size, dtype='float32') for y in range(size[0]):
python
{ "resource": "" }
q263726
to_permutation_matrix
validation
def to_permutation_matrix(matches): """Converts a permutation into a permutation matrix. `matches` is a dictionary whose keys are vertices and whose values are partners. For each vertex ``u`` and ``v``, entry (``u``, ``v``) in the returned matrix will be a ``1`` if and only if ``matches[u] == v``. Pre-condition: `matches` must be a permutation on an initial subset of the natural numbers. Returns a
python
{ "resource": "" }
q263727
four_blocks
validation
def four_blocks(topleft, topright, bottomleft, bottomright): """Convenience function that creates a block matrix with the specified blocks. Each argument must be a NumPy matrix. The two top
python
{ "resource": "" }
q263728
to_bipartite_matrix
validation
def to_bipartite_matrix(A): """Returns the adjacency matrix of a bipartite graph whose biadjacency matrix is `A`. `A` must be a NumPy array. If `A` has **m** rows and **n** columns, then the
python
{ "resource": "" }
q263729
to_pattern_matrix
validation
def to_pattern_matrix(D): """Returns the Boolean matrix in the same shape as `D` with ones exactly where there are nonzero entries in `D`. `D` must be a NumPy array. """ result = np.zeros_like(D) # This is a cleverer way of doing #
python
{ "resource": "" }
q263730
bump_version
validation
def bump_version(version, which=None): """Returns the result of incrementing `version`. If `which` is not specified, the "patch" part of the version number will be incremented. If `which` is specified, it must be ``'major'``, ``'minor'``, or ``'patch'``. If it is one of these three strings, the corresponding part of the version number will be incremented instead of the patch number. Returns a string representing the next version number. Example:: >>> bump_version('2.7.1') '2.7.2' >>> bump_version('2.7.1', 'minor') '2.8.0' >>> bump_version('2.7.1', 'major') '3.0.0' """ try: parts = [int(n) for n
python
{ "resource": "" }
q263731
get_version
validation
def get_version(filename, pattern): """Gets the current version from the specified file. This function assumes the file includes a string of the form:: <pattern> = <version>
python
{ "resource": "" }
q263732
fail
validation
def fail(message=None, exit_status=None): """Prints the specified message and exits the program with the specified exit status. """
python
{ "resource": "" }
q263733
git_tag
validation
def git_tag(tag): """Tags the current version.""" print('Tagging "{}"'.format(tag))
python
{ "resource": "" }
q263734
Renderer.initialize
validation
def initialize(self, templates_path, global_data): """initialize with templates' path parameters templates_path str the position of templates directory global_data dict globa data can be got in any templates"""
python
{ "resource": "" }
q263735
Renderer.render
validation
def render(self, template, **data): """Render data with template, return html unicodes. parameters template str the template's filename data dict the data to render
python
{ "resource": "" }
q263736
Renderer.render_to
validation
def render_to(self, path, template, **data): """Render data with template and then write to path""" html = self.render(template, **data)
python
{ "resource": "" }
q263737
render
validation
def render(template, **data): """shortcut to render data with `template`. Just add exception catch to `renderer.render`""" try: return renderer.render(template, **data)
python
{ "resource": "" }
q263738
GenericDataFrameAPIView.get_dataframe
validation
def get_dataframe(self): """ Get the DataFrame for this view. Defaults to using `self.dataframe`. This method should always be used rather than accessing `self.dataframe` directly, as `self.dataframe` gets evaluated only once, and those results are cached for all subsequent requests.
python
{ "resource": "" }
q263739
GenericDataFrameAPIView.index_row
validation
def index_row(self, dataframe): """ Indexes the row based on the request parameters. """
python
{ "resource": "" }
q263740
GenericDataFrameAPIView.get_object
validation
def get_object(self): """ Returns the row the view is displaying. You may want to override this if you need to provide non-standard queryset lookups. Eg if objects are referenced using multiple keyword arguments in the url conf. """ dataframe = self.filter_dataframe(self.get_dataframe()) assert self.lookup_url_kwarg in self.kwargs, ( 'Expected view %s to be called with a URL keyword argument ' 'named "%s". Fix your URL conf, or set the `.lookup_field` ' 'attribute on the view correctly.' %
python
{ "resource": "" }
q263741
GenericDataFrameAPIView.paginator
validation
def paginator(self): """ The paginator instance associated with the view, or `None`. """ if not hasattr(self, '_paginator'): if self.pagination_class is None: self._paginator = None
python
{ "resource": "" }
q263742
GenericDataFrameAPIView.paginate_dataframe
validation
def paginate_dataframe(self, dataframe): """ Return a single page of results, or `None` if pagination is disabled. """ if self.paginator is None: return
python
{ "resource": "" }
q263743
Config.parse
validation
def parse(self): """parse config, return a dict""" if exists(self.filepath): content = open(self.filepath).read().decode(charset) else: content = "" try:
python
{ "resource": "" }
q263744
render_to
validation
def render_to(path, template, **data): """shortcut to render data with `template` and then write to `path`. Just add exception catch to `renderer.render_to`""" try: renderer.render_to(path, template, **data)
python
{ "resource": "" }
q263745
Parser.parse
validation
def parse(self, source): """Parse ascii post source, return dict""" rt, title, title_pic, markdown = libparser.parse(source) if rt == -1: raise SeparatorNotFound elif rt == -2: raise PostTitleNotFound # change to unicode title, title_pic, markdown = map(to_unicode, (title, title_pic, markdown))
python
{ "resource": "" }
q263746
Parser.parse_filename
validation
def parse_filename(self, filepath): """parse post source files name to datetime object""" name = os.path.basename(filepath)[:-src_ext_len]
python
{ "resource": "" }
q263747
Server.run_server
validation
def run_server(self, port): """run a server binding to port""" try: self.server = MultiThreadedHTTPServer(('0.0.0.0', port), Handler) except socket.error, e: # failed to bind port
python
{ "resource": "" }
q263748
Server.get_files_stat
validation
def get_files_stat(self): """get source files' update time""" if not exists(Post.src_dir): logger.error(SourceDirectoryNotFound.__doc__) sys.exit(SourceDirectoryNotFound.exit_code) paths = []
python
{ "resource": "" }
q263749
Server.watch_files
validation
def watch_files(self): """watch files for changes, if changed, rebuild blog. this thread will quit if the main process ends""" try: while 1: sleep(1) # check every 1s try: files_stat = self.get_files_stat() except SystemExit: logger.error("Error occurred, server shut down") self.shutdown_server() if self.files_stat != files_stat: logger.info("Changes detected, start rebuilding..") try: generator.re_generate() global _root _root = generator.root except SystemExit: # catch sys.exit, it means fatal error
python
{ "resource": "" }
q263750
deploy_blog
validation
def deploy_blog(): """Deploy new blog to current directory""" logger.info(deploy_blog.__doc__) # `rsync -aqu path/to/res/* .`
python
{ "resource": "" }
q263751
using
validation
def using(context, alias): ''' Temporarily update the context to use the BlockContext for the given alias. ''' # An empty alias means look in the current widget set. if alias == '': yield context else: try: widgets = context.render_context[WIDGET_CONTEXT_KEY] except KeyError:
python
{ "resource": "" }
q263752
find_block
validation
def find_block(context, *names): ''' Find the first matching block in the current block_context ''' block_set = context.render_context[BLOCK_CONTEXT_KEY] for name in names: block =
python
{ "resource": "" }
q263753
load_widgets
validation
def load_widgets(context, **kwargs): ''' Load a series of widget libraries. ''' _soft = kwargs.pop('_soft', False) try: widgets = context.render_context[WIDGET_CONTEXT_KEY] except KeyError: widgets = context.render_context[WIDGET_CONTEXT_KEY] = {} for alias, template_name in kwargs.items(): if _soft and alias in widgets:
python
{ "resource": "" }
q263754
auto_widget
validation
def auto_widget(field): '''Return a list of widget names for the provided field.''' # Auto-detect info = { 'widget': field.field.widget.__class__.__name__, 'field': field.field.__class__.__name__,
python
{ "resource": "" }
q263755
reuse
validation
def reuse(context, block_list, **kwargs): ''' Allow reuse of a block within a template. {% reuse '_myblock' foo=bar %} If passed a list of block names, will use the first that matches: {% reuse list_of_block_names .... %} ''' try: block_context = context.render_context[BLOCK_CONTEXT_KEY] except KeyError: block_context = BlockContext() if not isinstance(block_list, (list, tuple)):
python
{ "resource": "" }
q263756
ChoiceWrapper.display
validation
def display(self): """ When dealing with optgroups, ensure that the value is properly force_text'd.
python
{ "resource": "" }
q263757
RedisBackend.create_message
validation
def create_message(self, level, msg_text, extra_tags='', date=None, url=None): """ Message instances are namedtuples of type `Message`. The date field is already serialized in datetime.isoformat ECMA-262 format """ if not date: now = timezone.now() else: now = date r = now.isoformat() if now.microsecond: r = r[:23] + r[26:] if
python
{ "resource": "" }
q263758
add_message_for
validation
def add_message_for(users, level, message_text, extra_tags='', date=None, url=None, fail_silently=False): """ Send a message to a list of users without passing through `django.contrib.messages` :param users: an iterable containing the recipients of the messages :param level: message level :param message_text: the string containing the message :param extra_tags: like the Django api, a string containing extra tags for the message :param date: a date, different than the default timezone.now
python
{ "resource": "" }
q263759
broadcast_message
validation
def broadcast_message(level, message_text, extra_tags='', date=None, url=None, fail_silently=False): """ Send a message to all users aka broadcast. :param level: message level :param message_text: the string containing the message :param extra_tags: like the Django api, a string containing extra tags for the message :param date: a date, different than the default timezone.now :param url: an optional url :param
python
{ "resource": "" }
q263760
mark_read
validation
def mark_read(user, message): """ Mark message instance as read for user. Returns True if the message was `unread` and thus actually marked as `read` or False in case it is already `read` or
python
{ "resource": "" }
q263761
mark_all_read
validation
def mark_all_read(user): """ Mark all message instances for a user as read. :param user: user instance
python
{ "resource": "" }
q263762
stored_messages_archive
validation
def stored_messages_archive(context, num_elements=10): """ Renders a list of archived messages for the current user """ if "user" in context: user = context["user"] if user.is_authenticated():
python
{ "resource": "" }
q263763
StorageMixin._get
validation
def _get(self, *args, **kwargs): """ Retrieve unread messages for current user, both from the inbox and from other storages """ messages, all_retrieved = super(StorageMixin, self)._get(*args, **kwargs) if self.user.is_authenticated():
python
{ "resource": "" }
q263764
StorageMixin.add
validation
def add(self, level, message, extra_tags=''): """ If the message level was configured for being stored and request.user is not anonymous, save it to the database. Otherwise, let some other class handle the message. Notice: controls like checking the message is not empty and the level is above the filter need to be performed here, but it could happen they'll be performed again later if the message does not need to be
python
{ "resource": "" }
q263765
StorageMixin._store
validation
def _store(self, messages, response, *args, **kwargs): """ persistent messages are already in the database inside the 'archive', so we can say they're already "stored". Here we put them in the inbox, or remove from the inbox in case the messages were iterated. messages contains only new msgs if self.used==True else contains both new and unread messages """ contrib_messages = [] if self.user.is_authenticated(): if not messages: # erase inbox
python
{ "resource": "" }
q263766
StorageMixin._prepare_messages
validation
def _prepare_messages(self, messages): """ Like the base class method, prepares a list of messages for storage
python
{ "resource": "" }
q263767
jocker
validation
def jocker(test_options=None): """Main entry point for script.""" version = ver_check() options =
python
{ "resource": "" }
q263768
init
validation
def init(base_level=DEFAULT_BASE_LOGGING_LEVEL, verbose_level=DEFAULT_VERBOSE_LOGGING_LEVEL, logging_config=None): """initializes a base logger you can use this to init a logger in any of your files. this will use config.py's LOGGER param and logging.dictConfig to configure the logger for you. :param int|logging.LEVEL base_level: desired base logging level :param int|logging.LEVEL verbose_level: desired verbose logging level :param dict logging_dict: dictConfig based configuration. used to override the default configuration from config.py :rtype: `python logger` """ if logging_config is None: logging_config = {} logging_config = logging_config or LOGGER # TODO: (IMPRV) only perform file related actions if file handler is # TODO: (IMPRV) defined. log_file = LOGGER['handlers']['file']['filename'] log_dir = os.path.dirname(os.path.expanduser(log_file)) if os.path.isfile(log_dir):
python
{ "resource": "" }
q263769
BaseConfigurator.configure_custom
validation
def configure_custom(self, config): """Configure an object with a user-supplied factory.""" c = config.pop('()') if not hasattr(c, '__call__') and \ hasattr(types, 'ClassType') and isinstance(c, types.ClassType): c = self.resolve(c) props = config.pop('.', None) #
python
{ "resource": "" }
q263770
_set_global_verbosity_level
validation
def _set_global_verbosity_level(is_verbose_output=False): """sets the global verbosity level for console and the jocker_lgr logger. :param bool is_verbose_output: should be output be
python
{ "resource": "" }
q263771
_import_config
validation
def _import_config(config_file): """returns a configuration object :param string config_file: path to config file """ # get config file path jocker_lgr.debug('config file is: {0}'.format(config_file)) # append to path for importing try: jocker_lgr.debug('importing config...') with open(config_file, 'r') as c: return yaml.safe_load(c.read())
python
{ "resource": "" }
q263772
execute
validation
def execute(varsfile, templatefile, outputfile=None, configfile=None, dryrun=False, build=False, push=False, verbose=False): """generates a Dockerfile, builds an image and pushes it to DockerHub A `Dockerfile` will be generated by Jinja2 according to the `varsfile` imported. If build is true, an image will be generated from the `outputfile` which is the generated Dockerfile and committed to the image:tag string supplied to `build`. If push is true, a build will be triggered and the produced image will be pushed to DockerHub upon completion. :param string varsfile: path to file with variables. :param string templatefile: path to template file to use. :param string outputfile: path to output Dockerfile. :param string configfile: path to yaml file with docker-py config. :param bool dryrun: mock run. :param build: False or the image:tag to build to. :param push: False
python
{ "resource": "" }
q263773
Jocker._parse_dumb_push_output
validation
def _parse_dumb_push_output(self, string): """since the push process outputs a single unicode string consisting of multiple JSON formatted "status" lines, we need to parse it so that it can be read as multiple strings. This will receive the string as an input, count curly braces and ignore any newlines. When the curly braces stack is 0, it will append the entire string it has read up until then to
python
{ "resource": "" }
q263774
upload_gif
validation
def upload_gif(gif): """Uploads an image file to Imgur""" client_id = os.environ.get('IMGUR_API_ID') client_secret = os.environ.get('IMGUR_API_SECRET') if client_id is None or client_secret is None: click.echo('Cannot upload -
python
{ "resource": "" }
q263775
is_dot
validation
def is_dot(ip): """Return true if the IP address is in dotted decimal notation.""" octets = str(ip).split('.') if len(octets) != 4: return False for i in octets: try:
python
{ "resource": "" }
q263776
is_bin
validation
def is_bin(ip): """Return true if the IP address is in binary notation.""" try: ip = str(ip) if len(ip) != 32:
python
{ "resource": "" }
q263777
is_oct
validation
def is_oct(ip): """Return true if the IP address is in octal notation.""" try: dec = int(str(ip), 8) except (TypeError, ValueError): return
python
{ "resource": "" }
q263778
is_dec
validation
def is_dec(ip): """Return true if the IP address is in decimal notation.""" try: dec = int(str(ip)) except ValueError:
python
{ "resource": "" }
q263779
_check_nm
validation
def _check_nm(nm, notation): """Function internally used to check if the given netmask is of the specified notation.""" # Convert to decimal, and check if it's in the list of valid netmasks. _NM_CHECK_FUNCT = { NM_DOT: _dot_to_dec, NM_HEX: _hex_to_dec, NM_BIN: _bin_to_dec,
python
{ "resource": "" }
q263780
is_bits_nm
validation
def is_bits_nm(nm): """Return true if the netmask is in bits notatation.""" try: bits = int(str(nm)) except ValueError:
python
{ "resource": "" }
q263781
is_wildcard_nm
validation
def is_wildcard_nm(nm): """Return true if the netmask is in wildcard bits notatation.""" try: dec = 0xFFFFFFFF - _dot_to_dec(nm, check=True) except ValueError:
python
{ "resource": "" }
q263782
_dot_to_dec
validation
def _dot_to_dec(ip, check=True): """Dotted decimal notation to decimal conversion.""" if check and not is_dot(ip): raise ValueError('_dot_to_dec: invalid IP: "%s"' % ip) octets = str(ip).split('.') dec =
python
{ "resource": "" }
q263783
_dec_to_dot
validation
def _dec_to_dot(ip): """Decimal to dotted decimal notation conversion.""" first = int((ip >> 24) & 255) second = int((ip >> 16) & 255) third =
python
{ "resource": "" }
q263784
_hex_to_dec
validation
def _hex_to_dec(ip, check=True): """Hexadecimal to decimal conversion.""" if check and not is_hex(ip):
python
{ "resource": "" }
q263785
_oct_to_dec
validation
def _oct_to_dec(ip, check=True): """Octal to decimal conversion.""" if check and not is_oct(ip): raise ValueError('_oct_to_dec: invalid IP: "%s"' % ip)
python
{ "resource": "" }
q263786
_bin_to_dec
validation
def _bin_to_dec(ip, check=True): """Binary to decimal conversion.""" if check and not is_bin(ip):
python
{ "resource": "" }
q263787
_BYTES_TO_BITS
validation
def _BYTES_TO_BITS(): """Generate a table to convert a whole byte to binary. This code was taken from the Python Cookbook, 2nd edition - O'Reilly.""" the_table = 256*[None] bits_per_byte = list(range(7, -1, -1)) for n in range(256): l = n
python
{ "resource": "" }
q263788
_dec_to_bin
validation
def _dec_to_bin(ip): """Decimal to binary conversion.""" bits = [] while ip: bits.append(_BYTES_TO_BITS[ip & 255])
python
{ "resource": "" }
q263789
_bits_to_dec
validation
def _bits_to_dec(nm, check=True): """Bits to decimal conversion.""" if check and not is_bits_nm(nm): raise
python
{ "resource": "" }
q263790
_wildcard_to_dec
validation
def _wildcard_to_dec(nm, check=False): """Wildcard bits to decimal conversion.""" if check and not is_wildcard_nm(nm):
python
{ "resource": "" }
q263791
_detect
validation
def _detect(ip, _isnm): """Function internally used to detect the notation of the given IP or netmask.""" ip = str(ip) if len(ip) > 1: if ip[0:2] == '0x': if _CHECK_FUNCT[IP_HEX][_isnm](ip): return IP_HEX elif ip[0] == '0': if _CHECK_FUNCT[IP_OCT][_isnm](ip): return IP_OCT if _CHECK_FUNCT[IP_DOT][_isnm](ip):
python
{ "resource": "" }
q263792
_convert
validation
def _convert(ip, notation, inotation, _check, _isnm): """Internally used to convert IPs and netmasks to other notations.""" inotation_orig = inotation notation_orig = notation inotation = _get_notation(inotation) notation = _get_notation(notation) if inotation is None: raise ValueError('_convert: unknown input notation: "%s"' % inotation_orig) if notation is None: raise ValueError('_convert: unknown output notation: "%s"' % notation_orig) docheck = _check or False if inotation == IP_UNKNOWN: inotation = _detect(ip, _isnm) if inotation == IP_UNKNOWN: raise ValueError('_convert: unable to guess input notation or invalid value') if _check is None: docheck = True # We _always_ check this case later. if _isnm: docheck = False dec = 0 if inotation == IP_DOT: dec = _dot_to_dec(ip, docheck) elif inotation == IP_HEX: dec = _hex_to_dec(ip, docheck) elif inotation == IP_BIN: dec = _bin_to_dec(ip, docheck) elif inotation == IP_OCT: dec = _oct_to_dec(ip, docheck) elif inotation == IP_DEC: dec = _dec_to_dec_long(ip, docheck) elif _isnm and inotation == NM_BITS: dec = _bits_to_dec(ip, docheck) elif _isnm and inotation == NM_WILDCARD: dec = _wildcard_to_dec(ip, docheck) else:
python
{ "resource": "" }
q263793
convert
validation
def convert(ip, notation=IP_DOT, inotation=IP_UNKNOWN, check=True): """Convert among IP address notations. Given an IP address, this function returns the address in another notation. @param ip: the IP address. @type ip: integers, strings or object with an appropriate __str()__ method. @param notation: the notation of the output (default: IP_DOT). @type notation: one of the IP_* constants, or the equivalent strings. @param inotation: force the input to be considered in the given notation (default the notation of the input is autodetected). @type inotation: one of the IP_* constants, or the equivalent strings. @param check: force the notation check on
python
{ "resource": "" }
q263794
convert_nm
validation
def convert_nm(nm, notation=IP_DOT, inotation=IP_UNKNOWN, check=True): """Convert a netmask to another notation."""
python
{ "resource": "" }
q263795
IPv4Address._add
validation
def _add(self, other): """Sum two IP addresses.""" if isinstance(other, self.__class__): sum_ = self._ip_dec + other._ip_dec elif isinstance(other, int): sum_ = self._ip_dec + other
python
{ "resource": "" }
q263796
IPv4Address._sub
validation
def _sub(self, other): """Subtract two IP addresses.""" if isinstance(other, self.__class__): sub = self._ip_dec - other._ip_dec if isinstance(other, int): sub = self._ip_dec - other
python
{ "resource": "" }
q263797
IPv4NetMask.get_bits
validation
def get_bits(self): """Return the bits notation of the netmask.""" return _convert(self._ip, notation=NM_BITS,
python
{ "resource": "" }
q263798
IPv4NetMask.get_wildcard
validation
def get_wildcard(self): """Return the wildcard bits notation of the netmask.""" return _convert(self._ip, notation=NM_WILDCARD,
python
{ "resource": "" }
q263799
CIDR.set
validation
def set(self, ip, netmask=None): """Set the IP address and the netmask.""" if isinstance(ip, str) and netmask is None: ipnm = ip.split('/') if len(ipnm) != 2: raise ValueError('set: invalid CIDR: "%s"' % ip) ip = ipnm[0] netmask = ipnm[1] if isinstance(ip, IPv4Address): self._ip = ip else: self._ip = IPv4Address(ip) if isinstance(netmask, IPv4NetMask): self._nm = netmask else: self._nm = IPv4NetMask(netmask) ipl = int(self._ip) nml = int(self._nm) base_add = ipl & nml self._ip_num = 0xFFFFFFFF - 1 - nml # NOTE: quite a mess. # This's here to handle /32 (-1) and /31 (0) netmasks. if self._ip_num in (-1, 0): if self._ip_num == -1: self._ip_num = 1 else: self._ip_num = 2 self._net_ip = None
python
{ "resource": "" }