INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Gets the sitelinks from a feed. | def GetSitelinksFromFeed(client, feed):
"""Gets the sitelinks from a feed.
Args:
client: an AdWordsClient instance.
feed: the feed used to retrieve sitelinks.
Returns:
A dictionary mapping the feed item ID to SiteLinkFromFeed.
"""
# Retrieve the feed's attribute mapping.
feed_mappings = GetFee... |
Gets the version from googleads/ common. py. | def GetVersion():
"""Gets the version from googleads/common.py.
We can't import this directly because new users would get ImportErrors on our
third party dependencies.
Returns:
The version of the library.
"""
with open(os.path.join('googleads', 'common.py')) as versions_file:
source = versions_fil... |
Builds the operations adding a Keyword Criterion to each AdGroup. | def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1):
"""Builds the operations adding a Keyword Criterion to each AdGroup.
Args:
adgroup_operations: a list containing the operations that will add AdGroups.
number_of_keywords: an int defining the number of Keywords to be created.
... |
Builds the operations adding desired number of AdGroups to given Campaigns. | def BuildAdGroupOperations(batch_job_helper,
campaign_operations, number_of_adgroups=1):
"""Builds the operations adding desired number of AdGroups to given Campaigns.
Note: When the AdGroups are created, they will have a different Id than those
generated here as a temporary Id. This i... |
Builds the operations needed to create a new Campaign. | def BuildCampaignOperations(batch_job_helper,
budget_operations, number_of_campaigns=1):
"""Builds the operations needed to create a new Campaign.
Note: When the Campaigns are created, they will have a different Id than those
generated here as a temporary Id. This is just used to iden... |
Creates an image and uploads it to the server. | def _CreateImage(media_service, opener, url):
"""Creates an image and uploads it to the server.
Args:
media_service: a SudsServiceProxy instance for AdWords's MediaService.
opener: an OpenerDirector instance.
url: a str URL used to load image data.
Returns:
The image that was successfully upload... |
Creates settings for dynamic display ad. | def _CreateDynamicDisplayAdSettings(media_service, opener):
"""Creates settings for dynamic display ad.
Args:
media_service: a SudsServiceProxy instance for AdWords's MediaService.
opener: an OpenerDirector instance.
Returns:
The dynamic display ad settings.
"""
image = _CreateImage(media_servic... |
Creates a budget and returns its budgetId. | def CreateBudget(client):
"""Creates a budget and returns its budgetId.
Args:
client: An AdWordsClient instance.
Returns:
An int budgetId for the created Budget.
"""
budget_service = client.GetService('BudgetService', version='v201809')
# Create a budget.
budget = {
'name': 'Interplanetar... |
Sets targeting criteria for the given campaign. | def SetCampaignTargetingCriteria(client, campaign):
"""Sets targeting criteria for the given campaign.
Args:
client: An AdWordsClient instance.
campaign: A suds object representing the campaign we wish to attach
targeting criteria.
"""
campaign_criterion_service = client.GetService('CampaignCrite... |
Displays an account tree. | def DisplayAccountTree(account, accounts, links, depth=0):
"""Displays an account tree.
Args:
account: dict The account to display.
accounts: dict Map from customerId to account.
links: dict Map from customerId to child links.
depth: int Depth of the current account in the tree.
"""
prefix = '-... |
Handle get request. | def get(self):
"""Handle get request."""
try:
app_user = InitUser()
if (app_user.client_id and app_user.client_secret and
app_user.adwords_manager_cid and app_user.developer_token and
app_user.refresh_token):
self.redirect('/showAccounts')
else:
self.redire... |
Helper function to generate a single row of a price table. | def CreatePriceTableRow(header, description, final_url, price_in_micros,
currency_code, price_unit, final_mobile_url=None):
"""Helper function to generate a single row of a price table.
Args:
header: A str containing the header text of this row.
description: A str description of thi... |
Creates a bidding strategy object. | def CreateBiddingStrategy(client):
"""Creates a bidding strategy object.
Args:
client: AdWordsClient the client to run the example with.
Returns:
dict An object representing a bidding strategy.
"""
# Initialize appropriate service.
bidding_strategy_service = client.GetService(
'BiddingStrate... |
Creates an explicit budget to be used only to create the Campaign. | def CreateSharedBudget(client):
"""Creates an explicit budget to be used only to create the Campaign.
Args:
client: AdWordsClient the client to run the example with.
Returns:
dict An object representing a shared budget.
"""
# Initialize appropriate service.
budget_service = client.GetService('Budg... |
Create a Campaign with a Shared Bidding Strategy. | def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id):
"""Create a Campaign with a Shared Bidding Strategy.
Args:
client: AdWordsClient the client to run the example with.
bidding_strategy_id: string the bidding strategy ID to use.
budget_id: string the shared budget ID to use.
... |
Helper function used by ReportWorker to download customer report. | def _DownloadReport(process_id, report_download_directory, customer_id,
report_definition):
"""Helper function used by ReportWorker to download customer report.
Note that multiprocessing differs between Windows / Unix environments. A
Process or its subclasses in Windows must be serializable w... |
Retrieves all CustomerIds in the account hierarchy. | def GetCustomerIDs(client):
"""Retrieves all CustomerIds in the account hierarchy.
Note that your configuration file must specify a client_customer_id belonging
to an AdWords manager account.
Args:
client: an AdWordsClient instance.
Raises:
Exception: if no CustomerIds could be found.
Returns:
... |
Handle get request. | def get(self):
"""Handle get request."""
client_customer_id = self.request.get('clientCustomerId')
template_values = {
'back_url': '/showAccounts',
'back_msg': 'View Accounts.',
'ccid': client_customer_id,
'logout_url': users.create_logout_url('/'),
'user_nickname': ... |
Handle post request. | def post(self):
"""Handle post request."""
client_customer_id = self.request.get('clientCustomerId')
if not client_customer_id:
self.redirect('/')
else:
self.redirect('/showCampaigns?clientCustomerId=%s' % client_customer_id) |
Creates a new Display Network campaign. | def CreateCampaign(client, merchant_id, budget_id):
"""Creates a new Display Network campaign.
Args:
client: an AdWordsClient instance.
merchant_id: a int merchant center ID.
budget_id: a int budget ID.
Returns:
The campaign that was successfully created.
"""
campaign_service = client.GetSer... |
Creates a dynamic remarketing campaign. | def CreateAdGroup(client, campaign_id):
"""Creates a dynamic remarketing campaign.
Args:
client: an AdWordsClient instance.
campaign_id: an int campaign ID.
Returns:
The ad group that was successfully created.
"""
ad_group_service = client.GetService('AdGroupService', 'v201809')
ad_group = {
... |
Creates a ResponsiveDisplayAd. | def CreateAd(client, opener, ad_group_id):
"""Creates a ResponsiveDisplayAd.
Args:
client: an AdWordsClient instance.
opener: an OpenerDirector instance.
ad_group_id: an int ad group ID.
Returns:
The ad group ad that was successfully created.
"""
ad_group_ad_service = client.GetService('AdGr... |
Links the provided ad group and user list. | def AttachUserList(client, ad_group_id, user_list_id):
"""Links the provided ad group and user list.
Args:
client: an AdWordsClient instance.
ad_group_id: an int ad group ID.
user_list_id: an int user list ID.
Returns:
The ad group criterion that was successfully created.
"""
ad_group_criter... |
Creates dynamic display ad settings. | def CreateDynamicDisplayAdSettings(client, opener):
"""Creates dynamic display ad settings.
Args:
client: an AdWordsClient instance.
opener: an OpenerDirector instance.
Returns:
A dict containing the dynamic display ad settings.
"""
media_service = client.GetService('MediaService', 'v201809')
... |
Retrieves the scope for the given API name. | def GetAPIScope(api_name):
"""Retrieves the scope for the given API name.
Args:
api_name: A string identifying the name of the API we want to retrieve a
scope for.
Returns:
A string that is the scope for the given API name.
Raises:
GoogleAdsValueError: If the given api_name is invalid; ac... |
Creates an OAuth2 HTTP header. | def CreateHttpHeader(self):
"""Creates an OAuth2 HTTP header.
The OAuth2 credentials will be refreshed as necessary. In the event that
the credentials fail to refresh, a message is logged but no exception is
raised.
Returns:
A dictionary containing one entry: the OAuth2 Bearer header under t... |
Creates an OAuth2 HTTP header. | def CreateHttpHeader(self):
"""Creates an OAuth2 HTTP header.
The OAuth2 credentials will be refreshed as necessary. In the event that
the credentials fail to refresh, a message is logged but no exception is
raised.
Returns:
A dictionary containing one entry: the OAuth2 Bearer header under t... |
Uses the Refresh Token to retrieve and set a new Access Token. | def Refresh(self):
"""Uses the Refresh Token to retrieve and set a new Access Token.
Raises:
google.auth.exceptions.RefreshError: If the refresh fails.
"""
with requests.Session() as session:
session.proxies = self.proxy_config.proxies
session.verify = not self.proxy_config.disable_ce... |
Creates the feed for DSA page URLs. | def _CreateFeed(client):
"""Creates the feed for DSA page URLs.
Args:
client: an AdWordsClient instance.
Returns:
A _DSAFeedDetails instance containing details about the created feed.
"""
# Get the FeedService.
feed_service = client.GetService('FeedService', version='v201809')
# Create operatio... |
Creates the feed mapping for DSA page feeds. | def _CreateFeedMapping(client, feed_details):
"""Creates the feed mapping for DSA page feeds.
Args:
client: an AdWordsClient instance.
feed_details: a _DSAFeedDetails instance.
"""
# Get the FeedMappingService.
feed_mapping_service = client.GetService('FeedMappingService',
... |
Creates the page URLs in the DSA page feed. | def _CreateFeedItems(client, feed_details, label_name):
"""Creates the page URLs in the DSA page feed.
Args:
client: an AdWordsClient instance.
feed_details: a _DSAFeedDetails instance.
label_name: a str containing the page feed URL label.
"""
# Get the FeedItemService.
feed_item_service = client... |
Updates the campaign DSA setting to DSA pagefeeds. | def _UpdateCampaignDSASetting(client, campaign_id, feed_id):
"""Updates the campaign DSA setting to DSA pagefeeds.
Args:
client: an AdWordsClient instance.
campaign_id: a str Campaign ID.
feed_id: a str page Feed ID.
Raises:
ValueError: If the given campaign is found not to be a dynamic search a... |
Set custom targeting for the page feed URLs based on a list of labels. | def _AddDSATargeting(client, ad_group_id, label_name):
"""Set custom targeting for the page feed URLs based on a list of labels.
Args:
client: an AdWordsClient instance.
ad_group_id: a str AdGroup ID.
label_name: a str label name.
Returns:
A suds.sudsobject.Object representing the newly created ... |
returns a value calculated from bits: param length: length of signal in bits: param is_float: value is float: param bits: value as bits ( array/ iterable ): param is_signed: value is signed: return: | def unpack_bitstring(length, is_float, is_signed, bits):
# type: (int, bool, bool, typing.Any) -> typing.Union[float, int]
"""
returns a value calculated from bits
:param length: length of signal in bits
:param is_float: value is float
:param bits: value as bits (array/iterable)
:param is_si... |
returns a value in bits: param length: length of signal in bits: param is_float: value is float: param value: value to encode: param signed: value is signed: return: | def pack_bitstring(length, is_float, value, signed):
"""
returns a value in bits
:param length: length of signal in bits
:param is_float: value is float
:param value: value to encode
:param signed: value is signed
:return:
"""
if is_float:
types = {
32: '>f',
... |
Set Definition default value. | def set_default(self, default): # type: (typing.Any) -> None
"""Set Definition default value.
:param default: default value; number, str or quoted str ("value")
"""
if default is not None and len(default) > 1 and default[0] == '"' and default[-1] == '"':
default = default[1... |
Get signal arxml - type and size based on the Signal properties. | def get_base_type_of_signal(signal):
# type: (canmatrix.Signal) -> typing.Tuple[str, int]
"""Get signal arxml-type and size based on the Signal properties."""
if signal.is_float:
if signal.size > 32:
create_type = "double"
size = 64
else:
create_type = "si... |
Parse the xml tree into ArTree objects. | def fill_tree_from_xml(tag, ar_tree, namespace):
# type: (_Element, ArTree, str) -> None
"""Parse the xml tree into ArTree objects."""
for child in tag: # type: _Element
name_elem = child.find('./' + namespace + 'SHORT-NAME')
# long_name = child.find('./' + namespace + 'LONG-NAME')
... |
Get path in translation - dictionary. | def ar_path_to_x_path(ar_path, dest_element=None):
# type: (str, typing.Optional[str]) -> str
"""Get path in translation-dictionary."""
ar_path_elements = ar_path.strip('/').split('/')
xpath = "."
for element in ar_path_elements[:-1]:
xpath += "//A:SHORT-NAME[text()='" + element + "']/.."
... |
Find sub - element of given path with given short name. | def get_element_by_path(tree, path_and_name, namespace):
# type: (_Element, str, str) -> typing.Union[_Element, None]
"""Find sub-element of given path with given short name."""
global xml_element_cache
namespace_map = {'A': namespace[1:-1]}
base_path, element_name = path_and_name.rsplit('/', 1)
... |
Get element from ArTree by path. | def get_cached_element_by_path(data_tree, path):
# type: (ArTree, str) -> typing.Optional[_Element]
"""Get element from ArTree by path."""
if not isinstance(data_tree, ArTree):
logger.warning("%s not called with ArTree, return None", get_cached_element_by_path.__name__)
return None
ptr =... |
Get first sub - child or referenced sub - child with given name. | def get_child(parent, tag_name, root_or_cache, namespace):
# type: (_Element, str, _DocRoot, str) -> typing.Optional[_Element]
"""Get first sub-child or referenced sub-child with given name."""
# logger.debug("get_child: " + tag_name)
if parent is None:
return None
ret = parent.find('.//' + ... |
Get element short name. | def get_element_name(parent, ns):
# type: (_Element, str) -> str
"""Get element short name."""
name = parent.find('./' + ns + 'SHORT-NAME')
if name is not None and name.text is not None:
return name.text
return "" |
Add signals from xml to the Frame. | def get_signals(signal_array, frame, root_or_cache, ns, multiplex_id, float_factory):
# type: (typing.Sequence[_Element], canmatrix.Frame, _DocRoot, str, _MultiplexId, typing.Callable) -> None
"""Add signals from xml to the Frame."""
global signal_rxs
group_id = 1
if signal_array is None: # Empty s... |
Get element description from XML. | def get_element_desc(element, ar_tree, ns):
# type: (_Element, _DocRoot, str) -> str
"""Get element description from XML."""
desc = get_child(element, "DESC", ar_tree, ns)
txt = get_child(desc, 'L-2[@L="DE"]', ar_tree, ns)
if txt is None:
txt = get_child(desc, 'L-2[@L="EN"]', ar_tree, ns)
... |
Extract signal from ECUc file. | def ecuc_extract_signal(signal_node, ns):
# type: (_Element, str) -> canmatrix.Signal
"""Extract signal from ECUc file."""
attributes = signal_node.findall(".//" + ns + "DEFINITION-REF") # type: typing.Sequence[_Element]
start_bit = None
size = 0
is_little = False
# endianness = None
# ... |
Append new child and return it. | def append_child(self, name, child): # type: (str, typing.Any) -> ArTree
"""Append new child and return it."""
temp = ArTree(name, child)
self._array.append(temp)
return temp |
Setup the root logger. Return the logger instance for possible further setting and use. | def setup_logger(): # type: () -> logging.Logger
"""Setup the root logger. Return the logger instance for possible further setting and use.
To be used from CLI scripts only.
"""
formatter = logging.Formatter(
fmt='%(levelname)s - %(module)s - %(message)s')
handler = logging.StreamHandler(... |
Dynamic reconfiguration of the log level | def set_log_level(logger, level): # type: (logging.Logger, int) -> None
"""Dynamic reconfiguration of the log level"""
if level > 2:
level = 2
if level < -1:
level = -1
levels = {
-1: logging.ERROR,
0: logging.WARN,
1: logging.INFO,
2: logging.DEBUG
... |
export canmatrix - object as. sym file ( compatible to PEAK - Systems ) | def dump(db, f, **options): # type: (canmatrix.CanMatrix, typing.IO, **typing.Any) -> None
"""
export canmatrix-object as .sym file (compatible to PEAK-Systems)
"""
global enum_dict
global enums
sym_encoding = options.get('symExportEncoding', 'iso-8859-1')
enum_dict = {}
enums = "{ENUM... |
Get all PGN values for given frame. | def list_pgn(db):
# type: (canmatrix.CanMatrix) -> typing.Tuple[typing.List[int], typing.List[canmatrix.ArbitrationId]]
"""
Get all PGN values for given frame.
:param db: CanMatrix database
:return: tuple of [pgn] and [arbitration_id]
"""
id_list = [x.arbitration_id for x in db.frames]
... |
Yield arbitration ids which has the same pgn. | def ids_sharing_same_pgn(id_x, pgn_x, id_y, pgn_y):
# type: (typing.Sequence[canmatrix.ArbitrationId], typing.Sequence[int], typing.Sequence[canmatrix.ArbitrationId], typing.Sequence[int]) -> typing.Iterable[typing.Tuple[canmatrix.ArbitrationId, canmatrix.ArbitrationId]]
"""Yield arbitration ids which has the s... |
Get string value for common strings. Method is far from complete but helping with odd arxml files. | def guess_value(text_value): # type: (str) -> str
"""
Get string value for common strings.
Method is far from complete but helping with odd arxml files.
:param text_value: value in text like "true"
:return: string for value like "1"
"""
if sys.version_info >= (3, 0):
text_value = t... |
Create populate and return the VersioneerConfig () object. | def get_config():
"""Create, populate and return the VersioneerConfig() object."""
# these strings are filled in when 'setup.py versioneer' creates
# _version.py
cfg = VersioneerConfig()
cfg.VCS = "git"
cfg.style = "pep440-post"
cfg.tag_prefix = ""
cfg.parentdir_prefix = "None"
cfg.v... |
Decorator to mark a method as the handler for a particular VCS. | def register_vcs_handler(vcs, method): # tyoe: (str, str) -> typing.Callable # decorator
"""Decorator to mark a method as the handler for a particular VCS."""
def decorate(f):
"""Store f in HANDLERS[vcs][method]."""
if vcs not in HANDLERS:
HANDLERS[vcs] = {}
HANDLERS[vcs][m... |
Get version from git describe in the root of the source tree. | def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
"""Get version from 'git describe' in the root of the source tree.
This only gets called if the git-archive 'subst' keywords were *not*
expanded, and _version.py hasn't already been rewritten with a short
version string, meani... |
Get version information or return default if unable to do so. | def get_versions():
"""Get version information or return default if unable to do so."""
# I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
# __file__, we can work backwards from there to the root. Some
# py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
#... |
Copy ECU ( s ) identified by Name or as Object from source CAN matrix to target CAN matrix. This function additionally copy all relevant Defines. | def copy_ecu(ecu_or_glob, source_db, target_db):
# type: (typing.Union[cm.Ecu, str], cm.CanMatrix, cm.CanMatrix) -> None
"""
Copy ECU(s) identified by Name or as Object from source CAN matrix to target CAN matrix.
This function additionally copy all relevant Defines.
:param ecu_or_glob: Ecu instanc... |
Copy ECU ( s ) identified by Name or as Object from source CAN matrix to target CAN matrix. This function additionally copy all relevant Frames and Defines. | def copy_ecu_with_frames(ecu_or_glob, source_db, target_db):
# type: (typing.Union[cm.Ecu, str], cm.CanMatrix, cm.CanMatrix) -> None
"""
Copy ECU(s) identified by Name or as Object from source CAN matrix to target CAN matrix.
This function additionally copy all relevant Frames and Defines.
:param e... |
Copy Signals identified by name from source CAN matrix to target CAN matrix. In target CanMatrix the signal is put without frame just on top level. | def copy_signal(signal_glob, source_db, target_db):
# type: (str, cm.CanMatrix, cm.CanMatrix) -> None
"""
Copy Signals identified by name from source CAN matrix to target CAN matrix.
In target CanMatrix the signal is put without frame, just on top level.
:param signal_glob: Signal glob pattern
... |
Copy a Frame identified by ArbitrationId from source CAN matrix to target CAN matrix. This function additionally copy all relevant ECUs and Defines. | def copy_frame(frame_id, source_db, target_db):
# type: (cm.ArbitrationId, cm.CanMatrix, cm.CanMatrix) -> bool
"""
Copy a Frame identified by ArbitrationId from source CAN matrix to target CAN matrix.
This function additionally copy all relevant ECUs and Defines.
:param frame_id: Frame arbitration ... |
Lazy init yaml because canmatrix might not be fully loaded when loading this format. | def __init_yaml():
"""Lazy init yaml because canmatrix might not be fully loaded when loading this format."""
global _yaml_initialized
if not _yaml_initialized:
_yaml_initialized = True
yaml.add_constructor(u'tag:yaml.org,2002:Frame', _frame_constructor)
yaml.add_constructor(u'tag:ya... |
Gets the XML field object of the given name. | def get_field(self, name):
"""
Gets the XML field object of the given name.
"""
# Quicker in case the exact name was used.
field = self._all_fields.get(name)
if field is not None:
return field
for field_name, field in self._all_fields.items():
... |
Tries getting the value of the given field. Tries it in the following order: show ( standard nice display ) value ( raw value ) showname ( extended nice display ). | def get_field_value(self, name, raw=False):
"""
Tries getting the value of the given field.
Tries it in the following order: show (standard nice display), value (raw value), showname (extended nice display).
:param name: The name of the field
:param raw: Only return raw value
... |
Sanitizes an XML field name ( since it might have characters which would make it inaccessible as a python attribute ). | def _sanitize_field_name(self, field_name):
"""
Sanitizes an XML field name (since it might have characters which would make it inaccessible as a python attribute).
"""
field_name = field_name.replace(self._field_prefix, '')
return field_name.replace('.', '_').replace('-', '_').l... |
Returns all lines that represent the fields of the layer ( both their names and values ). | def _get_all_field_lines(self):
"""
Returns all lines that represent the fields of the layer (both their names and values).
"""
for field in self._get_all_fields_with_alternates():
# Change to yield from
for line in self._get_field_or_layer_repr(field):
... |
Gets a field by its showname ( the name that appears in Wireshark s detailed display i. e. in User - Agent: Mozilla... User - Agent is the showname ) | def get_field_by_showname(self, showname):
"""
Gets a field by its "showname"
(the name that appears in Wireshark's detailed display i.e. in 'User-Agent: Mozilla...', 'User-Agent' is the
showname)
Returns None if not found.
"""
for field in self._get_all_fields... |
Gets a field by its full or partial name. | def get_field(self, name):
"""Gets a field by its full or partial name."""
# We only make the wrappers here (lazily) to avoid creating a ton of objects needlessly.
field = self._wrapped_fields.get(name)
if field is None:
is_fake = False
field = self._get_internal_... |
Gets the field by name or None if not found. | def _get_internal_field_by_name(self, name):
"""Gets the field by name, or None if not found."""
field = self._all_fields.get(name, self._all_fields.get('%s.%s' % (self._full_name, name)))
if field is not None:
return field
for field_name in self._all_fields:
# Sp... |
Creates the field lazily. | def _make_wrapped_field(self, name, field, is_fake=False, full_name=None):
"""Creates the field lazily.
If it's a simple field, wraps it in a container that adds extra features.
If it's a nested layer, creates a layer for it.
If it's an intermediate layer, copies over the relevant field... |
Checks whether the layer has the given field name. Can get a dotted name i. e. layer. sublayer. subsublayer. field | def has_field(self, dotted_name):
"""
Checks whether the layer has the given field name.
Can get a dotted name, i.e. layer.sublayer.subsublayer.field
"""
parts = dotted_name.split('.')
cur_layer = self
for part in parts:
if part in cur_layer.field_name... |
Returns the special tshark parameters to be used according to the configuration of this class. | def get_parameters(self, packet_count=None):
"""
Returns the special tshark parameters to be used according to the configuration of this class.
"""
params = super(InMemCapture, self).get_parameters(packet_count=packet_count)
params += ['-i', '-']
return params |
Parses binary packets and return a list of parsed packets. | def parse_packets(self, binary_packets):
"""
Parses binary packets and return a list of parsed packets.
DOES NOT CLOSE tshark. It must be closed manually by calling close() when you're done
working with it.
"""
if not binary_packets:
raise ValueError("Must su... |
DEPRECATED. Use parse_packet instead. This function adds the packet to the packets list and also closes and reopens tshark for each packet. ============== | def feed_packet(self, binary_packet, linktype=LinkTypes.ETHERNET):
"""
DEPRECATED. Use parse_packet instead.
This function adds the packet to the packets list, and also closes and reopens tshark for
each packet.
==============
Gets a binary (string) packet and parses & a... |
Gets a list of binary packets parses them using tshark and returns their parsed values. Keeps the packets in the internal packet list as well. | def feed_packets(self, binary_packets, linktype=LinkTypes.ETHERNET):
"""
Gets a list of binary packets, parses them using tshark and returns their parsed values.
Keeps the packets in the internal packet list as well.
By default, assumes the packets are ethernet packets. For another link... |
Finds the path of the tshark executable. If the user has provided a path or specified a location in config. ini it will be used. Otherwise default locations will be searched. | def get_process_path(tshark_path=None, process_name="tshark"):
"""
Finds the path of the tshark executable. If the user has provided a path
or specified a location in config.ini it will be used. Otherwise default
locations will be searched.
:param tshark_path: Path of the tshark binary
:raises ... |
Returns a list of interface numbers from the output tshark - D. Used internally to capture on multiple interfaces. | def get_tshark_interfaces(tshark_path=None):
"""
Returns a list of interface numbers from the output tshark -D. Used
internally to capture on multiple interfaces.
"""
parameters = [get_process_path(tshark_path), '-D']
with open(os.devnull, 'w') as null:
tshark_interfaces = subprocess.che... |
Returns the special tshark parameters to be used according to the configuration of this class. | def get_parameters(self, packet_count=None):
"""
Returns the special tshark parameters to be used according to the configuration of this class.
"""
params = super(PipeCapture, self).get_parameters(packet_count=packet_count)
params += ['-r', '-']
return params |
Returns a list of all the layers in the packet that are of the layer type ( an incase - sensitive string ). This is in order to retrieve layers which appear multiple times in the same packet ( i. e. double VLAN ) which cannot be retrieved by easier means. | def get_multiple_layers(self, layer_name):
"""
Returns a list of all the layers in the packet that are of the layer type (an incase-sensitive string).
This is in order to retrieve layers which appear multiple times in the same packet (i.e. double VLAN) which cannot be
retrieved by easier... |
Make lists out of duplicate keys. | def duplicate_object_hook(ordered_pairs):
"""Make lists out of duplicate keys."""
json_dict = {}
for key, val in ordered_pairs:
existing_val = json_dict.get(key)
if not existing_val:
json_dict[key] = val
else:
if isinstance(existing_val, list):
... |
Returns the next packet in the cap. If the capture s keep_packets flag is True will also keep it in the internal packet list. | def next(self):
"""
Returns the next packet in the cap.
If the capture's keep_packets flag is True, will also keep it in the internal packet list.
"""
if not self.keep_packets:
return self._packet_generator.send(None)
elif self._current_packet >= len(self._pac... |
Gets a TShark XML packet object or string and returns a pyshark Packet objec. t | def packet_from_xml_packet(xml_pkt, psml_structure=None):
"""
Gets a TShark XML packet object or string, and returns a pyshark Packet objec.t
:param xml_pkt: str or xml object.
:param psml_structure: a list of the fields in each packet summary in the psml data. If given, packets will
be returned as... |
Returns the special tshark parameters to be used according to the configuration of this class. | def get_parameters(self, packet_count=None):
"""
Returns the special tshark parameters to be used according to the configuration of this class.
"""
params = super(LiveRingCapture, self).get_parameters(packet_count=packet_count)
params += ['-b', 'filesize:' + str(self.ring_file_si... |
Returns the special tshark parameters to be used according to the configuration of this class. | def get_parameters(self, packet_count=None):
"""
Returns the special tshark parameters to be used according to the configuration of this class.
"""
params = super(LiveCapture, self).get_parameters(packet_count=packet_count)
# Read from STDIN
params += ['-r', '-']
... |
Reads the packets from the source ( cap interface etc. ) and adds it to the internal list. If 0 as the packet_count is given reads forever | def load_packets(self, packet_count=0, timeout=None):
"""
Reads the packets from the source (cap, interface, etc.) and adds it to the internal list.
If 0 as the packet_count is given, reads forever
:param packet_count: The amount of packets to add to the packet list (0 to read forever)
... |
Sets the capture to debug mode ( or turns it off if specified ). | def set_debug(self, set_to=True):
"""
Sets the capture to debug mode (or turns it off if specified).
"""
if set_to:
StreamHandler(sys.stdout).push_application()
self._log.level = logbook.DEBUG
self.debug = set_to |
Sets up a new eventloop as the current one according to the OS. | def _setup_eventloop(self):
"""
Sets up a new eventloop as the current one according to the OS.
"""
if os.name == 'nt':
self.eventloop = asyncio.ProactorEventLoop()
else:
self.eventloop = asyncio.new_event_loop()
asyncio.set_event_loop(self.eventlo... |
Gets data containing a ( part of ) tshark xml. | def _extract_tag_from_data(self, data, tag_name=b'packet'):
"""Gets data containing a (part of) tshark xml.
If the given tag is found in it, returns the tag data and the remaining data.
Otherwise returns None and the same data.
:param data: string of a partial tshark xml.
:retu... |
Returns a generator of packets. This is the sync version of packets_from_tshark. It wait for the completion of each coroutine and reimplements reading packets in a sync way yielding each packet as it arrives. | def _packets_from_tshark_sync(self, packet_count=None, existing_process=None):
"""
Returns a generator of packets.
This is the sync version of packets_from_tshark. It wait for the completion of each coroutine and
reimplements reading packets in a sync way, yielding each packet as it arr... |
Runs through all packets and calls the given callback ( a function ) with each one as it is read. If the capture is infinite ( i. e. a live capture ) it will run forever otherwise it will complete after all packets have been read. | def apply_on_packets(self, callback, timeout=None, packet_count=None):
"""
Runs through all packets and calls the given callback (a function) with each one as it is read.
If the capture is infinite (i.e. a live capture), it will run forever, otherwise it will complete after all
packets h... |
A coroutine which creates a tshark process runs the given callback on each packet that is received from it and closes the process when it is done. | async def packets_from_tshark(self, packet_callback, packet_count=None, close_tshark=True):
"""
A coroutine which creates a tshark process, runs the given callback on each packet that is received from it and
closes the process when it is done.
Do not use interactively. Can be used in or... |
A coroutine which goes through a stream and calls a given callback for each XML packet seen in it. | async def _go_through_packets_from_fd(self, fd, packet_callback, packet_count=None):
"""A coroutine which goes through a stream and calls a given callback for each XML packet seen in it."""
packets_captured = 0
self._log.debug('Starting to go through packets')
psml_struct, data = await ... |
Gets the current PSML ( packet summary xml ) structure in a tuple (( None leftover_data )) only if the capture is configured to return it else returns ( None leftover_data ). | async def _get_psml_struct(self, fd):
"""Gets the current PSML (packet summary xml) structure in a tuple ((None, leftover_data)),
only if the capture is configured to return it, else returns (None, leftover_data).
A coroutine.
"""
data = b''
psml_struct = None
i... |
A coroutine which returns a single packet if it can be read from the given StreamReader. | async def _get_packet_from_stream(self, stream, existing_data, got_first_packet=True, psml_structure=None):
"""A coroutine which returns a single packet if it can be read from the given StreamReader.
:return a tuple of (packet, remaining_data). The packet will be None if there was not enough XML data t... |
Returns a new tshark process with previously - set parameters. | async def _get_tshark_process(self, packet_count=None, stdin=None):
"""
Returns a new tshark process with previously-set parameters.
"""
if self.use_json:
output_type = 'json'
if not tshark_supports_json(self.tshark_path):
raise TSharkVersionExcept... |
Kill the given process and properly closes any pipes connected to it. | async def _cleanup_subprocess(self, process):
"""
Kill the given process and properly closes any pipes connected to it.
"""
if process.returncode is None:
try:
process.kill()
return await asyncio.wait_for(process.wait(), 1)
except c... |
Returns the special tshark parameters to be used according to the configuration of this class. | def get_parameters(self, packet_count=None):
"""
Returns the special tshark parameters to be used according to the configuration of this class.
"""
params = []
if self._capture_filter:
params += ['-f', self._capture_filter]
if self._display_filter:
... |
Gets the best value string this field has. | def get_default_value(self):
"""
Gets the best 'value' string this field has.
"""
val = self.show
if not val:
val = self.raw_value
if not val:
val = self.showname
return val |
Converts this field to binary ( assuming it s a binary string ) | def binary_value(self):
"""
Converts this field to binary (assuming it's a binary string)
"""
str_raw_value = str(self.raw_value)
if len(str_raw_value) % 2 == 1:
str_raw_value = '0' + str_raw_value
return binascii.unhexlify(str_raw_value) |
Build callgraph of func_list ignoring built - in functions | def callgraph(G, stmt_list):
"""
Build callgraph of func_list, ignoring
built-in functions
"""
func_list = []
for stmt in stmt_list:
try:
G.add_node(stmt.head.ident.name)
func_list.append(stmt)
except:
pass
for func in func_list:
as... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.