text stringlengths 81 112k |
|---|
Turn a URL into an Avro-safe name.
If the URL has no fragment, return this plain URL.
Extract either the last part of the URL fragment past the slash, otherwise
the whole fragment.
def avro_name(url): # type: (AnyStr) -> AnyStr
"""
Turn a URL into an Avro-safe name.
If the URL has no fragme... |
Convert our schema to be more avro like.
def make_valid_avro(items, # type: Avro
alltypes, # type: Dict[Text, Dict[Text, Any]]
found, # type: Set[Text]
union=False # type: bool
):
# type: (...) -> Union[Avro... |
Make a deep copy of list and dict objects.
Intentionally do not copy attributes. This is to discard CommentedMap and
CommentedSeq metadata which is very expensive with regular copy.deepcopy.
def deepcopy_strip(item): # type: (Any) -> Any
"""
Make a deep copy of list and dict objects.
Intentiona... |
Apply 'extend' and 'specialize' to fully materialize derived record types.
def extend_and_specialize(items, loader):
# type: (List[Dict[Text, Any]], Loader) -> List[Dict[Text, Any]]
"""
Apply 'extend' and 'specialize' to fully materialize derived record types.
"""
items = deepcopy_strip(items)
... |
All in one convenience function.
Call make_avro() and make_avro_schema_from_avro() separately if you need
the intermediate result for diagnostic output.
def make_avro_schema(i, # type: List[Any]
loader # type: Loader
): # type: (...) -> Names
"""
... |
Returns the last segment of the provided fragment or path.
def shortname(inputid): # type: (Text) -> Text
"""Returns the last segment of the provided fragment or path."""
parsed_id = urllib.parse.urlparse(inputid)
if parsed_id.fragment:
return parsed_id.fragment.split(u"/")[-1]
return parsed_i... |
Write a Grapviz inheritance graph for the supplied document.
def print_inheritance(doc, stream):
# type: (List[Dict[Text, Any]], IO) -> None
"""Write a Grapviz inheritance graph for the supplied document."""
stream.write("digraph {\n")
for entry in doc:
if entry["type"] == "record":
... |
Write a GraphViz graph of the relationships between the fields.
def print_fieldrefs(doc, loader, stream):
# type: (List[Dict[Text, Any]], Loader, IO) -> None
"""Write a GraphViz graph of the relationships between the fields."""
obj = extend_and_specialize(doc, loader)
primitives = set(("http://www.w3.... |
Retrieve the non-reserved properties from a dictionary of properties
@args reserved_props: The set of reserved properties to exclude
def get_other_props(all_props, reserved_props):
# type: (Dict, Tuple) -> Optional[Dict]
"""
Retrieve the non-reserved properties from a dictionary of properties
@args... |
Build Avro Schema from data parsed out of JSON string.
@arg names: A Name object (tracks seen names and default space)
def make_avsc_object(json_data, names=None):
# type: (Union[Dict[Text, Text], List[Any], Text], Optional[Names]) -> Schema
"""
Build Avro Schema from data parsed out of JSON string.
... |
Back out a namespace from full name.
def get_space(self):
# type: () -> Optional[Text]
"""Back out a namespace from full name."""
if self._full is None:
return None
if self._full.find('.') > 0:
return self._full.rsplit(".", 1)[0]
else:
return... |
Add a new schema object to the name set.
@arg name_attr: name value read in schema
@arg space_attr: namespace value read in schema.
@return: the Name that was just added.
def add_name(self, name_attr, space_attr, new_schema):
# type: (Text, Optional[Text], NamedSchema) -> Name
... |
We're going to need to make message parameters too.
def make_field_objects(field_data, names):
# type: (List[Dict[Text, Text]], Names) -> List[Field]
"""We're going to need to make message parameters too."""
field_objects = []
field_names = [] # type: List[Text]
for field in fi... |
function to get links
def search_function(root1, q, s, f, l, o='g'):
"""
function to get links
"""
global links
links = search(q, o, s, f, l)
root1.destroy()
root1.quit() |
to create loading progress bar
def task(ft):
"""
to create loading progress bar
"""
ft.pack(expand = True, fill = BOTH, side = TOP)
pb_hD = ttk.Progressbar(ft, orient = 'horizontal', mode = 'indeterminate')
pb_hD.pack(expand = True, fill = BOTH, side = TOP)
pb_hD.start(50)
ft.mainloop() |
function to fetch links and download them
def download_content_gui(**args):
"""
function to fetch links and download them
"""
global row
if not args ['directory']:
args ['directory'] = args ['query'].replace(' ', '-')
root1 = Frame(root)
t1 = threading.Thread(target = search_function, args = (root1,
... |
main function
def main():
"""
main function
"""
s = ttk.Style()
s.theme_use('clam')
ents = makeform(root)
root.mainloop() |
event for download button
def click_download(self, event):
"""
event for download button
"""
args ['parallel'] = self.p.get()
args ['file_type'] = self.optionmenu.get()
args ['no_redirects'] = self.t.get()
args ['query'] = self.entry_query.get()
args ['min_file_size'] = int( self.entry_min.get())
arg... |
function that gets called whenever entry is clicked
def on_entry_click(self, event):
"""
function that gets called whenever entry is clicked
"""
if event.widget.config('fg') [4] == 'grey':
event.widget.delete(0, "end" ) # delete all the text in the entry
event.widget.insert(0, '') #Insert blank for u... |
function that gets called whenever anywhere except entry is clicked
def on_focusout(self, event, a):
"""
function that gets called whenever anywhere except entry is clicked
"""
if event.widget.get() == '':
event.widget.insert(0, default_text[a])
event.widget.config(fg = 'grey') |
function to check input filetype against threat extensions list
def check_threat(self):
"""
function to check input filetype against threat extensions list
"""
is_high_threat = False
for val in THREAT_EXTENSIONS.values():
if type(val) == list:
for el in val:
if self.optionmenu.get() == el:
... |
dialogue box for choosing directory
def ask_dir(self):
"""
dialogue box for choosing directory
"""
args ['directory'] = askdirectory(**self.dir_opt)
self.dir_text.set(args ['directory']) |
function to fetch links equal to limit
every Google search result page has a start index.
every page contains 10 search results.
def get_google_links(limit, params, headers):
"""
function to fetch links equal to limit
every Google search result page has a start index.
every page contains 10 search results.
""... |
function to fetch links equal to limit
duckduckgo pagination is not static, so there is a limit on
maximum number of links that can be scraped
def get_duckduckgo_links(limit, params, headers):
"""
function to fetch links equal to limit
duckduckgo pagination is not static, so there is a limit on
maximum number ... |
function to scrape file links from html response
def scrape_links(html, engine):
"""
function to scrape file links from html response
"""
soup = BeautifulSoup(html, 'lxml')
links = []
if engine == 'd':
results = soup.findAll('a', {'class': 'result__a'})
for result in results:
link = result.get('href')[15... |
function to get return code of a url
Credits: http://blog.jasonantman.com/2013/06/python-script-to-check-a-list-of-urls-for-return-code-and-final-return-code-if-redirected/
def get_url_nofollow(url):
"""
function to get return code of a url
Credits: http://blog.jasonantman.com/2013/06/python-script-to-check-a-l... |
function to validate urls based on http(s) prefix and return code
def validate_links(links):
"""
function to validate urls based on http(s) prefix and return code
"""
valid_links = []
for link in links:
if link[:7] in "http://" or link[:8] in "https://":
valid_links.append(link)
if not valid_links:
prin... |
main function to search for links and return valid ones
def search(query, engine='g', site="", file_type = 'pdf', limit = 10):
"""
main function to search for links and return valid ones
"""
if site == "":
search_query = "filetype:{0} {1}".format(file_type, query)
else:
search_query = "site:{0} filetype:{1} {... |
function to check input filetype against threat extensions list
def check_threats(**args):
"""
function to check input filetype against threat extensions list
"""
is_high_threat = False
for val in THREAT_EXTENSIONS.values():
if type(val) == list:
for el in val:
if args['file_type'] == el:
is_high_t... |
function to check if input query is not None
and set missing arguments to default value
def validate_args(**args):
"""
function to check if input query is not None
and set missing arguments to default value
"""
if not args['query']:
print("\nMissing required query argument.")
sys.exit()
for key in DEFAUL... |
main function to fetch links and download them
def download_content(**args):
"""
main function to fetch links and download them
"""
args = validate_args(**args)
if not args['directory']:
args['directory'] = args['query'].replace(' ', '-')
print("Downloading {0} {1} files on topic {2} from {3} and saving to d... |
function to show valid file extensions
def show_filetypes(extensions):
"""
function to show valid file extensions
"""
for item in extensions.items():
val = item[1]
if type(item[1]) == list:
val = ", ".join(str(x) for x in item[1])
print("{0:4}: {1}".format(val, item[0])) |
Determine if a python datum is an instance of a schema.
def validate_ex(expected_schema, # type: Schema
datum, # type: Any
identifiers=None, # type: List[Text]
strict=False, # type: bool
... |
Force use of unicode.
def json_dump(obj, # type: Any
fp, # type: IO[str]
**kwargs # type: Any
): # type: (...) -> None
""" Force use of unicode. """
if six.PY2:
kwargs['encoding'] = 'utf-8'
json.dump(convert_to_dict(obj), fp, **kwargs) |
Force use of unicode.
def json_dumps(obj, # type: Any
**kwargs # type: Any
): # type: (...) -> str
""" Force use of unicode. """
if six.PY2:
kwargs['encoding'] = 'utf-8'
return json.dumps(convert_to_dict(obj), **kwargs) |
Generate classes with loaders for the given Schema Salad description.
def codegen(lang, # type: str
i, # type: List[Dict[Text, Any]]
schema_metadata, # type: Dict[Text, Any]
loader # type: Loader
): # type: (...) -> None
"""Gene... |
Return a list of subset of VM that match the pattern name
@param name (str): the vm name of the virtual machine
@param name (Obj): the vm object that represent the virtual
machine (can be Pro or Smart)
@return (list): the subset containing the serach result.
def find(... |
Reinitialize a VM.
:param admin_password: Administrator password.
:param debug: Flag to enable debug output.
:param ConfigureIPv6: Flag to enable IPv6 on the VM.
:param OSTemplateID: TemplateID to reinitialize the VM with.
:return: True in case of success, otherwise False
... |
Set the authentication data in the object, and if load is True
(default is True) it also retrieve the ip list and the vm list
in order to build the internal objects list.
@param (str) username: username of the cloud
@param (str) password: password of the cloud
@param (bool) load:... |
Poweroff a VM. If possible to pass the VM object or simply the ID
of the VM that we want to turn on.
Args:
server: VM Object that represent the VM to power off,
server_id: Int or Str representing the ID of the VM to power off.
Returns:
return True if json_obj[... |
Initialize the internal list containing each template available for each
hypervisor.
:return: [bool] True in case of success, otherwise False
def get_hypervisors(self):
"""
Initialize the internal list containing each template available for each
hypervisor.
:return: [b... |
Create the list of Server object inside the Datacenter objects.
Build an internal list of VM Objects (pro or smart) as iterator.
:return: bool
def get_servers(self):
"""
Create the list of Server object inside the Datacenter objects.
Build an internal list of VM Objects (pro or ... |
Return a list of templates that could have one or more elements.
Args:
name: name of the template to find.
hv: the ID of the hypervisor to search the template in
Returns:
A list of templates object. If hv is None will return all the
templates matching the ... |
Return an ip object representing a new bought IP
@param debug [Boolean] if true, request and response will be printed
@return (Ip): Ip object
def purchase_ip(self, debug=False):
"""
Return an ip object representing a new bought IP
@param debug [Boolean] if true, request and resp... |
Purchase a new VLAN.
:param debug: Log the json response if True
:param vlan_name: String representing the name of the vlan (virtual switch)
:return: a Vlan Object representing the vlan created
def purchase_vlan(self, vlan_name, debug=False):
"""
Purchase a new VLAN.
:pa... |
Remove a VLAN
:param vlan_resource_id:
:return:
def remove_vlan(self, vlan_resource_id):
"""
Remove a VLAN
:param vlan_resource_id:
:return:
"""
vlan_id = {'VLanResourceId': vlan_resource_id}
json_scheme = self.gen_def_json_scheme('SetRemoveVLan',... |
Delete an Ip from the boughs ip list
@param (str) ip_id: a string representing the resource id of the IP
@return: True if json method had success else False
def remove_ip(self, ip_id):
"""
Delete an Ip from the boughs ip list
@param (str) ip_id: a string representing the resourc... |
Retrieve the smart package id given is English name
@param (str) name: the Aruba Smart package size name, ie: "small", "medium", "large", "extra large".
@return: The package id that depends on the Data center and the size choosen.
def get_package_id(self, name):
"""
Retrieve the smart p... |
Retrieve a complete list of bought ip address related only to PRO Servers.
It create an internal object (Iplist) representing all of the ips object
iterated form the WS.
@param: None
@return: None
def get_ip(self):
"""
Retrieve a complete list of bought ip address relate... |
Generate the scheme for the json request.
:param req: String representing the name of the method to call
:param method_fields: A dictionary containing the method-specified fields
:rtype : json object representing the method call
def gen_def_json_scheme(self, req, method_fields=None):
""... |
:return: (dict) Response object content
def _commit(self):
"""
:return: (dict) Response object content
"""
assert self.uri is not None, Exception("BadArgument: uri property cannot be None")
url = '{}/{}'.format(self.uri, self.__class__.__name__)
serialized_json = jsonpic... |
Retrieve the current configured SharedStorages entries
:return: [list] List containing the current SharedStorages entries
def get(self):
"""
Retrieve the current configured SharedStorages entries
:return: [list] List containing the current SharedStorages entries
"""
requ... |
:type quantity: int
:type iqn: list[str]
:type name: str
:type protocol: SharedStorageProtocols
:param quantity: Amount of GB
:param iqn: List of IQN represented in string format
:param name: Name of the resource
:param protocol: Protocol to use
:return:
... |
Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object
def _get(self, *args, **kwargs):
"""Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object
"""
if 'ti... |
Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
def _get_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
"""
... |
Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
def _post(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if ... |
Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
def _post_xml(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
... |
Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'ti... |
Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
"""
... |
Test that application can authenticate to Crowd.
Attempts to authenticate the application user against
the Crowd server. In order for user authentication to
work, an application must be able to authenticate.
Returns:
bool:
True if the application authenticat... |
Authenticate a user account against the Crowd server.
Attempts to authenticate the user against the Crowd server.
Args:
username: The account username.
password: The account password.
Returns:
dict:
A dict mapping of user attributes if the ... |
Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple co... |
Validate a session token.
Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.
Args:
token: The session token.
remote: The remote address of the user.
... |
Terminates the session token, effectively logging out the user
from all crowd-enabled services.
Args:
token: The session token.
Returns:
True: If session terminated
None: If session termination failed
def terminate_session(self, token):
"""Terminat... |
Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
... |
Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
def get_user(self, username):
"""Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
... |
Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred
def set_active(self, username, active_state):
"""Set the active state of a user
... |
Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: True on success, False on failure.
def set_user_attribute(self, username, attribute, value,... |
Add a user to a group
:param username: The username to assign to the group
:param groupname: The group name into which to assign the user
:return: True on success, False on failure.
def add_user_to_group(self, username, groupname, raise_on_error=False):
"""Add a user to a group
... |
Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
True: Succeeded
False: If unsuccessful
def remove_user_from_group(self, ... |
Change new password for a user
Args:
username: The account username.
newpassword: The account new password.
raise_on_error: optional (default: False)
Returns:
True: Succeeded
False: If unsuccessful
def change_password(self, username, newpa... |
Sends the user a password reset link (by email)
Args:
username: The account username.
Returns:
True: Succeeded
False: If unsuccessful
def send_password_reset_link(self, username):
"""Sends the user a password reset link (by email)
Args:
... |
Retrieve a list of all group names that have <username> as a direct or indirect member.
Args:
username: The account username.
Returns:
list:
A list of strings of group names.
def get_nested_groups(self, username):
"""Retrieve a list of all group names ... |
Retrieves a list of all users that directly or indirectly belong to the given groupname.
Args:
groupname: The group name.
Returns:
list:
A list of strings of user names.
def get_nested_group_users(self, groupname):
"""Retrieves a list of all users that... |
Determines if the user exists.
Args:
username: The user name.
Returns:
bool:
True if the user exists in the Crowd application.
def user_exists(self, username):
"""Determines if the user exists.
Args:
username: The user name.
... |
Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups)
def get_memberships(self):
"""Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups)
... |
Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for... |
The versions associated with Blender
def versions(self) -> List(BlenderVersion):
"""
The versions associated with Blender
"""
return [BlenderVersion(tag) for tag in self.git_repo.tags] + [BlenderVersion(BLENDER_VERSION_MASTER)] |
Copy libraries from the bin directory and place them as appropriate
def run(self):
"""
Copy libraries from the bin directory and place them as appropriate
"""
self.announce("Moving library files", level=3)
# We have already built the libraries in the previous build_ext step
... |
Copy the required directory to the build directory and super().run()
def run(self):
"""
Copy the required directory to the build directory and super().run()
"""
self.announce("Moving scripts files", level=3)
self.skip_build = True
bin_dir = self.distribution.bin_dir
... |
Perform build_cmake before doing the 'normal' stuff
def run(self):
"""
Perform build_cmake before doing the 'normal' stuff
"""
for extension in self.extensions:
if extension.name == "bpy":
self.build_cmake(extension)
super().run() |
The steps required to build the extension
def build_cmake(self, extension: Extension):
"""
The steps required to build the extension
"""
# We import the setup_requires modules here because if we import them
# at the top this script will always fail as they won't be present
... |
:type addresses: list[str]
:param addresses: (list[str]) List of addresses to retrieve their reverse dns
Retrieve the current configured ReverseDns entries
:return: (list) List containing the current ReverseDns Addresses
def get(self, addresses):
"""
:type addresses: list[str]
... |
Assign one or more PTR record to a single IP Address
:type address: str
:type host_name: list[str]
:param address: (str) The IP address to configure
:param host_name: (list[str]) The list of strings representing PTR records
:return: (bool) True in case of success, False in case o... |
Remove all PTR records from the given address
:type addresses: List[str]
:param addresses: (List[str]) The IP Address to reset
:return: (bool) True in case of success, False in case of failure
def reset(self, addresses):
"""
Remove all PTR records from the given address
... |
:type healthCheckNotification: bool
:type instance: list[Instance]
:type ipAddressResourceId: list[int]
:type loadBalancerClassOfServiceID: int
:type name: str
:type notificationContacts: NotificationContacts or list[NotificationContact]
:type rules: Rules
:param ... |
Get the load balancer notifications for a specific rule within a specifying window time frame
:type startDate: datetime
:type endDate: datetime
:type loadBalancerID: int
:type loadBalancerRuleID: int
:param startDate: From Date
:param endDate: To Date
:param loadB... |
Check if the given authcfg_id (or the default) exists, and if it's valid
OAuth2, return the configuration or None
def get_oauth_authcfg(authcfg_id=AUTHCFG_ID):
"""Check if the given authcfg_id (or the default) exists, and if it's valid
OAuth2, return the configuration or None"""
# Handle empty strings
... |
Setup oauth configuration to access the BCS API,
return authcfg_id on success, None on failure
def setup_oauth(username, password, basemaps_token_uri, authcfg_id=AUTHCFG_ID, authcfg_name=AUTHCFG_NAME):
"""Setup oauth configuration to access the BCS API,
return authcfg_id on success, None on failure
"""... |
Create a new SearchQuery instance and execute a search against ES.
Args:
search: elasticsearch.search.Search object, that internally contains
the connection and query; this is the query that is executed. All
we are doing is logging the input and parsing the output.
search_te... |
Return True if an object is part of the search index queryset.
Sometimes it's useful to know if an object _should_ be indexed. If
an object is saved, how do you know if you should push that change
to the search index? The simplest (albeit not most efficient) way
is to check if it appear... |
Return queryset of objects from SearchQuery.results, **in order**.
EXPERIMENTAL: this will only work with results from a single index,
with a single doc_type - as we are returning a single QuerySet.
This method takes the hits JSON and converts that into a queryset
of all the relevant o... |
Prepare SQL statement consisting of a sequence of WHEN .. THEN statements.
def _raw_sql(self, values):
"""Prepare SQL statement consisting of a sequence of WHEN .. THEN statements."""
if isinstance(self.model._meta.pk, CharField):
when_clauses = " ".join(
[self._when("'{}'".... |
Key used for storing search docs in local cache.
def search_document_cache_key(self):
"""Key used for storing search docs in local cache."""
return "elasticsearch_django:{}.{}.{}".format(
self._meta.app_label, self._meta.model_name, self.pk
) |
Return True if the field can be serialized into a JSON doc.
def _is_field_serializable(self, field_name):
"""Return True if the field can be serialized into a JSON doc."""
return (
self._meta.get_field(field_name).get_internal_type()
in self.SIMPLE_UPDATE_FIELD_TYPES
) |
Clean the list of update_fields based on the index being updated.\
If any field in the update_fields list is not in the set of properties
defined by the index mapping for this model, then we ignore it. If
a field _is_ in the mapping, but the underlying model field is a
related object, a... |
Return a partial update document based on which fields have been updated.
If an object is saved with the `update_fields` argument passed
through, then it is assumed that this is a 'partial update'. In
this scenario we need a {property: value} dictionary containing
just the fields we wan... |
Return an object as represented in a bulk api operation.
Bulk API operations have a very specific format. This function will
call the standard `as_search_document` method on the object and then
wrap that up in the correct format for the action specified.
https://www.elastic.co/guide/en... |
Fetch the object's document from a search index by id.
def fetch_search_document(self, *, index):
"""Fetch the object's document from a search index by id."""
assert self.pk, "Object must have a primary key before being indexed."
client = get_client()
return client.get(index=index, doc_... |
Create or replace search document in named index.
Checks the local cache to see if the document has changed,
and if not aborts the update, else pushes to ES, and then
resets the local cache. Cache timeout is set as "cache_expiry"
in the settings, and defaults to 60s.
def index_search_d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.