_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q264900 | Nemo.register | validation | def register(self):
""" Register the app using Blueprint
:return: Nemo blueprint
:rtype: flask.Blueprint
"""
if self.app is not None:
if not self.blueprint:
self.blueprint = self.create_blueprint()
self.app.register_blueprint(self.blueprin... | python | {
"resource": ""
} |
q264901 | Nemo.register_filters | validation | def register_filters(self):
""" Register filters for Jinja to use
.. note:: Extends the dictionary filters of jinja_env using self._filters list
"""
for _filter, instance in self._filters:
if not instance:
self.app.jinja_env.filters[
_filt... | python | {
"resource": ""
} |
q264902 | Nemo.register_plugins | validation | def register_plugins(self):
""" Register plugins in Nemo instance
- Clear routes first if asked by one plugin
- Clear assets if asked by one plugin and replace by the last plugin registered static_folder
- Register each plugin
- Append plugin routes to registered routes
... | python | {
"resource": ""
} |
q264903 | Nemo.chunk | validation | def chunk(self, text, reffs):
""" Handle a list of references depending on the text identifier using the chunker dictionary.
:param text: Text object from which comes the references
:type text: MyCapytains.resources.texts.api.Text
:param reffs: List of references to transform
:t... | python | {
"resource": ""
} |
q264904 | add_tag | validation | def add_tag():
"""
Obtains the data from the pipe and appends the given tag.
"""
if len(sys.argv) > 1:
tag = sys.argv[1]
doc_mapper = DocMapper()
if doc_mapper.is_pipe:
count = 0
for obj in doc_mapper.get_pipe():
obj.add_tag(tag)
... | python | {
"resource": ""
} |
q264905 | Config.set | validation | def set(self, section, key, value):
"""
Creates the section value if it does not exists and sets the value.
Use write_config to actually set the value.
"""
if not section in self.config:
self.config.add_section(section)
self.config.set(section, key, va... | python | {
"resource": ""
} |
q264906 | Config.get | validation | def get(self, section, key):
"""
This function tries to retrieve the value from the configfile
otherwise will return a default.
"""
try:
return self.config.get(section, key)
except configparser.NoSectionError:
pass
except configpars... | python | {
"resource": ""
} |
q264907 | Config.config_dir | validation | def config_dir(self):
"""
Returns the configuration directory
"""
home = expanduser('~')
config_dir = os.path.join(home, '.jackal')
return config_dir | python | {
"resource": ""
} |
q264908 | Config.write_config | validation | def write_config(self, initialize_indices=False):
"""
Write the current config to disk to store them.
"""
if not os.path.exists(self.config_dir):
os.mkdir(self.config_dir)
with open(self.config_file, 'w') as configfile:
self.config.write(configfile)
... | python | {
"resource": ""
} |
q264909 | ensure_remote_branch_is_tracked | validation | def ensure_remote_branch_is_tracked(branch):
"""Track the specified remote branch if it is not already tracked."""
if branch == MASTER_BRANCH:
# We don't need to explicitly track the master branch, so we're done.
return
# Ensure the specified branch is in the local branch list.
output =... | python | {
"resource": ""
} |
q264910 | main | validation | def main(branch):
"""Checkout, update and branch from the specified branch."""
try:
# Ensure that we're in a git repository. This command is silent unless
# you're not actually in a git repository, in which case, you receive a
# "Not a git repository" error message.
output = subp... | python | {
"resource": ""
} |
q264911 | get_interface_name | validation | def get_interface_name():
"""
Returns the interface name of the first not link_local and not loopback interface.
"""
interface_name = ''
interfaces = psutil.net_if_addrs()
for name, details in interfaces.items():
for detail in details:
if detail.family == socket.AF_INET:
... | python | {
"resource": ""
} |
q264912 | Spoofing.load_targets | validation | def load_targets(self):
"""
load_targets will load the services with smb signing disabled and if ldap is enabled the services with the ldap port open.
"""
ldap_services = []
if self.ldap:
ldap_services = self.search.get_services(ports=[389], up=True)
self... | python | {
"resource": ""
} |
q264913 | Spoofing.write_targets | validation | def write_targets(self):
"""
write_targets will write the contents of ips and ldap_strings to the targets_file.
"""
if len(self.ldap_strings) == 0 and len(self.ips) == 0:
print_notification("No targets left")
if self.auto_exit:
if self.notifier... | python | {
"resource": ""
} |
q264914 | Spoofing.start_processes | validation | def start_processes(self):
"""
Starts the ntlmrelayx.py and responder processes.
Assumes you have these programs in your path.
"""
self.relay = subprocess.Popen(['ntlmrelayx.py', '-6', '-tf', self.targets_file, '-w', '-l', self.directory, '-of', self.output_file], cwd=sel... | python | {
"resource": ""
} |
q264915 | Spoofing.callback | validation | def callback(self, event):
"""
Function that gets called on each event from pyinotify.
"""
# IN_CLOSE_WRITE -> 0x00000008
if event.mask == 0x00000008:
if event.name.endswith('.json'):
print_success("Ldapdomaindump file found")
if ev... | python | {
"resource": ""
} |
q264916 | Spoofing.watch | validation | def watch(self):
"""
Watches directory for changes
"""
wm = pyinotify.WatchManager()
self.notifier = pyinotify.Notifier(wm, default_proc_fun=self.callback)
wm.add_watch(self.directory, pyinotify.ALL_EVENTS)
try:
self.notifier.loop()
except ... | python | {
"resource": ""
} |
q264917 | Spoofing.terminate_processes | validation | def terminate_processes(self):
"""
Terminate the processes.
"""
if self.relay:
self.relay.terminate()
if self.responder:
self.responder.terminate() | python | {
"resource": ""
} |
q264918 | Spoofing.wait | validation | def wait(self):
"""
This function waits for the relay and responding processes to exit.
Captures KeyboardInterrupt to shutdown these processes.
"""
try:
self.relay.wait()
self.responder.wait()
except KeyboardInterrupt:
print_not... | python | {
"resource": ""
} |
q264919 | QueryPrototype.getAnnotations | validation | def getAnnotations(self, targets, wildcard=".", include=None, exclude=None, limit=None, start=1, expand=False,
**kwargs):
""" Retrieve annotations from the query provider
:param targets: The CTS URN(s) to query as the target of annotations
:type targets: [MyCapytain.commo... | python | {
"resource": ""
} |
q264920 | Breadcrumb.render | validation | def render(self, **kwargs):
""" Make breadcrumbs for a route
:param kwargs: dictionary of named arguments used to construct the view
:type kwargs: dict
:return: List of dict items the view can use to construct the link.
:rtype: {str: list({ "link": str, "title", str, "args", dic... | python | {
"resource": ""
} |
q264921 | main | validation | def main():
"""
This function obtains hosts from core and starts a nessus scan on these hosts.
The nessus tag is appended to the host tags.
"""
config = Config()
core = HostSearch()
hosts = core.get_hosts(tags=['!nessus'], up=True)
hosts = [host for host in hosts]
host_ips = ... | python | {
"resource": ""
} |
q264922 | Nessus.get_template_uuid | validation | def get_template_uuid(self):
"""
Retrieves the uuid of the given template name.
"""
response = requests.get(self.url + 'editor/scan/templates', headers=self.headers, verify=False)
templates = json.loads(response.text)
for template in templates['templates']:
... | python | {
"resource": ""
} |
q264923 | Nessus.create_scan | validation | def create_scan(self, host_ips):
"""
Creates a scan with the given host ips
Returns the scan id of the created object.
"""
now = datetime.datetime.now()
data = {
"uuid": self.get_template_uuid(),
"settings": {
"name": "jacka... | python | {
"resource": ""
} |
q264924 | Nessus.start_scan | validation | def start_scan(self, scan_id):
"""
Starts the scan identified by the scan_id.s
"""
requests.post(self.url + 'scans/{}/launch'.format(scan_id), verify=False, headers=self.headers) | python | {
"resource": ""
} |
q264925 | cmpToDataStore_uri | validation | def cmpToDataStore_uri(base, ds1, ds2):
'''Bases the comparison of the datastores on URI alone.'''
ret = difflib.get_close_matches(base.uri, [ds1.uri, ds2.uri], 1, cutoff=0.5)
if len(ret) <= 0:
return 0
if ret[0] == ds1.uri:
return -1
return 1 | python | {
"resource": ""
} |
q264926 | JackalDoc.add_tag | validation | def add_tag(self, tag):
"""
Adds a tag to the list of tags and makes sure the result list contains only unique results.
"""
self.tags = list(set(self.tags or []) | set([tag])) | python | {
"resource": ""
} |
q264927 | JackalDoc.remove_tag | validation | def remove_tag(self, tag):
"""
Removes a tag from this object
"""
self.tags = list(set(self.tags or []) - set([tag])) | python | {
"resource": ""
} |
q264928 | JackalDoc.to_dict | validation | def to_dict(self, include_meta=False):
"""
Returns the result as a dictionary, provide the include_meta flag to als show information like index and doctype.
"""
result = super(JackalDoc, self).to_dict(include_meta=include_meta)
if include_meta:
source = result.pop... | python | {
"resource": ""
} |
q264929 | AnnotationsApiPlugin.r_annotations | validation | def r_annotations(self):
""" Route to retrieve annotations by target
:param target_urn: The CTS URN for which to retrieve annotations
:type target_urn: str
:return: a JSON string containing count and list of resources
:rtype: {str: Any}
"""
target = request.ar... | python | {
"resource": ""
} |
q264930 | Enum.lookup | validation | def lookup(cls, key, get=False):
"""Returns the label for a given Enum key"""
if get:
item = cls._item_dict.get(key)
return item.name if item else key
return cls._item_dict[key].name | python | {
"resource": ""
} |
q264931 | Enum.verbose | validation | def verbose(cls, key=False, default=''):
"""Returns the verbose name for a given enum value"""
if key is False:
items = cls._item_dict.values()
return [(x.key, x.value) for x in sorted(items, key=lambda x:x.sort or x.key)]
item = cls._item_dict.get(key)
return it... | python | {
"resource": ""
} |
q264932 | get_configured_dns | validation | def get_configured_dns():
"""
Returns the configured DNS servers with the use f nmcli.
"""
ips = []
try:
output = subprocess.check_output(['nmcli', 'device', 'show'])
output = output.decode('utf-8')
for line in output.split('\n'):
if 'DNS' in line:
... | python | {
"resource": ""
} |
q264933 | zone_transfer | validation | def zone_transfer(address, dns_name):
"""
Tries to perform a zone transfer.
"""
ips = []
try:
print_notification("Attempting dns zone transfer for {} on {}".format(dns_name, address))
z = dns.zone.from_xfr(dns.query.xfr(address, dns_name))
except dns.exception.FormError:
... | python | {
"resource": ""
} |
q264934 | resolve_domains | validation | def resolve_domains(domains, disable_zone=False):
"""
Resolves the list of domains and returns the ips.
"""
dnsresolver = dns.resolver.Resolver()
ips = []
for domain in domains:
print_notification("Resolving {}".format(domain))
try:
result = dnsresolver.query(do... | python | {
"resource": ""
} |
q264935 | parse_ips | validation | def parse_ips(ips, netmask, include_public):
"""
Parses the list of ips, turns these into ranges based on the netmask given.
Set include_public to True to include public IP adresses.
"""
hs = HostSearch()
rs = RangeSearch()
ranges = []
ips = list(set(ips))
included_ips = []
... | python | {
"resource": ""
} |
q264936 | create_connection | validation | def create_connection(conf):
"""
Creates a connection based upon the given configuration object.
"""
host_config = {}
host_config['hosts'] = [conf.get('jackal', 'host')]
if int(conf.get('jackal', 'use_ssl')):
host_config['use_ssl'] = True
if conf.get('jackal', 'ca_certs'):
... | python | {
"resource": ""
} |
q264937 | CoreSearch.search | validation | def search(self, number=None, *args, **kwargs):
"""
Searches the elasticsearch instance to retrieve the requested documents.
"""
search = self.create_search(*args, **kwargs)
try:
if number:
response = search[0:number]
else:
... | python | {
"resource": ""
} |
q264938 | CoreSearch.argument_search | validation | def argument_search(self):
"""
Uses the command line arguments to fill the search function and call it.
"""
arguments, _ = self.argparser.parse_known_args()
return self.search(**vars(arguments)) | python | {
"resource": ""
} |
q264939 | CoreSearch.count | validation | def count(self, *args, **kwargs):
"""
Returns the number of results after filtering with the given arguments.
"""
search = self.create_search(*args, **kwargs)
try:
return search.count()
except NotFoundError:
print_error("The index was not found... | python | {
"resource": ""
} |
q264940 | CoreSearch.argument_count | validation | def argument_count(self):
"""
Uses the command line arguments to fill the count function and call it.
"""
arguments, _ = self.argparser.parse_known_args()
return self.count(**vars(arguments)) | python | {
"resource": ""
} |
q264941 | CoreSearch.get_pipe | validation | def get_pipe(self, object_type):
"""
Returns a generator that maps the input of the pipe to an elasticsearch object.
Will call id_to_object if it cannot serialize the data from json.
"""
for line in sys.stdin:
try:
data = json.loads(line.strip(... | python | {
"resource": ""
} |
q264942 | RangeSearch.id_to_object | validation | def id_to_object(self, line):
"""
Resolves an ip adres to a range object, creating it if it doesn't exists.
"""
result = Range.get(line, ignore=404)
if not result:
result = Range(range=line)
result.save()
return result | python | {
"resource": ""
} |
q264943 | RangeSearch.argparser | validation | def argparser(self):
"""
Argparser option with search functionality specific for ranges.
"""
core_parser = self.core_parser
core_parser.add_argument('-r', '--range', type=str, help="The range to search for use")
return core_parser | python | {
"resource": ""
} |
q264944 | ServiceSearch.object_to_id | validation | def object_to_id(self, obj):
"""
Searches elasticsearch for objects with the same address, protocol, port and state.
"""
search = Service.search()
search = search.filter("term", address=obj.address)
search = search.filter("term", protocol=obj.protocol)
search ... | python | {
"resource": ""
} |
q264945 | UserSearch.id_to_object | validation | def id_to_object(self, line):
"""
Resolves the given id to a user object, if it doesn't exists it will be created.
"""
user = User.get(line, ignore=404)
if not user:
user = User(username=line)
user.save()
return user | python | {
"resource": ""
} |
q264946 | UserSearch.get_domains | validation | def get_domains(self):
"""
Retrieves the domains of the users from elastic.
"""
search = User.search()
search.aggs.bucket('domains', 'terms', field='domain', order={'_count': 'desc'}, size=100)
response = search.execute()
return [entry.key for entry in respons... | python | {
"resource": ""
} |
q264947 | DocMapper.get_pipe | validation | def get_pipe(self):
"""
Returns a list that maps the input of the pipe to an elasticsearch object.
Will call id_to_object if it cannot serialize the data from json.
"""
lines = []
for line in sys.stdin:
try:
lines.append(self.line_to_ob... | python | {
"resource": ""
} |
q264948 | Protocol.tree2commands | validation | def tree2commands(self, adapter, session, lastcmds, xsync):
'''Consumes an ET protocol tree and converts it to state.Command commands'''
# do some preliminary sanity checks...
# todo: do i really want to be using assert statements?...
assert xsync.tag == constants.NODE_SYNCML
assert len(xsync) == ... | python | {
"resource": ""
} |
q264949 | initialize_indices | validation | def initialize_indices():
"""
Initializes the indices
"""
Host.init()
Range.init()
Service.init()
User.init()
Credential.init()
Log.init() | python | {
"resource": ""
} |
q264950 | parse_single_computer | validation | def parse_single_computer(entry):
"""
Parse the entry into a computer object.
"""
computer = Computer(dns_hostname=get_field(entry, 'dNSHostName'), description=get_field(
entry, 'description'), os=get_field(entry, 'operatingSystem'), group_id=get_field(entry, 'primaryGroupID'))
try:
... | python | {
"resource": ""
} |
q264951 | parse_domain_computers | validation | def parse_domain_computers(filename):
"""
Parse the file and extract the computers, import the computers that resolve into jackal.
"""
with open(filename) as f:
data = json.loads(f.read())
hs = HostSearch()
count = 0
entry_count = 0
print_notification("Parsing {} entries".for... | python | {
"resource": ""
} |
q264952 | parse_user | validation | def parse_user(entry, domain_groups):
"""
Parses a single entry from the domaindump
"""
result = {}
distinguished_name = get_field(entry, 'distinguishedName')
result['domain'] = ".".join(distinguished_name.split(',DC=')[1:])
result['name'] = get_field(entry, 'name')
result['username'... | python | {
"resource": ""
} |
q264953 | parse_domain_users | validation | def parse_domain_users(domain_users_file, domain_groups_file):
"""
Parses the domain users and groups files.
"""
with open(domain_users_file) as f:
users = json.loads(f.read())
domain_groups = {}
if domain_groups_file:
with open(domain_groups_file) as f:
groups =... | python | {
"resource": ""
} |
q264954 | import_domaindump | validation | def import_domaindump():
"""
Parses ldapdomaindump files and stores hosts and users in elasticsearch.
"""
parser = argparse.ArgumentParser(
description="Imports users, groups and computers result files from the ldapdomaindump tool, will resolve the names from domain_computers output for IPs"... | python | {
"resource": ""
} |
q264955 | autocomplete | validation | def autocomplete(query, country=None, hurricanes=False, cities=True, timeout=5):
"""Make an autocomplete API request
This can be used to find cities and/or hurricanes by name
:param string query: city
:param string country: restrict search to a specific country. Must be a two letter country code
:... | python | {
"resource": ""
} |
q264956 | request | validation | def request(key, features, query, timeout=5):
"""Make an API request
:param string key: API key to use
:param list features: features to request. It must be a subset of :data:`FEATURES`
:param string query: query to send
:param integer timeout: timeout of the request
:returns: result of the API... | python | {
"resource": ""
} |
q264957 | _unicode | validation | def _unicode(string):
"""Try to convert a string to unicode using different encodings"""
for encoding in ['utf-8', 'latin1']:
try:
result = unicode(string, encoding)
return result
except UnicodeDecodeError:
pass
result = unicode(string, 'utf-8', 'replace')... | python | {
"resource": ""
} |
q264958 | http_get_provider | validation | def http_get_provider(provider,
request_url, params, token_secret, token_cookie = None):
'''Handle HTTP GET requests on an authentication endpoint.
Authentication flow begins when ``params`` has a ``login`` key with a value
of ``start``. For instance, ``/auth/twitter?login=start``.
... | python | {
"resource": ""
} |
q264959 | Target.to_json | validation | def to_json(self):
""" Method to call to get a serializable object for json.dump or jsonify based on the target
:return: dict
"""
if self.subreference is not None:
return {
"source": self.objectId,
"selector": {
"type": "Fr... | python | {
"resource": ""
} |
q264960 | AnnotationResource.read | validation | def read(self):
""" Read the contents of the Annotation Resource
:return: the contents of the resource
:rtype: str or bytes or flask.response
"""
if not self.__content__:
self.__retriever__ = self.__resolver__.resolve(self.uri)
self.__content__, self.__mi... | python | {
"resource": ""
} |
q264961 | build_index_and_mapping | validation | def build_index_and_mapping(triples):
"""index all triples into indexes and return their mappings"""
ents = bidict()
rels = bidict()
ent_id = 0
rel_id = 0
collected = []
for t in triples:
for e in (t.head, t.tail):
if e not in ents:
ents[e] = ent_id
... | python | {
"resource": ""
} |
q264962 | recover_triples_from_mapping | validation | def recover_triples_from_mapping(indexes, ents: bidict, rels: bidict):
"""recover triples from mapping."""
triples = []
for t in indexes:
triples.append(kgedata.Triple(ents.inverse[t.head], rels.inverse[t.relation], ents.inverse[t.tail]))
return triples | python | {
"resource": ""
} |
q264963 | _transform_triple_numpy | validation | def _transform_triple_numpy(x):
"""Transform triple index into a 1-D numpy array."""
return np.array([x.head, x.relation, x.tail], dtype=np.int64) | python | {
"resource": ""
} |
q264964 | pack_triples_numpy | validation | def pack_triples_numpy(triples):
"""Packs a list of triple indexes into a 2D numpy array."""
if len(triples) == 0:
return np.array([], dtype=np.int64)
return np.stack(list(map(_transform_triple_numpy, triples)), axis=0) | python | {
"resource": ""
} |
q264965 | remove_near_duplicate_relation | validation | def remove_near_duplicate_relation(triples, threshold=0.97):
"""If entity pairs in a relation is as close as another relations, only keep one relation of such set."""
logging.debug("remove duplicate")
_assert_threshold(threshold)
duplicate_rel_counter = defaultdict(list)
relations = set()
for ... | python | {
"resource": ""
} |
q264966 | remove_direct_link_triples | validation | def remove_direct_link_triples(train, valid, test):
"""Remove direct links in the training sets."""
pairs = set()
merged = valid + test
for t in merged:
pairs.add((t.head, t.tail))
filtered = filterfalse(lambda t: (t.head, t.tail) in pairs or (t.tail, t.head) in pairs, train)
return lis... | python | {
"resource": ""
} |
q264967 | Indexer.shrink_indexes_in_place | validation | def shrink_indexes_in_place(self, triples):
"""Uses a union find to find segment."""
_ent_roots = self.UnionFind(self._ent_id)
_rel_roots = self.UnionFind(self._rel_id)
for t in triples:
_ent_roots.add(t.head)
_ent_roots.add(t.tail)
_rel_roots.add(t.... | python | {
"resource": ""
} |
q264968 | IndexBuilder.freeze | validation | def freeze(self):
"""Create a usable data structure for serializing."""
data = super(IndexBuilder, self).freeze()
try:
# Sphinx >= 1.5 format
# Due to changes from github.com/sphinx-doc/sphinx/pull/2454
base_file_names = data['docnames']
except KeyErro... | python | {
"resource": ""
} |
q264969 | log_operation | validation | def log_operation(entities, operation_name, params=None):
"""Logs an operation done on an entity, possibly with other arguments
"""
if isinstance(entities, (list, tuple)):
entities = list(entities)
else:
entities = [entities]
p = {'name': operation_name, 'on': entities}
if param... | python | {
"resource": ""
} |
q264970 | log_state | validation | def log_state(entity, state):
"""Logs a new state of an entity
"""
p = {'on': entity, 'state': state}
_log(TYPE_CODES.STATE, p) | python | {
"resource": ""
} |
q264971 | log_update | validation | def log_update(entity, update):
"""Logs an update done on an entity
"""
p = {'on': entity, 'update': update}
_log(TYPE_CODES.UPDATE, p) | python | {
"resource": ""
} |
q264972 | log_error | validation | def log_error(error, result):
"""Logs an error
"""
p = {'error': error, 'result':result}
_log(TYPE_CODES.ERROR, p) | python | {
"resource": ""
} |
q264973 | dict_cursor | validation | def dict_cursor(func):
"""
Decorator that provides a dictionary cursor to the calling function
Adds the cursor as the second argument to the calling functions
Requires that the function being decorated is an instance of a class or object
that yields a cursor from a get_cursor(cursor_type=CursorTyp... | python | {
"resource": ""
} |
q264974 | cursor | validation | def cursor(func):
"""
Decorator that provides a cursor to the calling function
Adds the cursor as the second argument to the calling functions
Requires that the function being decorated is an instance of a class or object
that yields a cursor from a get_cursor() coroutine or provides such an objec... | python | {
"resource": ""
} |
q264975 | nt_cursor | validation | def nt_cursor(func):
"""
Decorator that provides a namedtuple cursor to the calling function
Adds the cursor as the second argument to the calling functions
Requires that the function being decorated is an instance of a class or object
that yields a cursor from a get_cursor(cursor_type=CursorType.... | python | {
"resource": ""
} |
q264976 | transaction | validation | def transaction(func):
"""
Provides a transacted cursor which will run in autocommit=false mode
For any exception the transaction will be rolled back.
Requires that the function being decorated is an instance of a class or object
that yields a cursor from a get_cursor(cursor_type=CursorType.NAMEDTU... | python | {
"resource": ""
} |
q264977 | PostgresStore.count | validation | def count(cls, cur, table:str, where_keys: list=None):
"""
gives the number of records in the table
Args:
table: a string indicating the name of the table
Returns:
an integer indicating the number of records in the table
"""
if where_keys:
... | python | {
"resource": ""
} |
q264978 | PostgresStore.insert | validation | def insert(cls, cur, table: str, values: dict):
"""
Creates an insert statement with only chosen fields
Args:
table: a string indicating the name of the table
values: a dict of fields and values to be inserted
Returns:
A 'Record' object with table co... | python | {
"resource": ""
} |
q264979 | PostgresStore.update | validation | def update(cls, cur, table: str, values: dict, where_keys: list) -> tuple:
"""
Creates an update query with only chosen fields
Supports only a single field where clause
Args:
table: a string indicating the name of the table
values: a dict of fields and values to ... | python | {
"resource": ""
} |
q264980 | PostgresStore.delete | validation | def delete(cls, cur, table: str, where_keys: list):
"""
Creates a delete query with where keys
Supports multiple where clause with and or or both
Args:
table: a string indicating the name of the table
where_keys: list of dictionary
example of where ke... | python | {
"resource": ""
} |
q264981 | PostgresStore.select | validation | def select(cls, cur, table: str, order_by: str, columns: list=None, where_keys: list=None, limit=100,
offset=0):
"""
Creates a select query for selective columns with where keys
Supports multiple where claus with and or or both
Args:
table: a string indicating... | python | {
"resource": ""
} |
q264982 | PostgresStore.raw_sql | validation | def raw_sql(cls, cur, query: str, values: tuple):
"""
Run a raw sql query
Args:
query : query string to execute
values : tuple of values to be used with the query
Returns:
result of query as list of named tuple
"""
yield from cur.exe... | python | {
"resource": ""
} |
q264983 | serialize_text | validation | def serialize_text(out, text):
"""This method is used to append content of the `text`
argument to the `out` argument.
Depending on how many lines in the text, a
padding can be added to all lines except the first
one.
Concatenation result is appended to the `out` argument.
"""
padding =... | python | {
"resource": ""
} |
q264984 | format_value | validation | def format_value(value):
"""This function should return unicode representation of the value
"""
value_id = id(value)
if value_id in recursion_breaker.processed:
return u'<recursion>'
recursion_breaker.processed.add(value_id)
try:
if isinstance(value, six.binary_type):
... | python | {
"resource": ""
} |
q264985 | traverse | validation | def traverse(element, query, deep=False):
"""
Helper function to traverse an element tree rooted at element, yielding nodes matching the query.
"""
# Grab the next part of the query (it will be chopped from the front each iteration).
part = query[0]
if not part:
# If the part is blank, w... | python | {
"resource": ""
} |
q264986 | parse_query | validation | def parse_query(query):
"""
Given a simplified XPath query string, returns an array of normalized query parts.
"""
parts = query.split('/')
norm = []
for p in parts:
p = p.strip()
if p:
norm.append(p)
elif '' not in norm:
norm.append('')
return... | python | {
"resource": ""
} |
q264987 | XmlElement.insert | validation | def insert(self, before, name, attrs=None, data=None):
"""
Inserts a new element as a child of this element, before the specified index or sibling.
:param before: An :class:`XmlElement` or a numeric index to insert the new node before
:param name: The tag name to add
:param attr... | python | {
"resource": ""
} |
q264988 | XmlElement.children | validation | def children(self, name=None, reverse=False):
"""
A generator yielding children of this node.
:param name: If specified, only consider elements with this tag name
:param reverse: If ``True``, children will be yielded in reverse declaration order
"""
elems = self._childre... | python | {
"resource": ""
} |
q264989 | XmlElement._match | validation | def _match(self, pred):
"""
Helper function to determine if this node matches the given predicate.
"""
if not pred:
return True
# Strip off the [ and ]
pred = pred[1:-1]
if pred.startswith('@'):
# An attribute predicate checks the existence... | python | {
"resource": ""
} |
q264990 | XmlElement.path | validation | def path(self, include_root=False):
"""
Returns a canonical path to this element, relative to the root node.
:param include_root: If ``True``, include the root node in the path. Defaults to ``False``.
"""
path = '%s[%d]' % (self.tagname, self.index or 0)
p = self.parent
... | python | {
"resource": ""
} |
q264991 | XmlElement.iter | validation | def iter(self, name=None):
"""
Recursively find any descendants of this node with the given tag name. If a tag name is omitted, this will
yield every descendant node.
:param name: If specified, only consider elements with this tag name
:returns: A generator yielding descendants ... | python | {
"resource": ""
} |
q264992 | XmlElement.last | validation | def last(self, name=None):
"""
Returns the last child of this node.
:param name: If specified, only consider elements with this tag name
:rtype: :class:`XmlElement`
"""
for c in self.children(name, reverse=True):
return c | python | {
"resource": ""
} |
q264993 | XmlElement.parents | validation | def parents(self, name=None):
"""
Yields all parents of this element, back to the root element.
:param name: If specified, only consider elements with this tag name
"""
p = self.parent
while p is not None:
if name is None or p.tagname == name:
... | python | {
"resource": ""
} |
q264994 | XmlElement.next | validation | def next(self, name=None):
"""
Returns the next sibling of this node.
:param name: If specified, only consider elements with this tag name
:rtype: :class:`XmlElement`
"""
if self.parent is None or self.index is None:
return None
for idx in xrange(self... | python | {
"resource": ""
} |
q264995 | XmlElement.prev | validation | def prev(self, name=None):
"""
Returns the previous sibling of this node.
:param name: If specified, only consider elements with this tag name
:rtype: :class:`XmlElement`
"""
if self.parent is None or self.index is None:
return None
for idx in xrange(... | python | {
"resource": ""
} |
q264996 | WebObsResultsParser.get_observations | validation | def get_observations(self):
"""
Parses the HTML table into a list of dictionaries, each of which
represents a single observation.
"""
if self.empty:
return []
rows = list(self.tbody)
observations = []
for row_observation, row_details in zip(row... | python | {
"resource": ""
} |
q264997 | get_cache_key | validation | def get_cache_key(prefix, *args, **kwargs):
"""
Calculates cache key based on `args` and `kwargs`.
`args` and `kwargs` must be instances of hashable types.
"""
hash_args_kwargs = hash(tuple(kwargs.iteritems()) + args)
return '{}_{}'.format(prefix, hash_args_kwargs) | python | {
"resource": ""
} |
q264998 | cache_func | validation | def cache_func(prefix, method=False):
"""
Cache result of function execution into the django cache backend.
Calculate cache key based on `prefix`, `args` and `kwargs` of the function.
For using like object method set `method=True`.
"""
def decorator(func):
@wraps(func)
def wrappe... | python | {
"resource": ""
} |
q264999 | get_or_default | validation | def get_or_default(func=None, default=None):
"""
Wrapper around Django's ORM `get` functionality.
Wrap anything that raises ObjectDoesNotExist exception
and provide the default value if necessary.
`default` by default is None. `default` can be any callable,
if it is callable it will be called wh... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.