body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
47574b4f9e57e1c9a4db9cb21fda60e61bad3eefc3bf033020b0a149e04f77a1
def disconnect(filename='cache.json'): '\n Connect to the local cache, so no internet connection is required.\n :returns: void\n ' global _CONNECTED, _CACHE try: with open(filename, 'r') as f: _CACHE = _recursively_convert_unicode_to_str(json.load(f))['data'] except FileNotFoundError: raise RedditException('The cache file \'{0}\' was not found, and I cannot disconnect without one. If you have not been given a cache.json file, then you can create a new one:\n >>> from reddit import reddit\n >>> reddit.connect()\n >>> reddit._start_editing()\n ...\n >>> reddit.get_posts("askreddit")\n ...\n >>> reddit._save_cache(\'{0}\')\n'.format(filename)) for key in _CACHE.keys(): _CACHE_COUNTER[key] = 0 _CONNECTED = False
Connect to the local cache, so no internet connection is required. :returns: void
python/reddit/reddit.py
disconnect
RealTimeWeb/reddit
2
python
def disconnect(filename='cache.json'): '\n Connect to the local cache, so no internet connection is required.\n :returns: void\n ' global _CONNECTED, _CACHE try: with open(filename, 'r') as f: _CACHE = _recursively_convert_unicode_to_str(json.load(f))['data'] except FileNotFoundError: raise RedditException('The cache file \'{0}\' was not found, and I cannot disconnect without one. If you have not been given a cache.json file, then you can create a new one:\n >>> from reddit import reddit\n >>> reddit.connect()\n >>> reddit._start_editing()\n ...\n >>> reddit.get_posts("askreddit")\n ...\n >>> reddit._save_cache(\'{0}\')\n'.format(filename)) for key in _CACHE.keys(): _CACHE_COUNTER[key] = 0 _CONNECTED = False
def disconnect(filename='cache.json'): '\n Connect to the local cache, so no internet connection is required.\n :returns: void\n ' global _CONNECTED, _CACHE try: with open(filename, 'r') as f: _CACHE = _recursively_convert_unicode_to_str(json.load(f))['data'] except FileNotFoundError: raise RedditException('The cache file \'{0}\' was not found, and I cannot disconnect without one. If you have not been given a cache.json file, then you can create a new one:\n >>> from reddit import reddit\n >>> reddit.connect()\n >>> reddit._start_editing()\n ...\n >>> reddit.get_posts("askreddit")\n ...\n >>> reddit._save_cache(\'{0}\')\n'.format(filename)) for key in _CACHE.keys(): _CACHE_COUNTER[key] = 0 _CONNECTED = False<|docstring|>Connect to the local cache, so no internet connection is required. :returns: void<|endoftext|>
e4e0122174e16a8b9158bbc0b3a828678f28a854b53f96f4b3925d67ba2c20c4
def _lookup(key): '\n Internal method that looks up a key in the local cache.\n :param key: Get the value based on the key from the cache.\n :type key: string\n :returns: void\n ' if (key not in _CACHE): return '' if (_CACHE_COUNTER[key] >= len(_CACHE[key][1:])): if (_CACHE[key][0] == 'empty'): return '' elif ((_CACHE[key][0] == 'repeat') and _CACHE[key][1:]): return _CACHE[key][(- 1)] elif (_CACHE[key][0] == 'repeat'): return '' else: _CACHE_COUNTER[key] = 1 else: _CACHE_COUNTER[key] += 1 if _CACHE[key]: return _CACHE[key][_CACHE_COUNTER[key]] else: return ''
Internal method that looks up a key in the local cache. :param key: Get the value based on the key from the cache. :type key: string :returns: void
python/reddit/reddit.py
_lookup
RealTimeWeb/reddit
2
python
def _lookup(key): '\n Internal method that looks up a key in the local cache.\n :param key: Get the value based on the key from the cache.\n :type key: string\n :returns: void\n ' if (key not in _CACHE): return if (_CACHE_COUNTER[key] >= len(_CACHE[key][1:])): if (_CACHE[key][0] == 'empty'): return elif ((_CACHE[key][0] == 'repeat') and _CACHE[key][1:]): return _CACHE[key][(- 1)] elif (_CACHE[key][0] == 'repeat'): return else: _CACHE_COUNTER[key] = 1 else: _CACHE_COUNTER[key] += 1 if _CACHE[key]: return _CACHE[key][_CACHE_COUNTER[key]] else: return
def _lookup(key): '\n Internal method that looks up a key in the local cache.\n :param key: Get the value based on the key from the cache.\n :type key: string\n :returns: void\n ' if (key not in _CACHE): return if (_CACHE_COUNTER[key] >= len(_CACHE[key][1:])): if (_CACHE[key][0] == 'empty'): return elif ((_CACHE[key][0] == 'repeat') and _CACHE[key][1:]): return _CACHE[key][(- 1)] elif (_CACHE[key][0] == 'repeat'): return else: _CACHE_COUNTER[key] = 1 else: _CACHE_COUNTER[key] += 1 if _CACHE[key]: return _CACHE[key][_CACHE_COUNTER[key]] else: return <|docstring|>Internal method that looks up a key in the local cache. :param key: Get the value based on the key from the cache. :type key: string :returns: void<|endoftext|>
5e824300d19c3e53245e1f7b77e2a5c395efc00c7f8bee538614e8a8aaa0845e
def _add_to_cache(key, value): '\n Internal method to add a new key-value to the local cache.\n :param str key: The new url to add to the cache\n :param str value: The HTTP response for this key.\n :returns: void\n ' if (key in _CACHE): _CACHE[key].append(value) else: _CACHE[key] = [_PATTERN, value] _CACHE_COUNTER[key] = 0
Internal method to add a new key-value to the local cache. :param str key: The new url to add to the cache :param str value: The HTTP response for this key. :returns: void
python/reddit/reddit.py
_add_to_cache
RealTimeWeb/reddit
2
python
def _add_to_cache(key, value): '\n Internal method to add a new key-value to the local cache.\n :param str key: The new url to add to the cache\n :param str value: The HTTP response for this key.\n :returns: void\n ' if (key in _CACHE): _CACHE[key].append(value) else: _CACHE[key] = [_PATTERN, value] _CACHE_COUNTER[key] = 0
def _add_to_cache(key, value): '\n Internal method to add a new key-value to the local cache.\n :param str key: The new url to add to the cache\n :param str value: The HTTP response for this key.\n :returns: void\n ' if (key in _CACHE): _CACHE[key].append(value) else: _CACHE[key] = [_PATTERN, value] _CACHE_COUNTER[key] = 0<|docstring|>Internal method to add a new key-value to the local cache. :param str key: The new url to add to the cache :param str value: The HTTP response for this key. :returns: void<|endoftext|>
de2489248a33fc076b19cfd23f29299d3e527e837fd70699504f9348fe058346
def _clear_key(key): '\n Internal method to remove a key from the local cache.\n :param str key: The url to remove from the cache\n ' if (key in _CACHE): del _CACHE[key]
Internal method to remove a key from the local cache. :param str key: The url to remove from the cache
python/reddit/reddit.py
_clear_key
RealTimeWeb/reddit
2
python
def _clear_key(key): '\n Internal method to remove a key from the local cache.\n :param str key: The url to remove from the cache\n ' if (key in _CACHE): del _CACHE[key]
def _clear_key(key): '\n Internal method to remove a key from the local cache.\n :param str key: The url to remove from the cache\n ' if (key in _CACHE): del _CACHE[key]<|docstring|>Internal method to remove a key from the local cache. :param str key: The url to remove from the cache<|endoftext|>
9723959d1111edd76808cc1eec2aadaafd0a5a1ebf931c20379f6c2988ca164e
def _save_cache(filename='cache.json'): '\n Internal method to save the cache in memory to a file, so that it can be used later.\n \n :param str filename: the location to store this at.\n ' with open(filename, 'w') as f: json.dump({'data': _CACHE, 'metadata': ''}, f)
Internal method to save the cache in memory to a file, so that it can be used later. :param str filename: the location to store this at.
python/reddit/reddit.py
_save_cache
RealTimeWeb/reddit
2
python
def _save_cache(filename='cache.json'): '\n Internal method to save the cache in memory to a file, so that it can be used later.\n \n :param str filename: the location to store this at.\n ' with open(filename, 'w') as f: json.dump({'data': _CACHE, 'metadata': }, f)
def _save_cache(filename='cache.json'): '\n Internal method to save the cache in memory to a file, so that it can be used later.\n \n :param str filename: the location to store this at.\n ' with open(filename, 'w') as f: json.dump({'data': _CACHE, 'metadata': }, f)<|docstring|>Internal method to save the cache in memory to a file, so that it can be used later. :param str filename: the location to store this at.<|endoftext|>
8ce2e2a72ea3ceeae2c8c83a641ac34a7960e6c5d837e36111e487f470243daa
def _get_posts_request(subreddit='all', sort_mode='hot', allow_nsfw=False): '\n Used to build the request string used by :func:`get_posts`.\n \n \n :param str subreddit: The subreddit that Posts will be returned from (without the "r/" preceeding it). Use "all" to return results from all subreddits.\n :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time).\n :returns: str\n ' return 'http://www.reddit.com/r/{}/{}.json?nsfw={}'.format(subreddit, sort_mode, allow_nsfw)
Used to build the request string used by :func:`get_posts`. :param str subreddit: The subreddit that Posts will be returned from (without the "r/" preceeding it). Use "all" to return results from all subreddits. :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time). :returns: str
python/reddit/reddit.py
_get_posts_request
RealTimeWeb/reddit
2
python
def _get_posts_request(subreddit='all', sort_mode='hot', allow_nsfw=False): '\n Used to build the request string used by :func:`get_posts`.\n \n \n :param str subreddit: The subreddit that Posts will be returned from (without the "r/" preceeding it). Use "all" to return results from all subreddits.\n :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time).\n :returns: str\n ' return 'http://www.reddit.com/r/{}/{}.json?nsfw={}'.format(subreddit, sort_mode, allow_nsfw)
def _get_posts_request(subreddit='all', sort_mode='hot', allow_nsfw=False): '\n Used to build the request string used by :func:`get_posts`.\n \n \n :param str subreddit: The subreddit that Posts will be returned from (without the "r/" preceeding it). Use "all" to return results from all subreddits.\n :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time).\n :returns: str\n ' return 'http://www.reddit.com/r/{}/{}.json?nsfw={}'.format(subreddit, sort_mode, allow_nsfw)<|docstring|>Used to build the request string used by :func:`get_posts`. :param str subreddit: The subreddit that Posts will be returned from (without the "r/" preceeding it). Use "all" to return results from all subreddits. :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time). :returns: str<|endoftext|>
8f8fb84f50deb081bb39715edfb55c1a571006be21c58f59228dc7096f935ebb
def _get_posts_string(subreddit='all', sort_mode='hot', allow_nsfw=False): '\n Like :func:`get_posts` except returns the raw data instead.\n \n :param str subreddit: The subreddit that Posts will be returned from (without the "r/" preceeding it). Use "all" to return results from all subreddits.\n :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time).\n :returns: str\n ' key = _get_posts_request(subreddit, sort_mode, allow_nsfw) result = (_get(key) if _CONNECTED else _lookup(key)) if (_CONNECTED and _EDITABLE): _add_to_cache(key, result) return result
Like :func:`get_posts` except returns the raw data instead. :param str subreddit: The subreddit that Posts will be returned from (without the "r/" preceeding it). Use "all" to return results from all subreddits. :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time). :returns: str
python/reddit/reddit.py
_get_posts_string
RealTimeWeb/reddit
2
python
def _get_posts_string(subreddit='all', sort_mode='hot', allow_nsfw=False): '\n Like :func:`get_posts` except returns the raw data instead.\n \n :param str subreddit: The subreddit that Posts will be returned from (without the "r/" preceeding it). Use "all" to return results from all subreddits.\n :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time).\n :returns: str\n ' key = _get_posts_request(subreddit, sort_mode, allow_nsfw) result = (_get(key) if _CONNECTED else _lookup(key)) if (_CONNECTED and _EDITABLE): _add_to_cache(key, result) return result
def _get_posts_string(subreddit='all', sort_mode='hot', allow_nsfw=False): '\n Like :func:`get_posts` except returns the raw data instead.\n \n :param str subreddit: The subreddit that Posts will be returned from (without the "r/" preceeding it). Use "all" to return results from all subreddits.\n :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time).\n :returns: str\n ' key = _get_posts_request(subreddit, sort_mode, allow_nsfw) result = (_get(key) if _CONNECTED else _lookup(key)) if (_CONNECTED and _EDITABLE): _add_to_cache(key, result) return result<|docstring|>Like :func:`get_posts` except returns the raw data instead. :param str subreddit: The subreddit that Posts will be returned from (without the "r/" preceeding it). Use "all" to return results from all subreddits. :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time). :returns: str<|endoftext|>
46a9df51a63b89e80ee0388d6ec40d06f9391ba936a3aa536d10091adea59264
def get_posts(subreddit='all', sort_mode='hot', allow_nsfw=False): '\n Retrieves all the posts.\n \n :param str subreddit: The subreddit that Posts will be returned from (without the "r/" preceeding it). Use "all" to return results from all subreddits.\n :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time). Finally, there is "random", which returns a single post at random from within this subreddit.\n :returns: list of Post\n ' if (sort_mode not in SORT_MODES): raise RedditException('Unknown sort mode: {}'.format(sort_mode)) try: result = _get_posts_string(subreddit, sort_mode, allow_nsfw) except HTTPError as e: if (e.code == 404): raise RedditException('This subreddit does not exist yet.') else: raise RedditException('Internet error ({}): {}'.format(e.code, e.reason)) if result: try: if (sort_mode == 'random'): json_result = _from_json(result)[0]['data']['children'] else: json_result = _from_json(result)['data']['children'] except KeyError: raise RedditException("The response from the server didn't have the right fields.") except ValueError: raise RedditException("The response from the server didn't make any sense.") if ('error' in json_result): raise RedditException('Error from Reddit: {}'.format(json_result.get('error', 'Unknown error.'))) posts = list(map(Post._from_json, json_result)) if (not allow_nsfw): posts = [post for post in posts if (not post.is_nsfw)] return posts elif _CONNECTED: raise RedditException('No response from the server.') else: raise RedditException('No data was in the cache for this subreddit.')
Retrieves all the posts. :param str subreddit: The subreddit that Posts will be returned from (without the "r/" preceeding it). Use "all" to return results from all subreddits. :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time). Finally, there is "random", which returns a single post at random from within this subreddit. :returns: list of Post
python/reddit/reddit.py
get_posts
RealTimeWeb/reddit
2
python
def get_posts(subreddit='all', sort_mode='hot', allow_nsfw=False): '\n Retrieves all the posts.\n \n :param str subreddit: The subreddit that Posts will be returned from (without the "r/" preceeding it). Use "all" to return results from all subreddits.\n :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time). Finally, there is "random", which returns a single post at random from within this subreddit.\n :returns: list of Post\n ' if (sort_mode not in SORT_MODES): raise RedditException('Unknown sort mode: {}'.format(sort_mode)) try: result = _get_posts_string(subreddit, sort_mode, allow_nsfw) except HTTPError as e: if (e.code == 404): raise RedditException('This subreddit does not exist yet.') else: raise RedditException('Internet error ({}): {}'.format(e.code, e.reason)) if result: try: if (sort_mode == 'random'): json_result = _from_json(result)[0]['data']['children'] else: json_result = _from_json(result)['data']['children'] except KeyError: raise RedditException("The response from the server didn't have the right fields.") except ValueError: raise RedditException("The response from the server didn't make any sense.") if ('error' in json_result): raise RedditException('Error from Reddit: {}'.format(json_result.get('error', 'Unknown error.'))) posts = list(map(Post._from_json, json_result)) if (not allow_nsfw): posts = [post for post in posts if (not post.is_nsfw)] return posts elif _CONNECTED: raise RedditException('No response from the server.') else: raise RedditException('No data was in the cache for this subreddit.')
def get_posts(subreddit='all', sort_mode='hot', allow_nsfw=False): '\n Retrieves all the posts.\n \n :param str subreddit: The subreddit that Posts will be returned from (without the "r/" preceeding it). Use "all" to return results from all subreddits.\n :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time). Finally, there is "random", which returns a single post at random from within this subreddit.\n :returns: list of Post\n ' if (sort_mode not in SORT_MODES): raise RedditException('Unknown sort mode: {}'.format(sort_mode)) try: result = _get_posts_string(subreddit, sort_mode, allow_nsfw) except HTTPError as e: if (e.code == 404): raise RedditException('This subreddit does not exist yet.') else: raise RedditException('Internet error ({}): {}'.format(e.code, e.reason)) if result: try: if (sort_mode == 'random'): json_result = _from_json(result)[0]['data']['children'] else: json_result = _from_json(result)['data']['children'] except KeyError: raise RedditException("The response from the server didn't have the right fields.") except ValueError: raise RedditException("The response from the server didn't make any sense.") if ('error' in json_result): raise RedditException('Error from Reddit: {}'.format(json_result.get('error', 'Unknown error.'))) posts = list(map(Post._from_json, json_result)) if (not allow_nsfw): posts = [post for post in posts if (not post.is_nsfw)] return posts elif _CONNECTED: raise RedditException('No response from the server.') else: raise RedditException('No data was in the cache for this subreddit.')<|docstring|>Retrieves all the posts. :param str subreddit: The subreddit that Posts will be returned from (without the "r/" preceeding it). Use "all" to return results from all subreddits. :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time). Finally, there is "random", which returns a single post at random from within this subreddit. :returns: list of Post<|endoftext|>
b682877d4987f7fa67afa074aaa7c90f4514a2478c02ee0265eaf9d90caff150
def _get_comments_request(post, sort_mode, max_depth, max_breadth): '\n Used to build the request string used by :func:`get_comments`.\n \n \n :param str post: The unique id of a Post from which Comments will be returned.\n :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time).\n :returns: str\n ' return 'http://www.reddit.com/r/all/comments/{}/{}.json?max_depth={}&max_breadth={}'.format(post, sort_mode, max_depth, max_breadth)
Used to build the request string used by :func:`get_comments`. :param str post: The unique id of a Post from which Comments will be returned. :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time). :returns: str
python/reddit/reddit.py
_get_comments_request
RealTimeWeb/reddit
2
python
def _get_comments_request(post, sort_mode, max_depth, max_breadth): '\n Used to build the request string used by :func:`get_comments`.\n \n \n :param str post: The unique id of a Post from which Comments will be returned.\n :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time).\n :returns: str\n ' return 'http://www.reddit.com/r/all/comments/{}/{}.json?max_depth={}&max_breadth={}'.format(post, sort_mode, max_depth, max_breadth)
def _get_comments_request(post, sort_mode, max_depth, max_breadth): '\n Used to build the request string used by :func:`get_comments`.\n \n \n :param str post: The unique id of a Post from which Comments will be returned.\n :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time).\n :returns: str\n ' return 'http://www.reddit.com/r/all/comments/{}/{}.json?max_depth={}&max_breadth={}'.format(post, sort_mode, max_depth, max_breadth)<|docstring|>Used to build the request string used by :func:`get_comments`. :param str post: The unique id of a Post from which Comments will be returned. :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time). :returns: str<|endoftext|>
17fd59eb83a70edfcd1d89b1635cac444e0ec8b32737057ddbee9ad4dfcaa6fb
def _get_comments_string(post, sort_mode, max_depth, max_breadth): '\n Like :func:`get_comments` except returns the raw data instead.\n \n :param str post: The unique id of a Post from which Comments will be returned.\n :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time).\n :returns: str\n ' key = _get_comments_request(post, sort_mode, max_depth, max_breadth) result = (_get(key) if _CONNECTED else _lookup(key)) if (_CONNECTED and _EDITABLE): _add_to_cache(key, result) return result
Like :func:`get_comments` except returns the raw data instead. :param str post: The unique id of a Post from which Comments will be returned. :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time). :returns: str
python/reddit/reddit.py
_get_comments_string
RealTimeWeb/reddit
2
python
def _get_comments_string(post, sort_mode, max_depth, max_breadth): '\n Like :func:`get_comments` except returns the raw data instead.\n \n :param str post: The unique id of a Post from which Comments will be returned.\n :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time).\n :returns: str\n ' key = _get_comments_request(post, sort_mode, max_depth, max_breadth) result = (_get(key) if _CONNECTED else _lookup(key)) if (_CONNECTED and _EDITABLE): _add_to_cache(key, result) return result
def _get_comments_string(post, sort_mode, max_depth, max_breadth): '\n Like :func:`get_comments` except returns the raw data instead.\n \n :param str post: The unique id of a Post from which Comments will be returned.\n :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time).\n :returns: str\n ' key = _get_comments_request(post, sort_mode, max_depth, max_breadth) result = (_get(key) if _CONNECTED else _lookup(key)) if (_CONNECTED and _EDITABLE): _add_to_cache(key, result) return result<|docstring|>Like :func:`get_comments` except returns the raw data instead. :param str post: The unique id of a Post from which Comments will be returned. :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time). :returns: str<|endoftext|>
f1d10f58f0ddfb6d07b061e64eab0a147a408dc953d009f3ec36694f56ea2fce
def get_comments(post, sort_mode='hot', max_depth=5, max_breadth=5): '\n Retrieves comments for a post.\n \n :param post: The unique id of a Post from which Comments will be returned.\n :type post: `str` or :ref:`Post`\n :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time).\n :param int max_depth: The maximum depth that comments will be retrieved from (i.e., how many descendants from the topmost comment). To go down infinitely, use None.\n :param int max_breadth: The maximum breadth that comments will be retrieved from (i.e., how many siblings from the topmost comment). Note that this breadth applies at every subtree - in effect, it is the branching factor. To get all siblings, use None.\n :returns: list of Comment\n ' if (sort_mode not in SORT_MODES): raise RedditException('Unknown sort mode: {}'.format(sort_mode)) if isinstance(post, Post): post = post.id elif (not isinstance(post, str)): raise RedditException('The post parameter should be a String or a Post') result = _get_comments_string(post, sort_mode, max_depth, max_breadth) if result: try: json_result = _from_json(result)[1]['data']['children'] except ValueError: raise RedditException("The response from the server didn't make any sense.") if ('error' in json_result): raise RedditException('Error from Reddit: {}'.format(json_result.get('error', 'Unknown error.'))) if (max_breadth is None): return [Comment._from_json(r, post, max_depth=(max_depth - 1)) for r in json_result] else: return [Comment._from_json(r, post, max_depth=(max_depth - 1), max_breadth=max_breadth) for r in json_result[:max_breadth]] elif _CONNECTED: raise RedditException('No response from the server.') else: raise RedditException('No data was in the cache for this comment.')
Retrieves comments for a post. :param post: The unique id of a Post from which Comments will be returned. :type post: `str` or :ref:`Post` :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time). :param int max_depth: The maximum depth that comments will be retrieved from (i.e., how many descendants from the topmost comment). To go down infinitely, use None. :param int max_breadth: The maximum breadth that comments will be retrieved from (i.e., how many siblings from the topmost comment). Note that this breadth applies at every subtree - in effect, it is the branching factor. To get all siblings, use None. :returns: list of Comment
python/reddit/reddit.py
get_comments
RealTimeWeb/reddit
2
python
def get_comments(post, sort_mode='hot', max_depth=5, max_breadth=5): '\n Retrieves comments for a post.\n \n :param post: The unique id of a Post from which Comments will be returned.\n :type post: `str` or :ref:`Post`\n :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time).\n :param int max_depth: The maximum depth that comments will be retrieved from (i.e., how many descendants from the topmost comment). To go down infinitely, use None.\n :param int max_breadth: The maximum breadth that comments will be retrieved from (i.e., how many siblings from the topmost comment). Note that this breadth applies at every subtree - in effect, it is the branching factor. To get all siblings, use None.\n :returns: list of Comment\n ' if (sort_mode not in SORT_MODES): raise RedditException('Unknown sort mode: {}'.format(sort_mode)) if isinstance(post, Post): post = post.id elif (not isinstance(post, str)): raise RedditException('The post parameter should be a String or a Post') result = _get_comments_string(post, sort_mode, max_depth, max_breadth) if result: try: json_result = _from_json(result)[1]['data']['children'] except ValueError: raise RedditException("The response from the server didn't make any sense.") if ('error' in json_result): raise RedditException('Error from Reddit: {}'.format(json_result.get('error', 'Unknown error.'))) if (max_breadth is None): return [Comment._from_json(r, post, max_depth=(max_depth - 1)) for r in json_result] else: return [Comment._from_json(r, post, max_depth=(max_depth - 1), max_breadth=max_breadth) for r in json_result[:max_breadth]] elif _CONNECTED: raise RedditException('No response from the server.') else: raise RedditException('No data was in the cache for this comment.')
def get_comments(post, sort_mode='hot', max_depth=5, max_breadth=5): '\n Retrieves comments for a post.\n \n :param post: The unique id of a Post from which Comments will be returned.\n :type post: `str` or :ref:`Post`\n :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time).\n :param int max_depth: The maximum depth that comments will be retrieved from (i.e., how many descendants from the topmost comment). To go down infinitely, use None.\n :param int max_breadth: The maximum breadth that comments will be retrieved from (i.e., how many siblings from the topmost comment). Note that this breadth applies at every subtree - in effect, it is the branching factor. To get all siblings, use None.\n :returns: list of Comment\n ' if (sort_mode not in SORT_MODES): raise RedditException('Unknown sort mode: {}'.format(sort_mode)) if isinstance(post, Post): post = post.id elif (not isinstance(post, str)): raise RedditException('The post parameter should be a String or a Post') result = _get_comments_string(post, sort_mode, max_depth, max_breadth) if result: try: json_result = _from_json(result)[1]['data']['children'] except ValueError: raise RedditException("The response from the server didn't make any sense.") if ('error' in json_result): raise RedditException('Error from Reddit: {}'.format(json_result.get('error', 'Unknown error.'))) if (max_breadth is None): return [Comment._from_json(r, post, max_depth=(max_depth - 1)) for r in json_result] else: return [Comment._from_json(r, post, max_depth=(max_depth - 1), max_breadth=max_breadth) for r in json_result[:max_breadth]] elif _CONNECTED: raise RedditException('No response from the server.') else: raise RedditException('No data was in the cache for this comment.')<|docstring|>Retrieves comments for a post. :param post: The unique id of a Post from which Comments will be returned. :type post: `str` or :ref:`Post` :param str sort_mode: The order that the Posts will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best" (similar to top, except that it uses a more complicated algorithm to have good posts jump to the top and stay there, and bad comments to work their way down, see http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html), "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time). :param int max_depth: The maximum depth that comments will be retrieved from (i.e., how many descendants from the topmost comment). To go down infinitely, use None. :param int max_breadth: The maximum breadth that comments will be retrieved from (i.e., how many siblings from the topmost comment). Note that this breadth applies at every subtree - in effect, it is the branching factor. To get all siblings, use None. :returns: list of Comment<|endoftext|>
704d9b6317237306a6aecf673e5d60f5cb8902f59af31e7870921e1d28bb9da9
def _get_more_comments_request(subreddit, post_id, comment_id, max_depth, max_breadth): '\n Used to build the request string used by :func:`get_comments`.\n \n \n :param str comment_id: The unique id of the items from which Comments will be returned.\n :param str subreddit: The subreddit of the items from which Comments will be returned.\n :param str post_id: The unique id of the post that will comments will be retrieved.\n :param str sort_mode: The order that the Comments will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best", "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time).\n :returns: str\n ' return 'http://www.reddit.com/r/{}/comments/{}/morechildrenread/{}/.json?max_depth={}&max_breadth={}'.format(subreddit, post_id, comment_id, max_depth, max_breadth)
Used to build the request string used by :func:`get_comments`. :param str comment_id: The unique id of the items from which Comments will be returned. :param str subreddit: The subreddit of the items from which Comments will be returned. :param str post_id: The unique id of the post that will comments will be retrieved. :param str sort_mode: The order that the Comments will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best", "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time). :returns: str
python/reddit/reddit.py
_get_more_comments_request
RealTimeWeb/reddit
2
python
def _get_more_comments_request(subreddit, post_id, comment_id, max_depth, max_breadth): '\n Used to build the request string used by :func:`get_comments`.\n \n \n :param str comment_id: The unique id of the items from which Comments will be returned.\n :param str subreddit: The subreddit of the items from which Comments will be returned.\n :param str post_id: The unique id of the post that will comments will be retrieved.\n :param str sort_mode: The order that the Comments will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best", "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time).\n :returns: str\n ' return 'http://www.reddit.com/r/{}/comments/{}/morechildrenread/{}/.json?max_depth={}&max_breadth={}'.format(subreddit, post_id, comment_id, max_depth, max_breadth)
def _get_more_comments_request(subreddit, post_id, comment_id, max_depth, max_breadth): '\n Used to build the request string used by :func:`get_comments`.\n \n \n :param str comment_id: The unique id of the items from which Comments will be returned.\n :param str subreddit: The subreddit of the items from which Comments will be returned.\n :param str post_id: The unique id of the post that will comments will be retrieved.\n :param str sort_mode: The order that the Comments will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best", "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time).\n :returns: str\n ' return 'http://www.reddit.com/r/{}/comments/{}/morechildrenread/{}/.json?max_depth={}&max_breadth={}'.format(subreddit, post_id, comment_id, max_depth, max_breadth)<|docstring|>Used to build the request string used by :func:`get_comments`. :param str comment_id: The unique id of the items from which Comments will be returned. :param str subreddit: The subreddit of the items from which Comments will be returned. :param str post_id: The unique id of the post that will comments will be retrieved. :param str sort_mode: The order that the Comments will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best", "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time). :returns: str<|endoftext|>
c0690a761b4ef466e2cf14f5d6189b72daa2e51ade964ccc3a472b10fc9a5634
def _get_more_comments_string(subreddit, post_id, comment_id, max_depth, max_breadth): '\n Used to build the request string used by :func:`get_comments`.\n \n :param str comment_id: The unique id of the items from which Comments will be returned.\n :param str subreddit: The subreddit of the items from which Comments will be returned.\n :param str post_id: The unique id of the post that will comments will be retrieved.\n :param str sort_mode: The order that the Comments will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best", "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time).\n :returns: str\n ' key = _get_more_comments_request(subreddit, post_id, comment_id, max_depth, max_breadth) result = (_get(key) if _CONNECTED else _lookup(key)) if (_CONNECTED and _EDITABLE): _add_to_cache(key, result) return result
Used to build the request string used by :func:`get_comments`. :param str comment_id: The unique id of the items from which Comments will be returned. :param str subreddit: The subreddit of the items from which Comments will be returned. :param str post_id: The unique id of the post that will comments will be retrieved. :param str sort_mode: The order that the Comments will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best", "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time). :returns: str
python/reddit/reddit.py
_get_more_comments_string
RealTimeWeb/reddit
2
python
def _get_more_comments_string(subreddit, post_id, comment_id, max_depth, max_breadth): '\n Used to build the request string used by :func:`get_comments`.\n \n :param str comment_id: The unique id of the items from which Comments will be returned.\n :param str subreddit: The subreddit of the items from which Comments will be returned.\n :param str post_id: The unique id of the post that will comments will be retrieved.\n :param str sort_mode: The order that the Comments will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best", "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time).\n :returns: str\n ' key = _get_more_comments_request(subreddit, post_id, comment_id, max_depth, max_breadth) result = (_get(key) if _CONNECTED else _lookup(key)) if (_CONNECTED and _EDITABLE): _add_to_cache(key, result) return result
def _get_more_comments_string(subreddit, post_id, comment_id, max_depth, max_breadth): '\n Used to build the request string used by :func:`get_comments`.\n \n :param str comment_id: The unique id of the items from which Comments will be returned.\n :param str subreddit: The subreddit of the items from which Comments will be returned.\n :param str post_id: The unique id of the post that will comments will be retrieved.\n :param str sort_mode: The order that the Comments will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best", "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time).\n :returns: str\n ' key = _get_more_comments_request(subreddit, post_id, comment_id, max_depth, max_breadth) result = (_get(key) if _CONNECTED else _lookup(key)) if (_CONNECTED and _EDITABLE): _add_to_cache(key, result) return result<|docstring|>Used to build the request string used by :func:`get_comments`. :param str comment_id: The unique id of the items from which Comments will be returned. :param str subreddit: The subreddit of the items from which Comments will be returned. :param str post_id: The unique id of the post that will comments will be retrieved. :param str sort_mode: The order that the Comments will be sorted by. Options are: "top" (ranked by upvotes minus downvotes), "best", "hot" (similar to "top", but weighted by time so that recent, popular posts are put near the top), "new" (posts will be sorted by creation time). :returns: str<|endoftext|>
899210ea05b96ad59553c7a88251eb995dec73a878ae8e03335545d21308d2f5
def __init__(self, id, author, subreddit, downs, ups, created, body, replies): "\n Creates a new Comment.\n \n :param str id: A unique ID for this Comment. A combination of letters, numbers, and dashes.\n :param str author: The username of the author of this Post.\n :param str subreddit: The subreddit that this Comment was made in (without the 'r/' at the front).\n :param int downs: The number of downvotes associated with this Comment.\n :param int ups: The number of upvotes associated with this Comment.\n :param int created: The date that this Comment was created.\n :param str body: The text of this post, without any markup.\n :param replies: A list of comments that are in reply to this one.\n :type replies: list of :ref:`Comment`\n :returns: Comment\n " self.id = id self.author = author self.subreddit = subreddit self.downs = downs self.ups = ups self.created = created self.body = body self.replies = replies
Creates a new Comment. :param str id: A unique ID for this Comment. A combination of letters, numbers, and dashes. :param str author: The username of the author of this Post. :param str subreddit: The subreddit that this Comment was made in (without the 'r/' at the front). :param int downs: The number of downvotes associated with this Comment. :param int ups: The number of upvotes associated with this Comment. :param int created: The date that this Comment was created. :param str body: The text of this post, without any markup. :param replies: A list of comments that are in reply to this one. :type replies: list of :ref:`Comment` :returns: Comment
python/reddit/reddit.py
__init__
RealTimeWeb/reddit
2
python
def __init__(self, id, author, subreddit, downs, ups, created, body, replies): "\n Creates a new Comment.\n \n :param str id: A unique ID for this Comment. A combination of letters, numbers, and dashes.\n :param str author: The username of the author of this Post.\n :param str subreddit: The subreddit that this Comment was made in (without the 'r/' at the front).\n :param int downs: The number of downvotes associated with this Comment.\n :param int ups: The number of upvotes associated with this Comment.\n :param int created: The date that this Comment was created.\n :param str body: The text of this post, without any markup.\n :param replies: A list of comments that are in reply to this one.\n :type replies: list of :ref:`Comment`\n :returns: Comment\n " self.id = id self.author = author self.subreddit = subreddit self.downs = downs self.ups = ups self.created = created self.body = body self.replies = replies
def __init__(self, id, author, subreddit, downs, ups, created, body, replies): "\n Creates a new Comment.\n \n :param str id: A unique ID for this Comment. A combination of letters, numbers, and dashes.\n :param str author: The username of the author of this Post.\n :param str subreddit: The subreddit that this Comment was made in (without the 'r/' at the front).\n :param int downs: The number of downvotes associated with this Comment.\n :param int ups: The number of upvotes associated with this Comment.\n :param int created: The date that this Comment was created.\n :param str body: The text of this post, without any markup.\n :param replies: A list of comments that are in reply to this one.\n :type replies: list of :ref:`Comment`\n :returns: Comment\n " self.id = id self.author = author self.subreddit = subreddit self.downs = downs self.ups = ups self.created = created self.body = body self.replies = replies<|docstring|>Creates a new Comment. :param str id: A unique ID for this Comment. A combination of letters, numbers, and dashes. :param str author: The username of the author of this Post. :param str subreddit: The subreddit that this Comment was made in (without the 'r/' at the front). :param int downs: The number of downvotes associated with this Comment. :param int ups: The number of upvotes associated with this Comment. :param int created: The date that this Comment was created. :param str body: The text of this post, without any markup. :param replies: A list of comments that are in reply to this one. :type replies: list of :ref:`Comment` :returns: Comment<|endoftext|>
e5dcc76785b5b2c4594d0f6a3d833d2812aacd8836debf45c78fa0e1b77ec92c
@staticmethod def _from_json(json_data, post_id='', max_depth=5, depth=0, max_breadth=None): '\n Creates a Comment from json data.\n \n :param dict json_data: The raw json data to parse\n :returns: Comment\n ' if 'data': data = json_data['data'] else: raise RedditException('The data from Reddit was invalid.') try: subreddit = data.get('subreddit', '') if (data['replies'] == ''): replies = [] else: children = data['replies']['data']['children'] if ((not children) or ((max_depth is not None) and (depth >= max_depth))): replies = [] elif (children[(- 1)]['kind'] == 'more'): rest = children[(- 1)]['data']['children'] replies = [Comment._from_json(r, post_id, max_depth, (depth + 1), max_breadth) for r in children[:(- 1)]][:max_breadth] if (max_breadth is None): replies += _get_more_comments(subreddit, post_id, rest, max_depth, (depth + 1), max_breadth) elif ((len(children) - 1) < max_breadth): replies += _get_more_comments(subreddit, post_id, rest[:(max_breadth - len(replies))], max_depth, (depth + 1), max_breadth) elif (max_breadth is None): replies = [Comment._from_json(r, post_id, max_depth, (depth + 1), max_breadth) for r in children] else: replies = [Comment._from_json(r, post_id, max_depth, (depth + 1), max_breadth) for r in children[:max_breadth]] except KeyError: raise RedditException('The Comment Data was invalid') return Comment(data.get('id', ''), data.get('author', ''), subreddit, _parse_int(data.get('downs', '0'), 0), _parse_int(data.get('ups', '0'), 0), _parse_int(data.get('created', '0'), 0), data.get('body', ''), replies)
Creates a Comment from json data. :param dict json_data: The raw json data to parse :returns: Comment
python/reddit/reddit.py
_from_json
RealTimeWeb/reddit
2
python
@staticmethod def _from_json(json_data, post_id=, max_depth=5, depth=0, max_breadth=None): '\n Creates a Comment from json data.\n \n :param dict json_data: The raw json data to parse\n :returns: Comment\n ' if 'data': data = json_data['data'] else: raise RedditException('The data from Reddit was invalid.') try: subreddit = data.get('subreddit', ) if (data['replies'] == ): replies = [] else: children = data['replies']['data']['children'] if ((not children) or ((max_depth is not None) and (depth >= max_depth))): replies = [] elif (children[(- 1)]['kind'] == 'more'): rest = children[(- 1)]['data']['children'] replies = [Comment._from_json(r, post_id, max_depth, (depth + 1), max_breadth) for r in children[:(- 1)]][:max_breadth] if (max_breadth is None): replies += _get_more_comments(subreddit, post_id, rest, max_depth, (depth + 1), max_breadth) elif ((len(children) - 1) < max_breadth): replies += _get_more_comments(subreddit, post_id, rest[:(max_breadth - len(replies))], max_depth, (depth + 1), max_breadth) elif (max_breadth is None): replies = [Comment._from_json(r, post_id, max_depth, (depth + 1), max_breadth) for r in children] else: replies = [Comment._from_json(r, post_id, max_depth, (depth + 1), max_breadth) for r in children[:max_breadth]] except KeyError: raise RedditException('The Comment Data was invalid') return Comment(data.get('id', ), data.get('author', ), subreddit, _parse_int(data.get('downs', '0'), 0), _parse_int(data.get('ups', '0'), 0), _parse_int(data.get('created', '0'), 0), data.get('body', ), replies)
@staticmethod def _from_json(json_data, post_id=, max_depth=5, depth=0, max_breadth=None): '\n Creates a Comment from json data.\n \n :param dict json_data: The raw json data to parse\n :returns: Comment\n ' if 'data': data = json_data['data'] else: raise RedditException('The data from Reddit was invalid.') try: subreddit = data.get('subreddit', ) if (data['replies'] == ): replies = [] else: children = data['replies']['data']['children'] if ((not children) or ((max_depth is not None) and (depth >= max_depth))): replies = [] elif (children[(- 1)]['kind'] == 'more'): rest = children[(- 1)]['data']['children'] replies = [Comment._from_json(r, post_id, max_depth, (depth + 1), max_breadth) for r in children[:(- 1)]][:max_breadth] if (max_breadth is None): replies += _get_more_comments(subreddit, post_id, rest, max_depth, (depth + 1), max_breadth) elif ((len(children) - 1) < max_breadth): replies += _get_more_comments(subreddit, post_id, rest[:(max_breadth - len(replies))], max_depth, (depth + 1), max_breadth) elif (max_breadth is None): replies = [Comment._from_json(r, post_id, max_depth, (depth + 1), max_breadth) for r in children] else: replies = [Comment._from_json(r, post_id, max_depth, (depth + 1), max_breadth) for r in children[:max_breadth]] except KeyError: raise RedditException('The Comment Data was invalid') return Comment(data.get('id', ), data.get('author', ), subreddit, _parse_int(data.get('downs', '0'), 0), _parse_int(data.get('ups', '0'), 0), _parse_int(data.get('created', '0'), 0), data.get('body', ), replies)<|docstring|>Creates a Comment from json data. :param dict json_data: The raw json data to parse :returns: Comment<|endoftext|>
a4201a4fd409172d682f3998c5bb22a5dae135e6a55cfef19f51045bfed7bf8e
def __init__(self, id, author, subreddit, downs, ups, created, title, content, is_nsfw, is_url): "\n Creates a new Post.\n \n :param str id: A unique ID for this Post. A combination of letters, numbers, and dashes.\n :param str author: The username of the author of this Post.\n :param str subreddit: The subreddit that this Post was made in (without the 'r/' at the front)\n :param int downs: The number of downvotes associated with this Post.\n :param int ups: The number of upvotes associated with this Post.\n :param int created: The date that this Post was created.\n :param str title: The title of this Post.\n :param str content: The text of the post, or a url if it is not a self Post.\n :param bool is_nsfw: Whether or not this Post is Not Safe for Work (NSFW).\n :param bool is_url: Whether or not this Post was text (False), or a URL (True).\n :returns: Post\n " self.id = id self.author = author self.subreddit = subreddit self.downs = downs self.ups = ups self.created = created self.title = title self.content = content self.is_nsfw = is_nsfw self.is_url = is_url
Creates a new Post. :param str id: A unique ID for this Post. A combination of letters, numbers, and dashes. :param str author: The username of the author of this Post. :param str subreddit: The subreddit that this Post was made in (without the 'r/' at the front) :param int downs: The number of downvotes associated with this Post. :param int ups: The number of upvotes associated with this Post. :param int created: The date that this Post was created. :param str title: The title of this Post. :param str content: The text of the post, or a url if it is not a self Post. :param bool is_nsfw: Whether or not this Post is Not Safe for Work (NSFW). :param bool is_url: Whether or not this Post was text (False), or a URL (True). :returns: Post
python/reddit/reddit.py
__init__
RealTimeWeb/reddit
2
python
def __init__(self, id, author, subreddit, downs, ups, created, title, content, is_nsfw, is_url): "\n Creates a new Post.\n \n :param str id: A unique ID for this Post. A combination of letters, numbers, and dashes.\n :param str author: The username of the author of this Post.\n :param str subreddit: The subreddit that this Post was made in (without the 'r/' at the front)\n :param int downs: The number of downvotes associated with this Post.\n :param int ups: The number of upvotes associated with this Post.\n :param int created: The date that this Post was created.\n :param str title: The title of this Post.\n :param str content: The text of the post, or a url if it is not a self Post.\n :param bool is_nsfw: Whether or not this Post is Not Safe for Work (NSFW).\n :param bool is_url: Whether or not this Post was text (False), or a URL (True).\n :returns: Post\n " self.id = id self.author = author self.subreddit = subreddit self.downs = downs self.ups = ups self.created = created self.title = title self.content = content self.is_nsfw = is_nsfw self.is_url = is_url
def __init__(self, id, author, subreddit, downs, ups, created, title, content, is_nsfw, is_url): "\n Creates a new Post.\n \n :param str id: A unique ID for this Post. A combination of letters, numbers, and dashes.\n :param str author: The username of the author of this Post.\n :param str subreddit: The subreddit that this Post was made in (without the 'r/' at the front)\n :param int downs: The number of downvotes associated with this Post.\n :param int ups: The number of upvotes associated with this Post.\n :param int created: The date that this Post was created.\n :param str title: The title of this Post.\n :param str content: The text of the post, or a url if it is not a self Post.\n :param bool is_nsfw: Whether or not this Post is Not Safe for Work (NSFW).\n :param bool is_url: Whether or not this Post was text (False), or a URL (True).\n :returns: Post\n " self.id = id self.author = author self.subreddit = subreddit self.downs = downs self.ups = ups self.created = created self.title = title self.content = content self.is_nsfw = is_nsfw self.is_url = is_url<|docstring|>Creates a new Post. :param str id: A unique ID for this Post. A combination of letters, numbers, and dashes. :param str author: The username of the author of this Post. :param str subreddit: The subreddit that this Post was made in (without the 'r/' at the front) :param int downs: The number of downvotes associated with this Post. :param int ups: The number of upvotes associated with this Post. :param int created: The date that this Post was created. :param str title: The title of this Post. :param str content: The text of the post, or a url if it is not a self Post. :param bool is_nsfw: Whether or not this Post is Not Safe for Work (NSFW). :param bool is_url: Whether or not this Post was text (False), or a URL (True). :returns: Post<|endoftext|>
39b9c2566cd56bbe4712a57da442ca9c3e7061dfdaf805ce73458f33c096d8fd
@staticmethod def _from_json(json_data): '\n Creates a Post from json data.\n \n :param json_data: The raw json data to parse\n :type json_data: dict\n :returns: Post\n ' if ('data' in json_data): data = json_data['data'] else: raise RedditException('The Post data from Reddit was invalid.') return Post(data.get('id', ''), data.get('author', ''), data.get('subreddit', ''), _parse_int(data.get('downs', '0'), 0), _parse_int(data.get('up', '0'), 0), _parse_int(data.get('created', '0'), 0), data.get('title', ''), (data.get('selftext', '') if data.get('is_self', False) else data.get('url', '')), _parse_boolean(data.get('over_18', False), True), _parse_boolean((not data.get('is_self', False)), False))
Creates a Post from json data. :param json_data: The raw json data to parse :type json_data: dict :returns: Post
python/reddit/reddit.py
_from_json
RealTimeWeb/reddit
2
python
@staticmethod def _from_json(json_data): '\n Creates a Post from json data.\n \n :param json_data: The raw json data to parse\n :type json_data: dict\n :returns: Post\n ' if ('data' in json_data): data = json_data['data'] else: raise RedditException('The Post data from Reddit was invalid.') return Post(data.get('id', ), data.get('author', ), data.get('subreddit', ), _parse_int(data.get('downs', '0'), 0), _parse_int(data.get('up', '0'), 0), _parse_int(data.get('created', '0'), 0), data.get('title', ), (data.get('selftext', ) if data.get('is_self', False) else data.get('url', )), _parse_boolean(data.get('over_18', False), True), _parse_boolean((not data.get('is_self', False)), False))
@staticmethod def _from_json(json_data): '\n Creates a Post from json data.\n \n :param json_data: The raw json data to parse\n :type json_data: dict\n :returns: Post\n ' if ('data' in json_data): data = json_data['data'] else: raise RedditException('The Post data from Reddit was invalid.') return Post(data.get('id', ), data.get('author', ), data.get('subreddit', ), _parse_int(data.get('downs', '0'), 0), _parse_int(data.get('up', '0'), 0), _parse_int(data.get('created', '0'), 0), data.get('title', ), (data.get('selftext', ) if data.get('is_self', False) else data.get('url', )), _parse_boolean(data.get('over_18', False), True), _parse_boolean((not data.get('is_self', False)), False))<|docstring|>Creates a Post from json data. :param json_data: The raw json data to parse :type json_data: dict :returns: Post<|endoftext|>
bad634d062853dfb45c73e3d873ce611e377d2b6597d7bbc10f92b132feb5fb1
def test_optimize_rounding_conv2d(): ' Test optimize rounding for Conv2d ' model = depthwise_conv2d_model() conv = model.layers[1] orig_weight = conv.get_weights()[0] opt_params = AdaroundHyperParameters(num_iterations=1, reg_param=0.01, beta_range=(20, 2), warm_start=0.2) conv_wrapper = AdaroundWrapper(conv, 4, QuantScheme.post_training_tf, False) inp_data = np.random.rand(1, 10, 10, 3).astype('float32') out_data = np.random.rand(1, 10, 10, 16).astype('float32') (hard_rounded_weight, soft_rounded_weight) = AdaroundOptimizer().optimize_rounding(conv_wrapper, tf.nn.relu, inp_data, out_data, opt_params) assert (orig_weight.shape == hard_rounded_weight.shape) assert np.allclose(orig_weight, hard_rounded_weight, atol=(2 * conv_wrapper.encoding.delta)) assert (orig_weight.shape == soft_rounded_weight.shape) assert np.allclose(orig_weight, soft_rounded_weight, atol=(2 * conv_wrapper.encoding.delta))
Test optimize rounding for Conv2d
TrainingExtensions/tensorflow/test/python/eager/test_adaround_keras.py
test_optimize_rounding_conv2d
aaronkjones/aimet
0
python
def test_optimize_rounding_conv2d(): ' ' model = depthwise_conv2d_model() conv = model.layers[1] orig_weight = conv.get_weights()[0] opt_params = AdaroundHyperParameters(num_iterations=1, reg_param=0.01, beta_range=(20, 2), warm_start=0.2) conv_wrapper = AdaroundWrapper(conv, 4, QuantScheme.post_training_tf, False) inp_data = np.random.rand(1, 10, 10, 3).astype('float32') out_data = np.random.rand(1, 10, 10, 16).astype('float32') (hard_rounded_weight, soft_rounded_weight) = AdaroundOptimizer().optimize_rounding(conv_wrapper, tf.nn.relu, inp_data, out_data, opt_params) assert (orig_weight.shape == hard_rounded_weight.shape) assert np.allclose(orig_weight, hard_rounded_weight, atol=(2 * conv_wrapper.encoding.delta)) assert (orig_weight.shape == soft_rounded_weight.shape) assert np.allclose(orig_weight, soft_rounded_weight, atol=(2 * conv_wrapper.encoding.delta))
def test_optimize_rounding_conv2d(): ' ' model = depthwise_conv2d_model() conv = model.layers[1] orig_weight = conv.get_weights()[0] opt_params = AdaroundHyperParameters(num_iterations=1, reg_param=0.01, beta_range=(20, 2), warm_start=0.2) conv_wrapper = AdaroundWrapper(conv, 4, QuantScheme.post_training_tf, False) inp_data = np.random.rand(1, 10, 10, 3).astype('float32') out_data = np.random.rand(1, 10, 10, 16).astype('float32') (hard_rounded_weight, soft_rounded_weight) = AdaroundOptimizer().optimize_rounding(conv_wrapper, tf.nn.relu, inp_data, out_data, opt_params) assert (orig_weight.shape == hard_rounded_weight.shape) assert np.allclose(orig_weight, hard_rounded_weight, atol=(2 * conv_wrapper.encoding.delta)) assert (orig_weight.shape == soft_rounded_weight.shape) assert np.allclose(orig_weight, soft_rounded_weight, atol=(2 * conv_wrapper.encoding.delta))<|docstring|>Test optimize rounding for Conv2d<|endoftext|>
da6d25a6720aca387045f54553bcd8a0d89e197357d8763b1d78958d443044de
def test_optimize_rounding_matmul(): ' Test optimize rounding for MatMul ' model = depthwise_conv2d_model() matmul = model.layers[6] orig_weight = matmul.get_weights()[0] opt_params = AdaroundHyperParameters(num_iterations=1, reg_param=0.01, beta_range=(20, 2), warm_start=0.2) matmul_wrapper = AdaroundWrapper(matmul, 4, QuantScheme.post_training_tf, False) inp_data = np.random.rand(1, 392).astype('float32') out_data = np.random.rand(1, 10).astype('float32') (hard_rounded_weight, soft_rounded_weight) = AdaroundOptimizer().optimize_rounding(matmul_wrapper, tf.nn.relu, inp_data, out_data, opt_params) assert (orig_weight.shape == hard_rounded_weight.shape) assert np.allclose(orig_weight, hard_rounded_weight, atol=(2 * matmul_wrapper.encoding.delta)) assert (orig_weight.shape == soft_rounded_weight.shape) assert np.allclose(orig_weight, soft_rounded_weight, atol=(2 * matmul_wrapper.encoding.delta))
Test optimize rounding for MatMul
TrainingExtensions/tensorflow/test/python/eager/test_adaround_keras.py
test_optimize_rounding_matmul
aaronkjones/aimet
0
python
def test_optimize_rounding_matmul(): ' ' model = depthwise_conv2d_model() matmul = model.layers[6] orig_weight = matmul.get_weights()[0] opt_params = AdaroundHyperParameters(num_iterations=1, reg_param=0.01, beta_range=(20, 2), warm_start=0.2) matmul_wrapper = AdaroundWrapper(matmul, 4, QuantScheme.post_training_tf, False) inp_data = np.random.rand(1, 392).astype('float32') out_data = np.random.rand(1, 10).astype('float32') (hard_rounded_weight, soft_rounded_weight) = AdaroundOptimizer().optimize_rounding(matmul_wrapper, tf.nn.relu, inp_data, out_data, opt_params) assert (orig_weight.shape == hard_rounded_weight.shape) assert np.allclose(orig_weight, hard_rounded_weight, atol=(2 * matmul_wrapper.encoding.delta)) assert (orig_weight.shape == soft_rounded_weight.shape) assert np.allclose(orig_weight, soft_rounded_weight, atol=(2 * matmul_wrapper.encoding.delta))
def test_optimize_rounding_matmul(): ' ' model = depthwise_conv2d_model() matmul = model.layers[6] orig_weight = matmul.get_weights()[0] opt_params = AdaroundHyperParameters(num_iterations=1, reg_param=0.01, beta_range=(20, 2), warm_start=0.2) matmul_wrapper = AdaroundWrapper(matmul, 4, QuantScheme.post_training_tf, False) inp_data = np.random.rand(1, 392).astype('float32') out_data = np.random.rand(1, 10).astype('float32') (hard_rounded_weight, soft_rounded_weight) = AdaroundOptimizer().optimize_rounding(matmul_wrapper, tf.nn.relu, inp_data, out_data, opt_params) assert (orig_weight.shape == hard_rounded_weight.shape) assert np.allclose(orig_weight, hard_rounded_weight, atol=(2 * matmul_wrapper.encoding.delta)) assert (orig_weight.shape == soft_rounded_weight.shape) assert np.allclose(orig_weight, soft_rounded_weight, atol=(2 * matmul_wrapper.encoding.delta))<|docstring|>Test optimize rounding for MatMul<|endoftext|>
46e655c6de807857b70e56095e474909734e35cc95c743e5c7843db7a1fe59f7
def test_optimize_rounding_depthwise_conv2d(): ' Test optimize rounding for Depthwise Conv2d ' model = depthwise_conv2d_model() depthwise_conv2d = model.layers[3] orig_weight = depthwise_conv2d.get_weights()[0] opt_params = AdaroundHyperParameters(num_iterations=1, reg_param=0.01, beta_range=(20, 2), warm_start=0.2) depthwise_conv_wrapper = AdaroundWrapper(depthwise_conv2d, 4, QuantScheme.post_training_tf, False) inp_data = np.random.rand(1, 5, 5, 10).astype('float32') out_data = np.random.rand(1, 3, 3, 10).astype('float32') (hard_rounded_weight, soft_rounded_weight) = AdaroundOptimizer().optimize_rounding(depthwise_conv_wrapper, tf.nn.relu, inp_data, out_data, opt_params) assert (orig_weight.shape == hard_rounded_weight.shape) assert np.allclose(orig_weight, hard_rounded_weight, atol=(2 * depthwise_conv_wrapper.encoding.delta)) assert (orig_weight.shape == soft_rounded_weight.shape) assert np.allclose(orig_weight, soft_rounded_weight, atol=(2 * depthwise_conv_wrapper.encoding.delta))
Test optimize rounding for Depthwise Conv2d
TrainingExtensions/tensorflow/test/python/eager/test_adaround_keras.py
test_optimize_rounding_depthwise_conv2d
aaronkjones/aimet
0
python
def test_optimize_rounding_depthwise_conv2d(): ' ' model = depthwise_conv2d_model() depthwise_conv2d = model.layers[3] orig_weight = depthwise_conv2d.get_weights()[0] opt_params = AdaroundHyperParameters(num_iterations=1, reg_param=0.01, beta_range=(20, 2), warm_start=0.2) depthwise_conv_wrapper = AdaroundWrapper(depthwise_conv2d, 4, QuantScheme.post_training_tf, False) inp_data = np.random.rand(1, 5, 5, 10).astype('float32') out_data = np.random.rand(1, 3, 3, 10).astype('float32') (hard_rounded_weight, soft_rounded_weight) = AdaroundOptimizer().optimize_rounding(depthwise_conv_wrapper, tf.nn.relu, inp_data, out_data, opt_params) assert (orig_weight.shape == hard_rounded_weight.shape) assert np.allclose(orig_weight, hard_rounded_weight, atol=(2 * depthwise_conv_wrapper.encoding.delta)) assert (orig_weight.shape == soft_rounded_weight.shape) assert np.allclose(orig_weight, soft_rounded_weight, atol=(2 * depthwise_conv_wrapper.encoding.delta))
def test_optimize_rounding_depthwise_conv2d(): ' ' model = depthwise_conv2d_model() depthwise_conv2d = model.layers[3] orig_weight = depthwise_conv2d.get_weights()[0] opt_params = AdaroundHyperParameters(num_iterations=1, reg_param=0.01, beta_range=(20, 2), warm_start=0.2) depthwise_conv_wrapper = AdaroundWrapper(depthwise_conv2d, 4, QuantScheme.post_training_tf, False) inp_data = np.random.rand(1, 5, 5, 10).astype('float32') out_data = np.random.rand(1, 3, 3, 10).astype('float32') (hard_rounded_weight, soft_rounded_weight) = AdaroundOptimizer().optimize_rounding(depthwise_conv_wrapper, tf.nn.relu, inp_data, out_data, opt_params) assert (orig_weight.shape == hard_rounded_weight.shape) assert np.allclose(orig_weight, hard_rounded_weight, atol=(2 * depthwise_conv_wrapper.encoding.delta)) assert (orig_weight.shape == soft_rounded_weight.shape) assert np.allclose(orig_weight, soft_rounded_weight, atol=(2 * depthwise_conv_wrapper.encoding.delta))<|docstring|>Test optimize rounding for Depthwise Conv2d<|endoftext|>
92765da58c4861e0dbab811d843eba0b0879e853ad9ff3f5994cdcd166711225
def test_compute_output_with_adarounded_weights(): ' Test compute output with adarounded weights for Conv layer ' np.random.seed(0) quant_scheme = QuantScheme.post_training_tf_enhanced weight_bw = 8 weight_data = np.random.rand(4, 4, 1, 1).astype(dtype='float32') weight_data = np.transpose(weight_data, (2, 3, 1, 0)) weight_tensor = tf.convert_to_tensor(weight_data, dtype=tf.float32) inp_data = np.random.rand(1, 4, 10, 10).astype(dtype='float32') inp_data_t = np.transpose(inp_data, (0, 2, 3, 1)) inp_tensor = tf.convert_to_tensor(inp_data_t, dtype=tf.float32) out_data = np.random.rand(1, 4, 10, 10).astype(dtype='float32') out_data_t = np.transpose(out_data, (0, 2, 3, 1)) out_tensor = tf.convert_to_tensor(out_data_t, dtype=tf.float32) _ = tf.nn.conv2d(inp_tensor, weight_tensor, strides=[1, 1, 1, 1], padding='SAME', data_format='NHWC', name='Conv2D') conv_layer = tf.keras.layers.Conv2D(4, 1, padding='same') conv_layer.build(input_shape=(1, 10, 10, 4)) conv_layer.set_weights(([weight_tensor] + conv_layer.get_weights()[1:])) conv_wrapper = AdaroundWrapper(conv_layer, weight_bw, quant_scheme, False) (hard_recons_error, soft_recons_error) = AdaroundOptimizer._eval_recons_err_metrics(conv_wrapper, None, inp_tensor, out_tensor) assert np.isclose(hard_recons_error, 0.6102066, atol=0.0001) assert np.isclose(soft_recons_error, 0.6107949, atol=0.0001)
Test compute output with adarounded weights for Conv layer
TrainingExtensions/tensorflow/test/python/eager/test_adaround_keras.py
test_compute_output_with_adarounded_weights
aaronkjones/aimet
0
python
def test_compute_output_with_adarounded_weights(): ' ' np.random.seed(0) quant_scheme = QuantScheme.post_training_tf_enhanced weight_bw = 8 weight_data = np.random.rand(4, 4, 1, 1).astype(dtype='float32') weight_data = np.transpose(weight_data, (2, 3, 1, 0)) weight_tensor = tf.convert_to_tensor(weight_data, dtype=tf.float32) inp_data = np.random.rand(1, 4, 10, 10).astype(dtype='float32') inp_data_t = np.transpose(inp_data, (0, 2, 3, 1)) inp_tensor = tf.convert_to_tensor(inp_data_t, dtype=tf.float32) out_data = np.random.rand(1, 4, 10, 10).astype(dtype='float32') out_data_t = np.transpose(out_data, (0, 2, 3, 1)) out_tensor = tf.convert_to_tensor(out_data_t, dtype=tf.float32) _ = tf.nn.conv2d(inp_tensor, weight_tensor, strides=[1, 1, 1, 1], padding='SAME', data_format='NHWC', name='Conv2D') conv_layer = tf.keras.layers.Conv2D(4, 1, padding='same') conv_layer.build(input_shape=(1, 10, 10, 4)) conv_layer.set_weights(([weight_tensor] + conv_layer.get_weights()[1:])) conv_wrapper = AdaroundWrapper(conv_layer, weight_bw, quant_scheme, False) (hard_recons_error, soft_recons_error) = AdaroundOptimizer._eval_recons_err_metrics(conv_wrapper, None, inp_tensor, out_tensor) assert np.isclose(hard_recons_error, 0.6102066, atol=0.0001) assert np.isclose(soft_recons_error, 0.6107949, atol=0.0001)
def test_compute_output_with_adarounded_weights(): ' ' np.random.seed(0) quant_scheme = QuantScheme.post_training_tf_enhanced weight_bw = 8 weight_data = np.random.rand(4, 4, 1, 1).astype(dtype='float32') weight_data = np.transpose(weight_data, (2, 3, 1, 0)) weight_tensor = tf.convert_to_tensor(weight_data, dtype=tf.float32) inp_data = np.random.rand(1, 4, 10, 10).astype(dtype='float32') inp_data_t = np.transpose(inp_data, (0, 2, 3, 1)) inp_tensor = tf.convert_to_tensor(inp_data_t, dtype=tf.float32) out_data = np.random.rand(1, 4, 10, 10).astype(dtype='float32') out_data_t = np.transpose(out_data, (0, 2, 3, 1)) out_tensor = tf.convert_to_tensor(out_data_t, dtype=tf.float32) _ = tf.nn.conv2d(inp_tensor, weight_tensor, strides=[1, 1, 1, 1], padding='SAME', data_format='NHWC', name='Conv2D') conv_layer = tf.keras.layers.Conv2D(4, 1, padding='same') conv_layer.build(input_shape=(1, 10, 10, 4)) conv_layer.set_weights(([weight_tensor] + conv_layer.get_weights()[1:])) conv_wrapper = AdaroundWrapper(conv_layer, weight_bw, quant_scheme, False) (hard_recons_error, soft_recons_error) = AdaroundOptimizer._eval_recons_err_metrics(conv_wrapper, None, inp_tensor, out_tensor) assert np.isclose(hard_recons_error, 0.6102066, atol=0.0001) assert np.isclose(soft_recons_error, 0.6107949, atol=0.0001)<|docstring|>Test compute output with adarounded weights for Conv layer<|endoftext|>
5e709027b9b1a23f3465199c303a24f1d18208b14edb3c5bb7d909419672aecf
def test_adaround_weights(): ' test adaround weights ' model = depthwise_conv2d_model() conv = model.layers[1] conv_wrapper = AdaroundWrapper(conv, 4, QuantScheme.post_training_tf, False) matmul = model.layers[6] matmul_wrapper = AdaroundWrapper(matmul, 4, QuantScheme.post_training_tf, False) depthwise_conv = model.layers[3] depthwise_conv_wrapper = AdaroundWrapper(depthwise_conv, 4, QuantScheme.post_training_tf, False) matmul_wrapper.use_soft_rounding.assign(False) quantized_weight = matmul_wrapper.adaround_weights() orig_weight = matmul_wrapper._weight_tensor assert (orig_weight.shape == quantized_weight.shape) assert np.allclose(orig_weight, quantized_weight, atol=(2 * matmul_wrapper.encoding.delta)) matmul_wrapper.use_soft_rounding.assign(True) quantized_weight = matmul_wrapper.adaround_weights() orig_weight = matmul_wrapper._weight_tensor assert (orig_weight.shape == quantized_weight.shape) assert np.allclose(orig_weight, quantized_weight, atol=(2 * matmul_wrapper.encoding.delta)) conv_wrapper.use_soft_rounding.assign(False) quantized_weight = conv_wrapper.adaround_weights() orig_weight = conv_wrapper._weight_tensor assert (orig_weight.shape == quantized_weight.shape) assert np.allclose(orig_weight, quantized_weight, atol=(2 * conv_wrapper.encoding.delta)) conv_wrapper.use_soft_rounding.assign(True) quantized_weight = conv_wrapper.adaround_weights() orig_weight = conv_wrapper._weight_tensor assert (orig_weight.shape == quantized_weight.shape) assert np.allclose(orig_weight, quantized_weight, atol=(2 * conv_wrapper.encoding.delta)) depthwise_conv_wrapper.use_soft_rounding.assign(False) quantized_weight = depthwise_conv_wrapper.adaround_weights() orig_weight = depthwise_conv_wrapper._weight_tensor assert (orig_weight.shape == quantized_weight.shape) assert np.allclose(orig_weight, quantized_weight, atol=(2 * depthwise_conv_wrapper.encoding.delta)) depthwise_conv_wrapper.use_soft_rounding.assign(True) quantized_weight = depthwise_conv_wrapper.adaround_weights() orig_weight = depthwise_conv_wrapper._weight_tensor assert (orig_weight.shape == quantized_weight.shape) assert np.allclose(orig_weight, quantized_weight, atol=(2 * depthwise_conv_wrapper.encoding.delta))
test adaround weights
TrainingExtensions/tensorflow/test/python/eager/test_adaround_keras.py
test_adaround_weights
aaronkjones/aimet
0
python
def test_adaround_weights(): ' ' model = depthwise_conv2d_model() conv = model.layers[1] conv_wrapper = AdaroundWrapper(conv, 4, QuantScheme.post_training_tf, False) matmul = model.layers[6] matmul_wrapper = AdaroundWrapper(matmul, 4, QuantScheme.post_training_tf, False) depthwise_conv = model.layers[3] depthwise_conv_wrapper = AdaroundWrapper(depthwise_conv, 4, QuantScheme.post_training_tf, False) matmul_wrapper.use_soft_rounding.assign(False) quantized_weight = matmul_wrapper.adaround_weights() orig_weight = matmul_wrapper._weight_tensor assert (orig_weight.shape == quantized_weight.shape) assert np.allclose(orig_weight, quantized_weight, atol=(2 * matmul_wrapper.encoding.delta)) matmul_wrapper.use_soft_rounding.assign(True) quantized_weight = matmul_wrapper.adaround_weights() orig_weight = matmul_wrapper._weight_tensor assert (orig_weight.shape == quantized_weight.shape) assert np.allclose(orig_weight, quantized_weight, atol=(2 * matmul_wrapper.encoding.delta)) conv_wrapper.use_soft_rounding.assign(False) quantized_weight = conv_wrapper.adaround_weights() orig_weight = conv_wrapper._weight_tensor assert (orig_weight.shape == quantized_weight.shape) assert np.allclose(orig_weight, quantized_weight, atol=(2 * conv_wrapper.encoding.delta)) conv_wrapper.use_soft_rounding.assign(True) quantized_weight = conv_wrapper.adaround_weights() orig_weight = conv_wrapper._weight_tensor assert (orig_weight.shape == quantized_weight.shape) assert np.allclose(orig_weight, quantized_weight, atol=(2 * conv_wrapper.encoding.delta)) depthwise_conv_wrapper.use_soft_rounding.assign(False) quantized_weight = depthwise_conv_wrapper.adaround_weights() orig_weight = depthwise_conv_wrapper._weight_tensor assert (orig_weight.shape == quantized_weight.shape) assert np.allclose(orig_weight, quantized_weight, atol=(2 * depthwise_conv_wrapper.encoding.delta)) depthwise_conv_wrapper.use_soft_rounding.assign(True) quantized_weight = depthwise_conv_wrapper.adaround_weights() orig_weight = depthwise_conv_wrapper._weight_tensor assert (orig_weight.shape == quantized_weight.shape) assert np.allclose(orig_weight, quantized_weight, atol=(2 * depthwise_conv_wrapper.encoding.delta))
def test_adaround_weights(): ' ' model = depthwise_conv2d_model() conv = model.layers[1] conv_wrapper = AdaroundWrapper(conv, 4, QuantScheme.post_training_tf, False) matmul = model.layers[6] matmul_wrapper = AdaroundWrapper(matmul, 4, QuantScheme.post_training_tf, False) depthwise_conv = model.layers[3] depthwise_conv_wrapper = AdaroundWrapper(depthwise_conv, 4, QuantScheme.post_training_tf, False) matmul_wrapper.use_soft_rounding.assign(False) quantized_weight = matmul_wrapper.adaround_weights() orig_weight = matmul_wrapper._weight_tensor assert (orig_weight.shape == quantized_weight.shape) assert np.allclose(orig_weight, quantized_weight, atol=(2 * matmul_wrapper.encoding.delta)) matmul_wrapper.use_soft_rounding.assign(True) quantized_weight = matmul_wrapper.adaround_weights() orig_weight = matmul_wrapper._weight_tensor assert (orig_weight.shape == quantized_weight.shape) assert np.allclose(orig_weight, quantized_weight, atol=(2 * matmul_wrapper.encoding.delta)) conv_wrapper.use_soft_rounding.assign(False) quantized_weight = conv_wrapper.adaround_weights() orig_weight = conv_wrapper._weight_tensor assert (orig_weight.shape == quantized_weight.shape) assert np.allclose(orig_weight, quantized_weight, atol=(2 * conv_wrapper.encoding.delta)) conv_wrapper.use_soft_rounding.assign(True) quantized_weight = conv_wrapper.adaround_weights() orig_weight = conv_wrapper._weight_tensor assert (orig_weight.shape == quantized_weight.shape) assert np.allclose(orig_weight, quantized_weight, atol=(2 * conv_wrapper.encoding.delta)) depthwise_conv_wrapper.use_soft_rounding.assign(False) quantized_weight = depthwise_conv_wrapper.adaround_weights() orig_weight = depthwise_conv_wrapper._weight_tensor assert (orig_weight.shape == quantized_weight.shape) assert np.allclose(orig_weight, quantized_weight, atol=(2 * depthwise_conv_wrapper.encoding.delta)) depthwise_conv_wrapper.use_soft_rounding.assign(True) quantized_weight = depthwise_conv_wrapper.adaround_weights() orig_weight = depthwise_conv_wrapper._weight_tensor assert (orig_weight.shape == quantized_weight.shape) assert np.allclose(orig_weight, quantized_weight, atol=(2 * depthwise_conv_wrapper.encoding.delta))<|docstring|>test adaround weights<|endoftext|>
ae1ced6012c14e7317e124121904dde649444e64fe88e4b86928d34388acd5d6
def word_break(s, word_list): '\n 输入:\n s = "catsanddog"\n s1 = "catsandog"\n wordDict = ["cat", "cats", "and", "sand", "dog"]\n 输出:\n ["cats and dog","cat sand dog"]\n []\n ' if (not s): return True lenth = len(s) dp = [False for i in range((lenth + 1))] dp[0] = True for i in range(1, (lenth + 1)): for j in range(i): if (dp[j] and (s[j:i] in word_list)): dp[i] = True break return dp[(- 1)]
输入: s = "catsanddog" s1 = "catsandog" wordDict = ["cat", "cats", "and", "sand", "dog"] 输出: ["cats and dog","cat sand dog"] []
api/app/tools/leetcode.py
word_break
yunfei07/vue-flask-in-action
0
python
def word_break(s, word_list): '\n 输入:\n s = "catsanddog"\n s1 = "catsandog"\n wordDict = ["cat", "cats", "and", "sand", "dog"]\n 输出:\n ["cats and dog","cat sand dog"]\n []\n ' if (not s): return True lenth = len(s) dp = [False for i in range((lenth + 1))] dp[0] = True for i in range(1, (lenth + 1)): for j in range(i): if (dp[j] and (s[j:i] in word_list)): dp[i] = True break return dp[(- 1)]
def word_break(s, word_list): '\n 输入:\n s = "catsanddog"\n s1 = "catsandog"\n wordDict = ["cat", "cats", "and", "sand", "dog"]\n 输出:\n ["cats and dog","cat sand dog"]\n []\n ' if (not s): return True lenth = len(s) dp = [False for i in range((lenth + 1))] dp[0] = True for i in range(1, (lenth + 1)): for j in range(i): if (dp[j] and (s[j:i] in word_list)): dp[i] = True break return dp[(- 1)]<|docstring|>输入: s = "catsanddog" s1 = "catsandog" wordDict = ["cat", "cats", "and", "sand", "dog"] 输出: ["cats and dog","cat sand dog"] []<|endoftext|>
611493392ef723316994ee6a0fe9dba78b70c48604e628b350fdca10c25fc2d8
def rotate(nums, k): '\n 输入: nums = [1,2,3,4,5,6,7], k = 3\n 输出: [5,6,7,1,2,3,4]\n ' for i in range(k): print(i) nums.insert(i, nums.pop(((i + k) + 1))) print(nums)
输入: nums = [1,2,3,4,5,6,7], k = 3 输出: [5,6,7,1,2,3,4]
api/app/tools/leetcode.py
rotate
yunfei07/vue-flask-in-action
0
python
def rotate(nums, k): '\n 输入: nums = [1,2,3,4,5,6,7], k = 3\n 输出: [5,6,7,1,2,3,4]\n ' for i in range(k): print(i) nums.insert(i, nums.pop(((i + k) + 1))) print(nums)
def rotate(nums, k): '\n 输入: nums = [1,2,3,4,5,6,7], k = 3\n 输出: [5,6,7,1,2,3,4]\n ' for i in range(k): print(i) nums.insert(i, nums.pop(((i + k) + 1))) print(nums)<|docstring|>输入: nums = [1,2,3,4,5,6,7], k = 3 输出: [5,6,7,1,2,3,4]<|endoftext|>
00944c4ede26ca9e9dcc99b27d2822c690e57f938825a34a43113a261316c545
def __virtual__(): '\n Only work on systems which exclusively use sysvinit\n ' disable = set(('RedHat', 'CentOS', 'Amazon', 'ScientificLinux', 'CloudLinux', 'Fedora', 'Gentoo', 'Ubuntu', 'Debian', 'Arch', 'Arch ARM', 'ALT', 'SUSE Enterprise Server', 'OEL', 'Linaro', 'elementary OS', 'McAfee OS Server')) if (__grains__.get('os', '') in disable): return False if (__grains__['kernel'] != 'Linux'): return False if (__grains__.get('os', '') == 'openSUSE'): try: if (int(__grains__.get('osrelease', '').split('.')[0]) >= 12): return False except ValueError: return False return 'service'
Only work on systems which exclusively use sysvinit
salt/modules/service.py
__virtual__
skrobul/salt
2
python
def __virtual__(): '\n \n ' disable = set(('RedHat', 'CentOS', 'Amazon', 'ScientificLinux', 'CloudLinux', 'Fedora', 'Gentoo', 'Ubuntu', 'Debian', 'Arch', 'Arch ARM', 'ALT', 'SUSE Enterprise Server', 'OEL', 'Linaro', 'elementary OS', 'McAfee OS Server')) if (__grains__.get('os', ) in disable): return False if (__grains__['kernel'] != 'Linux'): return False if (__grains__.get('os', ) == 'openSUSE'): try: if (int(__grains__.get('osrelease', ).split('.')[0]) >= 12): return False except ValueError: return False return 'service'
def __virtual__(): '\n \n ' disable = set(('RedHat', 'CentOS', 'Amazon', 'ScientificLinux', 'CloudLinux', 'Fedora', 'Gentoo', 'Ubuntu', 'Debian', 'Arch', 'Arch ARM', 'ALT', 'SUSE Enterprise Server', 'OEL', 'Linaro', 'elementary OS', 'McAfee OS Server')) if (__grains__.get('os', ) in disable): return False if (__grains__['kernel'] != 'Linux'): return False if (__grains__.get('os', ) == 'openSUSE'): try: if (int(__grains__.get('osrelease', ).split('.')[0]) >= 12): return False except ValueError: return False return 'service'<|docstring|>Only work on systems which exclusively use sysvinit<|endoftext|>
9b6fbe09554e218aeb3b4d879c197e467acc9c0ea6cffa26e42a28e0208b050a
def start(name): "\n Start the specified service\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.start <service name>\n " cmd = (os.path.join(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d'), name) + ' start') return (not __salt__['cmd.retcode'](cmd))
Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name>
salt/modules/service.py
start
skrobul/salt
2
python
def start(name): "\n Start the specified service\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.start <service name>\n " cmd = (os.path.join(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d'), name) + ' start') return (not __salt__['cmd.retcode'](cmd))
def start(name): "\n Start the specified service\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.start <service name>\n " cmd = (os.path.join(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d'), name) + ' start') return (not __salt__['cmd.retcode'](cmd))<|docstring|>Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name><|endoftext|>
7a89a9249a92a110e8623ff62c4524ac6bcffd54cb6f6189481d9c27de4279db
def stop(name): "\n Stop the specified service\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.stop <service name>\n " cmd = (os.path.join(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d'), name) + ' stop') return (not __salt__['cmd.retcode'](cmd))
Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name>
salt/modules/service.py
stop
skrobul/salt
2
python
def stop(name): "\n Stop the specified service\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.stop <service name>\n " cmd = (os.path.join(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d'), name) + ' stop') return (not __salt__['cmd.retcode'](cmd))
def stop(name): "\n Stop the specified service\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.stop <service name>\n " cmd = (os.path.join(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d'), name) + ' stop') return (not __salt__['cmd.retcode'](cmd))<|docstring|>Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name><|endoftext|>
c18f618926ed7ff46b35d322282f1351a48b8b9b15de1b09c18b1010f11e2040
def restart(name): "\n Restart the specified service\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.restart <service name>\n " cmd = (os.path.join(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d'), name) + ' restart') return (not __salt__['cmd.retcode'](cmd))
Restart the specified service CLI Example: .. code-block:: bash salt '*' service.restart <service name>
salt/modules/service.py
restart
skrobul/salt
2
python
def restart(name): "\n Restart the specified service\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.restart <service name>\n " cmd = (os.path.join(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d'), name) + ' restart') return (not __salt__['cmd.retcode'](cmd))
def restart(name): "\n Restart the specified service\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.restart <service name>\n " cmd = (os.path.join(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d'), name) + ' restart') return (not __salt__['cmd.retcode'](cmd))<|docstring|>Restart the specified service CLI Example: .. code-block:: bash salt '*' service.restart <service name><|endoftext|>
2ca8d96d84faa72e9b14b96b27ea233f4316b4b83c99765d5abd1440c30174b7
def status(name, sig=None): "\n Return the status for a service, returns the PID or an empty string if the\n service is running or not, pass a signature to use to find the service via\n ps\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.status <service name> [service signature]\n " return __salt__['status.pid']((sig if sig else name))
Return the status for a service, returns the PID or an empty string if the service is running or not, pass a signature to use to find the service via ps CLI Example: .. code-block:: bash salt '*' service.status <service name> [service signature]
salt/modules/service.py
status
skrobul/salt
2
python
def status(name, sig=None): "\n Return the status for a service, returns the PID or an empty string if the\n service is running or not, pass a signature to use to find the service via\n ps\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.status <service name> [service signature]\n " return __salt__['status.pid']((sig if sig else name))
def status(name, sig=None): "\n Return the status for a service, returns the PID or an empty string if the\n service is running or not, pass a signature to use to find the service via\n ps\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.status <service name> [service signature]\n " return __salt__['status.pid']((sig if sig else name))<|docstring|>Return the status for a service, returns the PID or an empty string if the service is running or not, pass a signature to use to find the service via ps CLI Example: .. code-block:: bash salt '*' service.status <service name> [service signature]<|endoftext|>
dc0947d4f8a7db3e759ff3cc566384ae86a6f0875b13ab9b5a562f5d63c68f00
def reload_(name): "\n Restart the specified service\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.reload <service name>\n " cmd = (os.path.join(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d'), name) + ' reload') return (not __salt__['cmd.retcode'](cmd))
Restart the specified service CLI Example: .. code-block:: bash salt '*' service.reload <service name>
salt/modules/service.py
reload_
skrobul/salt
2
python
def reload_(name): "\n Restart the specified service\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.reload <service name>\n " cmd = (os.path.join(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d'), name) + ' reload') return (not __salt__['cmd.retcode'](cmd))
def reload_(name): "\n Restart the specified service\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.reload <service name>\n " cmd = (os.path.join(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d'), name) + ' reload') return (not __salt__['cmd.retcode'](cmd))<|docstring|>Restart the specified service CLI Example: .. code-block:: bash salt '*' service.reload <service name><|endoftext|>
507fbe4e9d2fb6847d2010498ec2c13a25b7fdef608249066c6de5bbb6bd8a80
def available(name): "\n Returns ``True`` if the specified service is available, otherwise returns\n ``False``.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.available sshd\n " return (name in get_all())
Returns ``True`` if the specified service is available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.available sshd
salt/modules/service.py
available
skrobul/salt
2
python
def available(name): "\n Returns ``True`` if the specified service is available, otherwise returns\n ``False``.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.available sshd\n " return (name in get_all())
def available(name): "\n Returns ``True`` if the specified service is available, otherwise returns\n ``False``.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.available sshd\n " return (name in get_all())<|docstring|>Returns ``True`` if the specified service is available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.available sshd<|endoftext|>
d7d0e74d97acb947c2d142406241813ad17b4b2b70703131efa0eb5768e3e7bd
def missing(name): "\n The inverse of service.available.\n Returns ``True`` if the specified service is not available, otherwise returns\n ``False``.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.missing sshd\n " return (not (name in get_all()))
The inverse of service.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd
salt/modules/service.py
missing
skrobul/salt
2
python
def missing(name): "\n The inverse of service.available.\n Returns ``True`` if the specified service is not available, otherwise returns\n ``False``.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.missing sshd\n " return (not (name in get_all()))
def missing(name): "\n The inverse of service.available.\n Returns ``True`` if the specified service is not available, otherwise returns\n ``False``.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.missing sshd\n " return (not (name in get_all()))<|docstring|>The inverse of service.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd<|endoftext|>
4f1ed741ca9b375ada97bc11af2112143e04b75c3e61327e5e39ffe543a69bd0
def get_all(): "\n Return a list of all available services\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.get_all\n " if (not os.path.isdir(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d'))): return [] return sorted(os.listdir(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d')))
Return a list of all available services CLI Example: .. code-block:: bash salt '*' service.get_all
salt/modules/service.py
get_all
skrobul/salt
2
python
def get_all(): "\n Return a list of all available services\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.get_all\n " if (not os.path.isdir(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d'))): return [] return sorted(os.listdir(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d')))
def get_all(): "\n Return a list of all available services\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.get_all\n " if (not os.path.isdir(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d'))): return [] return sorted(os.listdir(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d')))<|docstring|>Return a list of all available services CLI Example: .. code-block:: bash salt '*' service.get_all<|endoftext|>
40606f3e16ecea2a70442047d322e76dcbcab5f649c2318486cd5a32ea2a928f
def identity_block(input_tensor, kernel_size, filters, stage, block, activation=True, include_batchnorm=False): "The identity block is the block that has no conv layer at shortcut.\n\n Args:\n input_tensor: input tensor\n kernel_size: default 3, the kernel size of\n middle conv layer at main path\n filters: list of integers, the filters of 3 conv layer at main path\n stage: integer, current stage label, used for generating layer names\n block: 'a','b'..., current block label, used for generating layer names\n activation: If True, include ReLU activation on the output.\n include_batchnorm: If True, include intermediate batchnorm layers.\n\n Returns:\n Output tensor for the block.\n " (filters1, filters2, filters3) = filters batchnorm_axis = 3 conv_name_base = ((('res' + str(stage)) + block) + '_branch') bn_name_base = ((('bn' + str(stage)) + block) + '_branch') x = tf.keras.layers.Conv2D(filters1, (1, 1), dilation_rate=(1, 1), kernel_initializer='glorot_uniform', name=(conv_name_base + '2a'))(input_tensor) if include_batchnorm: x = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(bn_name_base + '2a'))(x) x = tf.keras.layers.ReLU()(x) x = tf.keras.layers.Conv2D(filters2, kernel_size, dilation_rate=(1, 1), padding='same', kernel_initializer='glorot_uniform', name=(conv_name_base + '2b'))(x) if include_batchnorm: x = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(bn_name_base + '2b'))(x) x = tf.keras.layers.ReLU()(x) x = tf.keras.layers.Conv2D(filters3, (1, 1), dilation_rate=(1, 1), kernel_initializer='glorot_uniform', name=(conv_name_base + '2c'))(x) if include_batchnorm: x = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(bn_name_base + '2c'))(x) x = tf.keras.layers.add([x, input_tensor]) if activation: x = tf.keras.layers.ReLU()(x) return x
The identity block is the block that has no conv layer at shortcut. Args: input_tensor: input tensor kernel_size: default 3, the kernel size of middle conv layer at main path filters: list of integers, the filters of 3 conv layer at main path stage: integer, current stage label, used for generating layer names block: 'a','b'..., current block label, used for generating layer names activation: If True, include ReLU activation on the output. include_batchnorm: If True, include intermediate batchnorm layers. Returns: Output tensor for the block.
ravens/ravens/models/resnet.py
identity_block
wy-go/google-research
23,901
python
def identity_block(input_tensor, kernel_size, filters, stage, block, activation=True, include_batchnorm=False): "The identity block is the block that has no conv layer at shortcut.\n\n Args:\n input_tensor: input tensor\n kernel_size: default 3, the kernel size of\n middle conv layer at main path\n filters: list of integers, the filters of 3 conv layer at main path\n stage: integer, current stage label, used for generating layer names\n block: 'a','b'..., current block label, used for generating layer names\n activation: If True, include ReLU activation on the output.\n include_batchnorm: If True, include intermediate batchnorm layers.\n\n Returns:\n Output tensor for the block.\n " (filters1, filters2, filters3) = filters batchnorm_axis = 3 conv_name_base = ((('res' + str(stage)) + block) + '_branch') bn_name_base = ((('bn' + str(stage)) + block) + '_branch') x = tf.keras.layers.Conv2D(filters1, (1, 1), dilation_rate=(1, 1), kernel_initializer='glorot_uniform', name=(conv_name_base + '2a'))(input_tensor) if include_batchnorm: x = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(bn_name_base + '2a'))(x) x = tf.keras.layers.ReLU()(x) x = tf.keras.layers.Conv2D(filters2, kernel_size, dilation_rate=(1, 1), padding='same', kernel_initializer='glorot_uniform', name=(conv_name_base + '2b'))(x) if include_batchnorm: x = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(bn_name_base + '2b'))(x) x = tf.keras.layers.ReLU()(x) x = tf.keras.layers.Conv2D(filters3, (1, 1), dilation_rate=(1, 1), kernel_initializer='glorot_uniform', name=(conv_name_base + '2c'))(x) if include_batchnorm: x = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(bn_name_base + '2c'))(x) x = tf.keras.layers.add([x, input_tensor]) if activation: x = tf.keras.layers.ReLU()(x) return x
def identity_block(input_tensor, kernel_size, filters, stage, block, activation=True, include_batchnorm=False): "The identity block is the block that has no conv layer at shortcut.\n\n Args:\n input_tensor: input tensor\n kernel_size: default 3, the kernel size of\n middle conv layer at main path\n filters: list of integers, the filters of 3 conv layer at main path\n stage: integer, current stage label, used for generating layer names\n block: 'a','b'..., current block label, used for generating layer names\n activation: If True, include ReLU activation on the output.\n include_batchnorm: If True, include intermediate batchnorm layers.\n\n Returns:\n Output tensor for the block.\n " (filters1, filters2, filters3) = filters batchnorm_axis = 3 conv_name_base = ((('res' + str(stage)) + block) + '_branch') bn_name_base = ((('bn' + str(stage)) + block) + '_branch') x = tf.keras.layers.Conv2D(filters1, (1, 1), dilation_rate=(1, 1), kernel_initializer='glorot_uniform', name=(conv_name_base + '2a'))(input_tensor) if include_batchnorm: x = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(bn_name_base + '2a'))(x) x = tf.keras.layers.ReLU()(x) x = tf.keras.layers.Conv2D(filters2, kernel_size, dilation_rate=(1, 1), padding='same', kernel_initializer='glorot_uniform', name=(conv_name_base + '2b'))(x) if include_batchnorm: x = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(bn_name_base + '2b'))(x) x = tf.keras.layers.ReLU()(x) x = tf.keras.layers.Conv2D(filters3, (1, 1), dilation_rate=(1, 1), kernel_initializer='glorot_uniform', name=(conv_name_base + '2c'))(x) if include_batchnorm: x = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(bn_name_base + '2c'))(x) x = tf.keras.layers.add([x, input_tensor]) if activation: x = tf.keras.layers.ReLU()(x) return x<|docstring|>The identity block is the block that has no conv layer at shortcut. Args: input_tensor: input tensor kernel_size: default 3, the kernel size of middle conv layer at main path filters: list of integers, the filters of 3 conv layer at main path stage: integer, current stage label, used for generating layer names block: 'a','b'..., current block label, used for generating layer names activation: If True, include ReLU activation on the output. include_batchnorm: If True, include intermediate batchnorm layers. Returns: Output tensor for the block.<|endoftext|>
f81c2dfbe7c0a2844cda5cefe2bc55aa708072deb09febbd397d2840d124cdff
def conv_block(input_tensor, kernel_size, filters, stage, block, strides=(2, 2), activation=True, include_batchnorm=False): "A block that has a conv layer at shortcut.\n\n Note that from stage 3,\n the first conv layer at main path is with strides=(2, 2)\n And the shortcut should have strides=(2, 2) as well\n\n Args:\n input_tensor: input tensor\n kernel_size: default 3, the kernel size of\n middle conv layer at main path\n filters: list of integers, the filters of 3 conv layer at main path\n stage: integer, current stage label, used for generating layer names\n block: 'a','b'..., current block label, used for generating layer names\n strides: Strides for the first conv layer in the block.\n activation: If True, include ReLU activation on the output.\n include_batchnorm: If True, include intermediate batchnorm layers.\n\n Returns:\n Output tensor for the block.\n " (filters1, filters2, filters3) = filters batchnorm_axis = 3 conv_name_base = ((('res' + str(stage)) + block) + '_branch') bn_name_base = ((('bn' + str(stage)) + block) + '_branch') x = tf.keras.layers.Conv2D(filters1, (1, 1), strides=strides, dilation_rate=(1, 1), kernel_initializer='glorot_uniform', name=(conv_name_base + '2a'))(input_tensor) if include_batchnorm: x = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(bn_name_base + '2a'))(x) x = tf.keras.layers.ReLU()(x) x = tf.keras.layers.Conv2D(filters2, kernel_size, padding='same', dilation_rate=(1, 1), kernel_initializer='glorot_uniform', name=(conv_name_base + '2b'))(x) if include_batchnorm: x = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(bn_name_base + '2b'))(x) x = tf.keras.layers.ReLU()(x) x = tf.keras.layers.Conv2D(filters3, (1, 1), kernel_initializer='glorot_uniform', dilation_rate=(1, 1), name=(conv_name_base + '2c'))(x) if include_batchnorm: x = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(bn_name_base + '2c'))(x) shortcut = tf.keras.layers.Conv2D(filters3, (1, 1), strides=strides, dilation_rate=(1, 1), kernel_initializer='glorot_uniform', name=(conv_name_base + '1'))(input_tensor) if include_batchnorm: shortcut = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(bn_name_base + '1'))(shortcut) x = tf.keras.layers.add([x, shortcut]) if activation: x = tf.keras.layers.ReLU()(x) return x
A block that has a conv layer at shortcut. Note that from stage 3, the first conv layer at main path is with strides=(2, 2) And the shortcut should have strides=(2, 2) as well Args: input_tensor: input tensor kernel_size: default 3, the kernel size of middle conv layer at main path filters: list of integers, the filters of 3 conv layer at main path stage: integer, current stage label, used for generating layer names block: 'a','b'..., current block label, used for generating layer names strides: Strides for the first conv layer in the block. activation: If True, include ReLU activation on the output. include_batchnorm: If True, include intermediate batchnorm layers. Returns: Output tensor for the block.
ravens/ravens/models/resnet.py
conv_block
wy-go/google-research
23,901
python
def conv_block(input_tensor, kernel_size, filters, stage, block, strides=(2, 2), activation=True, include_batchnorm=False): "A block that has a conv layer at shortcut.\n\n Note that from stage 3,\n the first conv layer at main path is with strides=(2, 2)\n And the shortcut should have strides=(2, 2) as well\n\n Args:\n input_tensor: input tensor\n kernel_size: default 3, the kernel size of\n middle conv layer at main path\n filters: list of integers, the filters of 3 conv layer at main path\n stage: integer, current stage label, used for generating layer names\n block: 'a','b'..., current block label, used for generating layer names\n strides: Strides for the first conv layer in the block.\n activation: If True, include ReLU activation on the output.\n include_batchnorm: If True, include intermediate batchnorm layers.\n\n Returns:\n Output tensor for the block.\n " (filters1, filters2, filters3) = filters batchnorm_axis = 3 conv_name_base = ((('res' + str(stage)) + block) + '_branch') bn_name_base = ((('bn' + str(stage)) + block) + '_branch') x = tf.keras.layers.Conv2D(filters1, (1, 1), strides=strides, dilation_rate=(1, 1), kernel_initializer='glorot_uniform', name=(conv_name_base + '2a'))(input_tensor) if include_batchnorm: x = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(bn_name_base + '2a'))(x) x = tf.keras.layers.ReLU()(x) x = tf.keras.layers.Conv2D(filters2, kernel_size, padding='same', dilation_rate=(1, 1), kernel_initializer='glorot_uniform', name=(conv_name_base + '2b'))(x) if include_batchnorm: x = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(bn_name_base + '2b'))(x) x = tf.keras.layers.ReLU()(x) x = tf.keras.layers.Conv2D(filters3, (1, 1), kernel_initializer='glorot_uniform', dilation_rate=(1, 1), name=(conv_name_base + '2c'))(x) if include_batchnorm: x = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(bn_name_base + '2c'))(x) shortcut = tf.keras.layers.Conv2D(filters3, (1, 1), strides=strides, dilation_rate=(1, 1), kernel_initializer='glorot_uniform', name=(conv_name_base + '1'))(input_tensor) if include_batchnorm: shortcut = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(bn_name_base + '1'))(shortcut) x = tf.keras.layers.add([x, shortcut]) if activation: x = tf.keras.layers.ReLU()(x) return x
def conv_block(input_tensor, kernel_size, filters, stage, block, strides=(2, 2), activation=True, include_batchnorm=False): "A block that has a conv layer at shortcut.\n\n Note that from stage 3,\n the first conv layer at main path is with strides=(2, 2)\n And the shortcut should have strides=(2, 2) as well\n\n Args:\n input_tensor: input tensor\n kernel_size: default 3, the kernel size of\n middle conv layer at main path\n filters: list of integers, the filters of 3 conv layer at main path\n stage: integer, current stage label, used for generating layer names\n block: 'a','b'..., current block label, used for generating layer names\n strides: Strides for the first conv layer in the block.\n activation: If True, include ReLU activation on the output.\n include_batchnorm: If True, include intermediate batchnorm layers.\n\n Returns:\n Output tensor for the block.\n " (filters1, filters2, filters3) = filters batchnorm_axis = 3 conv_name_base = ((('res' + str(stage)) + block) + '_branch') bn_name_base = ((('bn' + str(stage)) + block) + '_branch') x = tf.keras.layers.Conv2D(filters1, (1, 1), strides=strides, dilation_rate=(1, 1), kernel_initializer='glorot_uniform', name=(conv_name_base + '2a'))(input_tensor) if include_batchnorm: x = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(bn_name_base + '2a'))(x) x = tf.keras.layers.ReLU()(x) x = tf.keras.layers.Conv2D(filters2, kernel_size, padding='same', dilation_rate=(1, 1), kernel_initializer='glorot_uniform', name=(conv_name_base + '2b'))(x) if include_batchnorm: x = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(bn_name_base + '2b'))(x) x = tf.keras.layers.ReLU()(x) x = tf.keras.layers.Conv2D(filters3, (1, 1), kernel_initializer='glorot_uniform', dilation_rate=(1, 1), name=(conv_name_base + '2c'))(x) if include_batchnorm: x = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(bn_name_base + '2c'))(x) shortcut = tf.keras.layers.Conv2D(filters3, (1, 1), strides=strides, dilation_rate=(1, 1), kernel_initializer='glorot_uniform', name=(conv_name_base + '1'))(input_tensor) if include_batchnorm: shortcut = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(bn_name_base + '1'))(shortcut) x = tf.keras.layers.add([x, shortcut]) if activation: x = tf.keras.layers.ReLU()(x) return x<|docstring|>A block that has a conv layer at shortcut. Note that from stage 3, the first conv layer at main path is with strides=(2, 2) And the shortcut should have strides=(2, 2) as well Args: input_tensor: input tensor kernel_size: default 3, the kernel size of middle conv layer at main path filters: list of integers, the filters of 3 conv layer at main path stage: integer, current stage label, used for generating layer names block: 'a','b'..., current block label, used for generating layer names strides: Strides for the first conv layer in the block. activation: If True, include ReLU activation on the output. include_batchnorm: If True, include intermediate batchnorm layers. Returns: Output tensor for the block.<|endoftext|>
5c62b3c8a02dda925ad63f288d1309b0eb87fa6415e3c1f1edfbbc588cd2c41f
def ResNet43_8s(input_shape, output_dim, include_batchnorm=False, batchnorm_axis=3, prefix='', cutoff_early=False): 'Build Resent 43 8s.' input_data = tf.keras.layers.Input(shape=input_shape) x = tf.keras.layers.Conv2D(64, (3, 3), strides=(1, 1), padding='same', kernel_initializer='glorot_uniform', name=(prefix + 'conv1'))(input_data) if include_batchnorm: x = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(prefix + 'bn_conv1'))(x) x = tf.keras.layers.ReLU()(x) if cutoff_early: x = conv_block(x, 5, [64, 64, output_dim], stage=2, block=(prefix + 'a'), strides=(1, 1), include_batchnorm=include_batchnorm) x = identity_block(x, 5, [64, 64, output_dim], stage=2, block=(prefix + 'b'), include_batchnorm=include_batchnorm) return (input_data, x) x = conv_block(x, 3, [64, 64, 64], stage=2, block=(prefix + 'a'), strides=(1, 1)) x = identity_block(x, 3, [64, 64, 64], stage=2, block=(prefix + 'b')) x = conv_block(x, 3, [128, 128, 128], stage=3, block=(prefix + 'a'), strides=(2, 2)) x = identity_block(x, 3, [128, 128, 128], stage=3, block=(prefix + 'b')) x = conv_block(x, 3, [256, 256, 256], stage=4, block=(prefix + 'a'), strides=(2, 2)) x = identity_block(x, 3, [256, 256, 256], stage=4, block=(prefix + 'b')) x = conv_block(x, 3, [512, 512, 512], stage=5, block=(prefix + 'a'), strides=(2, 2)) x = identity_block(x, 3, [512, 512, 512], stage=5, block=(prefix + 'b')) x = conv_block(x, 3, [256, 256, 256], stage=6, block=(prefix + 'a'), strides=(1, 1)) x = identity_block(x, 3, [256, 256, 256], stage=6, block=(prefix + 'b')) x = tf.keras.layers.UpSampling2D(size=(2, 2), interpolation='bilinear', name=(prefix + 'upsample_1'))(x) x = conv_block(x, 3, [128, 128, 128], stage=7, block=(prefix + 'a'), strides=(1, 1)) x = identity_block(x, 3, [128, 128, 128], stage=7, block=(prefix + 'b')) x = tf.keras.layers.UpSampling2D(size=(2, 2), interpolation='bilinear', name=(prefix + 'upsample_2'))(x) x = conv_block(x, 3, [64, 64, 64], stage=8, block=(prefix + 'a'), strides=(1, 1)) x = identity_block(x, 3, [64, 64, 64], stage=8, block=(prefix + 'b')) x = tf.keras.layers.UpSampling2D(size=(2, 2), interpolation='bilinear', name=(prefix + 'upsample_3'))(x) x = conv_block(x, 3, [16, 16, output_dim], stage=9, block=(prefix + 'a'), strides=(1, 1), activation=False) output = identity_block(x, 3, [16, 16, output_dim], stage=9, block=(prefix + 'b'), activation=False) return (input_data, output)
Build Resent 43 8s.
ravens/ravens/models/resnet.py
ResNet43_8s
wy-go/google-research
23,901
python
def ResNet43_8s(input_shape, output_dim, include_batchnorm=False, batchnorm_axis=3, prefix=, cutoff_early=False): input_data = tf.keras.layers.Input(shape=input_shape) x = tf.keras.layers.Conv2D(64, (3, 3), strides=(1, 1), padding='same', kernel_initializer='glorot_uniform', name=(prefix + 'conv1'))(input_data) if include_batchnorm: x = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(prefix + 'bn_conv1'))(x) x = tf.keras.layers.ReLU()(x) if cutoff_early: x = conv_block(x, 5, [64, 64, output_dim], stage=2, block=(prefix + 'a'), strides=(1, 1), include_batchnorm=include_batchnorm) x = identity_block(x, 5, [64, 64, output_dim], stage=2, block=(prefix + 'b'), include_batchnorm=include_batchnorm) return (input_data, x) x = conv_block(x, 3, [64, 64, 64], stage=2, block=(prefix + 'a'), strides=(1, 1)) x = identity_block(x, 3, [64, 64, 64], stage=2, block=(prefix + 'b')) x = conv_block(x, 3, [128, 128, 128], stage=3, block=(prefix + 'a'), strides=(2, 2)) x = identity_block(x, 3, [128, 128, 128], stage=3, block=(prefix + 'b')) x = conv_block(x, 3, [256, 256, 256], stage=4, block=(prefix + 'a'), strides=(2, 2)) x = identity_block(x, 3, [256, 256, 256], stage=4, block=(prefix + 'b')) x = conv_block(x, 3, [512, 512, 512], stage=5, block=(prefix + 'a'), strides=(2, 2)) x = identity_block(x, 3, [512, 512, 512], stage=5, block=(prefix + 'b')) x = conv_block(x, 3, [256, 256, 256], stage=6, block=(prefix + 'a'), strides=(1, 1)) x = identity_block(x, 3, [256, 256, 256], stage=6, block=(prefix + 'b')) x = tf.keras.layers.UpSampling2D(size=(2, 2), interpolation='bilinear', name=(prefix + 'upsample_1'))(x) x = conv_block(x, 3, [128, 128, 128], stage=7, block=(prefix + 'a'), strides=(1, 1)) x = identity_block(x, 3, [128, 128, 128], stage=7, block=(prefix + 'b')) x = tf.keras.layers.UpSampling2D(size=(2, 2), interpolation='bilinear', name=(prefix + 'upsample_2'))(x) x = conv_block(x, 3, [64, 64, 64], stage=8, block=(prefix + 'a'), strides=(1, 1)) x = identity_block(x, 3, [64, 64, 64], stage=8, block=(prefix + 'b')) x = tf.keras.layers.UpSampling2D(size=(2, 2), interpolation='bilinear', name=(prefix + 'upsample_3'))(x) x = conv_block(x, 3, [16, 16, output_dim], stage=9, block=(prefix + 'a'), strides=(1, 1), activation=False) output = identity_block(x, 3, [16, 16, output_dim], stage=9, block=(prefix + 'b'), activation=False) return (input_data, output)
def ResNet43_8s(input_shape, output_dim, include_batchnorm=False, batchnorm_axis=3, prefix=, cutoff_early=False): input_data = tf.keras.layers.Input(shape=input_shape) x = tf.keras.layers.Conv2D(64, (3, 3), strides=(1, 1), padding='same', kernel_initializer='glorot_uniform', name=(prefix + 'conv1'))(input_data) if include_batchnorm: x = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(prefix + 'bn_conv1'))(x) x = tf.keras.layers.ReLU()(x) if cutoff_early: x = conv_block(x, 5, [64, 64, output_dim], stage=2, block=(prefix + 'a'), strides=(1, 1), include_batchnorm=include_batchnorm) x = identity_block(x, 5, [64, 64, output_dim], stage=2, block=(prefix + 'b'), include_batchnorm=include_batchnorm) return (input_data, x) x = conv_block(x, 3, [64, 64, 64], stage=2, block=(prefix + 'a'), strides=(1, 1)) x = identity_block(x, 3, [64, 64, 64], stage=2, block=(prefix + 'b')) x = conv_block(x, 3, [128, 128, 128], stage=3, block=(prefix + 'a'), strides=(2, 2)) x = identity_block(x, 3, [128, 128, 128], stage=3, block=(prefix + 'b')) x = conv_block(x, 3, [256, 256, 256], stage=4, block=(prefix + 'a'), strides=(2, 2)) x = identity_block(x, 3, [256, 256, 256], stage=4, block=(prefix + 'b')) x = conv_block(x, 3, [512, 512, 512], stage=5, block=(prefix + 'a'), strides=(2, 2)) x = identity_block(x, 3, [512, 512, 512], stage=5, block=(prefix + 'b')) x = conv_block(x, 3, [256, 256, 256], stage=6, block=(prefix + 'a'), strides=(1, 1)) x = identity_block(x, 3, [256, 256, 256], stage=6, block=(prefix + 'b')) x = tf.keras.layers.UpSampling2D(size=(2, 2), interpolation='bilinear', name=(prefix + 'upsample_1'))(x) x = conv_block(x, 3, [128, 128, 128], stage=7, block=(prefix + 'a'), strides=(1, 1)) x = identity_block(x, 3, [128, 128, 128], stage=7, block=(prefix + 'b')) x = tf.keras.layers.UpSampling2D(size=(2, 2), interpolation='bilinear', name=(prefix + 'upsample_2'))(x) x = conv_block(x, 3, [64, 64, 64], stage=8, block=(prefix + 'a'), strides=(1, 1)) x = identity_block(x, 3, [64, 64, 64], stage=8, block=(prefix + 'b')) x = tf.keras.layers.UpSampling2D(size=(2, 2), interpolation='bilinear', name=(prefix + 'upsample_3'))(x) x = conv_block(x, 3, [16, 16, output_dim], stage=9, block=(prefix + 'a'), strides=(1, 1), activation=False) output = identity_block(x, 3, [16, 16, output_dim], stage=9, block=(prefix + 'b'), activation=False) return (input_data, output)<|docstring|>Build Resent 43 8s.<|endoftext|>
4e232ff8382f0987b3a49d1f0a1e2c71386abc2e2c8cda1ddbaaf1340b3dabbf
def ResNet36_4s(input_shape, output_dim, include_batchnorm=False, batchnorm_axis=3, prefix='', cutoff_early=False): 'Build Resent 36 4s.' input_data = tf.keras.layers.Input(shape=input_shape) x = tf.keras.layers.Conv2D(64, (3, 3), strides=(1, 1), padding='same', kernel_initializer='glorot_uniform', name=(prefix + 'conv1'))(input_data) if include_batchnorm: x = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(prefix + 'bn_conv1'))(x) x = tf.keras.layers.ReLU()(x) if cutoff_early: x = conv_block(x, 5, [64, 64, output_dim], stage=2, block=(prefix + 'a'), strides=(1, 1), include_batchnorm=include_batchnorm) x = identity_block(x, 5, [64, 64, output_dim], stage=2, block=(prefix + 'b'), include_batchnorm=include_batchnorm) return (input_data, x) x = conv_block(x, 3, [64, 64, 64], stage=2, block=(prefix + 'a'), strides=(1, 1)) x = identity_block(x, 3, [64, 64, 64], stage=2, block=(prefix + 'b')) x = conv_block(x, 3, [64, 64, 64], stage=3, block=(prefix + 'a'), strides=(2, 2)) x = identity_block(x, 3, [64, 64, 64], stage=3, block=(prefix + 'b')) x = conv_block(x, 3, [64, 64, 64], stage=4, block=(prefix + 'a'), strides=(2, 2)) x = identity_block(x, 3, [64, 64, 64], stage=4, block=(prefix + 'b')) x = tf.keras.layers.UpSampling2D(size=(2, 2), interpolation='bilinear', name=(prefix + 'upsample_2'))(x) x = conv_block(x, 3, [64, 64, 64], stage=8, block=(prefix + 'a'), strides=(1, 1)) x = identity_block(x, 3, [64, 64, 64], stage=8, block=(prefix + 'b')) x = tf.keras.layers.UpSampling2D(size=(2, 2), interpolation='bilinear', name=(prefix + 'upsample_3'))(x) x = conv_block(x, 3, [16, 16, output_dim], stage=9, block=(prefix + 'a'), strides=(1, 1), activation=False) output = identity_block(x, 3, [16, 16, output_dim], stage=9, block=(prefix + 'b'), activation=False) return (input_data, output)
Build Resent 36 4s.
ravens/ravens/models/resnet.py
ResNet36_4s
wy-go/google-research
23,901
python
def ResNet36_4s(input_shape, output_dim, include_batchnorm=False, batchnorm_axis=3, prefix=, cutoff_early=False): input_data = tf.keras.layers.Input(shape=input_shape) x = tf.keras.layers.Conv2D(64, (3, 3), strides=(1, 1), padding='same', kernel_initializer='glorot_uniform', name=(prefix + 'conv1'))(input_data) if include_batchnorm: x = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(prefix + 'bn_conv1'))(x) x = tf.keras.layers.ReLU()(x) if cutoff_early: x = conv_block(x, 5, [64, 64, output_dim], stage=2, block=(prefix + 'a'), strides=(1, 1), include_batchnorm=include_batchnorm) x = identity_block(x, 5, [64, 64, output_dim], stage=2, block=(prefix + 'b'), include_batchnorm=include_batchnorm) return (input_data, x) x = conv_block(x, 3, [64, 64, 64], stage=2, block=(prefix + 'a'), strides=(1, 1)) x = identity_block(x, 3, [64, 64, 64], stage=2, block=(prefix + 'b')) x = conv_block(x, 3, [64, 64, 64], stage=3, block=(prefix + 'a'), strides=(2, 2)) x = identity_block(x, 3, [64, 64, 64], stage=3, block=(prefix + 'b')) x = conv_block(x, 3, [64, 64, 64], stage=4, block=(prefix + 'a'), strides=(2, 2)) x = identity_block(x, 3, [64, 64, 64], stage=4, block=(prefix + 'b')) x = tf.keras.layers.UpSampling2D(size=(2, 2), interpolation='bilinear', name=(prefix + 'upsample_2'))(x) x = conv_block(x, 3, [64, 64, 64], stage=8, block=(prefix + 'a'), strides=(1, 1)) x = identity_block(x, 3, [64, 64, 64], stage=8, block=(prefix + 'b')) x = tf.keras.layers.UpSampling2D(size=(2, 2), interpolation='bilinear', name=(prefix + 'upsample_3'))(x) x = conv_block(x, 3, [16, 16, output_dim], stage=9, block=(prefix + 'a'), strides=(1, 1), activation=False) output = identity_block(x, 3, [16, 16, output_dim], stage=9, block=(prefix + 'b'), activation=False) return (input_data, output)
def ResNet36_4s(input_shape, output_dim, include_batchnorm=False, batchnorm_axis=3, prefix=, cutoff_early=False): input_data = tf.keras.layers.Input(shape=input_shape) x = tf.keras.layers.Conv2D(64, (3, 3), strides=(1, 1), padding='same', kernel_initializer='glorot_uniform', name=(prefix + 'conv1'))(input_data) if include_batchnorm: x = tf.keras.layers.BatchNormalization(axis=batchnorm_axis, name=(prefix + 'bn_conv1'))(x) x = tf.keras.layers.ReLU()(x) if cutoff_early: x = conv_block(x, 5, [64, 64, output_dim], stage=2, block=(prefix + 'a'), strides=(1, 1), include_batchnorm=include_batchnorm) x = identity_block(x, 5, [64, 64, output_dim], stage=2, block=(prefix + 'b'), include_batchnorm=include_batchnorm) return (input_data, x) x = conv_block(x, 3, [64, 64, 64], stage=2, block=(prefix + 'a'), strides=(1, 1)) x = identity_block(x, 3, [64, 64, 64], stage=2, block=(prefix + 'b')) x = conv_block(x, 3, [64, 64, 64], stage=3, block=(prefix + 'a'), strides=(2, 2)) x = identity_block(x, 3, [64, 64, 64], stage=3, block=(prefix + 'b')) x = conv_block(x, 3, [64, 64, 64], stage=4, block=(prefix + 'a'), strides=(2, 2)) x = identity_block(x, 3, [64, 64, 64], stage=4, block=(prefix + 'b')) x = tf.keras.layers.UpSampling2D(size=(2, 2), interpolation='bilinear', name=(prefix + 'upsample_2'))(x) x = conv_block(x, 3, [64, 64, 64], stage=8, block=(prefix + 'a'), strides=(1, 1)) x = identity_block(x, 3, [64, 64, 64], stage=8, block=(prefix + 'b')) x = tf.keras.layers.UpSampling2D(size=(2, 2), interpolation='bilinear', name=(prefix + 'upsample_3'))(x) x = conv_block(x, 3, [16, 16, output_dim], stage=9, block=(prefix + 'a'), strides=(1, 1), activation=False) output = identity_block(x, 3, [16, 16, output_dim], stage=9, block=(prefix + 'b'), activation=False) return (input_data, output)<|docstring|>Build Resent 36 4s.<|endoftext|>
fafbd46f495d731eb9f040dbad7e10647b8ac10a4ecb70928de41eeea0709f3c
def check_container(fn): " Ensure we're not trying to double up an external container\n with a Python instance that already has one. This would create\n dangling containers that may not get stopped programmatically.\n\n Note:\n This method is placed under ``base`` to prevent circular imports.\n\n Args:\n fn (Callable): wrapped function.\n\n Returns:\n Callable\n " @wraps(fn) def inner(self, *args, **kwargs): self.logger.debug('checking container before creation') if (self.factory is None): raise DockerException('no docker client defined as factory') if (getattr(self, 'container', None) is not None): raise DockerException(('container already exists for this driver instance (%s)' % self.container.name)) if (self.CONTAINER is None): raise DockerException('cannot create container without definition') try: self.factory.docker.ping() except APIError as e: self.logger.exception(e, exc_info=True) raise e else: self.logger.debug('checking passed') return fn(self, *args, **kwargs) return inner
Ensure we're not trying to double up an external container with a Python instance that already has one. This would create dangling containers that may not get stopped programmatically. Note: This method is placed under ``base`` to prevent circular imports. Args: fn (Callable): wrapped function. Returns: Callable
selenium_docker/drivers/__init__.py
check_container
vivint/selenium-docker
4
python
def check_container(fn): " Ensure we're not trying to double up an external container\n with a Python instance that already has one. This would create\n dangling containers that may not get stopped programmatically.\n\n Note:\n This method is placed under ``base`` to prevent circular imports.\n\n Args:\n fn (Callable): wrapped function.\n\n Returns:\n Callable\n " @wraps(fn) def inner(self, *args, **kwargs): self.logger.debug('checking container before creation') if (self.factory is None): raise DockerException('no docker client defined as factory') if (getattr(self, 'container', None) is not None): raise DockerException(('container already exists for this driver instance (%s)' % self.container.name)) if (self.CONTAINER is None): raise DockerException('cannot create container without definition') try: self.factory.docker.ping() except APIError as e: self.logger.exception(e, exc_info=True) raise e else: self.logger.debug('checking passed') return fn(self, *args, **kwargs) return inner
def check_container(fn): " Ensure we're not trying to double up an external container\n with a Python instance that already has one. This would create\n dangling containers that may not get stopped programmatically.\n\n Note:\n This method is placed under ``base`` to prevent circular imports.\n\n Args:\n fn (Callable): wrapped function.\n\n Returns:\n Callable\n " @wraps(fn) def inner(self, *args, **kwargs): self.logger.debug('checking container before creation') if (self.factory is None): raise DockerException('no docker client defined as factory') if (getattr(self, 'container', None) is not None): raise DockerException(('container already exists for this driver instance (%s)' % self.container.name)) if (self.CONTAINER is None): raise DockerException('cannot create container without definition') try: self.factory.docker.ping() except APIError as e: self.logger.exception(e, exc_info=True) raise e else: self.logger.debug('checking passed') return fn(self, *args, **kwargs) return inner<|docstring|>Ensure we're not trying to double up an external container with a Python instance that already has one. This would create dangling containers that may not get stopped programmatically. Note: This method is placed under ``base`` to prevent circular imports. Args: fn (Callable): wrapped function. Returns: Callable<|endoftext|>
7fbabd3c9e139b209d884d0c7594f9eec11b2be984f5bc7e18d1d0867e801282
def __init__(self, user_agent=None, proxy=None, cargs=None, ckwargs=None, extensions=None, logger=None, factory=None, flags=None): " Selenium compatible Remote Driver instance.\n\n Args:\n user_agent (str or Callable): overwrite browser's default\n user agent. If ``user_agent`` is a Callable then the result\n will be used as the user agent string for this browser\n instance.\n proxy (Proxy or SquidProxy): Proxy (or SquidProxy) instance\n that routes container traffic.\n cargs (list): container creation arguments.\n ckwargs (dict): container creation keyword arguments.\n extensions (list): list of file locations loaded as\n browser extensions.\n logger (:obj:`~logging.Logger`): logging module Logger instance.\n factory (:obj:`~selenium_docker.base.ContainerFactory`):\n abstract connection to a Docker Engine that does the primary\n interaction with starting and stopping containers.\n flags (:obj:`aenum.Flag`): bit flags used to turn advanced features\n on or off.\n\n Raises:\n ValueError: when ``proxy`` is an unknown/invalid value.\n Exception: when any problem occurs connecting the driver to its\n underlying container.\n " args = (cargs or []) ckwargs = (ckwargs or {}) extensions = (extensions or []) self.factory = (factory or ContainerFactory.get_default_factory()) self.factory.load_image(self.CONTAINER, background=False) self._name = ckwargs.setdefault('name', self.factory.gen_name()) self.logger = (logger or logging.getLogger(('%s.%s.%s' % (__name__, self.identity, self.name)))) self.container = self._make_container(**ckwargs) self._base_url = self.get_url() user_agent = (user_agent() if callable(user_agent) else user_agent) self._perform_check_container_ready() (self._proxy, self._proxy_container) = (None, None) if isinstance(proxy, Proxy): self._proxy_container = None self._proxy = proxy elif hasattr(proxy, 'selenium_proxy'): self._proxy_container = proxy self._proxy = proxy.selenium_proxy elif (proxy not in [None, False]): raise ValueError(('invalid proxy type, %s' % type(proxy))) self.flags = (self.Flags.DISABLED if (not flags) else flags) fn = juxt(self._capabilities, self._profile) (capabilities, profile) = fn(args, extensions, self._proxy, user_agent) try: super(DockerDriverBase, self).__init__(self._base_url, desired_capabilities=capabilities, browser_profile=profile, keep_alive=False) except Exception as e: self.logger.exception(e, exc_info=True) self.close_container() raise e self.implicitly_wait(self.IMPLICIT_WAIT_SECONDS) self._final(args, extensions, self._proxy, user_agent)
Selenium compatible Remote Driver instance. Args: user_agent (str or Callable): overwrite browser's default user agent. If ``user_agent`` is a Callable then the result will be used as the user agent string for this browser instance. proxy (Proxy or SquidProxy): Proxy (or SquidProxy) instance that routes container traffic. cargs (list): container creation arguments. ckwargs (dict): container creation keyword arguments. extensions (list): list of file locations loaded as browser extensions. logger (:obj:`~logging.Logger`): logging module Logger instance. factory (:obj:`~selenium_docker.base.ContainerFactory`): abstract connection to a Docker Engine that does the primary interaction with starting and stopping containers. flags (:obj:`aenum.Flag`): bit flags used to turn advanced features on or off. Raises: ValueError: when ``proxy`` is an unknown/invalid value. Exception: when any problem occurs connecting the driver to its underlying container.
selenium_docker/drivers/__init__.py
__init__
vivint/selenium-docker
4
python
def __init__(self, user_agent=None, proxy=None, cargs=None, ckwargs=None, extensions=None, logger=None, factory=None, flags=None): " Selenium compatible Remote Driver instance.\n\n Args:\n user_agent (str or Callable): overwrite browser's default\n user agent. If ``user_agent`` is a Callable then the result\n will be used as the user agent string for this browser\n instance.\n proxy (Proxy or SquidProxy): Proxy (or SquidProxy) instance\n that routes container traffic.\n cargs (list): container creation arguments.\n ckwargs (dict): container creation keyword arguments.\n extensions (list): list of file locations loaded as\n browser extensions.\n logger (:obj:`~logging.Logger`): logging module Logger instance.\n factory (:obj:`~selenium_docker.base.ContainerFactory`):\n abstract connection to a Docker Engine that does the primary\n interaction with starting and stopping containers.\n flags (:obj:`aenum.Flag`): bit flags used to turn advanced features\n on or off.\n\n Raises:\n ValueError: when ``proxy`` is an unknown/invalid value.\n Exception: when any problem occurs connecting the driver to its\n underlying container.\n " args = (cargs or []) ckwargs = (ckwargs or {}) extensions = (extensions or []) self.factory = (factory or ContainerFactory.get_default_factory()) self.factory.load_image(self.CONTAINER, background=False) self._name = ckwargs.setdefault('name', self.factory.gen_name()) self.logger = (logger or logging.getLogger(('%s.%s.%s' % (__name__, self.identity, self.name)))) self.container = self._make_container(**ckwargs) self._base_url = self.get_url() user_agent = (user_agent() if callable(user_agent) else user_agent) self._perform_check_container_ready() (self._proxy, self._proxy_container) = (None, None) if isinstance(proxy, Proxy): self._proxy_container = None self._proxy = proxy elif hasattr(proxy, 'selenium_proxy'): self._proxy_container = proxy self._proxy = proxy.selenium_proxy elif (proxy not in [None, False]): raise ValueError(('invalid proxy type, %s' % type(proxy))) self.flags = (self.Flags.DISABLED if (not flags) else flags) fn = juxt(self._capabilities, self._profile) (capabilities, profile) = fn(args, extensions, self._proxy, user_agent) try: super(DockerDriverBase, self).__init__(self._base_url, desired_capabilities=capabilities, browser_profile=profile, keep_alive=False) except Exception as e: self.logger.exception(e, exc_info=True) self.close_container() raise e self.implicitly_wait(self.IMPLICIT_WAIT_SECONDS) self._final(args, extensions, self._proxy, user_agent)
def __init__(self, user_agent=None, proxy=None, cargs=None, ckwargs=None, extensions=None, logger=None, factory=None, flags=None): " Selenium compatible Remote Driver instance.\n\n Args:\n user_agent (str or Callable): overwrite browser's default\n user agent. If ``user_agent`` is a Callable then the result\n will be used as the user agent string for this browser\n instance.\n proxy (Proxy or SquidProxy): Proxy (or SquidProxy) instance\n that routes container traffic.\n cargs (list): container creation arguments.\n ckwargs (dict): container creation keyword arguments.\n extensions (list): list of file locations loaded as\n browser extensions.\n logger (:obj:`~logging.Logger`): logging module Logger instance.\n factory (:obj:`~selenium_docker.base.ContainerFactory`):\n abstract connection to a Docker Engine that does the primary\n interaction with starting and stopping containers.\n flags (:obj:`aenum.Flag`): bit flags used to turn advanced features\n on or off.\n\n Raises:\n ValueError: when ``proxy`` is an unknown/invalid value.\n Exception: when any problem occurs connecting the driver to its\n underlying container.\n " args = (cargs or []) ckwargs = (ckwargs or {}) extensions = (extensions or []) self.factory = (factory or ContainerFactory.get_default_factory()) self.factory.load_image(self.CONTAINER, background=False) self._name = ckwargs.setdefault('name', self.factory.gen_name()) self.logger = (logger or logging.getLogger(('%s.%s.%s' % (__name__, self.identity, self.name)))) self.container = self._make_container(**ckwargs) self._base_url = self.get_url() user_agent = (user_agent() if callable(user_agent) else user_agent) self._perform_check_container_ready() (self._proxy, self._proxy_container) = (None, None) if isinstance(proxy, Proxy): self._proxy_container = None self._proxy = proxy elif hasattr(proxy, 'selenium_proxy'): self._proxy_container = proxy self._proxy = proxy.selenium_proxy elif (proxy not in [None, False]): raise ValueError(('invalid proxy type, %s' % type(proxy))) self.flags = (self.Flags.DISABLED if (not flags) else flags) fn = juxt(self._capabilities, self._profile) (capabilities, profile) = fn(args, extensions, self._proxy, user_agent) try: super(DockerDriverBase, self).__init__(self._base_url, desired_capabilities=capabilities, browser_profile=profile, keep_alive=False) except Exception as e: self.logger.exception(e, exc_info=True) self.close_container() raise e self.implicitly_wait(self.IMPLICIT_WAIT_SECONDS) self._final(args, extensions, self._proxy, user_agent)<|docstring|>Selenium compatible Remote Driver instance. Args: user_agent (str or Callable): overwrite browser's default user agent. If ``user_agent`` is a Callable then the result will be used as the user agent string for this browser instance. proxy (Proxy or SquidProxy): Proxy (or SquidProxy) instance that routes container traffic. cargs (list): container creation arguments. ckwargs (dict): container creation keyword arguments. extensions (list): list of file locations loaded as browser extensions. logger (:obj:`~logging.Logger`): logging module Logger instance. factory (:obj:`~selenium_docker.base.ContainerFactory`): abstract connection to a Docker Engine that does the primary interaction with starting and stopping containers. flags (:obj:`aenum.Flag`): bit flags used to turn advanced features on or off. Raises: ValueError: when ``proxy`` is an unknown/invalid value. Exception: when any problem occurs connecting the driver to its underlying container.<|endoftext|>
eaeb75d22827f5ff476201ce19506e67ca27c80ed0d049b0e3693b6f789e3317
@property def base_url(self): "str: read-only property of Selenium's base url. " return self._base_url
str: read-only property of Selenium's base url.
selenium_docker/drivers/__init__.py
base_url
vivint/selenium-docker
4
python
@property def base_url(self): " " return self._base_url
@property def base_url(self): " " return self._base_url<|docstring|>str: read-only property of Selenium's base url.<|endoftext|>
301370ac43f4ef12aeda67cca0419f71558a3af957f502828100be205690b2c7
@property def identity(self): "str: reference to the parent class' name. " return self.__class__.__name__
str: reference to the parent class' name.
selenium_docker/drivers/__init__.py
identity
vivint/selenium-docker
4
python
@property def identity(self): " " return self.__class__.__name__
@property def identity(self): " " return self.__class__.__name__<|docstring|>str: reference to the parent class' name.<|endoftext|>
18922bb98d4d9f1033e4fbac861defa8747f67a6b5bb40eecc77a2bad480e411
@property def name(self): "str: read-only property of the container's name. " return self._name
str: read-only property of the container's name.
selenium_docker/drivers/__init__.py
name
vivint/selenium-docker
4
python
@property def name(self): " " return self._name
@property def name(self): " " return self._name<|docstring|>str: read-only property of the container's name.<|endoftext|>
09c051ff55e0d57bd6d43503ce6ed65edb8451ea2d6e5ae82453b20011a1ffbc
@property def docker(self): ':obj:`docker.client.DockerClient`: reference' return self.factory.docker
:obj:`docker.client.DockerClient`: reference
selenium_docker/drivers/__init__.py
docker
vivint/selenium-docker
4
python
@property def docker(self): return self.factory.docker
@property def docker(self): return self.factory.docker<|docstring|>:obj:`docker.client.DockerClient`: reference<|endoftext|>
647128a690af487fa8b1ffb76e661aa2b19d8b46e24e08546435e5026f366c45
@check_container def _make_container(self, **kwargs): ' Create a running container on the given Docker engine.\n\n This container will contain the Selenium runtime, and ideally a\n browser instance to connect with.\n\n Args:\n **kwargs (dict): the specification of the docker container.\n\n Returns:\n :class:`~docker.models.containers.Container`\n ' self.logger.debug('creating container') return self.factory.start_container(self.CONTAINER, **kwargs)
Create a running container on the given Docker engine. This container will contain the Selenium runtime, and ideally a browser instance to connect with. Args: **kwargs (dict): the specification of the docker container. Returns: :class:`~docker.models.containers.Container`
selenium_docker/drivers/__init__.py
_make_container
vivint/selenium-docker
4
python
@check_container def _make_container(self, **kwargs): ' Create a running container on the given Docker engine.\n\n This container will contain the Selenium runtime, and ideally a\n browser instance to connect with.\n\n Args:\n **kwargs (dict): the specification of the docker container.\n\n Returns:\n :class:`~docker.models.containers.Container`\n ' self.logger.debug('creating container') return self.factory.start_container(self.CONTAINER, **kwargs)
@check_container def _make_container(self, **kwargs): ' Create a running container on the given Docker engine.\n\n This container will contain the Selenium runtime, and ideally a\n browser instance to connect with.\n\n Args:\n **kwargs (dict): the specification of the docker container.\n\n Returns:\n :class:`~docker.models.containers.Container`\n ' self.logger.debug('creating container') return self.factory.start_container(self.CONTAINER, **kwargs)<|docstring|>Create a running container on the given Docker engine. This container will contain the Selenium runtime, and ideally a browser instance to connect with. Args: **kwargs (dict): the specification of the docker container. Returns: :class:`~docker.models.containers.Container`<|endoftext|>
1a0adbc8123863e6cab2694f66f95e00f24fa0bcc81f5c1df645a0c08bd64e33
def _perform_check_container_ready(self): " Checks if the container is ready to use by calling a separate\n function. This function ``check_container_ready`` must manage its\n own retry logic if the check is to be performed more than once or over\n a span of time.\n\n Raises:\n :exc:`~docker.errors.DockerException`: when the container's\n creation and state cannot be verified.\n\n Returns:\n bool:\n ``True`` when ``check_container_ready()`` returns ``True``.\n " self.logger.debug('waiting for selenium to initialize') is_ready = self.check_container_ready() if (not is_ready): raise DockerException('could not verify container was ready') self.logger.debug('container created successfully') return is_ready
Checks if the container is ready to use by calling a separate function. This function ``check_container_ready`` must manage its own retry logic if the check is to be performed more than once or over a span of time. Raises: :exc:`~docker.errors.DockerException`: when the container's creation and state cannot be verified. Returns: bool: ``True`` when ``check_container_ready()`` returns ``True``.
selenium_docker/drivers/__init__.py
_perform_check_container_ready
vivint/selenium-docker
4
python
def _perform_check_container_ready(self): " Checks if the container is ready to use by calling a separate\n function. This function ``check_container_ready`` must manage its\n own retry logic if the check is to be performed more than once or over\n a span of time.\n\n Raises:\n :exc:`~docker.errors.DockerException`: when the container's\n creation and state cannot be verified.\n\n Returns:\n bool:\n ``True`` when ``check_container_ready()`` returns ``True``.\n " self.logger.debug('waiting for selenium to initialize') is_ready = self.check_container_ready() if (not is_ready): raise DockerException('could not verify container was ready') self.logger.debug('container created successfully') return is_ready
def _perform_check_container_ready(self): " Checks if the container is ready to use by calling a separate\n function. This function ``check_container_ready`` must manage its\n own retry logic if the check is to be performed more than once or over\n a span of time.\n\n Raises:\n :exc:`~docker.errors.DockerException`: when the container's\n creation and state cannot be verified.\n\n Returns:\n bool:\n ``True`` when ``check_container_ready()`` returns ``True``.\n " self.logger.debug('waiting for selenium to initialize') is_ready = self.check_container_ready() if (not is_ready): raise DockerException('could not verify container was ready') self.logger.debug('container created successfully') return is_ready<|docstring|>Checks if the container is ready to use by calling a separate function. This function ``check_container_ready`` must manage its own retry logic if the check is to be performed more than once or over a span of time. Raises: :exc:`~docker.errors.DockerException`: when the container's creation and state cannot be verified. Returns: bool: ``True`` when ``check_container_ready()`` returns ``True``.<|endoftext|>
5b0cb7a4049f99d0076231c44034eb1cecd495ae6a69de1f58ea91b7e5bb6f0d
@retry(wait=wait_fixed(0.5), stop=stop_after_delay(10)) def check_container_ready(self): ' Function that continuously checks if a container is ready.\n\n Note:\n This function should be wrapped in a `tenacity.retry` for\n continuously checking the status without failing.\n\n Raises:\n requests.RequestException: for any `requests` related exception.\n\n Returns:\n bool:\n ``True`` when the status is good. ``False`` if it cannot\n be verified or is in an unusable state.\n ' self.logger.debug('checking selenium status') resp = requests.get(self._base_url, timeout=(1.0, 1.0)) resp.raise_for_status() return (resp.status_code == requests.codes.ok)
Function that continuously checks if a container is ready. Note: This function should be wrapped in a `tenacity.retry` for continuously checking the status without failing. Raises: requests.RequestException: for any `requests` related exception. Returns: bool: ``True`` when the status is good. ``False`` if it cannot be verified or is in an unusable state.
selenium_docker/drivers/__init__.py
check_container_ready
vivint/selenium-docker
4
python
@retry(wait=wait_fixed(0.5), stop=stop_after_delay(10)) def check_container_ready(self): ' Function that continuously checks if a container is ready.\n\n Note:\n This function should be wrapped in a `tenacity.retry` for\n continuously checking the status without failing.\n\n Raises:\n requests.RequestException: for any `requests` related exception.\n\n Returns:\n bool:\n ``True`` when the status is good. ``False`` if it cannot\n be verified or is in an unusable state.\n ' self.logger.debug('checking selenium status') resp = requests.get(self._base_url, timeout=(1.0, 1.0)) resp.raise_for_status() return (resp.status_code == requests.codes.ok)
@retry(wait=wait_fixed(0.5), stop=stop_after_delay(10)) def check_container_ready(self): ' Function that continuously checks if a container is ready.\n\n Note:\n This function should be wrapped in a `tenacity.retry` for\n continuously checking the status without failing.\n\n Raises:\n requests.RequestException: for any `requests` related exception.\n\n Returns:\n bool:\n ``True`` when the status is good. ``False`` if it cannot\n be verified or is in an unusable state.\n ' self.logger.debug('checking selenium status') resp = requests.get(self._base_url, timeout=(1.0, 1.0)) resp.raise_for_status() return (resp.status_code == requests.codes.ok)<|docstring|>Function that continuously checks if a container is ready. Note: This function should be wrapped in a `tenacity.retry` for continuously checking the status without failing. Raises: requests.RequestException: for any `requests` related exception. Returns: bool: ``True`` when the status is good. ``False`` if it cannot be verified or is in an unusable state.<|endoftext|>
c0150ef5ecb60c9ca8f6a5b548dcbdc26bb658476e1cbdb651b6c384ef957079
def close_container(self): ' Removes the running container from the connected engine via\n :obj:`.DockerDriverBase.factory`.\n\n Returns:\n None\n ' if (not self.container): self.logger.warning('no container to stop') return self.logger.debug('closing and removing container') self.factory.stop_container(name=self.name) self.container = None
Removes the running container from the connected engine via :obj:`.DockerDriverBase.factory`. Returns: None
selenium_docker/drivers/__init__.py
close_container
vivint/selenium-docker
4
python
def close_container(self): ' Removes the running container from the connected engine via\n :obj:`.DockerDriverBase.factory`.\n\n Returns:\n None\n ' if (not self.container): self.logger.warning('no container to stop') return self.logger.debug('closing and removing container') self.factory.stop_container(name=self.name) self.container = None
def close_container(self): ' Removes the running container from the connected engine via\n :obj:`.DockerDriverBase.factory`.\n\n Returns:\n None\n ' if (not self.container): self.logger.warning('no container to stop') return self.logger.debug('closing and removing container') self.factory.stop_container(name=self.name) self.container = None<|docstring|>Removes the running container from the connected engine via :obj:`.DockerDriverBase.factory`. Returns: None<|endoftext|>
3abc4906742d4ddbd7470f0924ac9a82e52bf9ff5c3c9e8f45958d31e9a086fb
def f(self, flag): " Helper function for checking if we included a flag.\n\n Args:\n flag (:obj:`aenum.Flag`): instance of ``Flag``.\n\n Returns:\n bool: logical AND on an individual flag and a bit-flag set.\n\n Example::\n\n from selenium_docker.drivers.chrome import ChromeDriver, Flags\n\n driver = ChromeDriver(flags=Flags.ALL)\n driver.get('https://python.org')\n\n if driver.f(Flags.X_IMG): # no images allowed\n # do something\n pass\n\n driver.quit()\n " return (flag & self.flags)
Helper function for checking if we included a flag. Args: flag (:obj:`aenum.Flag`): instance of ``Flag``. Returns: bool: logical AND on an individual flag and a bit-flag set. Example:: from selenium_docker.drivers.chrome import ChromeDriver, Flags driver = ChromeDriver(flags=Flags.ALL) driver.get('https://python.org') if driver.f(Flags.X_IMG): # no images allowed # do something pass driver.quit()
selenium_docker/drivers/__init__.py
f
vivint/selenium-docker
4
python
def f(self, flag): " Helper function for checking if we included a flag.\n\n Args:\n flag (:obj:`aenum.Flag`): instance of ``Flag``.\n\n Returns:\n bool: logical AND on an individual flag and a bit-flag set.\n\n Example::\n\n from selenium_docker.drivers.chrome import ChromeDriver, Flags\n\n driver = ChromeDriver(flags=Flags.ALL)\n driver.get('https://python.org')\n\n if driver.f(Flags.X_IMG): # no images allowed\n # do something\n pass\n\n driver.quit()\n " return (flag & self.flags)
def f(self, flag): " Helper function for checking if we included a flag.\n\n Args:\n flag (:obj:`aenum.Flag`): instance of ``Flag``.\n\n Returns:\n bool: logical AND on an individual flag and a bit-flag set.\n\n Example::\n\n from selenium_docker.drivers.chrome import ChromeDriver, Flags\n\n driver = ChromeDriver(flags=Flags.ALL)\n driver.get('https://python.org')\n\n if driver.f(Flags.X_IMG): # no images allowed\n # do something\n pass\n\n driver.quit()\n " return (flag & self.flags)<|docstring|>Helper function for checking if we included a flag. Args: flag (:obj:`aenum.Flag`): instance of ``Flag``. Returns: bool: logical AND on an individual flag and a bit-flag set. Example:: from selenium_docker.drivers.chrome import ChromeDriver, Flags driver = ChromeDriver(flags=Flags.ALL) driver.get('https://python.org') if driver.f(Flags.X_IMG): # no images allowed # do something pass driver.quit()<|endoftext|>
850d46529ffd51427d909332e4d2f0adc1282375670de3fc36d1f432793cfffa
def get_url(self): ' Extract the hostname and port from a running docker container,\n return it as a URL-string we can connect to.\n\n References:\n :func:`selenium_docker.utils.ip_port`\n\n Returns:\n str\n ' (host, port) = ip_port(self.container, self.SELENIUM_PORT) base_url = self.BASE_URL.format(host=host, port=port) return base_url
Extract the hostname and port from a running docker container, return it as a URL-string we can connect to. References: :func:`selenium_docker.utils.ip_port` Returns: str
selenium_docker/drivers/__init__.py
get_url
vivint/selenium-docker
4
python
def get_url(self): ' Extract the hostname and port from a running docker container,\n return it as a URL-string we can connect to.\n\n References:\n :func:`selenium_docker.utils.ip_port`\n\n Returns:\n str\n ' (host, port) = ip_port(self.container, self.SELENIUM_PORT) base_url = self.BASE_URL.format(host=host, port=port) return base_url
def get_url(self): ' Extract the hostname and port from a running docker container,\n return it as a URL-string we can connect to.\n\n References:\n :func:`selenium_docker.utils.ip_port`\n\n Returns:\n str\n ' (host, port) = ip_port(self.container, self.SELENIUM_PORT) base_url = self.BASE_URL.format(host=host, port=port) return base_url<|docstring|>Extract the hostname and port from a running docker container, return it as a URL-string we can connect to. References: :func:`selenium_docker.utils.ip_port` Returns: str<|endoftext|>
6aa62205e62bcb5ed79a5113355eaaf13a7a49b917904f8a988c4f2a061add71
def quit(self): ' Alias for :func:`DockerDriverBase.close_container`.\n\n Generally this is called in a Selenium tests when you want to\n completely close and quit the active browser.\n\n Returns:\n None\n ' self.logger.debug('browser quit') self.close_container()
Alias for :func:`DockerDriverBase.close_container`. Generally this is called in a Selenium tests when you want to completely close and quit the active browser. Returns: None
selenium_docker/drivers/__init__.py
quit
vivint/selenium-docker
4
python
def quit(self): ' Alias for :func:`DockerDriverBase.close_container`.\n\n Generally this is called in a Selenium tests when you want to\n completely close and quit the active browser.\n\n Returns:\n None\n ' self.logger.debug('browser quit') self.close_container()
def quit(self): ' Alias for :func:`DockerDriverBase.close_container`.\n\n Generally this is called in a Selenium tests when you want to\n completely close and quit the active browser.\n\n Returns:\n None\n ' self.logger.debug('browser quit') self.close_container()<|docstring|>Alias for :func:`DockerDriverBase.close_container`. Generally this is called in a Selenium tests when you want to completely close and quit the active browser. Returns: None<|endoftext|>
df0a567306b0b9ea5267b3dd888386b7fc567f72ae1099d63d84f5beb0f6bea7
@property def filename(self): 'str: filename to apply to the extracted video stream.\n\n The filename will be formatted, ``<BROWSER>-docker-<TIMESTAMP>.mkv``.\n ' return ('%s-docker-%s.mkv' % (self.BROWSER, self._time)).lower()
str: filename to apply to the extracted video stream. The filename will be formatted, ``<BROWSER>-docker-<TIMESTAMP>.mkv``.
selenium_docker/drivers/__init__.py
filename
vivint/selenium-docker
4
python
@property def filename(self): 'str: filename to apply to the extracted video stream.\n\n The filename will be formatted, ``<BROWSER>-docker-<TIMESTAMP>.mkv``.\n ' return ('%s-docker-%s.mkv' % (self.BROWSER, self._time)).lower()
@property def filename(self): 'str: filename to apply to the extracted video stream.\n\n The filename will be formatted, ``<BROWSER>-docker-<TIMESTAMP>.mkv``.\n ' return ('%s-docker-%s.mkv' % (self.BROWSER, self._time)).lower()<|docstring|>str: filename to apply to the extracted video stream. The filename will be formatted, ``<BROWSER>-docker-<TIMESTAMP>.mkv``.<|endoftext|>
ef921d57684bc8e345fea5dd40d0f9309dde57263405fcf1c246d7cd3704276e
@property def is_recording(self): 'bool: the container is recording video right now.' return self.__is_recording
bool: the container is recording video right now.
selenium_docker/drivers/__init__.py
is_recording
vivint/selenium-docker
4
python
@property def is_recording(self): return self.__is_recording
@property def is_recording(self): return self.__is_recording<|docstring|>bool: the container is recording video right now.<|endoftext|>
cf72f933273a5394564408a8e5faa73a06afcf7dd05ec36ad5a1d3fe736d1e60
def quit(self): ' Stop video recording before closing the driver instance and\n removing the Docker container.\n\n Returns:\n None\n ' if self.__is_recording: self.stop_recording(self.save_path) super(VideoDriver, self).quit()
Stop video recording before closing the driver instance and removing the Docker container. Returns: None
selenium_docker/drivers/__init__.py
quit
vivint/selenium-docker
4
python
def quit(self): ' Stop video recording before closing the driver instance and\n removing the Docker container.\n\n Returns:\n None\n ' if self.__is_recording: self.stop_recording(self.save_path) super(VideoDriver, self).quit()
def quit(self): ' Stop video recording before closing the driver instance and\n removing the Docker container.\n\n Returns:\n None\n ' if self.__is_recording: self.stop_recording(self.save_path) super(VideoDriver, self).quit()<|docstring|>Stop video recording before closing the driver instance and removing the Docker container. Returns: None<|endoftext|>
38f246f1a47d8f99bca2d3063e549f885b7c0ac5567fe64294b38f7ed93f49aa
@check_engine def start_recording(self, metadata=None, environment=None): ' Starts the ffmpeg video recording inside the container.\n\n Args:\n metadata (dict): arbitrary data to attach to the video file.\n environment (dict): environment variables to inject inside the\n running container before launching ffmpeg.\n\n Returns:\n str:\n the absolute file path of the file being recorded, inside the\n Docker container.\n ' if self.__is_recording: raise RuntimeError('already recording, cannot start recording again') if (not metadata): metadata = {} self.__is_recording = True for (s, v) in [('title', self.filename), ('language', 'English'), ('encoded_by', 'docker+ffmpeg'), ('description', getattr(self, 'DESCRIPTION', config.ffmpeg_description))]: metadata.setdefault(s, v) cmd = self.commands.start_ffmpeg.format(resolution=config.ffmpeg_resolution, fps=config.ffmpeg_fps, metadata=parse_metadata(metadata), filename=self.__recording_path) self.logger.debug('starting recording to file %s', self.__recording_path) self.logger.debug('cmd: %s', cmd) self.container.exec_run(cmd, environment=environment, detach=True) return self.__recording_path
Starts the ffmpeg video recording inside the container. Args: metadata (dict): arbitrary data to attach to the video file. environment (dict): environment variables to inject inside the running container before launching ffmpeg. Returns: str: the absolute file path of the file being recorded, inside the Docker container.
selenium_docker/drivers/__init__.py
start_recording
vivint/selenium-docker
4
python
@check_engine def start_recording(self, metadata=None, environment=None): ' Starts the ffmpeg video recording inside the container.\n\n Args:\n metadata (dict): arbitrary data to attach to the video file.\n environment (dict): environment variables to inject inside the\n running container before launching ffmpeg.\n\n Returns:\n str:\n the absolute file path of the file being recorded, inside the\n Docker container.\n ' if self.__is_recording: raise RuntimeError('already recording, cannot start recording again') if (not metadata): metadata = {} self.__is_recording = True for (s, v) in [('title', self.filename), ('language', 'English'), ('encoded_by', 'docker+ffmpeg'), ('description', getattr(self, 'DESCRIPTION', config.ffmpeg_description))]: metadata.setdefault(s, v) cmd = self.commands.start_ffmpeg.format(resolution=config.ffmpeg_resolution, fps=config.ffmpeg_fps, metadata=parse_metadata(metadata), filename=self.__recording_path) self.logger.debug('starting recording to file %s', self.__recording_path) self.logger.debug('cmd: %s', cmd) self.container.exec_run(cmd, environment=environment, detach=True) return self.__recording_path
@check_engine def start_recording(self, metadata=None, environment=None): ' Starts the ffmpeg video recording inside the container.\n\n Args:\n metadata (dict): arbitrary data to attach to the video file.\n environment (dict): environment variables to inject inside the\n running container before launching ffmpeg.\n\n Returns:\n str:\n the absolute file path of the file being recorded, inside the\n Docker container.\n ' if self.__is_recording: raise RuntimeError('already recording, cannot start recording again') if (not metadata): metadata = {} self.__is_recording = True for (s, v) in [('title', self.filename), ('language', 'English'), ('encoded_by', 'docker+ffmpeg'), ('description', getattr(self, 'DESCRIPTION', config.ffmpeg_description))]: metadata.setdefault(s, v) cmd = self.commands.start_ffmpeg.format(resolution=config.ffmpeg_resolution, fps=config.ffmpeg_fps, metadata=parse_metadata(metadata), filename=self.__recording_path) self.logger.debug('starting recording to file %s', self.__recording_path) self.logger.debug('cmd: %s', cmd) self.container.exec_run(cmd, environment=environment, detach=True) return self.__recording_path<|docstring|>Starts the ffmpeg video recording inside the container. Args: metadata (dict): arbitrary data to attach to the video file. environment (dict): environment variables to inject inside the running container before launching ffmpeg. Returns: str: the absolute file path of the file being recorded, inside the Docker container.<|endoftext|>
fd994201f805fa11f8d215338e4d9f54e8310126214c7fa20f2c95a7b2f418f6
@check_engine def stop_recording(self, path, shard_by_date=True, environment=None): " Stops the ffmpeg video recording inside the container.\n\n Args:\n path (str): local directory where the video file should be stored.\n shard_by_date (bool): when ``True`` video files will be placed\n in a folder structure under ``path`` in the format of\n ``YYYY/MM/DD/<files>``.\n environment (dict): environment variables to inject inside the\n container before executing the commands to stop recording.\n\n Raises:\n ValueError: when ``path`` is not an existing folder path.\n IOError: when there's a problem creating the folder for video\n recorded files.\n\n Returns:\n str:\n file path to completed recording. This value is adjusted\n for ``shard_by_date``.\n " if (not self.__is_recording): raise RuntimeError('cannot stop recording, recording not in progress') self.container.exec_run(self.commands.stop_ffmpeg, environment=environment, detach=False) if (not os.path.isdir(path)): raise ValueError(('%s is not a directory' % path)) if shard_by_date: ts = datetime.fromtimestamp(self._time) path = os.path.join(path, str(ts.year), str(ts.month), str(ts.day)) if (not os.path.exists(path)): try: os.makedirs(path) except IOError as e: self.logger.exception(e, exc_info=True) raise e source = self.__recording_path destination = os.path.join(path, self.filename) tar_dest = ('%s.tar' % destination) (stream, stat) = self.container.get_archive(source) self.logger.debug('video stats, name:%s, size:%s', stat['name'], stat['size']) with open(tar_dest, 'wb') as out_file: out_file.write(stream.data) if (not tarfile.is_tarfile(tar_dest)): raise RuntimeError(('invalid tar file from container %s' % tar_dest)) self.logger.debug('extracting tar archive') tar = tarfile.open(name=tar_dest) tar.extractall(path) os.unlink(tar_dest) self.__is_recording = False self._time = int(time.time()) return destination
Stops the ffmpeg video recording inside the container. Args: path (str): local directory where the video file should be stored. shard_by_date (bool): when ``True`` video files will be placed in a folder structure under ``path`` in the format of ``YYYY/MM/DD/<files>``. environment (dict): environment variables to inject inside the container before executing the commands to stop recording. Raises: ValueError: when ``path`` is not an existing folder path. IOError: when there's a problem creating the folder for video recorded files. Returns: str: file path to completed recording. This value is adjusted for ``shard_by_date``.
selenium_docker/drivers/__init__.py
stop_recording
vivint/selenium-docker
4
python
@check_engine def stop_recording(self, path, shard_by_date=True, environment=None): " Stops the ffmpeg video recording inside the container.\n\n Args:\n path (str): local directory where the video file should be stored.\n shard_by_date (bool): when ``True`` video files will be placed\n in a folder structure under ``path`` in the format of\n ``YYYY/MM/DD/<files>``.\n environment (dict): environment variables to inject inside the\n container before executing the commands to stop recording.\n\n Raises:\n ValueError: when ``path`` is not an existing folder path.\n IOError: when there's a problem creating the folder for video\n recorded files.\n\n Returns:\n str:\n file path to completed recording. This value is adjusted\n for ``shard_by_date``.\n " if (not self.__is_recording): raise RuntimeError('cannot stop recording, recording not in progress') self.container.exec_run(self.commands.stop_ffmpeg, environment=environment, detach=False) if (not os.path.isdir(path)): raise ValueError(('%s is not a directory' % path)) if shard_by_date: ts = datetime.fromtimestamp(self._time) path = os.path.join(path, str(ts.year), str(ts.month), str(ts.day)) if (not os.path.exists(path)): try: os.makedirs(path) except IOError as e: self.logger.exception(e, exc_info=True) raise e source = self.__recording_path destination = os.path.join(path, self.filename) tar_dest = ('%s.tar' % destination) (stream, stat) = self.container.get_archive(source) self.logger.debug('video stats, name:%s, size:%s', stat['name'], stat['size']) with open(tar_dest, 'wb') as out_file: out_file.write(stream.data) if (not tarfile.is_tarfile(tar_dest)): raise RuntimeError(('invalid tar file from container %s' % tar_dest)) self.logger.debug('extracting tar archive') tar = tarfile.open(name=tar_dest) tar.extractall(path) os.unlink(tar_dest) self.__is_recording = False self._time = int(time.time()) return destination
@check_engine def stop_recording(self, path, shard_by_date=True, environment=None): " Stops the ffmpeg video recording inside the container.\n\n Args:\n path (str): local directory where the video file should be stored.\n shard_by_date (bool): when ``True`` video files will be placed\n in a folder structure under ``path`` in the format of\n ``YYYY/MM/DD/<files>``.\n environment (dict): environment variables to inject inside the\n container before executing the commands to stop recording.\n\n Raises:\n ValueError: when ``path`` is not an existing folder path.\n IOError: when there's a problem creating the folder for video\n recorded files.\n\n Returns:\n str:\n file path to completed recording. This value is adjusted\n for ``shard_by_date``.\n " if (not self.__is_recording): raise RuntimeError('cannot stop recording, recording not in progress') self.container.exec_run(self.commands.stop_ffmpeg, environment=environment, detach=False) if (not os.path.isdir(path)): raise ValueError(('%s is not a directory' % path)) if shard_by_date: ts = datetime.fromtimestamp(self._time) path = os.path.join(path, str(ts.year), str(ts.month), str(ts.day)) if (not os.path.exists(path)): try: os.makedirs(path) except IOError as e: self.logger.exception(e, exc_info=True) raise e source = self.__recording_path destination = os.path.join(path, self.filename) tar_dest = ('%s.tar' % destination) (stream, stat) = self.container.get_archive(source) self.logger.debug('video stats, name:%s, size:%s', stat['name'], stat['size']) with open(tar_dest, 'wb') as out_file: out_file.write(stream.data) if (not tarfile.is_tarfile(tar_dest)): raise RuntimeError(('invalid tar file from container %s' % tar_dest)) self.logger.debug('extracting tar archive') tar = tarfile.open(name=tar_dest) tar.extractall(path) os.unlink(tar_dest) self.__is_recording = False self._time = int(time.time()) return destination<|docstring|>Stops the ffmpeg video recording inside the container. Args: path (str): local directory where the video file should be stored. shard_by_date (bool): when ``True`` video files will be placed in a folder structure under ``path`` in the format of ``YYYY/MM/DD/<files>``. environment (dict): environment variables to inject inside the container before executing the commands to stop recording. Raises: ValueError: when ``path`` is not an existing folder path. IOError: when there's a problem creating the folder for video recorded files. Returns: str: file path to completed recording. This value is adjusted for ``shard_by_date``.<|endoftext|>
9f900480f4abfd1a9188a5e994e38e59bda6c0bdd6cd3f30dfc0eca0ed167078
def accuracy(output, target, topk=(1,)): 'Computes the accuracy over the k top predictions for the specified values of k' with torch.no_grad(): maxk = max(topk) batch_size = target.size(0) (_, pred) = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, (- 1)).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].reshape((- 1)).float().sum(0, keepdim=True) res.append(correct_k.mul_((100.0 / batch_size))) return res
Computes the accuracy over the k top predictions for the specified values of k
test_models.py
accuracy
ombretta/bag-of-local-features-models
0
python
def accuracy(output, target, topk=(1,)): with torch.no_grad(): maxk = max(topk) batch_size = target.size(0) (_, pred) = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, (- 1)).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].reshape((- 1)).float().sum(0, keepdim=True) res.append(correct_k.mul_((100.0 / batch_size))) return res
def accuracy(output, target, topk=(1,)): with torch.no_grad(): maxk = max(topk) batch_size = target.size(0) (_, pred) = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, (- 1)).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].reshape((- 1)).float().sum(0, keepdim=True) res.append(correct_k.mul_((100.0 / batch_size))) return res<|docstring|>Computes the accuracy over the k top predictions for the specified values of k<|endoftext|>
da2c5e40af19e3b2bcf5e9ceec2e93b5983bc91a3ee0333b3638d1776b7d3187
def test_get_zone_normal(self): '\n Test if it get current timezone (i.e. Asia/Calcutta)\n ' mock_read_ok = MagicMock(return_value={'pid': 78, 'retcode': 0, 'stderr': '', 'stdout': 'India Standard Time'}) with patch.dict(win_timezone.__salt__, {'cmd.run_all': mock_read_ok}): self.assertEqual(win_timezone.get_zone(), 'Asia/Calcutta')
Test if it get current timezone (i.e. Asia/Calcutta)
tests/unit/modules/test_win_timezone.py
test_get_zone_normal
sys4/salt
19
python
def test_get_zone_normal(self): '\n \n ' mock_read_ok = MagicMock(return_value={'pid': 78, 'retcode': 0, 'stderr': , 'stdout': 'India Standard Time'}) with patch.dict(win_timezone.__salt__, {'cmd.run_all': mock_read_ok}): self.assertEqual(win_timezone.get_zone(), 'Asia/Calcutta')
def test_get_zone_normal(self): '\n \n ' mock_read_ok = MagicMock(return_value={'pid': 78, 'retcode': 0, 'stderr': , 'stdout': 'India Standard Time'}) with patch.dict(win_timezone.__salt__, {'cmd.run_all': mock_read_ok}): self.assertEqual(win_timezone.get_zone(), 'Asia/Calcutta')<|docstring|>Test if it get current timezone (i.e. Asia/Calcutta)<|endoftext|>
ff7ca8a6b5714e6da26acde50c5419206f6893754c87344140688858e8795293
def test_get_zone_unknown(self): '\n Test get_zone with unknown timezone (i.e. Indian Standard Time)\n ' mock_read_error = MagicMock(return_value={'pid': 78, 'retcode': 0, 'stderr': '', 'stdout': 'Indian Standard Time'}) with patch.dict(win_timezone.__salt__, {'cmd.run_all': mock_read_error}): self.assertEqual(win_timezone.get_zone(), 'Unknown')
Test get_zone with unknown timezone (i.e. Indian Standard Time)
tests/unit/modules/test_win_timezone.py
test_get_zone_unknown
sys4/salt
19
python
def test_get_zone_unknown(self): '\n \n ' mock_read_error = MagicMock(return_value={'pid': 78, 'retcode': 0, 'stderr': , 'stdout': 'Indian Standard Time'}) with patch.dict(win_timezone.__salt__, {'cmd.run_all': mock_read_error}): self.assertEqual(win_timezone.get_zone(), 'Unknown')
def test_get_zone_unknown(self): '\n \n ' mock_read_error = MagicMock(return_value={'pid': 78, 'retcode': 0, 'stderr': , 'stdout': 'Indian Standard Time'}) with patch.dict(win_timezone.__salt__, {'cmd.run_all': mock_read_error}): self.assertEqual(win_timezone.get_zone(), 'Unknown')<|docstring|>Test get_zone with unknown timezone (i.e. Indian Standard Time)<|endoftext|>
60a572a47b331f85b3d05fdb3b4e92dc87964355e973c99b2db820d36ae99af2
def test_get_zone_error(self): '\n Test get_zone when it encounters an error\n ' mock_read_fatal = MagicMock(return_value={'pid': 78, 'retcode': 1, 'stderr': '', 'stdout': ''}) with patch.dict(win_timezone.__salt__, {'cmd.run_all': mock_read_fatal}): self.assertRaises(CommandExecutionError, win_timezone.get_zone)
Test get_zone when it encounters an error
tests/unit/modules/test_win_timezone.py
test_get_zone_error
sys4/salt
19
python
def test_get_zone_error(self): '\n \n ' mock_read_fatal = MagicMock(return_value={'pid': 78, 'retcode': 1, 'stderr': , 'stdout': }) with patch.dict(win_timezone.__salt__, {'cmd.run_all': mock_read_fatal}): self.assertRaises(CommandExecutionError, win_timezone.get_zone)
def test_get_zone_error(self): '\n \n ' mock_read_fatal = MagicMock(return_value={'pid': 78, 'retcode': 1, 'stderr': , 'stdout': }) with patch.dict(win_timezone.__salt__, {'cmd.run_all': mock_read_fatal}): self.assertRaises(CommandExecutionError, win_timezone.get_zone)<|docstring|>Test get_zone when it encounters an error<|endoftext|>
d1557ec1c1c2394430056f151307eccc640a1f1c52d6cbbe8b298a2db5fdb156
def test_get_offset(self): '\n Test if it get current numeric timezone offset from UCT (i.e. +0530)\n ' mock_read = MagicMock(return_value={'pid': 78, 'retcode': 0, 'stderr': '', 'stdout': 'India Standard Time'}) with patch.dict(win_timezone.__salt__, {'cmd.run_all': mock_read}): self.assertEqual(win_timezone.get_offset(), '+0530')
Test if it get current numeric timezone offset from UCT (i.e. +0530)
tests/unit/modules/test_win_timezone.py
test_get_offset
sys4/salt
19
python
def test_get_offset(self): '\n \n ' mock_read = MagicMock(return_value={'pid': 78, 'retcode': 0, 'stderr': , 'stdout': 'India Standard Time'}) with patch.dict(win_timezone.__salt__, {'cmd.run_all': mock_read}): self.assertEqual(win_timezone.get_offset(), '+0530')
def test_get_offset(self): '\n \n ' mock_read = MagicMock(return_value={'pid': 78, 'retcode': 0, 'stderr': , 'stdout': 'India Standard Time'}) with patch.dict(win_timezone.__salt__, {'cmd.run_all': mock_read}): self.assertEqual(win_timezone.get_offset(), '+0530')<|docstring|>Test if it get current numeric timezone offset from UCT (i.e. +0530)<|endoftext|>
159ca2c2628d18c03c3f6d311d3314c880837a7c12b487fecf7d9435eefe8f21
def test_get_zonecode(self): '\n Test if it get current timezone (i.e. PST, MDT, etc)\n ' mock_read = MagicMock(return_value={'pid': 78, 'retcode': 0, 'stderr': '', 'stdout': 'India Standard Time'}) with patch.dict(win_timezone.__salt__, {'cmd.run_all': mock_read}): self.assertEqual(win_timezone.get_zonecode(), 'IST')
Test if it get current timezone (i.e. PST, MDT, etc)
tests/unit/modules/test_win_timezone.py
test_get_zonecode
sys4/salt
19
python
def test_get_zonecode(self): '\n \n ' mock_read = MagicMock(return_value={'pid': 78, 'retcode': 0, 'stderr': , 'stdout': 'India Standard Time'}) with patch.dict(win_timezone.__salt__, {'cmd.run_all': mock_read}): self.assertEqual(win_timezone.get_zonecode(), 'IST')
def test_get_zonecode(self): '\n \n ' mock_read = MagicMock(return_value={'pid': 78, 'retcode': 0, 'stderr': , 'stdout': 'India Standard Time'}) with patch.dict(win_timezone.__salt__, {'cmd.run_all': mock_read}): self.assertEqual(win_timezone.get_zonecode(), 'IST')<|docstring|>Test if it get current timezone (i.e. PST, MDT, etc)<|endoftext|>
425fe0a1250b37b4455ffdde49f43b40510100df4902dbf5407b587822f9c953
def test_set_zone(self): '\n Test if it unlinks, then symlinks /etc/localtime to the set timezone.\n ' mock_write = MagicMock(return_value={'pid': 78, 'retcode': 0, 'stderr': '', 'stdout': ''}) mock_read = MagicMock(return_value={'pid': 78, 'retcode': 0, 'stderr': '', 'stdout': 'India Standard Time'}) with patch.dict(win_timezone.__salt__, {'cmd.run_all': mock_write}), patch.dict(win_timezone.__salt__, {'cmd.run_all': mock_read}): self.assertTrue(win_timezone.set_zone('Asia/Calcutta'))
Test if it unlinks, then symlinks /etc/localtime to the set timezone.
tests/unit/modules/test_win_timezone.py
test_set_zone
sys4/salt
19
python
def test_set_zone(self): '\n \n ' mock_write = MagicMock(return_value={'pid': 78, 'retcode': 0, 'stderr': , 'stdout': }) mock_read = MagicMock(return_value={'pid': 78, 'retcode': 0, 'stderr': , 'stdout': 'India Standard Time'}) with patch.dict(win_timezone.__salt__, {'cmd.run_all': mock_write}), patch.dict(win_timezone.__salt__, {'cmd.run_all': mock_read}): self.assertTrue(win_timezone.set_zone('Asia/Calcutta'))
def test_set_zone(self): '\n \n ' mock_write = MagicMock(return_value={'pid': 78, 'retcode': 0, 'stderr': , 'stdout': }) mock_read = MagicMock(return_value={'pid': 78, 'retcode': 0, 'stderr': , 'stdout': 'India Standard Time'}) with patch.dict(win_timezone.__salt__, {'cmd.run_all': mock_write}), patch.dict(win_timezone.__salt__, {'cmd.run_all': mock_read}): self.assertTrue(win_timezone.set_zone('Asia/Calcutta'))<|docstring|>Test if it unlinks, then symlinks /etc/localtime to the set timezone.<|endoftext|>
9f416f2f5541a05b17e86946987a721a495b6ad89ac1c421182ecc10bdc3c6c4
def test_zone_compare(self): '\n Test if it checks the md5sum between the given timezone, and\n the one set in /etc/localtime. Returns True if they match,\n and False if not. Mostly useful for running state checks.\n ' mock_read = MagicMock(return_value={'pid': 78, 'retcode': 0, 'stderr': '', 'stdout': 'India Standard Time'}) with patch.dict(win_timezone.__salt__, {'cmd.run_all': mock_read}): self.assertTrue(win_timezone.zone_compare('Asia/Calcutta'))
Test if it checks the md5sum between the given timezone, and the one set in /etc/localtime. Returns True if they match, and False if not. Mostly useful for running state checks.
tests/unit/modules/test_win_timezone.py
test_zone_compare
sys4/salt
19
python
def test_zone_compare(self): '\n Test if it checks the md5sum between the given timezone, and\n the one set in /etc/localtime. Returns True if they match,\n and False if not. Mostly useful for running state checks.\n ' mock_read = MagicMock(return_value={'pid': 78, 'retcode': 0, 'stderr': , 'stdout': 'India Standard Time'}) with patch.dict(win_timezone.__salt__, {'cmd.run_all': mock_read}): self.assertTrue(win_timezone.zone_compare('Asia/Calcutta'))
def test_zone_compare(self): '\n Test if it checks the md5sum between the given timezone, and\n the one set in /etc/localtime. Returns True if they match,\n and False if not. Mostly useful for running state checks.\n ' mock_read = MagicMock(return_value={'pid': 78, 'retcode': 0, 'stderr': , 'stdout': 'India Standard Time'}) with patch.dict(win_timezone.__salt__, {'cmd.run_all': mock_read}): self.assertTrue(win_timezone.zone_compare('Asia/Calcutta'))<|docstring|>Test if it checks the md5sum between the given timezone, and the one set in /etc/localtime. Returns True if they match, and False if not. Mostly useful for running state checks.<|endoftext|>
6e1d083d79a110072995781a41fc3279a5adc0b33e7982bfc7e56af484acf530
def test_get_hwclock(self): '\n Test if it get current hardware clock setting (UTC or localtime)\n ' self.assertEqual(win_timezone.get_hwclock(), 'localtime')
Test if it get current hardware clock setting (UTC or localtime)
tests/unit/modules/test_win_timezone.py
test_get_hwclock
sys4/salt
19
python
def test_get_hwclock(self): '\n \n ' self.assertEqual(win_timezone.get_hwclock(), 'localtime')
def test_get_hwclock(self): '\n \n ' self.assertEqual(win_timezone.get_hwclock(), 'localtime')<|docstring|>Test if it get current hardware clock setting (UTC or localtime)<|endoftext|>
0d95b7d3ad1de5bf7dac0d83bb261a8406a9949db7273594aab96b18661a164a
def test_set_hwclock(self): '\n Test if it sets the hardware clock to be either UTC or localtime\n ' self.assertFalse(win_timezone.set_hwclock('UTC'))
Test if it sets the hardware clock to be either UTC or localtime
tests/unit/modules/test_win_timezone.py
test_set_hwclock
sys4/salt
19
python
def test_set_hwclock(self): '\n \n ' self.assertFalse(win_timezone.set_hwclock('UTC'))
def test_set_hwclock(self): '\n \n ' self.assertFalse(win_timezone.set_hwclock('UTC'))<|docstring|>Test if it sets the hardware clock to be either UTC or localtime<|endoftext|>
2db2140d7036d21ce1d08911af616f08ece98caa4d3b15c479ebd573ff520a90
def __virtual__(): '\n Load only on Windows\n Requires PowerShell and the WebAdministration module\n ' if (not salt.utils.platform.is_windows()): return (False, 'Only available on Windows systems') powershell_info = __salt__['cmd.shell_info']('powershell', True) if (not powershell_info['installed']): return (False, 'PowerShell not available') if ('WebAdministration' not in powershell_info['modules']): return (False, 'IIS is not installed') return __virtualname__
Load only on Windows Requires PowerShell and the WebAdministration module
salt/modules/win_iis.py
__virtual__
Flowdalic/salt
9,425
python
def __virtual__(): '\n Load only on Windows\n Requires PowerShell and the WebAdministration module\n ' if (not salt.utils.platform.is_windows()): return (False, 'Only available on Windows systems') powershell_info = __salt__['cmd.shell_info']('powershell', True) if (not powershell_info['installed']): return (False, 'PowerShell not available') if ('WebAdministration' not in powershell_info['modules']): return (False, 'IIS is not installed') return __virtualname__
def __virtual__(): '\n Load only on Windows\n Requires PowerShell and the WebAdministration module\n ' if (not salt.utils.platform.is_windows()): return (False, 'Only available on Windows systems') powershell_info = __salt__['cmd.shell_info']('powershell', True) if (not powershell_info['installed']): return (False, 'PowerShell not available') if ('WebAdministration' not in powershell_info['modules']): return (False, 'IIS is not installed') return __virtualname__<|docstring|>Load only on Windows Requires PowerShell and the WebAdministration module<|endoftext|>
9d5c51742d8cd4562cb7040de1b9171b4ff1d9318042677b93f62bc282c4a144
def _get_binding_info(host_header='', ip_address='*', port=80): '\n Combine the host header, IP address, and TCP port into bindingInformation\n format. Binding Information specifies information to communicate with a\n site. It includes the IP address, the port number, and an optional host\n header (usually a host name) to communicate with the site.\n\n Args:\n host_header (str): Usually a hostname\n ip_address (str): The IP address\n port (int): The port\n\n Returns:\n str: A properly formatted bindingInformation string (IP:port:hostheader)\n eg: 192.168.0.12:80:www.contoso.com\n ' return ':'.join([ip_address, str(port), host_header.replace(' ', '')])
Combine the host header, IP address, and TCP port into bindingInformation format. Binding Information specifies information to communicate with a site. It includes the IP address, the port number, and an optional host header (usually a host name) to communicate with the site. Args: host_header (str): Usually a hostname ip_address (str): The IP address port (int): The port Returns: str: A properly formatted bindingInformation string (IP:port:hostheader) eg: 192.168.0.12:80:www.contoso.com
salt/modules/win_iis.py
_get_binding_info
Flowdalic/salt
9,425
python
def _get_binding_info(host_header=, ip_address='*', port=80): '\n Combine the host header, IP address, and TCP port into bindingInformation\n format. Binding Information specifies information to communicate with a\n site. It includes the IP address, the port number, and an optional host\n header (usually a host name) to communicate with the site.\n\n Args:\n host_header (str): Usually a hostname\n ip_address (str): The IP address\n port (int): The port\n\n Returns:\n str: A properly formatted bindingInformation string (IP:port:hostheader)\n eg: 192.168.0.12:80:www.contoso.com\n ' return ':'.join([ip_address, str(port), host_header.replace(' ', )])
def _get_binding_info(host_header=, ip_address='*', port=80): '\n Combine the host header, IP address, and TCP port into bindingInformation\n format. Binding Information specifies information to communicate with a\n site. It includes the IP address, the port number, and an optional host\n header (usually a host name) to communicate with the site.\n\n Args:\n host_header (str): Usually a hostname\n ip_address (str): The IP address\n port (int): The port\n\n Returns:\n str: A properly formatted bindingInformation string (IP:port:hostheader)\n eg: 192.168.0.12:80:www.contoso.com\n ' return ':'.join([ip_address, str(port), host_header.replace(' ', )])<|docstring|>Combine the host header, IP address, and TCP port into bindingInformation format. Binding Information specifies information to communicate with a site. It includes the IP address, the port number, and an optional host header (usually a host name) to communicate with the site. Args: host_header (str): Usually a hostname ip_address (str): The IP address port (int): The port Returns: str: A properly formatted bindingInformation string (IP:port:hostheader) eg: 192.168.0.12:80:www.contoso.com<|endoftext|>
c478de4bc802b0539588ba0e5fec67f49bb50cb7291eb7e347a3ef967224f24b
def _list_certs(certificate_store='My'): '\n List details of available certificates in the LocalMachine certificate\n store.\n\n Args:\n certificate_store (str): The name of the certificate store on the local\n machine.\n\n Returns:\n dict: A dictionary of certificates found in the store\n ' ret = dict() blacklist_keys = ['DnsNameList', 'Thumbprint'] ps_cmd = ['Get-ChildItem', '-Path', "'Cert:\\LocalMachine\\{}'".format(certificate_store), '|', 'Select-Object DnsNameList, SerialNumber, Subject, Thumbprint, Version'] cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True) try: items = salt.utils.json.loads(cmd_ret['stdout'], strict=False) except ValueError: raise CommandExecutionError('Unable to parse return data as Json.') for item in items: cert_info = dict() for key in item: if (key not in blacklist_keys): cert_info[key.lower()] = item[key] cert_info['dnsnames'] = [] if item['DnsNameList']: cert_info['dnsnames'] = [name['Unicode'] for name in item['DnsNameList']] ret[item['Thumbprint']] = cert_info return ret
List details of available certificates in the LocalMachine certificate store. Args: certificate_store (str): The name of the certificate store on the local machine. Returns: dict: A dictionary of certificates found in the store
salt/modules/win_iis.py
_list_certs
Flowdalic/salt
9,425
python
def _list_certs(certificate_store='My'): '\n List details of available certificates in the LocalMachine certificate\n store.\n\n Args:\n certificate_store (str): The name of the certificate store on the local\n machine.\n\n Returns:\n dict: A dictionary of certificates found in the store\n ' ret = dict() blacklist_keys = ['DnsNameList', 'Thumbprint'] ps_cmd = ['Get-ChildItem', '-Path', "'Cert:\\LocalMachine\\{}'".format(certificate_store), '|', 'Select-Object DnsNameList, SerialNumber, Subject, Thumbprint, Version'] cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True) try: items = salt.utils.json.loads(cmd_ret['stdout'], strict=False) except ValueError: raise CommandExecutionError('Unable to parse return data as Json.') for item in items: cert_info = dict() for key in item: if (key not in blacklist_keys): cert_info[key.lower()] = item[key] cert_info['dnsnames'] = [] if item['DnsNameList']: cert_info['dnsnames'] = [name['Unicode'] for name in item['DnsNameList']] ret[item['Thumbprint']] = cert_info return ret
def _list_certs(certificate_store='My'): '\n List details of available certificates in the LocalMachine certificate\n store.\n\n Args:\n certificate_store (str): The name of the certificate store on the local\n machine.\n\n Returns:\n dict: A dictionary of certificates found in the store\n ' ret = dict() blacklist_keys = ['DnsNameList', 'Thumbprint'] ps_cmd = ['Get-ChildItem', '-Path', "'Cert:\\LocalMachine\\{}'".format(certificate_store), '|', 'Select-Object DnsNameList, SerialNumber, Subject, Thumbprint, Version'] cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True) try: items = salt.utils.json.loads(cmd_ret['stdout'], strict=False) except ValueError: raise CommandExecutionError('Unable to parse return data as Json.') for item in items: cert_info = dict() for key in item: if (key not in blacklist_keys): cert_info[key.lower()] = item[key] cert_info['dnsnames'] = [] if item['DnsNameList']: cert_info['dnsnames'] = [name['Unicode'] for name in item['DnsNameList']] ret[item['Thumbprint']] = cert_info return ret<|docstring|>List details of available certificates in the LocalMachine certificate store. Args: certificate_store (str): The name of the certificate store on the local machine. Returns: dict: A dictionary of certificates found in the store<|endoftext|>
90aff56e0b64415cb9f1b2ec04805393b1d30ada11b17e83bcde4e7d97731c6e
def _srvmgr(cmd, return_json=False): '\n Execute a powershell command from the WebAdministration PS module.\n\n Args:\n cmd (list): The command to execute in a list\n return_json (bool): True formats the return in JSON, False just returns\n the output of the command.\n\n Returns:\n str: The output from the command\n ' if isinstance(cmd, list): cmd = ' '.join(cmd) if return_json: cmd = 'ConvertTo-Json -Compress -Depth 4 -InputObject @({})'.format(cmd) cmd = 'Import-Module WebAdministration; {}'.format(cmd) ret = __salt__['cmd.run_all'](cmd, shell='powershell', python_shell=True) if (ret['retcode'] != 0): log.error('Unable to execute command: %s\nError: %s', cmd, ret['stderr']) return ret
Execute a powershell command from the WebAdministration PS module. Args: cmd (list): The command to execute in a list return_json (bool): True formats the return in JSON, False just returns the output of the command. Returns: str: The output from the command
salt/modules/win_iis.py
_srvmgr
Flowdalic/salt
9,425
python
def _srvmgr(cmd, return_json=False): '\n Execute a powershell command from the WebAdministration PS module.\n\n Args:\n cmd (list): The command to execute in a list\n return_json (bool): True formats the return in JSON, False just returns\n the output of the command.\n\n Returns:\n str: The output from the command\n ' if isinstance(cmd, list): cmd = ' '.join(cmd) if return_json: cmd = 'ConvertTo-Json -Compress -Depth 4 -InputObject @({})'.format(cmd) cmd = 'Import-Module WebAdministration; {}'.format(cmd) ret = __salt__['cmd.run_all'](cmd, shell='powershell', python_shell=True) if (ret['retcode'] != 0): log.error('Unable to execute command: %s\nError: %s', cmd, ret['stderr']) return ret
def _srvmgr(cmd, return_json=False): '\n Execute a powershell command from the WebAdministration PS module.\n\n Args:\n cmd (list): The command to execute in a list\n return_json (bool): True formats the return in JSON, False just returns\n the output of the command.\n\n Returns:\n str: The output from the command\n ' if isinstance(cmd, list): cmd = ' '.join(cmd) if return_json: cmd = 'ConvertTo-Json -Compress -Depth 4 -InputObject @({})'.format(cmd) cmd = 'Import-Module WebAdministration; {}'.format(cmd) ret = __salt__['cmd.run_all'](cmd, shell='powershell', python_shell=True) if (ret['retcode'] != 0): log.error('Unable to execute command: %s\nError: %s', cmd, ret['stderr']) return ret<|docstring|>Execute a powershell command from the WebAdministration PS module. Args: cmd (list): The command to execute in a list return_json (bool): True formats the return in JSON, False just returns the output of the command. Returns: str: The output from the command<|endoftext|>
c52e3f68e774f8549105c0a4d0387eea731c0e4c9c0c726127f0ad96f9083b55
def _collection_match_to_index(pspath, colfilter, name, match): '\n Returns index of collection item matching the match dictionary.\n ' collection = get_webconfiguration_settings(pspath, [{'name': name, 'filter': colfilter}])[0]['value'] for (idx, collect_dict) in enumerate(collection): if all(((item in collect_dict.items()) for item in match.items())): return idx return (- 1)
Returns index of collection item matching the match dictionary.
salt/modules/win_iis.py
_collection_match_to_index
Flowdalic/salt
9,425
python
def _collection_match_to_index(pspath, colfilter, name, match): '\n \n ' collection = get_webconfiguration_settings(pspath, [{'name': name, 'filter': colfilter}])[0]['value'] for (idx, collect_dict) in enumerate(collection): if all(((item in collect_dict.items()) for item in match.items())): return idx return (- 1)
def _collection_match_to_index(pspath, colfilter, name, match): '\n \n ' collection = get_webconfiguration_settings(pspath, [{'name': name, 'filter': colfilter}])[0]['value'] for (idx, collect_dict) in enumerate(collection): if all(((item in collect_dict.items()) for item in match.items())): return idx return (- 1)<|docstring|>Returns index of collection item matching the match dictionary.<|endoftext|>
d612e7073b60c3b726e58b6098b865c25edaf68df27434366a9b1b29fe972060
def _prepare_settings(pspath, settings): '\n Prepare settings before execution with get or set functions.\n Removes settings with a match parameter when index is not found.\n ' prepared_settings = [] for setting in settings: if (setting.get('name', None) is None): log.warning('win_iis: Setting has no name: %s', setting) continue if (setting.get('filter', None) is None): log.warning('win_iis: Setting has no filter: %s', setting) continue match = re.search('Collection\\[(\\{.*\\})\\]', setting['name']) if match: name = setting['name'][:(match.start(1) - 1)] match_dict = yaml.load(match.group(1)) index = _collection_match_to_index(pspath, setting['filter'], name, match_dict) if (index == (- 1)): log.warning('win_iis: No match found for setting: %s', setting) else: setting['name'] = setting['name'].replace(match.group(1), str(index)) prepared_settings.append(setting) else: prepared_settings.append(setting) return prepared_settings
Prepare settings before execution with get or set functions. Removes settings with a match parameter when index is not found.
salt/modules/win_iis.py
_prepare_settings
Flowdalic/salt
9,425
python
def _prepare_settings(pspath, settings): '\n Prepare settings before execution with get or set functions.\n Removes settings with a match parameter when index is not found.\n ' prepared_settings = [] for setting in settings: if (setting.get('name', None) is None): log.warning('win_iis: Setting has no name: %s', setting) continue if (setting.get('filter', None) is None): log.warning('win_iis: Setting has no filter: %s', setting) continue match = re.search('Collection\\[(\\{.*\\})\\]', setting['name']) if match: name = setting['name'][:(match.start(1) - 1)] match_dict = yaml.load(match.group(1)) index = _collection_match_to_index(pspath, setting['filter'], name, match_dict) if (index == (- 1)): log.warning('win_iis: No match found for setting: %s', setting) else: setting['name'] = setting['name'].replace(match.group(1), str(index)) prepared_settings.append(setting) else: prepared_settings.append(setting) return prepared_settings
def _prepare_settings(pspath, settings): '\n Prepare settings before execution with get or set functions.\n Removes settings with a match parameter when index is not found.\n ' prepared_settings = [] for setting in settings: if (setting.get('name', None) is None): log.warning('win_iis: Setting has no name: %s', setting) continue if (setting.get('filter', None) is None): log.warning('win_iis: Setting has no filter: %s', setting) continue match = re.search('Collection\\[(\\{.*\\})\\]', setting['name']) if match: name = setting['name'][:(match.start(1) - 1)] match_dict = yaml.load(match.group(1)) index = _collection_match_to_index(pspath, setting['filter'], name, match_dict) if (index == (- 1)): log.warning('win_iis: No match found for setting: %s', setting) else: setting['name'] = setting['name'].replace(match.group(1), str(index)) prepared_settings.append(setting) else: prepared_settings.append(setting) return prepared_settings<|docstring|>Prepare settings before execution with get or set functions. Removes settings with a match parameter when index is not found.<|endoftext|>
41d451ef1ffc8cdc9e40eacfb002c1b364ffe08f78b58efd7487f431c45e9028
def list_sites(): "\n List all the currently deployed websites.\n\n Returns:\n dict: A dictionary of the IIS sites and their properties.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.list_sites\n " ret = dict() ps_cmd = ['Get-ChildItem', '-Path', "'IIS:\\Sites'", '|', 'Select-Object applicationPool, Bindings, ID, Name, PhysicalPath, State'] keep_keys = ('certificateHash', 'certificateStoreName', 'protocol', 'sslFlags') cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True) try: items = salt.utils.json.loads(cmd_ret['stdout'], strict=False) except ValueError: raise CommandExecutionError('Unable to parse return data as Json.') for item in items: bindings = dict() for binding in item['bindings']['Collection']: if (binding['protocol'] not in ['http', 'https']): continue filtered_binding = dict() for key in binding: if (key in keep_keys): filtered_binding.update({key.lower(): binding[key]}) binding_info = binding['bindingInformation'].split(':', 2) (ipaddress, port, hostheader) = [element.strip() for element in binding_info] filtered_binding.update({'hostheader': hostheader, 'ipaddress': ipaddress, 'port': port}) bindings[binding['bindingInformation']] = filtered_binding ret[item['name']] = {'apppool': item['applicationPool'], 'bindings': bindings, 'id': item['id'], 'state': item['state'], 'sourcepath': item['physicalPath']} if (not ret): log.warning('No sites found in output: %s', cmd_ret['stdout']) return ret
List all the currently deployed websites. Returns: dict: A dictionary of the IIS sites and their properties. CLI Example: .. code-block:: bash salt '*' win_iis.list_sites
salt/modules/win_iis.py
list_sites
Flowdalic/salt
9,425
python
def list_sites(): "\n List all the currently deployed websites.\n\n Returns:\n dict: A dictionary of the IIS sites and their properties.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.list_sites\n " ret = dict() ps_cmd = ['Get-ChildItem', '-Path', "'IIS:\\Sites'", '|', 'Select-Object applicationPool, Bindings, ID, Name, PhysicalPath, State'] keep_keys = ('certificateHash', 'certificateStoreName', 'protocol', 'sslFlags') cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True) try: items = salt.utils.json.loads(cmd_ret['stdout'], strict=False) except ValueError: raise CommandExecutionError('Unable to parse return data as Json.') for item in items: bindings = dict() for binding in item['bindings']['Collection']: if (binding['protocol'] not in ['http', 'https']): continue filtered_binding = dict() for key in binding: if (key in keep_keys): filtered_binding.update({key.lower(): binding[key]}) binding_info = binding['bindingInformation'].split(':', 2) (ipaddress, port, hostheader) = [element.strip() for element in binding_info] filtered_binding.update({'hostheader': hostheader, 'ipaddress': ipaddress, 'port': port}) bindings[binding['bindingInformation']] = filtered_binding ret[item['name']] = {'apppool': item['applicationPool'], 'bindings': bindings, 'id': item['id'], 'state': item['state'], 'sourcepath': item['physicalPath']} if (not ret): log.warning('No sites found in output: %s', cmd_ret['stdout']) return ret
def list_sites(): "\n List all the currently deployed websites.\n\n Returns:\n dict: A dictionary of the IIS sites and their properties.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.list_sites\n " ret = dict() ps_cmd = ['Get-ChildItem', '-Path', "'IIS:\\Sites'", '|', 'Select-Object applicationPool, Bindings, ID, Name, PhysicalPath, State'] keep_keys = ('certificateHash', 'certificateStoreName', 'protocol', 'sslFlags') cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True) try: items = salt.utils.json.loads(cmd_ret['stdout'], strict=False) except ValueError: raise CommandExecutionError('Unable to parse return data as Json.') for item in items: bindings = dict() for binding in item['bindings']['Collection']: if (binding['protocol'] not in ['http', 'https']): continue filtered_binding = dict() for key in binding: if (key in keep_keys): filtered_binding.update({key.lower(): binding[key]}) binding_info = binding['bindingInformation'].split(':', 2) (ipaddress, port, hostheader) = [element.strip() for element in binding_info] filtered_binding.update({'hostheader': hostheader, 'ipaddress': ipaddress, 'port': port}) bindings[binding['bindingInformation']] = filtered_binding ret[item['name']] = {'apppool': item['applicationPool'], 'bindings': bindings, 'id': item['id'], 'state': item['state'], 'sourcepath': item['physicalPath']} if (not ret): log.warning('No sites found in output: %s', cmd_ret['stdout']) return ret<|docstring|>List all the currently deployed websites. Returns: dict: A dictionary of the IIS sites and their properties. CLI Example: .. code-block:: bash salt '*' win_iis.list_sites<|endoftext|>
8f30f7ed924772974cc6cbc89154baa937d885e1175138a64ff2817a8489ef4c
def create_site(name, sourcepath, apppool='', hostheader='', ipaddress='*', port=80, protocol='http'): "\n Create a basic website in IIS.\n\n .. note::\n\n This function only validates against the site name, and will return True\n even if the site already exists with a different configuration. It will\n not modify the configuration of an existing site.\n\n Args:\n name (str): The IIS site name.\n sourcepath (str): The physical path of the IIS site.\n apppool (str): The name of the IIS application pool.\n hostheader (str): The host header of the binding. Usually the hostname\n or website name, ie: www.contoso.com\n ipaddress (str): The IP address of the binding.\n port (int): The TCP port of the binding.\n protocol (str): The application protocol of the binding. (http, https,\n etc.)\n\n Returns:\n bool: True if successful, otherwise False.\n\n .. note::\n\n If an application pool is specified, and that application pool does not\n already exist, it will be created.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.create_site name='My Test Site' sourcepath='c:\\stage' apppool='TestPool'\n " protocol = str(protocol).lower() site_path = 'IIS:\\Sites\\{}'.format(name) binding_info = _get_binding_info(hostheader, ipaddress, port) current_sites = list_sites() if (name in current_sites): log.debug("Site '%s' already present.", name) return True if (protocol not in _VALID_PROTOCOLS): message = "Invalid protocol '{}' specified. Valid formats: {}".format(protocol, _VALID_PROTOCOLS) raise SaltInvocationError(message) ps_cmd = ['New-Item', '-Path', "'{}'".format(site_path), '-PhysicalPath', "'{}'".format(sourcepath), '-Bindings', "@{{ protocol='{0}'; bindingInformation='{1}' }};".format(protocol, binding_info)] if apppool: if (apppool in list_apppools()): log.debug('Utilizing pre-existing application pool: %s', apppool) else: log.debug('Application pool will be created: %s', apppool) create_apppool(apppool) ps_cmd.extend(['Set-ItemProperty', '-Path', "'{}'".format(site_path), '-Name', 'ApplicationPool', '-Value', "'{}'".format(apppool)]) cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to create site: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) log.debug('Site created successfully: %s', name) return True
Create a basic website in IIS. .. note:: This function only validates against the site name, and will return True even if the site already exists with a different configuration. It will not modify the configuration of an existing site. Args: name (str): The IIS site name. sourcepath (str): The physical path of the IIS site. apppool (str): The name of the IIS application pool. hostheader (str): The host header of the binding. Usually the hostname or website name, ie: www.contoso.com ipaddress (str): The IP address of the binding. port (int): The TCP port of the binding. protocol (str): The application protocol of the binding. (http, https, etc.) Returns: bool: True if successful, otherwise False. .. note:: If an application pool is specified, and that application pool does not already exist, it will be created. CLI Example: .. code-block:: bash salt '*' win_iis.create_site name='My Test Site' sourcepath='c:\stage' apppool='TestPool'
salt/modules/win_iis.py
create_site
Flowdalic/salt
9,425
python
def create_site(name, sourcepath, apppool=, hostheader=, ipaddress='*', port=80, protocol='http'): "\n Create a basic website in IIS.\n\n .. note::\n\n This function only validates against the site name, and will return True\n even if the site already exists with a different configuration. It will\n not modify the configuration of an existing site.\n\n Args:\n name (str): The IIS site name.\n sourcepath (str): The physical path of the IIS site.\n apppool (str): The name of the IIS application pool.\n hostheader (str): The host header of the binding. Usually the hostname\n or website name, ie: www.contoso.com\n ipaddress (str): The IP address of the binding.\n port (int): The TCP port of the binding.\n protocol (str): The application protocol of the binding. (http, https,\n etc.)\n\n Returns:\n bool: True if successful, otherwise False.\n\n .. note::\n\n If an application pool is specified, and that application pool does not\n already exist, it will be created.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.create_site name='My Test Site' sourcepath='c:\\stage' apppool='TestPool'\n " protocol = str(protocol).lower() site_path = 'IIS:\\Sites\\{}'.format(name) binding_info = _get_binding_info(hostheader, ipaddress, port) current_sites = list_sites() if (name in current_sites): log.debug("Site '%s' already present.", name) return True if (protocol not in _VALID_PROTOCOLS): message = "Invalid protocol '{}' specified. Valid formats: {}".format(protocol, _VALID_PROTOCOLS) raise SaltInvocationError(message) ps_cmd = ['New-Item', '-Path', "'{}'".format(site_path), '-PhysicalPath', "'{}'".format(sourcepath), '-Bindings', "@{{ protocol='{0}'; bindingInformation='{1}' }};".format(protocol, binding_info)] if apppool: if (apppool in list_apppools()): log.debug('Utilizing pre-existing application pool: %s', apppool) else: log.debug('Application pool will be created: %s', apppool) create_apppool(apppool) ps_cmd.extend(['Set-ItemProperty', '-Path', "'{}'".format(site_path), '-Name', 'ApplicationPool', '-Value', "'{}'".format(apppool)]) cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to create site: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) log.debug('Site created successfully: %s', name) return True
def create_site(name, sourcepath, apppool=, hostheader=, ipaddress='*', port=80, protocol='http'): "\n Create a basic website in IIS.\n\n .. note::\n\n This function only validates against the site name, and will return True\n even if the site already exists with a different configuration. It will\n not modify the configuration of an existing site.\n\n Args:\n name (str): The IIS site name.\n sourcepath (str): The physical path of the IIS site.\n apppool (str): The name of the IIS application pool.\n hostheader (str): The host header of the binding. Usually the hostname\n or website name, ie: www.contoso.com\n ipaddress (str): The IP address of the binding.\n port (int): The TCP port of the binding.\n protocol (str): The application protocol of the binding. (http, https,\n etc.)\n\n Returns:\n bool: True if successful, otherwise False.\n\n .. note::\n\n If an application pool is specified, and that application pool does not\n already exist, it will be created.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.create_site name='My Test Site' sourcepath='c:\\stage' apppool='TestPool'\n " protocol = str(protocol).lower() site_path = 'IIS:\\Sites\\{}'.format(name) binding_info = _get_binding_info(hostheader, ipaddress, port) current_sites = list_sites() if (name in current_sites): log.debug("Site '%s' already present.", name) return True if (protocol not in _VALID_PROTOCOLS): message = "Invalid protocol '{}' specified. Valid formats: {}".format(protocol, _VALID_PROTOCOLS) raise SaltInvocationError(message) ps_cmd = ['New-Item', '-Path', "'{}'".format(site_path), '-PhysicalPath', "'{}'".format(sourcepath), '-Bindings', "@{{ protocol='{0}'; bindingInformation='{1}' }};".format(protocol, binding_info)] if apppool: if (apppool in list_apppools()): log.debug('Utilizing pre-existing application pool: %s', apppool) else: log.debug('Application pool will be created: %s', apppool) create_apppool(apppool) ps_cmd.extend(['Set-ItemProperty', '-Path', "'{}'".format(site_path), '-Name', 'ApplicationPool', '-Value', "'{}'".format(apppool)]) cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to create site: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) log.debug('Site created successfully: %s', name) return True<|docstring|>Create a basic website in IIS. .. note:: This function only validates against the site name, and will return True even if the site already exists with a different configuration. It will not modify the configuration of an existing site. Args: name (str): The IIS site name. sourcepath (str): The physical path of the IIS site. apppool (str): The name of the IIS application pool. hostheader (str): The host header of the binding. Usually the hostname or website name, ie: www.contoso.com ipaddress (str): The IP address of the binding. port (int): The TCP port of the binding. protocol (str): The application protocol of the binding. (http, https, etc.) Returns: bool: True if successful, otherwise False. .. note:: If an application pool is specified, and that application pool does not already exist, it will be created. CLI Example: .. code-block:: bash salt '*' win_iis.create_site name='My Test Site' sourcepath='c:\stage' apppool='TestPool'<|endoftext|>
d5c54055f837926c99b9fb3ff5e18fef111fa7f7bde136d4fae7b575a29d09de
def modify_site(name, sourcepath=None, apppool=None): "\n Modify a basic website in IIS.\n\n .. versionadded:: 2017.7.0\n\n Args:\n name (str): The IIS site name.\n sourcepath (str): The physical path of the IIS site.\n apppool (str): The name of the IIS application pool.\n\n Returns:\n bool: True if successful, otherwise False.\n\n .. note::\n\n If an application pool is specified, and that application pool does not\n already exist, it will be created.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.modify_site name='My Test Site' sourcepath='c:\\new_path' apppool='NewTestPool'\n " site_path = 'IIS:\\Sites\\{}'.format(name) current_sites = list_sites() if (name not in current_sites): log.debug("Site '%s' not defined.", name) return False ps_cmd = list() if sourcepath: ps_cmd.extend(['Set-ItemProperty', '-Path', "'{}'".format(site_path), '-Name', 'PhysicalPath', '-Value', "'{}'".format(sourcepath)]) if apppool: if (apppool in list_apppools()): log.debug('Utilizing pre-existing application pool: %s', apppool) else: log.debug('Application pool will be created: %s', apppool) create_apppool(apppool) if ps_cmd: ps_cmd.append(';') ps_cmd.extend(['Set-ItemProperty', '-Path', "'{}'".format(site_path), '-Name', 'ApplicationPool', '-Value', "'{}'".format(apppool)]) cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to modify site: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) log.debug('Site modified successfully: %s', name) return True
Modify a basic website in IIS. .. versionadded:: 2017.7.0 Args: name (str): The IIS site name. sourcepath (str): The physical path of the IIS site. apppool (str): The name of the IIS application pool. Returns: bool: True if successful, otherwise False. .. note:: If an application pool is specified, and that application pool does not already exist, it will be created. CLI Example: .. code-block:: bash salt '*' win_iis.modify_site name='My Test Site' sourcepath='c:\new_path' apppool='NewTestPool'
salt/modules/win_iis.py
modify_site
Flowdalic/salt
9,425
python
def modify_site(name, sourcepath=None, apppool=None): "\n Modify a basic website in IIS.\n\n .. versionadded:: 2017.7.0\n\n Args:\n name (str): The IIS site name.\n sourcepath (str): The physical path of the IIS site.\n apppool (str): The name of the IIS application pool.\n\n Returns:\n bool: True if successful, otherwise False.\n\n .. note::\n\n If an application pool is specified, and that application pool does not\n already exist, it will be created.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.modify_site name='My Test Site' sourcepath='c:\\new_path' apppool='NewTestPool'\n " site_path = 'IIS:\\Sites\\{}'.format(name) current_sites = list_sites() if (name not in current_sites): log.debug("Site '%s' not defined.", name) return False ps_cmd = list() if sourcepath: ps_cmd.extend(['Set-ItemProperty', '-Path', "'{}'".format(site_path), '-Name', 'PhysicalPath', '-Value', "'{}'".format(sourcepath)]) if apppool: if (apppool in list_apppools()): log.debug('Utilizing pre-existing application pool: %s', apppool) else: log.debug('Application pool will be created: %s', apppool) create_apppool(apppool) if ps_cmd: ps_cmd.append(';') ps_cmd.extend(['Set-ItemProperty', '-Path', "'{}'".format(site_path), '-Name', 'ApplicationPool', '-Value', "'{}'".format(apppool)]) cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to modify site: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) log.debug('Site modified successfully: %s', name) return True
def modify_site(name, sourcepath=None, apppool=None): "\n Modify a basic website in IIS.\n\n .. versionadded:: 2017.7.0\n\n Args:\n name (str): The IIS site name.\n sourcepath (str): The physical path of the IIS site.\n apppool (str): The name of the IIS application pool.\n\n Returns:\n bool: True if successful, otherwise False.\n\n .. note::\n\n If an application pool is specified, and that application pool does not\n already exist, it will be created.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.modify_site name='My Test Site' sourcepath='c:\\new_path' apppool='NewTestPool'\n " site_path = 'IIS:\\Sites\\{}'.format(name) current_sites = list_sites() if (name not in current_sites): log.debug("Site '%s' not defined.", name) return False ps_cmd = list() if sourcepath: ps_cmd.extend(['Set-ItemProperty', '-Path', "'{}'".format(site_path), '-Name', 'PhysicalPath', '-Value', "'{}'".format(sourcepath)]) if apppool: if (apppool in list_apppools()): log.debug('Utilizing pre-existing application pool: %s', apppool) else: log.debug('Application pool will be created: %s', apppool) create_apppool(apppool) if ps_cmd: ps_cmd.append(';') ps_cmd.extend(['Set-ItemProperty', '-Path', "'{}'".format(site_path), '-Name', 'ApplicationPool', '-Value', "'{}'".format(apppool)]) cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to modify site: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) log.debug('Site modified successfully: %s', name) return True<|docstring|>Modify a basic website in IIS. .. versionadded:: 2017.7.0 Args: name (str): The IIS site name. sourcepath (str): The physical path of the IIS site. apppool (str): The name of the IIS application pool. Returns: bool: True if successful, otherwise False. .. note:: If an application pool is specified, and that application pool does not already exist, it will be created. CLI Example: .. code-block:: bash salt '*' win_iis.modify_site name='My Test Site' sourcepath='c:\new_path' apppool='NewTestPool'<|endoftext|>
05d04aa089119e019232652fe8e3103345f4abc7a303e49f2d11abe53b9decd2
def remove_site(name): "\n Delete a website from IIS.\n\n Args:\n name (str): The IIS site name.\n\n Returns:\n bool: True if successful, otherwise False\n\n .. note::\n\n This will not remove the application pool used by the site.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.remove_site name='My Test Site'\n\n " current_sites = list_sites() if (name not in current_sites): log.debug('Site already absent: %s', name) return True ps_cmd = ['Remove-WebSite', '-Name', "'{}'".format(name)] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to remove site: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) log.debug('Site removed successfully: %s', name) return True
Delete a website from IIS. Args: name (str): The IIS site name. Returns: bool: True if successful, otherwise False .. note:: This will not remove the application pool used by the site. CLI Example: .. code-block:: bash salt '*' win_iis.remove_site name='My Test Site'
salt/modules/win_iis.py
remove_site
Flowdalic/salt
9,425
python
def remove_site(name): "\n Delete a website from IIS.\n\n Args:\n name (str): The IIS site name.\n\n Returns:\n bool: True if successful, otherwise False\n\n .. note::\n\n This will not remove the application pool used by the site.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.remove_site name='My Test Site'\n\n " current_sites = list_sites() if (name not in current_sites): log.debug('Site already absent: %s', name) return True ps_cmd = ['Remove-WebSite', '-Name', "'{}'".format(name)] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to remove site: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) log.debug('Site removed successfully: %s', name) return True
def remove_site(name): "\n Delete a website from IIS.\n\n Args:\n name (str): The IIS site name.\n\n Returns:\n bool: True if successful, otherwise False\n\n .. note::\n\n This will not remove the application pool used by the site.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.remove_site name='My Test Site'\n\n " current_sites = list_sites() if (name not in current_sites): log.debug('Site already absent: %s', name) return True ps_cmd = ['Remove-WebSite', '-Name', "'{}'".format(name)] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to remove site: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) log.debug('Site removed successfully: %s', name) return True<|docstring|>Delete a website from IIS. Args: name (str): The IIS site name. Returns: bool: True if successful, otherwise False .. note:: This will not remove the application pool used by the site. CLI Example: .. code-block:: bash salt '*' win_iis.remove_site name='My Test Site'<|endoftext|>
ce8fe42764eeb3febfd24a3a80bb46c595f5a3d2191ba8ed4217626c716507fa
def stop_site(name): "\n Stop a Web Site in IIS.\n\n .. versionadded:: 2017.7.0\n\n Args:\n name (str): The name of the website to stop.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.stop_site name='My Test Site'\n " ps_cmd = ['Stop-WebSite', "'{}'".format(name)] cmd_ret = _srvmgr(ps_cmd) return (cmd_ret['retcode'] == 0)
Stop a Web Site in IIS. .. versionadded:: 2017.7.0 Args: name (str): The name of the website to stop. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.stop_site name='My Test Site'
salt/modules/win_iis.py
stop_site
Flowdalic/salt
9,425
python
def stop_site(name): "\n Stop a Web Site in IIS.\n\n .. versionadded:: 2017.7.0\n\n Args:\n name (str): The name of the website to stop.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.stop_site name='My Test Site'\n " ps_cmd = ['Stop-WebSite', "'{}'".format(name)] cmd_ret = _srvmgr(ps_cmd) return (cmd_ret['retcode'] == 0)
def stop_site(name): "\n Stop a Web Site in IIS.\n\n .. versionadded:: 2017.7.0\n\n Args:\n name (str): The name of the website to stop.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.stop_site name='My Test Site'\n " ps_cmd = ['Stop-WebSite', "'{}'".format(name)] cmd_ret = _srvmgr(ps_cmd) return (cmd_ret['retcode'] == 0)<|docstring|>Stop a Web Site in IIS. .. versionadded:: 2017.7.0 Args: name (str): The name of the website to stop. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.stop_site name='My Test Site'<|endoftext|>
eb34f2b4f34ff56a09a4a01410a04f08191cef55c6feef3e764f095a04193bd8
def start_site(name): "\n Start a Web Site in IIS.\n\n .. versionadded:: 2017.7.0\n\n Args:\n name (str): The name of the website to start.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.start_site name='My Test Site'\n " ps_cmd = ['Start-WebSite', "'{}'".format(name)] cmd_ret = _srvmgr(ps_cmd) return (cmd_ret['retcode'] == 0)
Start a Web Site in IIS. .. versionadded:: 2017.7.0 Args: name (str): The name of the website to start. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.start_site name='My Test Site'
salt/modules/win_iis.py
start_site
Flowdalic/salt
9,425
python
def start_site(name): "\n Start a Web Site in IIS.\n\n .. versionadded:: 2017.7.0\n\n Args:\n name (str): The name of the website to start.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.start_site name='My Test Site'\n " ps_cmd = ['Start-WebSite', "'{}'".format(name)] cmd_ret = _srvmgr(ps_cmd) return (cmd_ret['retcode'] == 0)
def start_site(name): "\n Start a Web Site in IIS.\n\n .. versionadded:: 2017.7.0\n\n Args:\n name (str): The name of the website to start.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.start_site name='My Test Site'\n " ps_cmd = ['Start-WebSite', "'{}'".format(name)] cmd_ret = _srvmgr(ps_cmd) return (cmd_ret['retcode'] == 0)<|docstring|>Start a Web Site in IIS. .. versionadded:: 2017.7.0 Args: name (str): The name of the website to start. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.start_site name='My Test Site'<|endoftext|>
32e8bb5944966be4730230acf0c2816580e9436759bac099fffec722c68bef65
def restart_site(name): "\n Restart a Web Site in IIS.\n\n .. versionadded:: 2017.7.0\n\n Args:\n name (str): The name of the website to restart.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.restart_site name='My Test Site'\n " return (stop_site(name) and start_site(name))
Restart a Web Site in IIS. .. versionadded:: 2017.7.0 Args: name (str): The name of the website to restart. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.restart_site name='My Test Site'
salt/modules/win_iis.py
restart_site
Flowdalic/salt
9,425
python
def restart_site(name): "\n Restart a Web Site in IIS.\n\n .. versionadded:: 2017.7.0\n\n Args:\n name (str): The name of the website to restart.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.restart_site name='My Test Site'\n " return (stop_site(name) and start_site(name))
def restart_site(name): "\n Restart a Web Site in IIS.\n\n .. versionadded:: 2017.7.0\n\n Args:\n name (str): The name of the website to restart.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.restart_site name='My Test Site'\n " return (stop_site(name) and start_site(name))<|docstring|>Restart a Web Site in IIS. .. versionadded:: 2017.7.0 Args: name (str): The name of the website to restart. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.restart_site name='My Test Site'<|endoftext|>
1772b3e1ebeba78775a748bae3e9da1ec956a6f8715930b39f1fe20ac8385194
def list_bindings(site): "\n Get all configured IIS bindings for the specified site.\n\n Args:\n site (str): The name if the IIS Site\n\n Returns:\n dict: A dictionary of the binding names and properties.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.list_bindings site\n " ret = dict() sites = list_sites() if (site not in sites): log.warning('Site not found: %s', site) return ret ret = sites[site]['bindings'] if (not ret): log.warning('No bindings found for site: %s', site) return ret
Get all configured IIS bindings for the specified site. Args: site (str): The name if the IIS Site Returns: dict: A dictionary of the binding names and properties. CLI Example: .. code-block:: bash salt '*' win_iis.list_bindings site
salt/modules/win_iis.py
list_bindings
Flowdalic/salt
9,425
python
def list_bindings(site): "\n Get all configured IIS bindings for the specified site.\n\n Args:\n site (str): The name if the IIS Site\n\n Returns:\n dict: A dictionary of the binding names and properties.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.list_bindings site\n " ret = dict() sites = list_sites() if (site not in sites): log.warning('Site not found: %s', site) return ret ret = sites[site]['bindings'] if (not ret): log.warning('No bindings found for site: %s', site) return ret
def list_bindings(site): "\n Get all configured IIS bindings for the specified site.\n\n Args:\n site (str): The name if the IIS Site\n\n Returns:\n dict: A dictionary of the binding names and properties.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.list_bindings site\n " ret = dict() sites = list_sites() if (site not in sites): log.warning('Site not found: %s', site) return ret ret = sites[site]['bindings'] if (not ret): log.warning('No bindings found for site: %s', site) return ret<|docstring|>Get all configured IIS bindings for the specified site. Args: site (str): The name if the IIS Site Returns: dict: A dictionary of the binding names and properties. CLI Example: .. code-block:: bash salt '*' win_iis.list_bindings site<|endoftext|>
eaa526e6d319c1b22271b16b060e86e43f4b2d94759c53444e8faff453f79669
def create_binding(site, hostheader='', ipaddress='*', port=80, protocol='http', sslflags=None): "\n Create an IIS Web Binding.\n\n .. note::\n\n This function only validates against the binding\n ipaddress:port:hostheader combination, and will return True even if the\n binding already exists with a different configuration. It will not\n modify the configuration of an existing binding.\n\n Args:\n site (str): The IIS site name.\n hostheader (str): The host header of the binding. Usually a hostname.\n ipaddress (str): The IP address of the binding.\n port (int): The TCP port of the binding.\n protocol (str): The application protocol of the binding.\n sslflags (str): The flags representing certificate type and storage of\n the binding.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.create_binding site='site0' hostheader='example.com' ipaddress='*' port='80'\n " protocol = str(protocol).lower() name = _get_binding_info(hostheader, ipaddress, port) if (protocol not in _VALID_PROTOCOLS): message = "Invalid protocol '{}' specified. Valid formats: {}".format(protocol, _VALID_PROTOCOLS) raise SaltInvocationError(message) if sslflags: sslflags = int(sslflags) if (sslflags not in _VALID_SSL_FLAGS): raise SaltInvocationError("Invalid sslflags '{}' specified. Valid sslflags range: {}..{}".format(sslflags, _VALID_SSL_FLAGS[0], _VALID_SSL_FLAGS[(- 1)])) current_bindings = list_bindings(site) if (name in current_bindings): log.debug('Binding already present: %s', name) return True if sslflags: ps_cmd = ['New-WebBinding', '-Name', "'{}'".format(site), '-HostHeader', "'{}'".format(hostheader), '-IpAddress', "'{}'".format(ipaddress), '-Port', "'{}'".format(port), '-Protocol', "'{}'".format(protocol), '-SslFlags', '{}'.format(sslflags)] else: ps_cmd = ['New-WebBinding', '-Name', "'{}'".format(site), '-HostHeader', "'{}'".format(hostheader), '-IpAddress', "'{}'".format(ipaddress), '-Port', "'{}'".format(port), '-Protocol', "'{}'".format(protocol)] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to create binding: {}\nError: {}'.format(site, cmd_ret['stderr']) raise CommandExecutionError(msg) if (name in list_bindings(site)): log.debug('Binding created successfully: %s', site) return True log.error('Unable to create binding: %s', site) return False
Create an IIS Web Binding. .. note:: This function only validates against the binding ipaddress:port:hostheader combination, and will return True even if the binding already exists with a different configuration. It will not modify the configuration of an existing binding. Args: site (str): The IIS site name. hostheader (str): The host header of the binding. Usually a hostname. ipaddress (str): The IP address of the binding. port (int): The TCP port of the binding. protocol (str): The application protocol of the binding. sslflags (str): The flags representing certificate type and storage of the binding. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.create_binding site='site0' hostheader='example.com' ipaddress='*' port='80'
salt/modules/win_iis.py
create_binding
Flowdalic/salt
9,425
python
def create_binding(site, hostheader=, ipaddress='*', port=80, protocol='http', sslflags=None): "\n Create an IIS Web Binding.\n\n .. note::\n\n This function only validates against the binding\n ipaddress:port:hostheader combination, and will return True even if the\n binding already exists with a different configuration. It will not\n modify the configuration of an existing binding.\n\n Args:\n site (str): The IIS site name.\n hostheader (str): The host header of the binding. Usually a hostname.\n ipaddress (str): The IP address of the binding.\n port (int): The TCP port of the binding.\n protocol (str): The application protocol of the binding.\n sslflags (str): The flags representing certificate type and storage of\n the binding.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.create_binding site='site0' hostheader='example.com' ipaddress='*' port='80'\n " protocol = str(protocol).lower() name = _get_binding_info(hostheader, ipaddress, port) if (protocol not in _VALID_PROTOCOLS): message = "Invalid protocol '{}' specified. Valid formats: {}".format(protocol, _VALID_PROTOCOLS) raise SaltInvocationError(message) if sslflags: sslflags = int(sslflags) if (sslflags not in _VALID_SSL_FLAGS): raise SaltInvocationError("Invalid sslflags '{}' specified. Valid sslflags range: {}..{}".format(sslflags, _VALID_SSL_FLAGS[0], _VALID_SSL_FLAGS[(- 1)])) current_bindings = list_bindings(site) if (name in current_bindings): log.debug('Binding already present: %s', name) return True if sslflags: ps_cmd = ['New-WebBinding', '-Name', "'{}'".format(site), '-HostHeader', "'{}'".format(hostheader), '-IpAddress', "'{}'".format(ipaddress), '-Port', "'{}'".format(port), '-Protocol', "'{}'".format(protocol), '-SslFlags', '{}'.format(sslflags)] else: ps_cmd = ['New-WebBinding', '-Name', "'{}'".format(site), '-HostHeader', "'{}'".format(hostheader), '-IpAddress', "'{}'".format(ipaddress), '-Port', "'{}'".format(port), '-Protocol', "'{}'".format(protocol)] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to create binding: {}\nError: {}'.format(site, cmd_ret['stderr']) raise CommandExecutionError(msg) if (name in list_bindings(site)): log.debug('Binding created successfully: %s', site) return True log.error('Unable to create binding: %s', site) return False
def create_binding(site, hostheader=, ipaddress='*', port=80, protocol='http', sslflags=None): "\n Create an IIS Web Binding.\n\n .. note::\n\n This function only validates against the binding\n ipaddress:port:hostheader combination, and will return True even if the\n binding already exists with a different configuration. It will not\n modify the configuration of an existing binding.\n\n Args:\n site (str): The IIS site name.\n hostheader (str): The host header of the binding. Usually a hostname.\n ipaddress (str): The IP address of the binding.\n port (int): The TCP port of the binding.\n protocol (str): The application protocol of the binding.\n sslflags (str): The flags representing certificate type and storage of\n the binding.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.create_binding site='site0' hostheader='example.com' ipaddress='*' port='80'\n " protocol = str(protocol).lower() name = _get_binding_info(hostheader, ipaddress, port) if (protocol not in _VALID_PROTOCOLS): message = "Invalid protocol '{}' specified. Valid formats: {}".format(protocol, _VALID_PROTOCOLS) raise SaltInvocationError(message) if sslflags: sslflags = int(sslflags) if (sslflags not in _VALID_SSL_FLAGS): raise SaltInvocationError("Invalid sslflags '{}' specified. Valid sslflags range: {}..{}".format(sslflags, _VALID_SSL_FLAGS[0], _VALID_SSL_FLAGS[(- 1)])) current_bindings = list_bindings(site) if (name in current_bindings): log.debug('Binding already present: %s', name) return True if sslflags: ps_cmd = ['New-WebBinding', '-Name', "'{}'".format(site), '-HostHeader', "'{}'".format(hostheader), '-IpAddress', "'{}'".format(ipaddress), '-Port', "'{}'".format(port), '-Protocol', "'{}'".format(protocol), '-SslFlags', '{}'.format(sslflags)] else: ps_cmd = ['New-WebBinding', '-Name', "'{}'".format(site), '-HostHeader', "'{}'".format(hostheader), '-IpAddress', "'{}'".format(ipaddress), '-Port', "'{}'".format(port), '-Protocol', "'{}'".format(protocol)] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to create binding: {}\nError: {}'.format(site, cmd_ret['stderr']) raise CommandExecutionError(msg) if (name in list_bindings(site)): log.debug('Binding created successfully: %s', site) return True log.error('Unable to create binding: %s', site) return False<|docstring|>Create an IIS Web Binding. .. note:: This function only validates against the binding ipaddress:port:hostheader combination, and will return True even if the binding already exists with a different configuration. It will not modify the configuration of an existing binding. Args: site (str): The IIS site name. hostheader (str): The host header of the binding. Usually a hostname. ipaddress (str): The IP address of the binding. port (int): The TCP port of the binding. protocol (str): The application protocol of the binding. sslflags (str): The flags representing certificate type and storage of the binding. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.create_binding site='site0' hostheader='example.com' ipaddress='*' port='80'<|endoftext|>
5d59123f4cd4b2fb9712cb47656fd82ac8ab57175984e57d7775a74f295e1175
def modify_binding(site, binding, hostheader=None, ipaddress=None, port=None, sslflags=None): "\n Modify an IIS Web Binding. Use ``site`` and ``binding`` to target the\n binding.\n\n .. versionadded:: 2017.7.0\n\n Args:\n site (str): The IIS site name.\n binding (str): The binding to edit. This is a combination of the\n IP address, port, and hostheader. It is in the following format:\n ipaddress:port:hostheader. For example, ``*:80:`` or\n ``*:80:salt.com``\n hostheader (str): The host header of the binding. Usually the hostname.\n ipaddress (str): The IP address of the binding.\n port (int): The TCP port of the binding.\n sslflags (str): The flags representing certificate type and storage of\n the binding.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n The following will seat the host header of binding ``*:80:`` for ``site0``\n to ``example.com``\n\n .. code-block:: bash\n\n salt '*' win_iis.modify_binding site='site0' binding='*:80:' hostheader='example.com'\n " if ((sslflags is not None) and (sslflags not in _VALID_SSL_FLAGS)): raise SaltInvocationError("Invalid sslflags '{}' specified. Valid sslflags range: {}..{}".format(sslflags, _VALID_SSL_FLAGS[0], _VALID_SSL_FLAGS[(- 1)])) current_sites = list_sites() if (site not in current_sites): log.debug("Site '%s' not defined.", site) return False current_bindings = list_bindings(site) if (binding not in current_bindings): log.debug("Binding '%s' not defined.", binding) return False (i, p, h) = binding.split(':') new_binding = ':'.join([(ipaddress if (ipaddress is not None) else i), (str(port) if (port is not None) else str(p)), (hostheader if (hostheader is not None) else h)]) if (new_binding != binding): ps_cmd = ['Set-WebBinding', '-Name', "'{}'".format(site), '-BindingInformation', "'{}'".format(binding), '-PropertyName', 'BindingInformation', '-Value', "'{}'".format(new_binding)] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to modify binding: {}\nError: {}'.format(binding, cmd_ret['stderr']) raise CommandExecutionError(msg) if ((sslflags is not None) and (sslflags != current_sites[site]['bindings'][binding]['sslflags'])): ps_cmd = ['Set-WebBinding', '-Name', "'{}'".format(site), '-BindingInformation', "'{}'".format(new_binding), '-PropertyName', 'sslflags', '-Value', "'{}'".format(sslflags)] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to modify binding SSL Flags: {}\nError: {}'.format(sslflags, cmd_ret['stderr']) raise CommandExecutionError(msg) log.debug('Binding modified successfully: %s', binding) return True
Modify an IIS Web Binding. Use ``site`` and ``binding`` to target the binding. .. versionadded:: 2017.7.0 Args: site (str): The IIS site name. binding (str): The binding to edit. This is a combination of the IP address, port, and hostheader. It is in the following format: ipaddress:port:hostheader. For example, ``*:80:`` or ``*:80:salt.com`` hostheader (str): The host header of the binding. Usually the hostname. ipaddress (str): The IP address of the binding. port (int): The TCP port of the binding. sslflags (str): The flags representing certificate type and storage of the binding. Returns: bool: True if successful, otherwise False CLI Example: The following will seat the host header of binding ``*:80:`` for ``site0`` to ``example.com`` .. code-block:: bash salt '*' win_iis.modify_binding site='site0' binding='*:80:' hostheader='example.com'
salt/modules/win_iis.py
modify_binding
Flowdalic/salt
9,425
python
def modify_binding(site, binding, hostheader=None, ipaddress=None, port=None, sslflags=None): "\n Modify an IIS Web Binding. Use ``site`` and ``binding`` to target the\n binding.\n\n .. versionadded:: 2017.7.0\n\n Args:\n site (str): The IIS site name.\n binding (str): The binding to edit. This is a combination of the\n IP address, port, and hostheader. It is in the following format:\n ipaddress:port:hostheader. For example, ``*:80:`` or\n ``*:80:salt.com``\n hostheader (str): The host header of the binding. Usually the hostname.\n ipaddress (str): The IP address of the binding.\n port (int): The TCP port of the binding.\n sslflags (str): The flags representing certificate type and storage of\n the binding.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n The following will seat the host header of binding ``*:80:`` for ``site0``\n to ``example.com``\n\n .. code-block:: bash\n\n salt '*' win_iis.modify_binding site='site0' binding='*:80:' hostheader='example.com'\n " if ((sslflags is not None) and (sslflags not in _VALID_SSL_FLAGS)): raise SaltInvocationError("Invalid sslflags '{}' specified. Valid sslflags range: {}..{}".format(sslflags, _VALID_SSL_FLAGS[0], _VALID_SSL_FLAGS[(- 1)])) current_sites = list_sites() if (site not in current_sites): log.debug("Site '%s' not defined.", site) return False current_bindings = list_bindings(site) if (binding not in current_bindings): log.debug("Binding '%s' not defined.", binding) return False (i, p, h) = binding.split(':') new_binding = ':'.join([(ipaddress if (ipaddress is not None) else i), (str(port) if (port is not None) else str(p)), (hostheader if (hostheader is not None) else h)]) if (new_binding != binding): ps_cmd = ['Set-WebBinding', '-Name', "'{}'".format(site), '-BindingInformation', "'{}'".format(binding), '-PropertyName', 'BindingInformation', '-Value', "'{}'".format(new_binding)] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to modify binding: {}\nError: {}'.format(binding, cmd_ret['stderr']) raise CommandExecutionError(msg) if ((sslflags is not None) and (sslflags != current_sites[site]['bindings'][binding]['sslflags'])): ps_cmd = ['Set-WebBinding', '-Name', "'{}'".format(site), '-BindingInformation', "'{}'".format(new_binding), '-PropertyName', 'sslflags', '-Value', "'{}'".format(sslflags)] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to modify binding SSL Flags: {}\nError: {}'.format(sslflags, cmd_ret['stderr']) raise CommandExecutionError(msg) log.debug('Binding modified successfully: %s', binding) return True
def modify_binding(site, binding, hostheader=None, ipaddress=None, port=None, sslflags=None): "\n Modify an IIS Web Binding. Use ``site`` and ``binding`` to target the\n binding.\n\n .. versionadded:: 2017.7.0\n\n Args:\n site (str): The IIS site name.\n binding (str): The binding to edit. This is a combination of the\n IP address, port, and hostheader. It is in the following format:\n ipaddress:port:hostheader. For example, ``*:80:`` or\n ``*:80:salt.com``\n hostheader (str): The host header of the binding. Usually the hostname.\n ipaddress (str): The IP address of the binding.\n port (int): The TCP port of the binding.\n sslflags (str): The flags representing certificate type and storage of\n the binding.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n The following will seat the host header of binding ``*:80:`` for ``site0``\n to ``example.com``\n\n .. code-block:: bash\n\n salt '*' win_iis.modify_binding site='site0' binding='*:80:' hostheader='example.com'\n " if ((sslflags is not None) and (sslflags not in _VALID_SSL_FLAGS)): raise SaltInvocationError("Invalid sslflags '{}' specified. Valid sslflags range: {}..{}".format(sslflags, _VALID_SSL_FLAGS[0], _VALID_SSL_FLAGS[(- 1)])) current_sites = list_sites() if (site not in current_sites): log.debug("Site '%s' not defined.", site) return False current_bindings = list_bindings(site) if (binding not in current_bindings): log.debug("Binding '%s' not defined.", binding) return False (i, p, h) = binding.split(':') new_binding = ':'.join([(ipaddress if (ipaddress is not None) else i), (str(port) if (port is not None) else str(p)), (hostheader if (hostheader is not None) else h)]) if (new_binding != binding): ps_cmd = ['Set-WebBinding', '-Name', "'{}'".format(site), '-BindingInformation', "'{}'".format(binding), '-PropertyName', 'BindingInformation', '-Value', "'{}'".format(new_binding)] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to modify binding: {}\nError: {}'.format(binding, cmd_ret['stderr']) raise CommandExecutionError(msg) if ((sslflags is not None) and (sslflags != current_sites[site]['bindings'][binding]['sslflags'])): ps_cmd = ['Set-WebBinding', '-Name', "'{}'".format(site), '-BindingInformation', "'{}'".format(new_binding), '-PropertyName', 'sslflags', '-Value', "'{}'".format(sslflags)] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to modify binding SSL Flags: {}\nError: {}'.format(sslflags, cmd_ret['stderr']) raise CommandExecutionError(msg) log.debug('Binding modified successfully: %s', binding) return True<|docstring|>Modify an IIS Web Binding. Use ``site`` and ``binding`` to target the binding. .. versionadded:: 2017.7.0 Args: site (str): The IIS site name. binding (str): The binding to edit. This is a combination of the IP address, port, and hostheader. It is in the following format: ipaddress:port:hostheader. For example, ``*:80:`` or ``*:80:salt.com`` hostheader (str): The host header of the binding. Usually the hostname. ipaddress (str): The IP address of the binding. port (int): The TCP port of the binding. sslflags (str): The flags representing certificate type and storage of the binding. Returns: bool: True if successful, otherwise False CLI Example: The following will seat the host header of binding ``*:80:`` for ``site0`` to ``example.com`` .. code-block:: bash salt '*' win_iis.modify_binding site='site0' binding='*:80:' hostheader='example.com'<|endoftext|>
8c144fc3c0db59bb9a036e35013defcf13aa3b892de554a945585a1335e18db3
def remove_binding(site, hostheader='', ipaddress='*', port=80): "\n Remove an IIS binding.\n\n Args:\n site (str): The IIS site name.\n hostheader (str): The host header of the binding.\n ipaddress (str): The IP address of the binding.\n port (int): The TCP port of the binding.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.remove_binding site='site0' hostheader='example.com' ipaddress='*' port='80'\n " name = _get_binding_info(hostheader, ipaddress, port) current_bindings = list_bindings(site) if (name not in current_bindings): log.debug('Binding already absent: %s', name) return True ps_cmd = ['Remove-WebBinding', '-HostHeader', "'{}'".format(hostheader), '-IpAddress', "'{}'".format(ipaddress), '-Port', "'{}'".format(port)] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to remove binding: {}\nError: {}'.format(site, cmd_ret['stderr']) raise CommandExecutionError(msg) if (name not in list_bindings(site)): log.debug('Binding removed successfully: %s', site) return True log.error('Unable to remove binding: %s', site) return False
Remove an IIS binding. Args: site (str): The IIS site name. hostheader (str): The host header of the binding. ipaddress (str): The IP address of the binding. port (int): The TCP port of the binding. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.remove_binding site='site0' hostheader='example.com' ipaddress='*' port='80'
salt/modules/win_iis.py
remove_binding
Flowdalic/salt
9,425
python
def remove_binding(site, hostheader=, ipaddress='*', port=80): "\n Remove an IIS binding.\n\n Args:\n site (str): The IIS site name.\n hostheader (str): The host header of the binding.\n ipaddress (str): The IP address of the binding.\n port (int): The TCP port of the binding.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.remove_binding site='site0' hostheader='example.com' ipaddress='*' port='80'\n " name = _get_binding_info(hostheader, ipaddress, port) current_bindings = list_bindings(site) if (name not in current_bindings): log.debug('Binding already absent: %s', name) return True ps_cmd = ['Remove-WebBinding', '-HostHeader', "'{}'".format(hostheader), '-IpAddress', "'{}'".format(ipaddress), '-Port', "'{}'".format(port)] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to remove binding: {}\nError: {}'.format(site, cmd_ret['stderr']) raise CommandExecutionError(msg) if (name not in list_bindings(site)): log.debug('Binding removed successfully: %s', site) return True log.error('Unable to remove binding: %s', site) return False
def remove_binding(site, hostheader=, ipaddress='*', port=80): "\n Remove an IIS binding.\n\n Args:\n site (str): The IIS site name.\n hostheader (str): The host header of the binding.\n ipaddress (str): The IP address of the binding.\n port (int): The TCP port of the binding.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.remove_binding site='site0' hostheader='example.com' ipaddress='*' port='80'\n " name = _get_binding_info(hostheader, ipaddress, port) current_bindings = list_bindings(site) if (name not in current_bindings): log.debug('Binding already absent: %s', name) return True ps_cmd = ['Remove-WebBinding', '-HostHeader', "'{}'".format(hostheader), '-IpAddress', "'{}'".format(ipaddress), '-Port', "'{}'".format(port)] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to remove binding: {}\nError: {}'.format(site, cmd_ret['stderr']) raise CommandExecutionError(msg) if (name not in list_bindings(site)): log.debug('Binding removed successfully: %s', site) return True log.error('Unable to remove binding: %s', site) return False<|docstring|>Remove an IIS binding. Args: site (str): The IIS site name. hostheader (str): The host header of the binding. ipaddress (str): The IP address of the binding. port (int): The TCP port of the binding. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.remove_binding site='site0' hostheader='example.com' ipaddress='*' port='80'<|endoftext|>
0ace7ae41a5435efec659f7251326ecbeabc3ea39fca8daf21b209943ec35671
def list_cert_bindings(site): "\n List certificate bindings for an IIS site.\n\n .. versionadded:: 2016.11.0\n\n Args:\n site (str): The IIS site name.\n\n Returns:\n dict: A dictionary of the binding names and properties.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.list_bindings site\n " ret = dict() sites = list_sites() if (site not in sites): log.warning('Site not found: %s', site) return ret for binding in sites[site]['bindings']: if sites[site]['bindings'][binding]['certificatehash']: ret[binding] = sites[site]['bindings'][binding] if (not ret): log.warning('No certificate bindings found for site: %s', site) return ret
List certificate bindings for an IIS site. .. versionadded:: 2016.11.0 Args: site (str): The IIS site name. Returns: dict: A dictionary of the binding names and properties. CLI Example: .. code-block:: bash salt '*' win_iis.list_bindings site
salt/modules/win_iis.py
list_cert_bindings
Flowdalic/salt
9,425
python
def list_cert_bindings(site): "\n List certificate bindings for an IIS site.\n\n .. versionadded:: 2016.11.0\n\n Args:\n site (str): The IIS site name.\n\n Returns:\n dict: A dictionary of the binding names and properties.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.list_bindings site\n " ret = dict() sites = list_sites() if (site not in sites): log.warning('Site not found: %s', site) return ret for binding in sites[site]['bindings']: if sites[site]['bindings'][binding]['certificatehash']: ret[binding] = sites[site]['bindings'][binding] if (not ret): log.warning('No certificate bindings found for site: %s', site) return ret
def list_cert_bindings(site): "\n List certificate bindings for an IIS site.\n\n .. versionadded:: 2016.11.0\n\n Args:\n site (str): The IIS site name.\n\n Returns:\n dict: A dictionary of the binding names and properties.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.list_bindings site\n " ret = dict() sites = list_sites() if (site not in sites): log.warning('Site not found: %s', site) return ret for binding in sites[site]['bindings']: if sites[site]['bindings'][binding]['certificatehash']: ret[binding] = sites[site]['bindings'][binding] if (not ret): log.warning('No certificate bindings found for site: %s', site) return ret<|docstring|>List certificate bindings for an IIS site. .. versionadded:: 2016.11.0 Args: site (str): The IIS site name. Returns: dict: A dictionary of the binding names and properties. CLI Example: .. code-block:: bash salt '*' win_iis.list_bindings site<|endoftext|>
49eeb24af8a3c8ce80fa708b40e71a6b9851168e79149530c2710720b4d12c52
def create_cert_binding(name, site, hostheader='', ipaddress='*', port=443, sslflags=0): "\n Assign a certificate to an IIS Web Binding.\n\n .. versionadded:: 2016.11.0\n\n .. note::\n\n The web binding that the certificate is being assigned to must already\n exist.\n\n Args:\n name (str): The thumbprint of the certificate.\n site (str): The IIS site name.\n hostheader (str): The host header of the binding.\n ipaddress (str): The IP address of the binding.\n port (int): The TCP port of the binding.\n sslflags (int): Flags representing certificate type and certificate storage of the binding.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.create_cert_binding name='AAA000' site='site0' hostheader='example.com' ipaddress='*' port='443'\n " name = str(name).upper() binding_info = _get_binding_info(hostheader, ipaddress, port) if (_iisVersion() < 8): binding_info = (binding_info.rpartition(':')[0] + ':') binding_path = 'IIS:\\SslBindings\\{}'.format(binding_info.replace(':', '!')) if (sslflags not in _VALID_SSL_FLAGS): raise SaltInvocationError("Invalid sslflags '{}' specified. Valid sslflags range: {}..{}".format(sslflags, _VALID_SSL_FLAGS[0], _VALID_SSL_FLAGS[(- 1)])) current_bindings = list_bindings(site) if (binding_info not in current_bindings): log.error('Binding not present: %s', binding_info) return False current_name = None for current_binding in current_bindings: if (binding_info == current_binding): current_name = current_bindings[current_binding]['certificatehash'] log.debug('Current certificate thumbprint: %s', current_name) log.debug('New certificate thumbprint: %s', name) if (name == current_name): log.debug('Certificate already present for binding: %s', name) return True certs = _list_certs() if (name not in certs): log.error('Certificate not present: %s', name) return False if (_iisVersion() < 8): iis7path = binding_path.replace('\\*!', '\\0.0.0.0!') if iis7path.endswith('!'): iis7path = iis7path[:(- 1)] ps_cmd = ['New-Item', '-Path', "'{}'".format(iis7path), '-Thumbprint', "'{}'".format(name)] else: ps_cmd = ['New-Item', '-Path', "'{}'".format(binding_path), '-Thumbprint', "'{}'".format(name), '-SSLFlags', '{}'.format(sslflags)] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to create certificate binding: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) new_cert_bindings = list_cert_bindings(site) if (binding_info not in new_cert_bindings): log.error('Binding not present: %s', binding_info) return False if (name == new_cert_bindings[binding_info]['certificatehash']): log.debug('Certificate binding created successfully: %s', name) return True log.error('Unable to create certificate binding: %s', name) return False
Assign a certificate to an IIS Web Binding. .. versionadded:: 2016.11.0 .. note:: The web binding that the certificate is being assigned to must already exist. Args: name (str): The thumbprint of the certificate. site (str): The IIS site name. hostheader (str): The host header of the binding. ipaddress (str): The IP address of the binding. port (int): The TCP port of the binding. sslflags (int): Flags representing certificate type and certificate storage of the binding. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.create_cert_binding name='AAA000' site='site0' hostheader='example.com' ipaddress='*' port='443'
salt/modules/win_iis.py
create_cert_binding
Flowdalic/salt
9,425
python
def create_cert_binding(name, site, hostheader=, ipaddress='*', port=443, sslflags=0): "\n Assign a certificate to an IIS Web Binding.\n\n .. versionadded:: 2016.11.0\n\n .. note::\n\n The web binding that the certificate is being assigned to must already\n exist.\n\n Args:\n name (str): The thumbprint of the certificate.\n site (str): The IIS site name.\n hostheader (str): The host header of the binding.\n ipaddress (str): The IP address of the binding.\n port (int): The TCP port of the binding.\n sslflags (int): Flags representing certificate type and certificate storage of the binding.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.create_cert_binding name='AAA000' site='site0' hostheader='example.com' ipaddress='*' port='443'\n " name = str(name).upper() binding_info = _get_binding_info(hostheader, ipaddress, port) if (_iisVersion() < 8): binding_info = (binding_info.rpartition(':')[0] + ':') binding_path = 'IIS:\\SslBindings\\{}'.format(binding_info.replace(':', '!')) if (sslflags not in _VALID_SSL_FLAGS): raise SaltInvocationError("Invalid sslflags '{}' specified. Valid sslflags range: {}..{}".format(sslflags, _VALID_SSL_FLAGS[0], _VALID_SSL_FLAGS[(- 1)])) current_bindings = list_bindings(site) if (binding_info not in current_bindings): log.error('Binding not present: %s', binding_info) return False current_name = None for current_binding in current_bindings: if (binding_info == current_binding): current_name = current_bindings[current_binding]['certificatehash'] log.debug('Current certificate thumbprint: %s', current_name) log.debug('New certificate thumbprint: %s', name) if (name == current_name): log.debug('Certificate already present for binding: %s', name) return True certs = _list_certs() if (name not in certs): log.error('Certificate not present: %s', name) return False if (_iisVersion() < 8): iis7path = binding_path.replace('\\*!', '\\0.0.0.0!') if iis7path.endswith('!'): iis7path = iis7path[:(- 1)] ps_cmd = ['New-Item', '-Path', "'{}'".format(iis7path), '-Thumbprint', "'{}'".format(name)] else: ps_cmd = ['New-Item', '-Path', "'{}'".format(binding_path), '-Thumbprint', "'{}'".format(name), '-SSLFlags', '{}'.format(sslflags)] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to create certificate binding: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) new_cert_bindings = list_cert_bindings(site) if (binding_info not in new_cert_bindings): log.error('Binding not present: %s', binding_info) return False if (name == new_cert_bindings[binding_info]['certificatehash']): log.debug('Certificate binding created successfully: %s', name) return True log.error('Unable to create certificate binding: %s', name) return False
def create_cert_binding(name, site, hostheader=, ipaddress='*', port=443, sslflags=0): "\n Assign a certificate to an IIS Web Binding.\n\n .. versionadded:: 2016.11.0\n\n .. note::\n\n The web binding that the certificate is being assigned to must already\n exist.\n\n Args:\n name (str): The thumbprint of the certificate.\n site (str): The IIS site name.\n hostheader (str): The host header of the binding.\n ipaddress (str): The IP address of the binding.\n port (int): The TCP port of the binding.\n sslflags (int): Flags representing certificate type and certificate storage of the binding.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.create_cert_binding name='AAA000' site='site0' hostheader='example.com' ipaddress='*' port='443'\n " name = str(name).upper() binding_info = _get_binding_info(hostheader, ipaddress, port) if (_iisVersion() < 8): binding_info = (binding_info.rpartition(':')[0] + ':') binding_path = 'IIS:\\SslBindings\\{}'.format(binding_info.replace(':', '!')) if (sslflags not in _VALID_SSL_FLAGS): raise SaltInvocationError("Invalid sslflags '{}' specified. Valid sslflags range: {}..{}".format(sslflags, _VALID_SSL_FLAGS[0], _VALID_SSL_FLAGS[(- 1)])) current_bindings = list_bindings(site) if (binding_info not in current_bindings): log.error('Binding not present: %s', binding_info) return False current_name = None for current_binding in current_bindings: if (binding_info == current_binding): current_name = current_bindings[current_binding]['certificatehash'] log.debug('Current certificate thumbprint: %s', current_name) log.debug('New certificate thumbprint: %s', name) if (name == current_name): log.debug('Certificate already present for binding: %s', name) return True certs = _list_certs() if (name not in certs): log.error('Certificate not present: %s', name) return False if (_iisVersion() < 8): iis7path = binding_path.replace('\\*!', '\\0.0.0.0!') if iis7path.endswith('!'): iis7path = iis7path[:(- 1)] ps_cmd = ['New-Item', '-Path', "'{}'".format(iis7path), '-Thumbprint', "'{}'".format(name)] else: ps_cmd = ['New-Item', '-Path', "'{}'".format(binding_path), '-Thumbprint', "'{}'".format(name), '-SSLFlags', '{}'.format(sslflags)] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to create certificate binding: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) new_cert_bindings = list_cert_bindings(site) if (binding_info not in new_cert_bindings): log.error('Binding not present: %s', binding_info) return False if (name == new_cert_bindings[binding_info]['certificatehash']): log.debug('Certificate binding created successfully: %s', name) return True log.error('Unable to create certificate binding: %s', name) return False<|docstring|>Assign a certificate to an IIS Web Binding. .. versionadded:: 2016.11.0 .. note:: The web binding that the certificate is being assigned to must already exist. Args: name (str): The thumbprint of the certificate. site (str): The IIS site name. hostheader (str): The host header of the binding. ipaddress (str): The IP address of the binding. port (int): The TCP port of the binding. sslflags (int): Flags representing certificate type and certificate storage of the binding. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.create_cert_binding name='AAA000' site='site0' hostheader='example.com' ipaddress='*' port='443'<|endoftext|>
6cb44aa2bb4ae031b9c26b057e9aec22004ca964dfcffbb4ea44aaa93daac1ce
def remove_cert_binding(name, site, hostheader='', ipaddress='*', port=443): "\n Remove a certificate from an IIS Web Binding.\n\n .. versionadded:: 2016.11.0\n\n .. note::\n\n This function only removes the certificate from the web binding. It does\n not remove the web binding itself.\n\n Args:\n name (str): The thumbprint of the certificate.\n site (str): The IIS site name.\n hostheader (str): The host header of the binding.\n ipaddress (str): The IP address of the binding.\n port (int): The TCP port of the binding.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.remove_cert_binding name='AAA000' site='site0' hostheader='example.com' ipaddress='*' port='443'\n " name = str(name).upper() binding_info = _get_binding_info(hostheader, ipaddress, port) ps_cmd = ['$Site = Get-ChildItem', '-Path', "'IIS:\\Sites'", '|', 'Where-Object', " {{ $_.Name -Eq '{0}' }};".format(site), '$Binding = $Site.Bindings.Collection', '| Where-Object { $_.bindingInformation', "-Eq '{0}' }};".format(binding_info), '$Binding.RemoveSslCertificate()'] current_cert_bindings = list_cert_bindings(site) if (binding_info not in current_cert_bindings): log.warning('Binding not found: %s', binding_info) return True if (name != current_cert_bindings[binding_info]['certificatehash']): log.debug('Certificate binding already absent: %s', name) return True cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to remove certificate binding: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) new_cert_bindings = list_cert_bindings(site) if (binding_info not in new_cert_bindings): log.warning('Binding not found: %s', binding_info) return True if (name != new_cert_bindings[binding_info]['certificatehash']): log.debug('Certificate binding removed successfully: %s', name) return True log.error('Unable to remove certificate binding: %s', name) return False
Remove a certificate from an IIS Web Binding. .. versionadded:: 2016.11.0 .. note:: This function only removes the certificate from the web binding. It does not remove the web binding itself. Args: name (str): The thumbprint of the certificate. site (str): The IIS site name. hostheader (str): The host header of the binding. ipaddress (str): The IP address of the binding. port (int): The TCP port of the binding. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.remove_cert_binding name='AAA000' site='site0' hostheader='example.com' ipaddress='*' port='443'
salt/modules/win_iis.py
remove_cert_binding
Flowdalic/salt
9,425
python
def remove_cert_binding(name, site, hostheader=, ipaddress='*', port=443): "\n Remove a certificate from an IIS Web Binding.\n\n .. versionadded:: 2016.11.0\n\n .. note::\n\n This function only removes the certificate from the web binding. It does\n not remove the web binding itself.\n\n Args:\n name (str): The thumbprint of the certificate.\n site (str): The IIS site name.\n hostheader (str): The host header of the binding.\n ipaddress (str): The IP address of the binding.\n port (int): The TCP port of the binding.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.remove_cert_binding name='AAA000' site='site0' hostheader='example.com' ipaddress='*' port='443'\n " name = str(name).upper() binding_info = _get_binding_info(hostheader, ipaddress, port) ps_cmd = ['$Site = Get-ChildItem', '-Path', "'IIS:\\Sites'", '|', 'Where-Object', " {{ $_.Name -Eq '{0}' }};".format(site), '$Binding = $Site.Bindings.Collection', '| Where-Object { $_.bindingInformation', "-Eq '{0}' }};".format(binding_info), '$Binding.RemoveSslCertificate()'] current_cert_bindings = list_cert_bindings(site) if (binding_info not in current_cert_bindings): log.warning('Binding not found: %s', binding_info) return True if (name != current_cert_bindings[binding_info]['certificatehash']): log.debug('Certificate binding already absent: %s', name) return True cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to remove certificate binding: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) new_cert_bindings = list_cert_bindings(site) if (binding_info not in new_cert_bindings): log.warning('Binding not found: %s', binding_info) return True if (name != new_cert_bindings[binding_info]['certificatehash']): log.debug('Certificate binding removed successfully: %s', name) return True log.error('Unable to remove certificate binding: %s', name) return False
def remove_cert_binding(name, site, hostheader=, ipaddress='*', port=443): "\n Remove a certificate from an IIS Web Binding.\n\n .. versionadded:: 2016.11.0\n\n .. note::\n\n This function only removes the certificate from the web binding. It does\n not remove the web binding itself.\n\n Args:\n name (str): The thumbprint of the certificate.\n site (str): The IIS site name.\n hostheader (str): The host header of the binding.\n ipaddress (str): The IP address of the binding.\n port (int): The TCP port of the binding.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.remove_cert_binding name='AAA000' site='site0' hostheader='example.com' ipaddress='*' port='443'\n " name = str(name).upper() binding_info = _get_binding_info(hostheader, ipaddress, port) ps_cmd = ['$Site = Get-ChildItem', '-Path', "'IIS:\\Sites'", '|', 'Where-Object', " {{ $_.Name -Eq '{0}' }};".format(site), '$Binding = $Site.Bindings.Collection', '| Where-Object { $_.bindingInformation', "-Eq '{0}' }};".format(binding_info), '$Binding.RemoveSslCertificate()'] current_cert_bindings = list_cert_bindings(site) if (binding_info not in current_cert_bindings): log.warning('Binding not found: %s', binding_info) return True if (name != current_cert_bindings[binding_info]['certificatehash']): log.debug('Certificate binding already absent: %s', name) return True cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to remove certificate binding: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) new_cert_bindings = list_cert_bindings(site) if (binding_info not in new_cert_bindings): log.warning('Binding not found: %s', binding_info) return True if (name != new_cert_bindings[binding_info]['certificatehash']): log.debug('Certificate binding removed successfully: %s', name) return True log.error('Unable to remove certificate binding: %s', name) return False<|docstring|>Remove a certificate from an IIS Web Binding. .. versionadded:: 2016.11.0 .. note:: This function only removes the certificate from the web binding. It does not remove the web binding itself. Args: name (str): The thumbprint of the certificate. site (str): The IIS site name. hostheader (str): The host header of the binding. ipaddress (str): The IP address of the binding. port (int): The TCP port of the binding. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.remove_cert_binding name='AAA000' site='site0' hostheader='example.com' ipaddress='*' port='443'<|endoftext|>
c77d8fcf37a2aeec8166064d8fc3bc6c822d450c598808873c60cf6856fa9c6e
def list_apppools(): "\n List all configured IIS application pools.\n\n Returns:\n dict: A dictionary of IIS application pools and their details.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.list_apppools\n " ret = dict() ps_cmd = [] ps_cmd.append("Get-ChildItem -Path 'IIS:\\AppPools' | Select-Object Name, State") ps_cmd.append(", @{ Name = 'Applications'; Expression = { $AppPool = $_.Name;") ps_cmd.append("$AppPath = 'machine/webroot/apphost';") ps_cmd.append("$FilterBase = '/system.applicationHost/sites/site/application';") ps_cmd.append('$FilterBase += "[@applicationPool = \'$($AppPool)\' and @path";') ps_cmd.append('$FilterRoot = "$($FilterBase) = \'/\']/parent::*";') ps_cmd.append('$FilterNonRoot = "$($FilterBase) != \'/\']";') ps_cmd.append('Get-WebConfigurationProperty -Filter $FilterRoot -PsPath $AppPath -Name Name') ps_cmd.append('| ForEach-Object { $_.Value };') ps_cmd.append('Get-WebConfigurationProperty -Filter $FilterNonRoot -PsPath $AppPath -Name Path') ps_cmd.append("| ForEach-Object { $_.Value } | Where-Object { $_ -ne '/' }") ps_cmd.append('} }') cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True) try: items = salt.utils.json.loads(cmd_ret['stdout'], strict=False) except ValueError: raise CommandExecutionError('Unable to parse return data as Json.') for item in items: applications = list() if isinstance(item['Applications'], dict): if ('value' in item['Applications']): applications += item['Applications']['value'] else: applications.append(item['Applications']) ret[item['name']] = {'state': item['state'], 'applications': applications} if (not ret): log.warning('No application pools found in output: %s', cmd_ret['stdout']) return ret
List all configured IIS application pools. Returns: dict: A dictionary of IIS application pools and their details. CLI Example: .. code-block:: bash salt '*' win_iis.list_apppools
salt/modules/win_iis.py
list_apppools
Flowdalic/salt
9,425
python
def list_apppools(): "\n List all configured IIS application pools.\n\n Returns:\n dict: A dictionary of IIS application pools and their details.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.list_apppools\n " ret = dict() ps_cmd = [] ps_cmd.append("Get-ChildItem -Path 'IIS:\\AppPools' | Select-Object Name, State") ps_cmd.append(", @{ Name = 'Applications'; Expression = { $AppPool = $_.Name;") ps_cmd.append("$AppPath = 'machine/webroot/apphost';") ps_cmd.append("$FilterBase = '/system.applicationHost/sites/site/application';") ps_cmd.append('$FilterBase += "[@applicationPool = \'$($AppPool)\' and @path";') ps_cmd.append('$FilterRoot = "$($FilterBase) = \'/\']/parent::*";') ps_cmd.append('$FilterNonRoot = "$($FilterBase) != \'/\']";') ps_cmd.append('Get-WebConfigurationProperty -Filter $FilterRoot -PsPath $AppPath -Name Name') ps_cmd.append('| ForEach-Object { $_.Value };') ps_cmd.append('Get-WebConfigurationProperty -Filter $FilterNonRoot -PsPath $AppPath -Name Path') ps_cmd.append("| ForEach-Object { $_.Value } | Where-Object { $_ -ne '/' }") ps_cmd.append('} }') cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True) try: items = salt.utils.json.loads(cmd_ret['stdout'], strict=False) except ValueError: raise CommandExecutionError('Unable to parse return data as Json.') for item in items: applications = list() if isinstance(item['Applications'], dict): if ('value' in item['Applications']): applications += item['Applications']['value'] else: applications.append(item['Applications']) ret[item['name']] = {'state': item['state'], 'applications': applications} if (not ret): log.warning('No application pools found in output: %s', cmd_ret['stdout']) return ret
def list_apppools(): "\n List all configured IIS application pools.\n\n Returns:\n dict: A dictionary of IIS application pools and their details.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.list_apppools\n " ret = dict() ps_cmd = [] ps_cmd.append("Get-ChildItem -Path 'IIS:\\AppPools' | Select-Object Name, State") ps_cmd.append(", @{ Name = 'Applications'; Expression = { $AppPool = $_.Name;") ps_cmd.append("$AppPath = 'machine/webroot/apphost';") ps_cmd.append("$FilterBase = '/system.applicationHost/sites/site/application';") ps_cmd.append('$FilterBase += "[@applicationPool = \'$($AppPool)\' and @path";') ps_cmd.append('$FilterRoot = "$($FilterBase) = \'/\']/parent::*";') ps_cmd.append('$FilterNonRoot = "$($FilterBase) != \'/\']";') ps_cmd.append('Get-WebConfigurationProperty -Filter $FilterRoot -PsPath $AppPath -Name Name') ps_cmd.append('| ForEach-Object { $_.Value };') ps_cmd.append('Get-WebConfigurationProperty -Filter $FilterNonRoot -PsPath $AppPath -Name Path') ps_cmd.append("| ForEach-Object { $_.Value } | Where-Object { $_ -ne '/' }") ps_cmd.append('} }') cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True) try: items = salt.utils.json.loads(cmd_ret['stdout'], strict=False) except ValueError: raise CommandExecutionError('Unable to parse return data as Json.') for item in items: applications = list() if isinstance(item['Applications'], dict): if ('value' in item['Applications']): applications += item['Applications']['value'] else: applications.append(item['Applications']) ret[item['name']] = {'state': item['state'], 'applications': applications} if (not ret): log.warning('No application pools found in output: %s', cmd_ret['stdout']) return ret<|docstring|>List all configured IIS application pools. Returns: dict: A dictionary of IIS application pools and their details. CLI Example: .. code-block:: bash salt '*' win_iis.list_apppools<|endoftext|>
242c467b49786594f1050ddedb982511a435a9261d99df48b239211ad9f7a4e0
def create_apppool(name): "\n Create an IIS application pool.\n\n .. note::\n\n This function only validates against the application pool name, and will\n return True even if the application pool already exists with a different\n configuration. It will not modify the configuration of an existing\n application pool.\n\n Args:\n name (str): The name of the IIS application pool.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.create_apppool name='MyTestPool'\n " current_apppools = list_apppools() apppool_path = 'IIS:\\AppPools\\{}'.format(name) if (name in current_apppools): log.debug("Application pool '%s' already present.", name) return True ps_cmd = ['New-Item', '-Path', "'{}'".format(apppool_path)] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to create application pool: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) log.debug('Application pool created successfully: %s', name) return True
Create an IIS application pool. .. note:: This function only validates against the application pool name, and will return True even if the application pool already exists with a different configuration. It will not modify the configuration of an existing application pool. Args: name (str): The name of the IIS application pool. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.create_apppool name='MyTestPool'
salt/modules/win_iis.py
create_apppool
Flowdalic/salt
9,425
python
def create_apppool(name): "\n Create an IIS application pool.\n\n .. note::\n\n This function only validates against the application pool name, and will\n return True even if the application pool already exists with a different\n configuration. It will not modify the configuration of an existing\n application pool.\n\n Args:\n name (str): The name of the IIS application pool.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.create_apppool name='MyTestPool'\n " current_apppools = list_apppools() apppool_path = 'IIS:\\AppPools\\{}'.format(name) if (name in current_apppools): log.debug("Application pool '%s' already present.", name) return True ps_cmd = ['New-Item', '-Path', "'{}'".format(apppool_path)] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to create application pool: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) log.debug('Application pool created successfully: %s', name) return True
def create_apppool(name): "\n Create an IIS application pool.\n\n .. note::\n\n This function only validates against the application pool name, and will\n return True even if the application pool already exists with a different\n configuration. It will not modify the configuration of an existing\n application pool.\n\n Args:\n name (str): The name of the IIS application pool.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.create_apppool name='MyTestPool'\n " current_apppools = list_apppools() apppool_path = 'IIS:\\AppPools\\{}'.format(name) if (name in current_apppools): log.debug("Application pool '%s' already present.", name) return True ps_cmd = ['New-Item', '-Path', "'{}'".format(apppool_path)] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to create application pool: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) log.debug('Application pool created successfully: %s', name) return True<|docstring|>Create an IIS application pool. .. note:: This function only validates against the application pool name, and will return True even if the application pool already exists with a different configuration. It will not modify the configuration of an existing application pool. Args: name (str): The name of the IIS application pool. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.create_apppool name='MyTestPool'<|endoftext|>
072865bb53aab48265aedbd26cc49a7172535b2e035a232c138ec254c1d756cd
def remove_apppool(name): "\n Remove an IIS application pool.\n\n Args:\n name (str): The name of the IIS application pool.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.remove_apppool name='MyTestPool'\n " current_apppools = list_apppools() apppool_path = 'IIS:\\AppPools\\{}'.format(name) if (name not in current_apppools): log.debug('Application pool already absent: %s', name) return True ps_cmd = ['Remove-Item', '-Path', "'{}'".format(apppool_path), '-Recurse'] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to remove application pool: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) log.debug('Application pool removed successfully: %s', name) return True
Remove an IIS application pool. Args: name (str): The name of the IIS application pool. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.remove_apppool name='MyTestPool'
salt/modules/win_iis.py
remove_apppool
Flowdalic/salt
9,425
python
def remove_apppool(name): "\n Remove an IIS application pool.\n\n Args:\n name (str): The name of the IIS application pool.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.remove_apppool name='MyTestPool'\n " current_apppools = list_apppools() apppool_path = 'IIS:\\AppPools\\{}'.format(name) if (name not in current_apppools): log.debug('Application pool already absent: %s', name) return True ps_cmd = ['Remove-Item', '-Path', "'{}'".format(apppool_path), '-Recurse'] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to remove application pool: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) log.debug('Application pool removed successfully: %s', name) return True
def remove_apppool(name): "\n Remove an IIS application pool.\n\n Args:\n name (str): The name of the IIS application pool.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.remove_apppool name='MyTestPool'\n " current_apppools = list_apppools() apppool_path = 'IIS:\\AppPools\\{}'.format(name) if (name not in current_apppools): log.debug('Application pool already absent: %s', name) return True ps_cmd = ['Remove-Item', '-Path', "'{}'".format(apppool_path), '-Recurse'] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to remove application pool: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) log.debug('Application pool removed successfully: %s', name) return True<|docstring|>Remove an IIS application pool. Args: name (str): The name of the IIS application pool. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.remove_apppool name='MyTestPool'<|endoftext|>
10affa9017fe5198ba79b926b0e0e9df2ae883abe1970302b88485327572d854
def stop_apppool(name): "\n Stop an IIS application pool.\n\n .. versionadded:: 2017.7.0\n\n Args:\n name (str): The name of the App Pool to stop.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.stop_apppool name='MyTestPool'\n " ps_cmd = ['Stop-WebAppPool', "'{}'".format(name)] cmd_ret = _srvmgr(ps_cmd) return (cmd_ret['retcode'] == 0)
Stop an IIS application pool. .. versionadded:: 2017.7.0 Args: name (str): The name of the App Pool to stop. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.stop_apppool name='MyTestPool'
salt/modules/win_iis.py
stop_apppool
Flowdalic/salt
9,425
python
def stop_apppool(name): "\n Stop an IIS application pool.\n\n .. versionadded:: 2017.7.0\n\n Args:\n name (str): The name of the App Pool to stop.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.stop_apppool name='MyTestPool'\n " ps_cmd = ['Stop-WebAppPool', "'{}'".format(name)] cmd_ret = _srvmgr(ps_cmd) return (cmd_ret['retcode'] == 0)
def stop_apppool(name): "\n Stop an IIS application pool.\n\n .. versionadded:: 2017.7.0\n\n Args:\n name (str): The name of the App Pool to stop.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.stop_apppool name='MyTestPool'\n " ps_cmd = ['Stop-WebAppPool', "'{}'".format(name)] cmd_ret = _srvmgr(ps_cmd) return (cmd_ret['retcode'] == 0)<|docstring|>Stop an IIS application pool. .. versionadded:: 2017.7.0 Args: name (str): The name of the App Pool to stop. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.stop_apppool name='MyTestPool'<|endoftext|>
ec4112aae8c4385b3dce4d69df43df19d97a7c39225c47e405b2a58412228c50
def start_apppool(name): "\n Start an IIS application pool.\n\n .. versionadded:: 2017.7.0\n\n Args:\n name (str): The name of the App Pool to start.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.start_apppool name='MyTestPool'\n " ps_cmd = ['Start-WebAppPool', "'{}'".format(name)] cmd_ret = _srvmgr(ps_cmd) return (cmd_ret['retcode'] == 0)
Start an IIS application pool. .. versionadded:: 2017.7.0 Args: name (str): The name of the App Pool to start. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.start_apppool name='MyTestPool'
salt/modules/win_iis.py
start_apppool
Flowdalic/salt
9,425
python
def start_apppool(name): "\n Start an IIS application pool.\n\n .. versionadded:: 2017.7.0\n\n Args:\n name (str): The name of the App Pool to start.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.start_apppool name='MyTestPool'\n " ps_cmd = ['Start-WebAppPool', "'{}'".format(name)] cmd_ret = _srvmgr(ps_cmd) return (cmd_ret['retcode'] == 0)
def start_apppool(name): "\n Start an IIS application pool.\n\n .. versionadded:: 2017.7.0\n\n Args:\n name (str): The name of the App Pool to start.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.start_apppool name='MyTestPool'\n " ps_cmd = ['Start-WebAppPool', "'{}'".format(name)] cmd_ret = _srvmgr(ps_cmd) return (cmd_ret['retcode'] == 0)<|docstring|>Start an IIS application pool. .. versionadded:: 2017.7.0 Args: name (str): The name of the App Pool to start. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.start_apppool name='MyTestPool'<|endoftext|>
ac1dfd342b8ce01c503eea11bb9c9d0cecff9f5531d0abb6782f9610e898e18b
def restart_apppool(name): "\n Restart an IIS application pool.\n\n .. versionadded:: 2016.11.0\n\n Args:\n name (str): The name of the IIS application pool.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.restart_apppool name='MyTestPool'\n " ps_cmd = ['Restart-WebAppPool', "'{}'".format(name)] cmd_ret = _srvmgr(ps_cmd) return (cmd_ret['retcode'] == 0)
Restart an IIS application pool. .. versionadded:: 2016.11.0 Args: name (str): The name of the IIS application pool. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.restart_apppool name='MyTestPool'
salt/modules/win_iis.py
restart_apppool
Flowdalic/salt
9,425
python
def restart_apppool(name): "\n Restart an IIS application pool.\n\n .. versionadded:: 2016.11.0\n\n Args:\n name (str): The name of the IIS application pool.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.restart_apppool name='MyTestPool'\n " ps_cmd = ['Restart-WebAppPool', "'{}'".format(name)] cmd_ret = _srvmgr(ps_cmd) return (cmd_ret['retcode'] == 0)
def restart_apppool(name): "\n Restart an IIS application pool.\n\n .. versionadded:: 2016.11.0\n\n Args:\n name (str): The name of the IIS application pool.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.restart_apppool name='MyTestPool'\n " ps_cmd = ['Restart-WebAppPool', "'{}'".format(name)] cmd_ret = _srvmgr(ps_cmd) return (cmd_ret['retcode'] == 0)<|docstring|>Restart an IIS application pool. .. versionadded:: 2016.11.0 Args: name (str): The name of the IIS application pool. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.restart_apppool name='MyTestPool'<|endoftext|>
14f01df3a09a19cc6cf4742c2bbda64a12890f7c2396905153d17e9712741248
def get_container_setting(name, container, settings): '\n Get the value of the setting for the IIS container.\n\n .. versionadded:: 2016.11.0\n\n Args:\n name (str): The name of the IIS container.\n container (str): The type of IIS container. The container types are:\n AppPools, Sites, SslBindings\n settings (dict): A dictionary of the setting names and their values.\n\n Returns:\n dict: A dictionary of the provided settings and their values.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt \'*\' win_iis.get_container_setting name=\'MyTestPool\' container=\'AppPools\'\n settings="[\'processModel.identityType\']"\n ' ret = dict() ps_cmd = list() ps_cmd_validate = list() container_path = 'IIS:\\{}\\{}'.format(container, name) if (not settings): log.warning('No settings provided') return ret ps_cmd.append('$Settings = @{};') for setting in settings: ps_cmd_validate.extend(['Get-ItemProperty', '-Path', "'{}'".format(container_path), '-Name', "'{}'".format(setting), '-ErrorAction', 'Stop', '|', 'Out-Null;']) ps_cmd.append("$Property = Get-ItemProperty -Path '{}'".format(container_path)) ps_cmd.append("-Name '{}' -ErrorAction Stop;".format(setting)) ps_cmd.append('if (([String]::IsNullOrEmpty($Property) -eq $False) -and') ps_cmd.append("($Property.GetType()).Name -eq 'ConfigurationAttribute') {") ps_cmd.append('$Property = $Property | Select-Object') ps_cmd.append('-ExpandProperty Value };') ps_cmd.append("$Settings['{}'] = [String] $Property;".format(setting)) ps_cmd.append('$Property = $Null;') cmd_ret = _srvmgr(cmd=ps_cmd_validate, return_json=True) if (cmd_ret['retcode'] != 0): message = 'One or more invalid property names were specified for the provided container.' raise SaltInvocationError(message) ps_cmd.append('$Settings') cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True) try: items = salt.utils.json.loads(cmd_ret['stdout'], strict=False) if isinstance(items, list): ret.update(items[0]) else: ret.update(items) except ValueError: raise CommandExecutionError('Unable to parse return data as Json.') return ret
Get the value of the setting for the IIS container. .. versionadded:: 2016.11.0 Args: name (str): The name of the IIS container. container (str): The type of IIS container. The container types are: AppPools, Sites, SslBindings settings (dict): A dictionary of the setting names and their values. Returns: dict: A dictionary of the provided settings and their values. CLI Example: .. code-block:: bash salt '*' win_iis.get_container_setting name='MyTestPool' container='AppPools' settings="['processModel.identityType']"
salt/modules/win_iis.py
get_container_setting
Flowdalic/salt
9,425
python
def get_container_setting(name, container, settings): '\n Get the value of the setting for the IIS container.\n\n .. versionadded:: 2016.11.0\n\n Args:\n name (str): The name of the IIS container.\n container (str): The type of IIS container. The container types are:\n AppPools, Sites, SslBindings\n settings (dict): A dictionary of the setting names and their values.\n\n Returns:\n dict: A dictionary of the provided settings and their values.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt \'*\' win_iis.get_container_setting name=\'MyTestPool\' container=\'AppPools\'\n settings="[\'processModel.identityType\']"\n ' ret = dict() ps_cmd = list() ps_cmd_validate = list() container_path = 'IIS:\\{}\\{}'.format(container, name) if (not settings): log.warning('No settings provided') return ret ps_cmd.append('$Settings = @{};') for setting in settings: ps_cmd_validate.extend(['Get-ItemProperty', '-Path', "'{}'".format(container_path), '-Name', "'{}'".format(setting), '-ErrorAction', 'Stop', '|', 'Out-Null;']) ps_cmd.append("$Property = Get-ItemProperty -Path '{}'".format(container_path)) ps_cmd.append("-Name '{}' -ErrorAction Stop;".format(setting)) ps_cmd.append('if (([String]::IsNullOrEmpty($Property) -eq $False) -and') ps_cmd.append("($Property.GetType()).Name -eq 'ConfigurationAttribute') {") ps_cmd.append('$Property = $Property | Select-Object') ps_cmd.append('-ExpandProperty Value };') ps_cmd.append("$Settings['{}'] = [String] $Property;".format(setting)) ps_cmd.append('$Property = $Null;') cmd_ret = _srvmgr(cmd=ps_cmd_validate, return_json=True) if (cmd_ret['retcode'] != 0): message = 'One or more invalid property names were specified for the provided container.' raise SaltInvocationError(message) ps_cmd.append('$Settings') cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True) try: items = salt.utils.json.loads(cmd_ret['stdout'], strict=False) if isinstance(items, list): ret.update(items[0]) else: ret.update(items) except ValueError: raise CommandExecutionError('Unable to parse return data as Json.') return ret
def get_container_setting(name, container, settings): '\n Get the value of the setting for the IIS container.\n\n .. versionadded:: 2016.11.0\n\n Args:\n name (str): The name of the IIS container.\n container (str): The type of IIS container. The container types are:\n AppPools, Sites, SslBindings\n settings (dict): A dictionary of the setting names and their values.\n\n Returns:\n dict: A dictionary of the provided settings and their values.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt \'*\' win_iis.get_container_setting name=\'MyTestPool\' container=\'AppPools\'\n settings="[\'processModel.identityType\']"\n ' ret = dict() ps_cmd = list() ps_cmd_validate = list() container_path = 'IIS:\\{}\\{}'.format(container, name) if (not settings): log.warning('No settings provided') return ret ps_cmd.append('$Settings = @{};') for setting in settings: ps_cmd_validate.extend(['Get-ItemProperty', '-Path', "'{}'".format(container_path), '-Name', "'{}'".format(setting), '-ErrorAction', 'Stop', '|', 'Out-Null;']) ps_cmd.append("$Property = Get-ItemProperty -Path '{}'".format(container_path)) ps_cmd.append("-Name '{}' -ErrorAction Stop;".format(setting)) ps_cmd.append('if (([String]::IsNullOrEmpty($Property) -eq $False) -and') ps_cmd.append("($Property.GetType()).Name -eq 'ConfigurationAttribute') {") ps_cmd.append('$Property = $Property | Select-Object') ps_cmd.append('-ExpandProperty Value };') ps_cmd.append("$Settings['{}'] = [String] $Property;".format(setting)) ps_cmd.append('$Property = $Null;') cmd_ret = _srvmgr(cmd=ps_cmd_validate, return_json=True) if (cmd_ret['retcode'] != 0): message = 'One or more invalid property names were specified for the provided container.' raise SaltInvocationError(message) ps_cmd.append('$Settings') cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True) try: items = salt.utils.json.loads(cmd_ret['stdout'], strict=False) if isinstance(items, list): ret.update(items[0]) else: ret.update(items) except ValueError: raise CommandExecutionError('Unable to parse return data as Json.') return ret<|docstring|>Get the value of the setting for the IIS container. .. versionadded:: 2016.11.0 Args: name (str): The name of the IIS container. container (str): The type of IIS container. The container types are: AppPools, Sites, SslBindings settings (dict): A dictionary of the setting names and their values. Returns: dict: A dictionary of the provided settings and their values. CLI Example: .. code-block:: bash salt '*' win_iis.get_container_setting name='MyTestPool' container='AppPools' settings="['processModel.identityType']"<|endoftext|>
5946d90d22fcf52ea8ee23f1427efca8802da83585987592f266205ffe49056a
def set_container_setting(name, container, settings): '\n Set the value of the setting for an IIS container.\n\n .. versionadded:: 2016.11.0\n\n Args:\n name (str): The name of the IIS container.\n container (str): The type of IIS container. The container types are:\n AppPools, Sites, SslBindings\n settings (dict): A dictionary of the setting names and their values.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt \'*\' win_iis.set_container_setting name=\'MyTestPool\' container=\'AppPools\'\n settings="{\'managedPipeLineMode\': \'Integrated\'}"\n ' identityType_map2string = {'0': 'LocalSystem', '1': 'LocalService', '2': 'NetworkService', '3': 'SpecificUser', '4': 'ApplicationPoolIdentity'} identityType_map2numeric = {'LocalSystem': '0', 'LocalService': '1', 'NetworkService': '2', 'SpecificUser': '3', 'ApplicationPoolIdentity': '4'} ps_cmd = list() container_path = 'IIS:\\{}\\{}'.format(container, name) if (not settings): log.warning('No settings provided') return False for setting in settings: settings[setting] = str(settings[setting]) current_settings = get_container_setting(name=name, container=container, settings=settings.keys()) if (settings == current_settings): log.debug('Settings already contain the provided values.') return True for setting in settings: try: complex(settings[setting]) value = settings[setting] except ValueError: value = "'{}'".format(settings[setting]) if ((setting == 'processModel.identityType') and (settings[setting] in identityType_map2numeric.keys())): value = identityType_map2numeric[settings[setting]] ps_cmd.extend(['Set-ItemProperty', '-Path', "'{}'".format(container_path), '-Name', "'{}'".format(setting), '-Value', '{};'.format(value)]) cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to set settings for {}: {}'.format(container, name) raise CommandExecutionError(msg) new_settings = get_container_setting(name=name, container=container, settings=settings.keys()) failed_settings = dict() for setting in settings: if ((setting == 'processModel.identityType') and (settings[setting] in identityType_map2string.keys())): settings[setting] = identityType_map2string[settings[setting]] if (str(settings[setting]) != str(new_settings[setting])): failed_settings[setting] = settings[setting] if failed_settings: log.error('Failed to change settings: %s', failed_settings) return False log.debug('Settings configured successfully: %s', settings.keys()) return True
Set the value of the setting for an IIS container. .. versionadded:: 2016.11.0 Args: name (str): The name of the IIS container. container (str): The type of IIS container. The container types are: AppPools, Sites, SslBindings settings (dict): A dictionary of the setting names and their values. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.set_container_setting name='MyTestPool' container='AppPools' settings="{'managedPipeLineMode': 'Integrated'}"
salt/modules/win_iis.py
set_container_setting
Flowdalic/salt
9,425
python
def set_container_setting(name, container, settings): '\n Set the value of the setting for an IIS container.\n\n .. versionadded:: 2016.11.0\n\n Args:\n name (str): The name of the IIS container.\n container (str): The type of IIS container. The container types are:\n AppPools, Sites, SslBindings\n settings (dict): A dictionary of the setting names and their values.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt \'*\' win_iis.set_container_setting name=\'MyTestPool\' container=\'AppPools\'\n settings="{\'managedPipeLineMode\': \'Integrated\'}"\n ' identityType_map2string = {'0': 'LocalSystem', '1': 'LocalService', '2': 'NetworkService', '3': 'SpecificUser', '4': 'ApplicationPoolIdentity'} identityType_map2numeric = {'LocalSystem': '0', 'LocalService': '1', 'NetworkService': '2', 'SpecificUser': '3', 'ApplicationPoolIdentity': '4'} ps_cmd = list() container_path = 'IIS:\\{}\\{}'.format(container, name) if (not settings): log.warning('No settings provided') return False for setting in settings: settings[setting] = str(settings[setting]) current_settings = get_container_setting(name=name, container=container, settings=settings.keys()) if (settings == current_settings): log.debug('Settings already contain the provided values.') return True for setting in settings: try: complex(settings[setting]) value = settings[setting] except ValueError: value = "'{}'".format(settings[setting]) if ((setting == 'processModel.identityType') and (settings[setting] in identityType_map2numeric.keys())): value = identityType_map2numeric[settings[setting]] ps_cmd.extend(['Set-ItemProperty', '-Path', "'{}'".format(container_path), '-Name', "'{}'".format(setting), '-Value', '{};'.format(value)]) cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to set settings for {}: {}'.format(container, name) raise CommandExecutionError(msg) new_settings = get_container_setting(name=name, container=container, settings=settings.keys()) failed_settings = dict() for setting in settings: if ((setting == 'processModel.identityType') and (settings[setting] in identityType_map2string.keys())): settings[setting] = identityType_map2string[settings[setting]] if (str(settings[setting]) != str(new_settings[setting])): failed_settings[setting] = settings[setting] if failed_settings: log.error('Failed to change settings: %s', failed_settings) return False log.debug('Settings configured successfully: %s', settings.keys()) return True
def set_container_setting(name, container, settings): '\n Set the value of the setting for an IIS container.\n\n .. versionadded:: 2016.11.0\n\n Args:\n name (str): The name of the IIS container.\n container (str): The type of IIS container. The container types are:\n AppPools, Sites, SslBindings\n settings (dict): A dictionary of the setting names and their values.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt \'*\' win_iis.set_container_setting name=\'MyTestPool\' container=\'AppPools\'\n settings="{\'managedPipeLineMode\': \'Integrated\'}"\n ' identityType_map2string = {'0': 'LocalSystem', '1': 'LocalService', '2': 'NetworkService', '3': 'SpecificUser', '4': 'ApplicationPoolIdentity'} identityType_map2numeric = {'LocalSystem': '0', 'LocalService': '1', 'NetworkService': '2', 'SpecificUser': '3', 'ApplicationPoolIdentity': '4'} ps_cmd = list() container_path = 'IIS:\\{}\\{}'.format(container, name) if (not settings): log.warning('No settings provided') return False for setting in settings: settings[setting] = str(settings[setting]) current_settings = get_container_setting(name=name, container=container, settings=settings.keys()) if (settings == current_settings): log.debug('Settings already contain the provided values.') return True for setting in settings: try: complex(settings[setting]) value = settings[setting] except ValueError: value = "'{}'".format(settings[setting]) if ((setting == 'processModel.identityType') and (settings[setting] in identityType_map2numeric.keys())): value = identityType_map2numeric[settings[setting]] ps_cmd.extend(['Set-ItemProperty', '-Path', "'{}'".format(container_path), '-Name', "'{}'".format(setting), '-Value', '{};'.format(value)]) cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to set settings for {}: {}'.format(container, name) raise CommandExecutionError(msg) new_settings = get_container_setting(name=name, container=container, settings=settings.keys()) failed_settings = dict() for setting in settings: if ((setting == 'processModel.identityType') and (settings[setting] in identityType_map2string.keys())): settings[setting] = identityType_map2string[settings[setting]] if (str(settings[setting]) != str(new_settings[setting])): failed_settings[setting] = settings[setting] if failed_settings: log.error('Failed to change settings: %s', failed_settings) return False log.debug('Settings configured successfully: %s', settings.keys()) return True<|docstring|>Set the value of the setting for an IIS container. .. versionadded:: 2016.11.0 Args: name (str): The name of the IIS container. container (str): The type of IIS container. The container types are: AppPools, Sites, SslBindings settings (dict): A dictionary of the setting names and their values. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.set_container_setting name='MyTestPool' container='AppPools' settings="{'managedPipeLineMode': 'Integrated'}"<|endoftext|>
7b6774a95eec53ef2ca3a30a9ab0ee294290631749b52a6830540a41a5c50108
def list_apps(site): "\n Get all configured IIS applications for the specified site.\n\n Args:\n site (str): The IIS site name.\n\n Returns: A dictionary of the application names and properties.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.list_apps site\n " ret = dict() ps_cmd = list() ps_cmd.append("Get-WebApplication -Site '{}'".format(site)) ps_cmd.append('| Select-Object applicationPool, path, PhysicalPath, preloadEnabled,') ps_cmd.append("@{ Name='name'; Expression={ $_.path.Split('/', 2)[-1] } },") ps_cmd.append("@{ Name='protocols'; Expression={ @( $_.enabledProtocols.Split(',')") ps_cmd.append('| Foreach-Object { $_.Trim() } ) } }') cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True) try: items = salt.utils.json.loads(cmd_ret['stdout'], strict=False) except ValueError: raise CommandExecutionError('Unable to parse return data as Json.') for item in items: protocols = list() if isinstance(item['protocols'], dict): if ('value' in item['protocols']): protocols += item['protocols']['value'] else: protocols.append(item['protocols']) ret[item['name']] = {'apppool': item['applicationPool'], 'path': item['path'], 'preload': item['preloadEnabled'], 'protocols': protocols, 'sourcepath': item['PhysicalPath']} if (not ret): log.warning('No apps found in output: %s', cmd_ret) return ret
Get all configured IIS applications for the specified site. Args: site (str): The IIS site name. Returns: A dictionary of the application names and properties. CLI Example: .. code-block:: bash salt '*' win_iis.list_apps site
salt/modules/win_iis.py
list_apps
Flowdalic/salt
9,425
python
def list_apps(site): "\n Get all configured IIS applications for the specified site.\n\n Args:\n site (str): The IIS site name.\n\n Returns: A dictionary of the application names and properties.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.list_apps site\n " ret = dict() ps_cmd = list() ps_cmd.append("Get-WebApplication -Site '{}'".format(site)) ps_cmd.append('| Select-Object applicationPool, path, PhysicalPath, preloadEnabled,') ps_cmd.append("@{ Name='name'; Expression={ $_.path.Split('/', 2)[-1] } },") ps_cmd.append("@{ Name='protocols'; Expression={ @( $_.enabledProtocols.Split(',')") ps_cmd.append('| Foreach-Object { $_.Trim() } ) } }') cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True) try: items = salt.utils.json.loads(cmd_ret['stdout'], strict=False) except ValueError: raise CommandExecutionError('Unable to parse return data as Json.') for item in items: protocols = list() if isinstance(item['protocols'], dict): if ('value' in item['protocols']): protocols += item['protocols']['value'] else: protocols.append(item['protocols']) ret[item['name']] = {'apppool': item['applicationPool'], 'path': item['path'], 'preload': item['preloadEnabled'], 'protocols': protocols, 'sourcepath': item['PhysicalPath']} if (not ret): log.warning('No apps found in output: %s', cmd_ret) return ret
def list_apps(site): "\n Get all configured IIS applications for the specified site.\n\n Args:\n site (str): The IIS site name.\n\n Returns: A dictionary of the application names and properties.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.list_apps site\n " ret = dict() ps_cmd = list() ps_cmd.append("Get-WebApplication -Site '{}'".format(site)) ps_cmd.append('| Select-Object applicationPool, path, PhysicalPath, preloadEnabled,') ps_cmd.append("@{ Name='name'; Expression={ $_.path.Split('/', 2)[-1] } },") ps_cmd.append("@{ Name='protocols'; Expression={ @( $_.enabledProtocols.Split(',')") ps_cmd.append('| Foreach-Object { $_.Trim() } ) } }') cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True) try: items = salt.utils.json.loads(cmd_ret['stdout'], strict=False) except ValueError: raise CommandExecutionError('Unable to parse return data as Json.') for item in items: protocols = list() if isinstance(item['protocols'], dict): if ('value' in item['protocols']): protocols += item['protocols']['value'] else: protocols.append(item['protocols']) ret[item['name']] = {'apppool': item['applicationPool'], 'path': item['path'], 'preload': item['preloadEnabled'], 'protocols': protocols, 'sourcepath': item['PhysicalPath']} if (not ret): log.warning('No apps found in output: %s', cmd_ret) return ret<|docstring|>Get all configured IIS applications for the specified site. Args: site (str): The IIS site name. Returns: A dictionary of the application names and properties. CLI Example: .. code-block:: bash salt '*' win_iis.list_apps site<|endoftext|>
11857f5d94eff3cfa667dd7fc36de35f8449320e6767633639e58bcd0a91e653
def create_app(name, site, sourcepath, apppool=None): "\n Create an IIS application.\n\n .. note::\n\n This function only validates against the application name, and will\n return True even if the application already exists with a different\n configuration. It will not modify the configuration of an existing\n application.\n\n Args:\n name (str): The IIS application.\n site (str): The IIS site name.\n sourcepath (str): The physical path.\n apppool (str): The name of the IIS application pool.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.create_app name='app0' site='site0' sourcepath='C:\\site0' apppool='site0'\n " current_apps = list_apps(site) if (name in current_apps): log.debug('Application already present: %s', name) return True if (not os.path.isdir(sourcepath)): log.error('Path is not present: %s', sourcepath) return False ps_cmd = ['New-WebApplication', '-Name', "'{}'".format(name), '-Site', "'{}'".format(site), '-PhysicalPath', "'{}'".format(sourcepath)] if apppool: ps_cmd.extend(['-ApplicationPool', "'{}'".format(apppool)]) cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to create application: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) new_apps = list_apps(site) if (name in new_apps): log.debug('Application created successfully: %s', name) return True log.error('Unable to create application: %s', name) return False
Create an IIS application. .. note:: This function only validates against the application name, and will return True even if the application already exists with a different configuration. It will not modify the configuration of an existing application. Args: name (str): The IIS application. site (str): The IIS site name. sourcepath (str): The physical path. apppool (str): The name of the IIS application pool. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.create_app name='app0' site='site0' sourcepath='C:\site0' apppool='site0'
salt/modules/win_iis.py
create_app
Flowdalic/salt
9,425
python
def create_app(name, site, sourcepath, apppool=None): "\n Create an IIS application.\n\n .. note::\n\n This function only validates against the application name, and will\n return True even if the application already exists with a different\n configuration. It will not modify the configuration of an existing\n application.\n\n Args:\n name (str): The IIS application.\n site (str): The IIS site name.\n sourcepath (str): The physical path.\n apppool (str): The name of the IIS application pool.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.create_app name='app0' site='site0' sourcepath='C:\\site0' apppool='site0'\n " current_apps = list_apps(site) if (name in current_apps): log.debug('Application already present: %s', name) return True if (not os.path.isdir(sourcepath)): log.error('Path is not present: %s', sourcepath) return False ps_cmd = ['New-WebApplication', '-Name', "'{}'".format(name), '-Site', "'{}'".format(site), '-PhysicalPath', "'{}'".format(sourcepath)] if apppool: ps_cmd.extend(['-ApplicationPool', "'{}'".format(apppool)]) cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to create application: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) new_apps = list_apps(site) if (name in new_apps): log.debug('Application created successfully: %s', name) return True log.error('Unable to create application: %s', name) return False
def create_app(name, site, sourcepath, apppool=None): "\n Create an IIS application.\n\n .. note::\n\n This function only validates against the application name, and will\n return True even if the application already exists with a different\n configuration. It will not modify the configuration of an existing\n application.\n\n Args:\n name (str): The IIS application.\n site (str): The IIS site name.\n sourcepath (str): The physical path.\n apppool (str): The name of the IIS application pool.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.create_app name='app0' site='site0' sourcepath='C:\\site0' apppool='site0'\n " current_apps = list_apps(site) if (name in current_apps): log.debug('Application already present: %s', name) return True if (not os.path.isdir(sourcepath)): log.error('Path is not present: %s', sourcepath) return False ps_cmd = ['New-WebApplication', '-Name', "'{}'".format(name), '-Site', "'{}'".format(site), '-PhysicalPath', "'{}'".format(sourcepath)] if apppool: ps_cmd.extend(['-ApplicationPool', "'{}'".format(apppool)]) cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to create application: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) new_apps = list_apps(site) if (name in new_apps): log.debug('Application created successfully: %s', name) return True log.error('Unable to create application: %s', name) return False<|docstring|>Create an IIS application. .. note:: This function only validates against the application name, and will return True even if the application already exists with a different configuration. It will not modify the configuration of an existing application. Args: name (str): The IIS application. site (str): The IIS site name. sourcepath (str): The physical path. apppool (str): The name of the IIS application pool. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.create_app name='app0' site='site0' sourcepath='C:\site0' apppool='site0'<|endoftext|>
7d2f1ec9315196045a35e61774ad6d3af1febb4a1b288eba03c8bc23eebc72fb
def remove_app(name, site): "\n Remove an IIS application.\n\n Args:\n name (str): The application name.\n site (str): The IIS site name.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.remove_app name='app0' site='site0'\n " current_apps = list_apps(site) if (name not in current_apps): log.debug('Application already absent: %s', name) return True ps_cmd = ['Remove-WebApplication', '-Name', "'{}'".format(name), '-Site', "'{}'".format(site)] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to remove application: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) new_apps = list_apps(site) if (name not in new_apps): log.debug('Application removed successfully: %s', name) return True log.error('Unable to remove application: %s', name) return False
Remove an IIS application. Args: name (str): The application name. site (str): The IIS site name. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.remove_app name='app0' site='site0'
salt/modules/win_iis.py
remove_app
Flowdalic/salt
9,425
python
def remove_app(name, site): "\n Remove an IIS application.\n\n Args:\n name (str): The application name.\n site (str): The IIS site name.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.remove_app name='app0' site='site0'\n " current_apps = list_apps(site) if (name not in current_apps): log.debug('Application already absent: %s', name) return True ps_cmd = ['Remove-WebApplication', '-Name', "'{}'".format(name), '-Site', "'{}'".format(site)] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to remove application: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) new_apps = list_apps(site) if (name not in new_apps): log.debug('Application removed successfully: %s', name) return True log.error('Unable to remove application: %s', name) return False
def remove_app(name, site): "\n Remove an IIS application.\n\n Args:\n name (str): The application name.\n site (str): The IIS site name.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.remove_app name='app0' site='site0'\n " current_apps = list_apps(site) if (name not in current_apps): log.debug('Application already absent: %s', name) return True ps_cmd = ['Remove-WebApplication', '-Name', "'{}'".format(name), '-Site', "'{}'".format(site)] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to remove application: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) new_apps = list_apps(site) if (name not in new_apps): log.debug('Application removed successfully: %s', name) return True log.error('Unable to remove application: %s', name) return False<|docstring|>Remove an IIS application. Args: name (str): The application name. site (str): The IIS site name. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.remove_app name='app0' site='site0'<|endoftext|>
dc51467d90c546473eb94d50493583e1aa4e94737ce12b5b86e6f5afa044429d
def list_vdirs(site, app=_DEFAULT_APP): "\n Get all configured IIS virtual directories for the specified site, or for\n the combination of site and application.\n\n Args:\n site (str): The IIS site name.\n app (str): The IIS application.\n\n Returns:\n dict: A dictionary of the virtual directory names and properties.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.list_vdirs site\n " ret = dict() ps_cmd = ['Get-WebVirtualDirectory', '-Site', "'{}'".format(site), '-Application', "'{}'".format(app), '|', "Select-Object PhysicalPath, @{ Name = 'name';", "Expression = { $_.path.Trim('/') } }"] cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True) try: items = salt.utils.json.loads(cmd_ret['stdout'], strict=False) except ValueError: raise CommandExecutionError('Unable to parse return data as Json.') for item in items: ret[item['name']] = {'sourcepath': item['physicalPath']} if (not ret): log.warning('No vdirs found in output: %s', cmd_ret) return ret
Get all configured IIS virtual directories for the specified site, or for the combination of site and application. Args: site (str): The IIS site name. app (str): The IIS application. Returns: dict: A dictionary of the virtual directory names and properties. CLI Example: .. code-block:: bash salt '*' win_iis.list_vdirs site
salt/modules/win_iis.py
list_vdirs
Flowdalic/salt
9,425
python
def list_vdirs(site, app=_DEFAULT_APP): "\n Get all configured IIS virtual directories for the specified site, or for\n the combination of site and application.\n\n Args:\n site (str): The IIS site name.\n app (str): The IIS application.\n\n Returns:\n dict: A dictionary of the virtual directory names and properties.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.list_vdirs site\n " ret = dict() ps_cmd = ['Get-WebVirtualDirectory', '-Site', "'{}'".format(site), '-Application', "'{}'".format(app), '|', "Select-Object PhysicalPath, @{ Name = 'name';", "Expression = { $_.path.Trim('/') } }"] cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True) try: items = salt.utils.json.loads(cmd_ret['stdout'], strict=False) except ValueError: raise CommandExecutionError('Unable to parse return data as Json.') for item in items: ret[item['name']] = {'sourcepath': item['physicalPath']} if (not ret): log.warning('No vdirs found in output: %s', cmd_ret) return ret
def list_vdirs(site, app=_DEFAULT_APP): "\n Get all configured IIS virtual directories for the specified site, or for\n the combination of site and application.\n\n Args:\n site (str): The IIS site name.\n app (str): The IIS application.\n\n Returns:\n dict: A dictionary of the virtual directory names and properties.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.list_vdirs site\n " ret = dict() ps_cmd = ['Get-WebVirtualDirectory', '-Site', "'{}'".format(site), '-Application', "'{}'".format(app), '|', "Select-Object PhysicalPath, @{ Name = 'name';", "Expression = { $_.path.Trim('/') } }"] cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True) try: items = salt.utils.json.loads(cmd_ret['stdout'], strict=False) except ValueError: raise CommandExecutionError('Unable to parse return data as Json.') for item in items: ret[item['name']] = {'sourcepath': item['physicalPath']} if (not ret): log.warning('No vdirs found in output: %s', cmd_ret) return ret<|docstring|>Get all configured IIS virtual directories for the specified site, or for the combination of site and application. Args: site (str): The IIS site name. app (str): The IIS application. Returns: dict: A dictionary of the virtual directory names and properties. CLI Example: .. code-block:: bash salt '*' win_iis.list_vdirs site<|endoftext|>
b74228f87499ea9a4d9056babfc307911a34af953e58252141ab50f7b88e0330
def create_vdir(name, site, sourcepath, app=_DEFAULT_APP): "\n Create an IIS virtual directory.\n\n .. note::\n\n This function only validates against the virtual directory name, and\n will return True even if the virtual directory already exists with a\n different configuration. It will not modify the configuration of an\n existing virtual directory.\n\n Args:\n name (str): The virtual directory name.\n site (str): The IIS site name.\n sourcepath (str): The physical path.\n app (str): The IIS application.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.create_vdir name='vd0' site='site0' sourcepath='C:\\inetpub\\vdirs\\vd0'\n " current_vdirs = list_vdirs(site, app) if (name in current_vdirs): log.debug('Virtual directory already present: %s', name) return True if (not os.path.isdir(sourcepath)): log.error('Path is not present: %s', sourcepath) return False ps_cmd = ['New-WebVirtualDirectory', '-Name', "'{}'".format(name), '-Site', "'{}'".format(site), '-PhysicalPath', "'{}'".format(sourcepath)] if (app != _DEFAULT_APP): ps_cmd.extend(['-Application', "'{}'".format(app)]) cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to create virtual directory: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) new_vdirs = list_vdirs(site, app) if (name in new_vdirs): log.debug('Virtual directory created successfully: %s', name) return True log.error('Unable to create virtual directory: %s', name) return False
Create an IIS virtual directory. .. note:: This function only validates against the virtual directory name, and will return True even if the virtual directory already exists with a different configuration. It will not modify the configuration of an existing virtual directory. Args: name (str): The virtual directory name. site (str): The IIS site name. sourcepath (str): The physical path. app (str): The IIS application. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.create_vdir name='vd0' site='site0' sourcepath='C:\inetpub\vdirs\vd0'
salt/modules/win_iis.py
create_vdir
Flowdalic/salt
9,425
python
def create_vdir(name, site, sourcepath, app=_DEFAULT_APP): "\n Create an IIS virtual directory.\n\n .. note::\n\n This function only validates against the virtual directory name, and\n will return True even if the virtual directory already exists with a\n different configuration. It will not modify the configuration of an\n existing virtual directory.\n\n Args:\n name (str): The virtual directory name.\n site (str): The IIS site name.\n sourcepath (str): The physical path.\n app (str): The IIS application.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.create_vdir name='vd0' site='site0' sourcepath='C:\\inetpub\\vdirs\\vd0'\n " current_vdirs = list_vdirs(site, app) if (name in current_vdirs): log.debug('Virtual directory already present: %s', name) return True if (not os.path.isdir(sourcepath)): log.error('Path is not present: %s', sourcepath) return False ps_cmd = ['New-WebVirtualDirectory', '-Name', "'{}'".format(name), '-Site', "'{}'".format(site), '-PhysicalPath', "'{}'".format(sourcepath)] if (app != _DEFAULT_APP): ps_cmd.extend(['-Application', "'{}'".format(app)]) cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to create virtual directory: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) new_vdirs = list_vdirs(site, app) if (name in new_vdirs): log.debug('Virtual directory created successfully: %s', name) return True log.error('Unable to create virtual directory: %s', name) return False
def create_vdir(name, site, sourcepath, app=_DEFAULT_APP): "\n Create an IIS virtual directory.\n\n .. note::\n\n This function only validates against the virtual directory name, and\n will return True even if the virtual directory already exists with a\n different configuration. It will not modify the configuration of an\n existing virtual directory.\n\n Args:\n name (str): The virtual directory name.\n site (str): The IIS site name.\n sourcepath (str): The physical path.\n app (str): The IIS application.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.create_vdir name='vd0' site='site0' sourcepath='C:\\inetpub\\vdirs\\vd0'\n " current_vdirs = list_vdirs(site, app) if (name in current_vdirs): log.debug('Virtual directory already present: %s', name) return True if (not os.path.isdir(sourcepath)): log.error('Path is not present: %s', sourcepath) return False ps_cmd = ['New-WebVirtualDirectory', '-Name', "'{}'".format(name), '-Site', "'{}'".format(site), '-PhysicalPath', "'{}'".format(sourcepath)] if (app != _DEFAULT_APP): ps_cmd.extend(['-Application', "'{}'".format(app)]) cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to create virtual directory: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) new_vdirs = list_vdirs(site, app) if (name in new_vdirs): log.debug('Virtual directory created successfully: %s', name) return True log.error('Unable to create virtual directory: %s', name) return False<|docstring|>Create an IIS virtual directory. .. note:: This function only validates against the virtual directory name, and will return True even if the virtual directory already exists with a different configuration. It will not modify the configuration of an existing virtual directory. Args: name (str): The virtual directory name. site (str): The IIS site name. sourcepath (str): The physical path. app (str): The IIS application. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.create_vdir name='vd0' site='site0' sourcepath='C:\inetpub\vdirs\vd0'<|endoftext|>
1b07f53640418573615078ed4401aa30d263dd8148e364c6bde17c950f2ce469
def remove_vdir(name, site, app=_DEFAULT_APP): "\n Remove an IIS virtual directory.\n\n Args:\n name (str): The virtual directory name.\n site (str): The IIS site name.\n app (str): The IIS application.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.remove_vdir name='vdir0' site='site0'\n " current_vdirs = list_vdirs(site, app) app_path = os.path.join(*app.rstrip('/').split('/')) if app_path: app_path = '{}\\'.format(app_path) vdir_path = 'IIS:\\Sites\\{}\\{}{}'.format(site, app_path, name) if (name not in current_vdirs): log.debug('Virtual directory already absent: %s', name) return True ps_cmd = ['Remove-Item', '-Path', "'{}'".format(vdir_path), '-Recurse'] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to remove virtual directory: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) new_vdirs = list_vdirs(site, app) if (name not in new_vdirs): log.debug('Virtual directory removed successfully: %s', name) return True log.error('Unable to remove virtual directory: %s', name) return False
Remove an IIS virtual directory. Args: name (str): The virtual directory name. site (str): The IIS site name. app (str): The IIS application. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.remove_vdir name='vdir0' site='site0'
salt/modules/win_iis.py
remove_vdir
Flowdalic/salt
9,425
python
def remove_vdir(name, site, app=_DEFAULT_APP): "\n Remove an IIS virtual directory.\n\n Args:\n name (str): The virtual directory name.\n site (str): The IIS site name.\n app (str): The IIS application.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.remove_vdir name='vdir0' site='site0'\n " current_vdirs = list_vdirs(site, app) app_path = os.path.join(*app.rstrip('/').split('/')) if app_path: app_path = '{}\\'.format(app_path) vdir_path = 'IIS:\\Sites\\{}\\{}{}'.format(site, app_path, name) if (name not in current_vdirs): log.debug('Virtual directory already absent: %s', name) return True ps_cmd = ['Remove-Item', '-Path', "'{}'".format(vdir_path), '-Recurse'] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to remove virtual directory: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) new_vdirs = list_vdirs(site, app) if (name not in new_vdirs): log.debug('Virtual directory removed successfully: %s', name) return True log.error('Unable to remove virtual directory: %s', name) return False
def remove_vdir(name, site, app=_DEFAULT_APP): "\n Remove an IIS virtual directory.\n\n Args:\n name (str): The virtual directory name.\n site (str): The IIS site name.\n app (str): The IIS application.\n\n Returns:\n bool: True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.remove_vdir name='vdir0' site='site0'\n " current_vdirs = list_vdirs(site, app) app_path = os.path.join(*app.rstrip('/').split('/')) if app_path: app_path = '{}\\'.format(app_path) vdir_path = 'IIS:\\Sites\\{}\\{}{}'.format(site, app_path, name) if (name not in current_vdirs): log.debug('Virtual directory already absent: %s', name) return True ps_cmd = ['Remove-Item', '-Path', "'{}'".format(vdir_path), '-Recurse'] cmd_ret = _srvmgr(ps_cmd) if (cmd_ret['retcode'] != 0): msg = 'Unable to remove virtual directory: {}\nError: {}'.format(name, cmd_ret['stderr']) raise CommandExecutionError(msg) new_vdirs = list_vdirs(site, app) if (name not in new_vdirs): log.debug('Virtual directory removed successfully: %s', name) return True log.error('Unable to remove virtual directory: %s', name) return False<|docstring|>Remove an IIS virtual directory. Args: name (str): The virtual directory name. site (str): The IIS site name. app (str): The IIS application. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.remove_vdir name='vdir0' site='site0'<|endoftext|>
2e2f7e8e30b451f53cd017004de44098cc827aa099f838cb7b0f553bd4e60500
def list_backups(): "\n List the IIS Configuration Backups on the System.\n\n .. versionadded:: 2017.7.0\n\n .. note::\n Backups are made when a configuration is edited. Manual backups are\n stored in the ``$env:Windir\\System32\\inetsrv\\backup`` folder.\n\n Returns:\n dict: A dictionary of IIS Configurations backed up on the system.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.list_backups\n " ret = dict() ps_cmd = ['Get-WebConfigurationBackup', '|', 'Select Name, CreationDate,', '@{N="FormattedDate"; E={$_.CreationDate.ToString("G")}}'] cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True) try: items = salt.utils.json.loads(cmd_ret['stdout'], strict=False) except ValueError: raise CommandExecutionError('Unable to parse return data as Json.') for item in items: if item['FormattedDate']: ret[item['Name']] = item['FormattedDate'] else: ret[item['Name']] = item['CreationDate'] if (not ret): log.warning('No backups found in output: %s', cmd_ret) return ret
List the IIS Configuration Backups on the System. .. versionadded:: 2017.7.0 .. note:: Backups are made when a configuration is edited. Manual backups are stored in the ``$env:Windir\System32\inetsrv\backup`` folder. Returns: dict: A dictionary of IIS Configurations backed up on the system. CLI Example: .. code-block:: bash salt '*' win_iis.list_backups
salt/modules/win_iis.py
list_backups
Flowdalic/salt
9,425
python
def list_backups(): "\n List the IIS Configuration Backups on the System.\n\n .. versionadded:: 2017.7.0\n\n .. note::\n Backups are made when a configuration is edited. Manual backups are\n stored in the ``$env:Windir\\System32\\inetsrv\\backup`` folder.\n\n Returns:\n dict: A dictionary of IIS Configurations backed up on the system.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.list_backups\n " ret = dict() ps_cmd = ['Get-WebConfigurationBackup', '|', 'Select Name, CreationDate,', '@{N="FormattedDate"; E={$_.CreationDate.ToString("G")}}'] cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True) try: items = salt.utils.json.loads(cmd_ret['stdout'], strict=False) except ValueError: raise CommandExecutionError('Unable to parse return data as Json.') for item in items: if item['FormattedDate']: ret[item['Name']] = item['FormattedDate'] else: ret[item['Name']] = item['CreationDate'] if (not ret): log.warning('No backups found in output: %s', cmd_ret) return ret
def list_backups(): "\n List the IIS Configuration Backups on the System.\n\n .. versionadded:: 2017.7.0\n\n .. note::\n Backups are made when a configuration is edited. Manual backups are\n stored in the ``$env:Windir\\System32\\inetsrv\\backup`` folder.\n\n Returns:\n dict: A dictionary of IIS Configurations backed up on the system.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' win_iis.list_backups\n " ret = dict() ps_cmd = ['Get-WebConfigurationBackup', '|', 'Select Name, CreationDate,', '@{N="FormattedDate"; E={$_.CreationDate.ToString("G")}}'] cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True) try: items = salt.utils.json.loads(cmd_ret['stdout'], strict=False) except ValueError: raise CommandExecutionError('Unable to parse return data as Json.') for item in items: if item['FormattedDate']: ret[item['Name']] = item['FormattedDate'] else: ret[item['Name']] = item['CreationDate'] if (not ret): log.warning('No backups found in output: %s', cmd_ret) return ret<|docstring|>List the IIS Configuration Backups on the System. .. versionadded:: 2017.7.0 .. note:: Backups are made when a configuration is edited. Manual backups are stored in the ``$env:Windir\System32\inetsrv\backup`` folder. Returns: dict: A dictionary of IIS Configurations backed up on the system. CLI Example: .. code-block:: bash salt '*' win_iis.list_backups<|endoftext|>