_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q226200
SoltraEdge.api_related
train
def api_related(self, query): ''' Find related objects through SoltraEdge API ''' url = "{0}/{1}/related/?format=json".format(self.base_url, query) response = requests.get(url, headers=self.headers, verify=self.verify_ssl) if response.status_code == 200: ret...
python
{ "resource": "" }
q226201
SoltraEdge.tlp_classifiers
train
def tlp_classifiers(self, name_tlp, val_tlp): ''' Classifier between Cortex and Soltra. Soltra uses name-TLP, and Cortex "value-TLP" ''' classifier = { "WHITE": 0, "GREEN": 1, "AMBER": 2, "RED": 3 } valid = True ...
python
{ "resource": "" }
q226202
SoltraEdge.pop_object
train
def pop_object(self, element): ''' Pop the object element if the object contains an higher TLP then allowed. ''' redacted_text = "Redacted. Object contained TLP value higher than allowed." element['id'] = '' element['url'] = '' element['type'] = '' eleme...
python
{ "resource": "" }
q226203
__query
train
def __query(domain, limit=100): """Using the shell script to query pdns.cert.at is a hack, but python raises an error every time using subprocess functions to call whois. So this hack is avoiding calling whois directly. Ugly, but works. :param domain: The domain pdns is queried with. :type domain: str ...
python
{ "resource": "" }
q226204
OLEToolsSubmodule.analyze_vba
train
def analyze_vba(self, path): """Analyze a given sample for malicious vba.""" try: vba_parser = VBA_Parser_CLI(path, relaxed=True) vbaparser_result = vba_parser.process_file_json(show_decoded_strings=True, display_code=...
python
{ "resource": "" }
q226205
Reader.get
train
def get(self, ip_address): """Return the record for the ip_address in the MaxMind DB Arguments: ip_address -- an IP address in the standard string notation """ address = ipaddress.ip_address(ip_address) if address.version == 6 and self._metadata.ip_version == 4: ...
python
{ "resource": "" }
q226206
CrtshAnalyzer.search
train
def search(self, domain, wildcard=True): """ Search crt.sh for the given domain. domain -- Domain to search for wildcard -- Whether or not to prepend a wildcard to the domain (default: True) Return a list of a certificate dict: { "issuer...
python
{ "resource": "" }
q226207
MISPClient.__search
train
def __search(self, value, type_attribute): """Search method call wrapper. :param value: value to search for. :type value: str :param type_attribute: attribute types to search for. :type type_attribute: [list, none] """ results = [] if not value: ...
python
{ "resource": "" }
q226208
TorBlutmagieClient.search_tor_node
train
def search_tor_node(self, data_type, data): """Lookup an artifact to check if it is a known tor exit node. :param data_type: The artifact type. Must be one of 'ip', 'fqdn' or 'domain' :param data: The artifact to lookup :type data_type: str :type data: ...
python
{ "resource": "" }
q226209
YaraAnalyzer.check
train
def check(self, file): """ Checks a given file against all available yara rules :param file: Path to file :type file:str :returns: Python dictionary containing the results :rtype: list """ result = [] for rule in self.ruleset: matches ...
python
{ "resource": "" }
q226210
CIRCLPassiveDNSAnalyzer.query
train
def query(self, domain): """The actual query happens here. Time from queries is replaced with isoformat. :param domain: The domain which should gets queried. :type domain: str :returns: List of dicts containing the search results. :rtype: [list, dict] """ result ...
python
{ "resource": "" }
q226211
CIRCLPassiveSSLAnalyzer.query_ip
train
def query_ip(self, ip): """ Queries Circl.lu Passive SSL for an ip using PyPSSL class. Returns error if nothing is found. :param ip: IP to query for :type ip: str :returns: python dict of results :rtype: dict """ try: result = self.pssl.query(...
python
{ "resource": "" }
q226212
CIRCLPassiveSSLAnalyzer.query_certificate
train
def query_certificate(self, cert_hash): """ Queries Circl.lu Passive SSL for a certificate hash using PyPSSL class. Returns error if nothing is found. :param cert_hash: hash to query for :type cert_hash: str :return: python dict of results :rtype: dict """ ...
python
{ "resource": "" }
q226213
GreyNoiseAnalyzer._get_level
train
def _get_level(current_level, new_intention): """ Map GreyNoise intentions to Cortex maliciousness levels. Accept a Cortex level and a GreyNoise intention, the return the more malicious of the two. :param current_level: A Cortex maliciousness level https://github.com/TheHive...
python
{ "resource": "" }
q226214
GreyNoiseAnalyzer.summary
train
def summary(self, raw): """ Return one taxonomy summarizing the reported tags If there is only one tag, use it as the predicate If there are multiple tags, use "entries" as the predicate Use the total count as the value Use the most malicious level found ...
python
{ "resource": "" }
q226215
PublicApi.scan_file
train
def scan_file(self, this_file): """ Submit a file to be scanned by VirusTotal :param this_file: File to be scanned (32MB file size limit) :return: JSON response that contains scan_id and permalink. """ params = {'apikey': self.api_key} try: if type(this_file)...
python
{ "resource": "" }
q226216
PublicApi.scan_url
train
def scan_url(self, this_url): """ Submit a URL to be scanned by VirusTotal. :param this_url: The URL that should be scanned. This parameter accepts a list of URLs (up to 4 with the standard request rate) so as to perform a batch scanning request with one single call. The ...
python
{ "resource": "" }
q226217
PrivateApi.get_file
train
def get_file(self, this_hash): """ Download a file by its hash. Downloads a file from VirusTotal's store given one of its hashes. This call can be used in conjuction with the file searching call in order to download samples that match a given set of criteria. :param this_hash: The md5/...
python
{ "resource": "" }
q226218
PrivateApi.get_url_report
train
def get_url_report(self, this_url, scan='0', allinfo=1): """ Get the scan results for a URL. :param this_url: A URL for which you want to retrieve the most recent report. You may also specify a scan_id (sha256-timestamp as returned by the URL submission API) to access a specific report. At the ...
python
{ "resource": "" }
q226219
PrivateApi.get_comments
train
def get_comments(self, resource, before=None): """ Get comments for a file or URL. Retrieve a list of VirusTotal Community comments for a given file or URL. VirusTotal Community comments are user submitted reviews on a given item, these comments may contain anything from the in-the-wild locatio...
python
{ "resource": "" }
q226220
IntelApi.save_downloaded_file
train
def save_downloaded_file(filename, save_file_at, file_stream): """ Save Downloaded File to Disk Helper Function :param save_file_at: Path of where to save the file. :param file_stream: File stream :param filename: Name to save the file. """ filename = os.path.join(save_f...
python
{ "resource": "" }
q226221
PlaceRecord.name
train
def name(self): """Dict with locale codes as keys and localized name as value""" # pylint:disable=E1101 return next((self.names.get(x) for x in self._locales if x in self.names), None)
python
{ "resource": "" }
q226222
PatrowlAnalyzer.summary
train
def summary(self, raw): """Parse, format and return scan summary.""" taxonomies = [] level = "info" namespace = "Patrowl" # getreport service if self.service == 'getreport': if 'risk_level' in raw and raw['risk_level']: risk_level = raw['risk_...
python
{ "resource": "" }
q226223
PatrowlAnalyzer.run
train
def run(self): """Run the analyzer.""" try: if self.service == 'getreport': service_url = '{}/assets/api/v1/details/{}'.format( self.url, self.get_data()) headers = { 'Authorization': 'token {}'.format(s...
python
{ "resource": "" }
q226224
BackscatterAnalyzer.run
train
def run(self): """Run the process to get observation data from Backscatter.io.""" kwargs = {'query': self.get_data()} if self.data_type == "ip": kwargs.update({'query_type': 'ip'}) elif self.data_type == "network": kwargs.update({'query_type': 'network'}) ...
python
{ "resource": "" }
q226225
BackscatterAnalyzer.summary
train
def summary(self, raw): """Use the Backscatter.io summary data to create a view.""" taxonomies = list() level = 'info' namespace = 'Backscatter.io' if self.service == 'observations': summary = raw.get('results', dict()).get('summary', dict()) taxonomies =...
python
{ "resource": "" }
q226226
Decoder.decode
train
def decode(self, offset): """Decode a section of the data section starting at offset Arguments: offset -- the location of the data structure to decode """ new_offset = offset + 1 (ctrl_byte,) = struct.unpack(b'!B', self._buffer[offset:new_offset]) type_num = ctrl...
python
{ "resource": "" }
q226227
VMRayClient.get_sample
train
def get_sample(self, samplehash): """ Downloads information about a sample using a given hash. :param samplehash: hash to search for. Has to be either md5, sha1 or sha256 :type samplehash: str :returns: Dictionary of results :rtype: dict """ apiurl = '/re...
python
{ "resource": "" }
q226228
VMRayClient.submit_sample
train
def submit_sample(self, filepath, filename, tags=['TheHive']): """ Uploads a new sample to VMRay api. Filename gets sent base64 encoded. :param filepath: path to sample :type filepath: str :param filename: filename of the original file :type filename: str :param ...
python
{ "resource": "" }
q226229
ManalyzeSubmodule.build_results
train
def build_results(self, results): """Properly format the results""" self.add_result_subsection( 'Exploit mitigation techniques', { 'level': results.get('Plugins', {}).get('mitigation', {}).get('level', None), 'summary': results.get('Plugins', {}).g...
python
{ "resource": "" }
q226230
v4_int_to_packed
train
def v4_int_to_packed(address): """The binary representation of this address. Args: address: An integer representation of an IPv4 IP address. Returns: The binary representation of this address. Raises: ValueError: If the integer is too large to be an IPv4 IP address. ...
python
{ "resource": "" }
q226231
_get_prefix_length
train
def _get_prefix_length(number1, number2, bits): """Get the number of leading bits that are same for two numbers. Args: number1: an integer. number2: another integer. bits: the maximum number of bits to compare. Returns: The number of leading bits that are the same for two n...
python
{ "resource": "" }
q226232
_BaseNet._prefix_from_ip_int
train
def _prefix_from_ip_int(self, ip_int): """Return prefix length from a bitwise netmask. Args: ip_int: An integer, the netmask in expanded bitwise format. Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid n...
python
{ "resource": "" }
q226233
_BaseNet._prefix_from_prefix_string
train
def _prefix_from_prefix_string(self, prefixlen_str): """Turn a prefix length string into an integer. Args: prefixlen_str: A decimal string containing the prefix length. Returns: The prefix length as an integer. Raises: NetmaskValueError: If the inpu...
python
{ "resource": "" }
q226234
_BaseNet.masked
train
def masked(self): """Return the network object with the host bits masked out.""" return IPNetwork('%s/%d' % (self.network, self._prefixlen), version=self._version)
python
{ "resource": "" }
q226235
_BaseV6._string_from_ip_int
train
def _string_from_ip_int(self, ip_int=None): """Turns a 128-bit integer into hexadecimal notation. Args: ip_int: An integer, the IP address. Returns: A string, the hexadecimal representation of the address. Raises: ValueError: The address is bigger t...
python
{ "resource": "" }
q226236
Api.scan_file
train
def scan_file(self, this_file, this_filename): """ Submit a file to be scanned by Malwares :param this_file: File to be scanned (200MB file size limit) :param this_filename: Filename for scanned file :return: JSON response that contains scan_id and permalink. """ params ...
python
{ "resource": "" }
q226237
SafebrowsingClient.__prepare_body
train
def __prepare_body(self, search_value, search_type='url'): """ Prepares the http body for querying safebrowsing api. Maybe the list need to get adjusted. :param search_value: value to search for :type search_value: str :param search_type: 'url' or 'ip' :type search_type:...
python
{ "resource": "" }
q226238
RobtexAnalyzer.query_rpdns
train
def query_rpdns(self): """ Queries robtex reverse pdns-api using an ip as parameter :return: Dictionary containing results :rtype: list """ results = requests.get('https://freeapi.robtex.com/pdns/reverse/{}'.format(self.get_data())).text.split('\r\n') jsonresults...
python
{ "resource": "" }
q226239
RTFObjectSubmodule.module_summary
train
def module_summary(self): """Count the malicious and suspicious sections, check for CVE description""" suspicious = 0 malicious = 0 count = 0 cve = False taxonomies = [] for section in self.results: if section['submodule_section_content']['class'] == ...
python
{ "resource": "" }
q226240
TorProjectClient.search_tor_node
train
def search_tor_node(self, ip): """Lookup an IP address to check if it is a known tor exit node. :param ip: The IP address to lookup :type ip: str :return: Data relative to the tor node. If `ip`is a tor exit node it will contain a `node` key with the hash of the node and...
python
{ "resource": "" }
q226241
CensysAnalyzer.search_hosts
train
def search_hosts(self, ip): """ Searches for a host using its ipv4 address :param ip: ipv4 address as string :type ip: str :return: dict """ c = CensysIPv4(api_id=self.__uid, api_secret=self.__api_key) return c.view(ip)
python
{ "resource": "" }
q226242
CensysAnalyzer.search_certificate
train
def search_certificate(self, hash): """ Searches for a specific certificate using its hash :param hash: certificate hash :type hash: str :return: dict """ c = CensysCertificates(api_id=self.__uid, api_secret=self.__api_key) return c.view(hash)
python
{ "resource": "" }
q226243
StopforumspamClient.get_data
train
def get_data(self, datatype, data): """ Look for an IP address or an email address in the spammer database. :param datatype: Which type of data is to be looked up. Allowed values are 'ip' or 'mail'. :param data: The value to be looked up through the API. :type d...
python
{ "resource": "" }
q226244
Factory.construct
train
def construct(cls, faker, path_to_factories=None): """ Create a new factory container. :param faker: A faker generator instance :type faker: faker.Generator :param path_to_factories: The path to factories :type path_to_factories: str :rtype: Factory """...
python
{ "resource": "" }
q226245
Factory.define
train
def define(self, klass, name="default"): """ Define a class with a given set of attributes. :param klass: The class :type klass: class :param name: The short name :type name: str """ def decorate(func): @wraps(func) def wrapped(*...
python
{ "resource": "" }
q226246
Factory.create_as
train
def create_as(self, klass, name, **attributes): """ Create an instance of the given model and type and persist it to the database. :param klass: The class :type klass: class :param name: The type :type name: str :param attributes: The instance attributes ...
python
{ "resource": "" }
q226247
Factory.make_as
train
def make_as(self, klass, name, **attributes): """ Create an instance of the given model and type. :param klass: The class :type klass: class :param name: The type :type name: str :param attributes: The instance attributes :type attributes: dict ...
python
{ "resource": "" }
q226248
Factory.of
train
def of(self, klass, name="default"): """ Create a builder for the given model. :param klass: The class :type klass: class :param name: The type :type name: str :return: orator.orm.factory_builder.FactoryBuilder """ return FactoryBuilder( ...
python
{ "resource": "" }
q226249
Factory.build
train
def build(self, klass, name="default", amount=None): """ Makes a factory builder with a specified amount. :param klass: The class :type klass: class :param name: The type :type name: str :param amount: The number of models to create :type amount: int ...
python
{ "resource": "" }
q226250
SchemaGrammar._get_renamed_diff
train
def _get_renamed_diff(self, blueprint, command, column, schema): """ Get a new column instance with the new column name. :param blueprint: The blueprint :type blueprint: Blueprint :param command: The command :type command: Fluent :param column: The column ...
python
{ "resource": "" }
q226251
SchemaGrammar._set_renamed_columns
train
def _set_renamed_columns(self, table_diff, command, column): """ Set the renamed columns on the table diff. :rtype: orator.dbal.TableDiff """ new_column = Column(command.to, column.get_type(), column.to_dict()) table_diff.renamed_columns = {command.from_: new_column} ...
python
{ "resource": "" }
q226252
SchemaGrammar._get_command_by_name
train
def _get_command_by_name(self, blueprint, name): """ Get the primary key command it it exists. """ commands = self._get_commands_by_name(blueprint, name) if len(commands): return commands[0]
python
{ "resource": "" }
q226253
SchemaGrammar._get_commands_by_name
train
def _get_commands_by_name(self, blueprint, name): """ Get all of the commands with a given name. """ return list(filter(lambda value: value.name == name, blueprint.get_commands()))
python
{ "resource": "" }
q226254
SchemaGrammar.prefix_list
train
def prefix_list(self, prefix, values): """ Add a prefix to a list of values. """ return list(map(lambda value: prefix + " " + value, values))
python
{ "resource": "" }
q226255
SchemaGrammar._get_default_value
train
def _get_default_value(self, value): """ Format a value so that it can be used in "default" clauses. """ if isinstance(value, QueryExpression): return value if isinstance(value, bool): return "'%s'" % int(value) return "'%s'" % value
python
{ "resource": "" }
q226256
SchemaGrammar._get_changed_diff
train
def _get_changed_diff(self, blueprint, schema): """ Get the table diffrence for the given changes. :param blueprint: The blueprint :type blueprint: Blueprint :param schema: The schema :type schema: orator.dbal.SchemaManager :rtype: orator.dbal.TableDiff ...
python
{ "resource": "" }
q226257
SchemaGrammar._get_table_with_column_changes
train
def _get_table_with_column_changes(self, blueprint, table): """ Get a copy of the given table after making the column changes. :param blueprint: The blueprint :type blueprint: Blueprint :type table: orator.dbal.table.Table :rtype: orator.dbal.table.Table """ ...
python
{ "resource": "" }
q226258
SchemaGrammar._get_column_for_change
train
def _get_column_for_change(self, table, fluent): """ Get the column instance for a column change. :type table: orator.dbal.table.Table :rtype: orator.dbal.column.Column """ return table.change_column( fluent.name, self._get_column_change_options(fluent) ...
python
{ "resource": "" }
q226259
Pivot._get_delete_query
train
def _get_delete_query(self): """ Get the query builder for a delete operation on the pivot. :rtype: orator.orm.Builder """ foreign = self.get_attribute(self.__foreign_key) query = self.new_query().where(self.__foreign_key, foreign) return query.where(self.__oth...
python
{ "resource": "" }
q226260
Pivot.set_pivot_keys
train
def set_pivot_keys(self, foreign_key, other_key): """ Set the key names for the pivot model instance """ self.__foreign_key = foreign_key self.__other_key = other_key return self
python
{ "resource": "" }
q226261
FactoryBuilder.create
train
def create(self, **attributes): """ Create a collection of models and persist them to the database. :param attributes: The models attributes :type attributes: dict :return: mixed """ results = self.make(**attributes) if self._amount == 1: if...
python
{ "resource": "" }
q226262
FactoryBuilder.make
train
def make(self, **attributes): """ Create a collection of models. :param attributes: The models attributes :type attributes: dict :return: mixed """ if self._amount == 1: return self._make_instance(**attributes) else: results = [] ...
python
{ "resource": "" }
q226263
FactoryBuilder._make_instance
train
def _make_instance(self, **attributes): """ Make an instance of the model with the given attributes. :param attributes: The models attributes :type attributes: dict :return: mixed """ definition = self._definitions[self._klass][self._name](self._faker) d...
python
{ "resource": "" }
q226264
run
train
def run(wrapped): """ Special decorator encapsulating query method. """ @wraps(wrapped) def _run(self, query, bindings=None, *args, **kwargs): self._reconnect_if_missing_connection() start = time.time() try: result = wrapped(self, query, bindings, *args, **kwarg...
python
{ "resource": "" }
q226265
BelongsToMany.where_pivot
train
def where_pivot(self, column, operator=None, value=None, boolean="and"): """ Set a where clause for a pivot table column. :param column: The column of the where clause, can also be a QueryBuilder instance for sub where :type column: str|Builder :param operator: The operator of ...
python
{ "resource": "" }
q226266
BelongsToMany.or_where_pivot
train
def or_where_pivot(self, column, operator=None, value=None): """ Set an or where clause for a pivot table column. :param column: The column of the where clause, can also be a QueryBuilder instance for sub where :type column: str|Builder :param operator: The operator of the wher...
python
{ "resource": "" }
q226267
BelongsToMany.first
train
def first(self, columns=None): """ Execute the query and get the first result. :type columns: list """ self._query.take(1) results = self.get(columns) if len(results) > 0: return results.first() return
python
{ "resource": "" }
q226268
BelongsToMany.first_or_fail
train
def first_or_fail(self, columns=None): """ Execute the query and get the first result or raise an exception. :type columns: list :raises: ModelNotFound """ model = self.first(columns) if model is not None: return model raise ModelNotFound(se...
python
{ "resource": "" }
q226269
BelongsToMany._hydrate_pivot_relation
train
def _hydrate_pivot_relation(self, models): """ Hydrate the pivot table relationship on the models. :type models: list """ for model in models: pivot = self.new_existing_pivot(self._clean_pivot_attributes(model)) model.set_relation("pivot", pivot)
python
{ "resource": "" }
q226270
BelongsToMany.touch
train
def touch(self): """ Touch all of the related models of the relationship. """ key = self.get_related().get_key_name() columns = self.get_related_fresh_update() ids = self.get_related_ids() if len(ids) > 0: self.get_related().new_query().where_in(key...
python
{ "resource": "" }
q226271
BelongsToMany.get_related_ids
train
def get_related_ids(self): """ Get all of the IDs for the related models. :rtype: list """ related = self.get_related() full_key = related.get_qualified_key_name() return self.get_query().select(full_key).lists(related.get_key_name())
python
{ "resource": "" }
q226272
BelongsToMany.save_many
train
def save_many(self, models, joinings=None): """ Save a list of new models and attach them to the parent model :type models: list :type joinings: dict :rtype: list """ if joinings is None: joinings = {} for key, model in enumerate(models): ...
python
{ "resource": "" }
q226273
BelongsToMany.first_or_create
train
def first_or_create( self, _attributes=None, _joining=None, _touch=True, **attributes ): """ Get the first related model record matching the attributes or create it. :param attributes: The attributes :type attributes: dict :rtype: Model """ if _attr...
python
{ "resource": "" }
q226274
BelongsToMany.sync
train
def sync(self, ids, detaching=True): """ Sync the intermediate tables with a list of IDs or collection of models """ changes = {"attached": [], "detached": [], "updated": []} if isinstance(ids, Collection): ids = ids.model_keys() current = self._new_pivot_qu...
python
{ "resource": "" }
q226275
BelongsToMany._format_sync_list
train
def _format_sync_list(self, records): """ Format the sync list so that it is keyed by ID. """ results = {} for attributes in records: if not isinstance(attributes, dict): id, attributes = attributes, {} else: id = list(attr...
python
{ "resource": "" }
q226276
BelongsToMany.attach
train
def attach(self, id, attributes=None, touch=True): """ Attach a model to the parent. """ if isinstance(id, orator.orm.Model): id = id.get_key() query = self.new_pivot_statement() if not isinstance(id, list): id = [id] query.insert(self._...
python
{ "resource": "" }
q226277
BelongsToMany._create_attach_records
train
def _create_attach_records(self, ids, attributes): """ Create a list of records to insert into the pivot table. """ records = [] timed = self._has_pivot_column(self.created_at()) or self._has_pivot_column( self.updated_at() ) for key, value in enumer...
python
{ "resource": "" }
q226278
BelongsToMany._attacher
train
def _attacher(self, key, value, attributes, timed): """ Create a full attachment record payload. """ id, extra = self._get_attach_id(key, value, attributes) record = self._create_attach_record(id, timed) if extra: record.update(extra) return record
python
{ "resource": "" }
q226279
BelongsToMany._get_attach_id
train
def _get_attach_id(self, key, value, attributes): """ Get the attach record ID and extra attributes. """ if isinstance(value, dict): key = list(value.keys())[0] attributes.update(value[key]) return [key, attributes] return value, attributes
python
{ "resource": "" }
q226280
BelongsToMany._set_timestamps_on_attach
train
def _set_timestamps_on_attach(self, record, exists=False): """ Set the creation an update timestamps on an attach record. """ fresh = self._parent.fresh_timestamp() if not exists and self._has_pivot_column(self.created_at()): record[self.created_at()] = fresh ...
python
{ "resource": "" }
q226281
BelongsToMany.detach
train
def detach(self, ids=None, touch=True): """ Detach models from the relationship. """ if isinstance(ids, orator.orm.model.Model): ids = ids.get_key() if ids is None: ids = [] query = self._new_pivot_query() if not isinstance(ids, list): ...
python
{ "resource": "" }
q226282
BelongsToMany.touch_if_touching
train
def touch_if_touching(self): """ Touch if the parent model is being touched. """ if self._touching_parent(): self.get_parent().touch() if self.get_parent().touches(self._relation_name): self.touch()
python
{ "resource": "" }
q226283
BelongsToMany.with_pivot
train
def with_pivot(self, *columns): """ Set the columns on the pivot table to retrieve. """ columns = list(columns) self._pivot_columns += columns return self
python
{ "resource": "" }
q226284
BelongsToMany.with_timestamps
train
def with_timestamps(self, created_at=None, updated_at=None): """ Specify that the pivot table has creation and update columns. """ if not created_at: created_at = self.created_at() if not updated_at: updated_at = self.updated_at() return self.wit...
python
{ "resource": "" }
q226285
BelongsTo._get_eager_model_keys
train
def _get_eager_model_keys(self, models): """ Gather the keys from a list of related models. :type models: list :rtype: list """ keys = [] for model in models: value = getattr(model, self._foreign_key) if value is not None and value not ...
python
{ "resource": "" }
q226286
BelongsTo.update
train
def update(self, _attributes=None, **attributes): """ Update the parent model on the relationship. :param attributes: The update attributes :type attributes: dict :rtype: mixed """ if _attributes is not None: attributes.update(_attributes) i...
python
{ "resource": "" }
q226287
MorphTo._build_dictionary
train
def _build_dictionary(self, models): """ Build a dictionary with the models. :param models: The models :type models: Collection """ for model in models: key = getattr(model, self._morph_type, None) if key: foreign = getattr(model, ...
python
{ "resource": "" }
q226288
MorphTo.get_eager
train
def get_eager(self): """ Get the relationship for eager loading. :rtype: Collection """ for type in self._dictionary.keys(): self._match_to_morph_parents(type, self._get_results_by_type(type)) return self._models
python
{ "resource": "" }
q226289
MorphTo._match_to_morph_parents
train
def _match_to_morph_parents(self, type, results): """ Match the results for a given type to their parent. :param type: The parent type :type type: str :param results: The results to match to their parent :type results: Collection """ for result in result...
python
{ "resource": "" }
q226290
MorphTo._get_results_by_type
train
def _get_results_by_type(self, type): """ Get all the relation results for a type. :param type: The type :type type: str :rtype: Collection """ instance = self._create_model_by_type(type) key = instance.get_key_name() query = instance.new_query...
python
{ "resource": "" }
q226291
MorphTo._gather_keys_by_type
train
def _gather_keys_by_type(self, type): """ Gather all of the foreign keys for a given type. :param type: The type :type type: str :rtype: BaseCollection """ foreign = self._foreign_key keys = ( BaseCollection.make(list(self._dictionary[type]....
python
{ "resource": "" }
q226292
Table.set_primary_key
train
def set_primary_key(self, columns, index_name=False): """ Set the primary key. :type columns: list :type index_name: str or bool :rtype: Table """ self._add_index( self._create_index(columns, index_name or "primary", True, True) ) fo...
python
{ "resource": "" }
q226293
Table.drop_index
train
def drop_index(self, name): """ Drops an index from this table. :param name: The index name :type name: str """ name = self._normalize_identifier(name) if not self.has_index(name): raise IndexDoesNotExist(name, self._name) del self._indexes[n...
python
{ "resource": "" }
q226294
Table.rename_index
train
def rename_index(self, old_name, new_name=None): """ Renames an index. :param old_name: The name of the index to rename from. :type old_name: str :param new_name: The name of the index to rename to. :type new_name: str or None :rtype: Table """ ...
python
{ "resource": "" }
q226295
Table.columns_are_indexed
train
def columns_are_indexed(self, columns): """ Checks if an index begins in the order of the given columns. :type columns: list :rtype: bool """ for index in self._indexes.values(): if index.spans_columns(columns): return True return Fa...
python
{ "resource": "" }
q226296
Table._create_index
train
def _create_index( self, columns, name, is_unique, is_primary, flags=None, options=None ): """ Creates an Index instance. :param columns: The index columns :type columns: list :param name: The index name :type name: str :param is_unique: Whether the...
python
{ "resource": "" }
q226297
Table.add_column
train
def add_column(self, name, type_name, options=None): """ Adds a new column. :param name: The column name :type name: str :param type_name: The column type :type type_name: str :param options: The column options :type options: dict :rtype: Colum...
python
{ "resource": "" }
q226298
Table.change_column
train
def change_column(self, name, options): """ Changes column details. :param name: The column to change. :type name: str :param options: The new options. :type options: str :rtype: Table """ column = self.get_column(name) column.set_option...
python
{ "resource": "" }
q226299
Table.drop_column
train
def drop_column(self, name): """ Drops a Column from the Table :param name: The name of the column :type name: str :rtype: Table """ name = self._normalize_identifier(name) del self._columns[name] return self
python
{ "resource": "" }