code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def validate_primary_group_on_delete(sender, instance, **kwargs): """Validate primary_group on user profiles when a group is deleted.""" for user in instance.user_set.all(): profile = user.profile if profile.primary_group == instance: profile.primary_group = None profile....
Validate primary_group on user profiles when a group is deleted.
validate_primary_group_on_delete
python
inventree/InvenTree
src/backend/InvenTree/users/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/models.py
MIT
def validate_primary_group_on_group_change(sender, instance, action, **kwargs): """Validate primary_group on user profiles when a group is added or removed.""" if action in ['post_add', 'post_remove']: profile = instance.profile if profile.primary_group and profile.primary_group not in instance....
Validate primary_group on user profiles when a group is added or removed.
validate_primary_group_on_group_change
python
inventree/InvenTree
src/backend/InvenTree/users/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/models.py
MIT
def get_granular_scope(method, role=None, type='r'): """Generate a granular scope string for a given method and role.""" if role: return f'{type}:{method}:{role}' return f'{type}:{method}'
Generate a granular scope string for a given method and role.
get_granular_scope
python
inventree/InvenTree
src/backend/InvenTree/users/oauth2_scopes.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/oauth2_scopes.py
MIT
def split_model(model_label: str) -> tuple[str, str]: """Split a model string into its component parts. Arguments: model_label: The model class to check (e.g. 'part_partcategory') Returns: A tuple of the model and app names (e.g. ('partcategory', 'part')) """ *app, model = model_la...
Split a model string into its component parts. Arguments: model_label: The model class to check (e.g. 'part_partcategory') Returns: A tuple of the model and app names (e.g. ('partcategory', 'part'))
split_model
python
inventree/InvenTree
src/backend/InvenTree/users/permissions.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/permissions.py
MIT
def split_permission(app: str, perm: str) -> tuple[str, str]: """Split the permission string into its component parts. Arguments: app: The application name (e.g. 'part') perm: The permission string (e.g. 'view_part' / 'delete_partcategory') Returns: A tuple of the permission and mo...
Split the permission string into its component parts. Arguments: app: The application name (e.g. 'part') perm: The permission string (e.g. 'view_part' / 'delete_partcategory') Returns: A tuple of the permission and model names
split_permission
python
inventree/InvenTree
src/backend/InvenTree/users/permissions.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/permissions.py
MIT
def check_user_role( user: User, role: str, permission: str, allow_inactive: bool = False ) -> bool: """Check if a user has a particular role:permission combination. Arguments: user: The user object to check role: The role to check (e.g. 'part' / 'stock') permission: The permission ...
Check if a user has a particular role:permission combination. Arguments: user: The user object to check role: The role to check (e.g. 'part' / 'stock') permission: The permission to check (e.g. 'view' / 'delete') allow_inactive: If False, disallow inactive users from having permissi...
check_user_role
python
inventree/InvenTree
src/backend/InvenTree/users/permissions.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/permissions.py
MIT
def check_user_permission( user: User, model: models.Model, permission: str, allow_inactive: bool = False ) -> bool: """Check if the user has a particular permission against a given model type. Arguments: user: The user object to check model: The model class to check (e.g. 'part') p...
Check if the user has a particular permission against a given model type. Arguments: user: The user object to check model: The model class to check (e.g. 'part') permission: The permission to check (e.g. 'view' / 'delete') allow_inactive: If False, disallow inactive users from havin...
check_user_permission
python
inventree/InvenTree
src/backend/InvenTree/users/permissions.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/permissions.py
MIT
def get_ruleset_models() -> dict: """Return a dictionary of models associated with each ruleset. This function maps particular database models to each ruleset. """ ruleset_models = { RuleSetEnum.ADMIN: [ 'auth_group', 'auth_user', 'auth_permission', ...
Return a dictionary of models associated with each ruleset. This function maps particular database models to each ruleset.
get_ruleset_models
python
inventree/InvenTree
src/backend/InvenTree/users/ruleset.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/ruleset.py
MIT
def get_ruleset_ignore() -> list[str]: """Return a list of database tables which do not require permissions.""" return [ # Core django models (not user configurable) 'admin_logentry', 'contenttypes_contenttype', # Models which currently do not require permissions 'common_...
Return a list of database tables which do not require permissions.
get_ruleset_ignore
python
inventree/InvenTree
src/backend/InvenTree/users/ruleset.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/ruleset.py
MIT
def generate_permission_dict(permissions) -> dict: """Generate a dictionary of permissions for a given set of permissions.""" perms = {} for permission in permissions: perm, model = permission.codename.split('_') if model not in perms: perms[model] = [] perms[model].ap...
Generate a dictionary of permissions for a given set of permissions.
generate_permission_dict
python
inventree/InvenTree
src/backend/InvenTree/users/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/serializers.py
MIT
def generate_roles_dict(roles) -> dict: """Generate a dictionary of roles for a given set of roles.""" # Build out an (initially empty) dictionary of roles role_dict = {name: [] for name, _ in RULESET_CHOICES} for role in roles: permissions = [] for permission in ['view', 'add', 'chang...
Generate a dictionary of roles for a given set of roles.
generate_roles_dict
python
inventree/InvenTree
src/backend/InvenTree/users/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/serializers.py
MIT
def get_in_use(self, token: ApiToken) -> bool: """Return True if the token is currently used to call the endpoint.""" from InvenTree.middleware import get_token_from_request request = self.context.get('request') rq_token = get_token_from_request(request) return token.key == rq_t...
Return True if the token is currently used to call the endpoint.
get_in_use
python
inventree/InvenTree
src/backend/InvenTree/users/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/serializers.py
MIT
def validate(self, data): """Validate the data for the serializer.""" if 'user' not in data: data['user'] = self.context['request'].user return super().validate(data)
Validate the data for the serializer.
validate
python
inventree/InvenTree
src/backend/InvenTree/users/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/serializers.py
MIT
def validate_is_superuser(self, value): """Only a superuser account can adjust this value!""" request_user = self.context['request'].user if 'is_superuser' in self.context['request'].data: if not request_user.is_superuser: raise PermissionDenied({ ...
Only a superuser account can adjust this value!
validate_is_superuser
python
inventree/InvenTree
src/backend/InvenTree/users/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/serializers.py
MIT
def update(self, instance, validated_data): """Update the user instance with the provided data.""" # Update the groups associated with the user groups = validated_data.pop('group_ids', None) instance = super().update(instance, validated_data) if groups is not None: ...
Update the user instance with the provided data.
update
python
inventree/InvenTree
src/backend/InvenTree/users/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/serializers.py
MIT
def create(self, validated_data): """Send an e email to the user after creation.""" from InvenTree.helpers_model import get_base_url from InvenTree.tasks import email_user, offload_task base_url = get_base_url() instance = super().create(validated_data) # Make sure the...
Send an e email to the user after creation.
create
python
inventree/InvenTree
src/backend/InvenTree/users/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/serializers.py
MIT
def rebuild_all_permissions() -> None: """Rebuild all user permissions. This function is called when a user is created or when a group is modified. It rebuilds the permissions for all users in the system. """ logger.info('Rebuilding permissions') # Rebuild permissions for each group for gr...
Rebuild all user permissions. This function is called when a user is created or when a group is modified. It rebuilds the permissions for all users in the system.
rebuild_all_permissions
python
inventree/InvenTree
src/backend/InvenTree/users/tasks.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/tasks.py
MIT
def update_group_roles(group: Group, debug: bool = False) -> None: """Update the roles for a particular group. Arguments: group: The group object to update roles for. debug: Whether to enable debug logging This function performs the following tasks: - Remove any RuleSet objects which h...
Update the roles for a particular group. Arguments: group: The group object to update roles for. debug: Whether to enable debug logging This function performs the following tasks: - Remove any RuleSet objects which have become outdated - Ensure that the group has a mapped RuleSet for e...
update_group_roles
python
inventree/InvenTree
src/backend/InvenTree/users/tasks.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/tasks.py
MIT
def add_model(name, action, allowed): """Add a new model to the pile. Args: name: The name of the model e.g. part_part action: The permission action e.g. view allowed: Whether or not the action is allowed """ if action not in ['view', 'add', 'change',...
Add a new model to the pile. Args: name: The name of the model e.g. part_part action: The permission action e.g. view allowed: Whether or not the action is allowed
add_model
python
inventree/InvenTree
src/backend/InvenTree/users/tasks.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/tasks.py
MIT
def get_permission_object(permission_string): """Find the permission object in the database, from the simplified permission string. Args: permission_string: a simplified permission_string e.g. 'part.view_partcategory' Returns the permission object in the database associated with th...
Find the permission object in the database, from the simplified permission string. Args: permission_string: a simplified permission_string e.g. 'part.view_partcategory' Returns the permission object in the database associated with the permission string
get_permission_object
python
inventree/InvenTree
src/backend/InvenTree/users/tasks.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/tasks.py
MIT
def test_ruleset_models(self): """Test that the role rulesets work as intended.""" keys = G_RULESETS.keys() # Check if there are any rulesets which do not have models defined missing = [name for name in RULESET_NAMES if name not in keys] if len(missing) > 0: # pragma: no cove...
Test that the role rulesets work as intended.
test_ruleset_models
python
inventree/InvenTree
src/backend/InvenTree/users/tests.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/tests.py
MIT
def test_model_names(self): """Test that each model defined in the rulesets is valid, based on the database schema!""" available_models = apps.get_models() available_tables = set() # Extract each available database model and construct a formatted string for model in available_m...
Test that each model defined in the rulesets is valid, based on the database schema!
test_model_names
python
inventree/InvenTree
src/backend/InvenTree/users/tests.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/tests.py
MIT
def test_scope_names(self): """Ensure that the rulesets map to scopes and vice versa.""" # Check that each scope has a corresponding ruleset missing = [scope for scope in G_SCOPES if scope not in G_RULESETS] if len(missing) > 0: # pragma: no cover print('INVE-E6: The follow...
Ensure that the rulesets map to scopes and vice versa.
test_scope_names
python
inventree/InvenTree
src/backend/InvenTree/users/tests.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/tests.py
MIT
def test_permission_assign(self): """Test that the permission assigning works!""" # Create a new group group = Group.objects.create(name='Test group') rulesets = group.rule_sets.all() # Rulesets should have been created automatically for this group self.assertEqual(rule...
Test that the permission assigning works!
test_permission_assign
python
inventree/InvenTree
src/backend/InvenTree/users/tests.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/tests.py
MIT
def test_display_name(self): """Test the display name for the owner.""" owner = Owner.get_owner(self.user) self.assertEqual(owner.name(), 'testuser') self.assertEqual(str(owner), 'testuser (user)') # Change setting set_global_setting('DISPLAY_FULL_NAMES', True) s...
Test the display name for the owner.
test_display_name
python
inventree/InvenTree
src/backend/InvenTree/users/tests.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/tests.py
MIT
def test_primary_group_validation(self): """Test that primary_group is a group that the user is a member of.""" new_group = Group.objects.create(name='New Group') profile = self.user.profile profile.primary_group = new_group profile.save() self.assertIsNone(profile.primar...
Test that primary_group is a group that the user is a member of.
test_primary_group_validation
python
inventree/InvenTree
src/backend/InvenTree/users/tests.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/tests.py
MIT
def test_user_options(self): """Tests for the User OPTIONS request.""" self.assignRole('admin.add') response = self.options(reverse('api-user-list'), expected_code=200) self.user.is_staff = True self.user.save() # User is a *staff* user with *admin* role, so can POST ag...
Tests for the User OPTIONS request.
test_user_options
python
inventree/InvenTree
src/backend/InvenTree/users/test_api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/test_api.py
MIT
def test_group_api(self): """Tests for the Group API endpoints.""" response = self.get(reverse('api-group-list'), expected_code=200) self.assertIn('name', response.data[0]) self.assertEqual(len(response.data), Group.objects.count()) # Check detail URL pk = response.dat...
Tests for the Group API endpoints.
test_group_api
python
inventree/InvenTree
src/backend/InvenTree/users/test_api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/test_api.py
MIT
def test_user_roles(self): """Test the user 'roles' API endpoint.""" url = reverse('api-user-roles') response = self.get(url, expected_code=200) data = response.data # User has no 'permissions' yet self.assertEqual(len(data['permissions']), 0) self.assertEqual(l...
Test the user 'roles' API endpoint.
test_user_roles
python
inventree/InvenTree
src/backend/InvenTree/users/test_api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/test_api.py
MIT
def prepare(self): """Setup the initial state of the database before migrations.""" User = self.old_state.apps.get_model('auth', 'user') User.objects.create(username='fred', email='fred@fred.com', password='password') User.objects.create(username='brad', email='brad@fred.com', password...
Setup the initial state of the database before migrations.
prepare
python
inventree/InvenTree
src/backend/InvenTree/users/test_migrations.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/test_migrations.py
MIT
def test_backfill_user_profiles(self): """Test that user profiles are created during the migration.""" User = self.new_state.apps.get_model('auth', 'user') UserProfile = self.new_state.apps.get_model('users', 'UserProfile') self.assertEqual(User.objects.count(), 2) self.assertEq...
Test that user profiles are created during the migration.
test_backfill_user_profiles
python
inventree/InvenTree
src/backend/InvenTree/users/test_migrations.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/test_migrations.py
MIT
def test_users_exist(self): """Test that users exist in the database.""" User = self.new_state.apps.get_model('auth', 'user') Authenticator = self.new_state.apps.get_model('mfa', 'Authenticator') self.assertEqual(User.objects.count(), 2) # 2 Tokens - both for user 1 self...
Test that users exist in the database.
test_users_exist
python
inventree/InvenTree
src/backend/InvenTree/users/test_migrations.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/test_migrations.py
MIT
def move_mfa(apps, schema_editor): """Data migration to switch to django-allauth's new built-in MFA.""" adapter = get_adapter() authenticators = [] for totp in TOTPDevice.objects.filter(confirmed=True).iterator(): recovery_codes = set() for sdevice in StaticDevice.objects.filter( ...
Data migration to switch to django-allauth's new built-in MFA.
move_mfa
python
inventree/InvenTree
src/backend/InvenTree/users/migrations/0013_migrate_mfa_20240408_1659.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/users/migrations/0013_migrate_mfa_20240408_1659.py
MIT
def assertSettings(self, settings_data): """Helper to test if needed args are in the settings.""" self.assertIn('debug', settings_data) self.assertIn('server_list', settings_data) self.assertIn('show_server_selector', settings_data) self.assertIn('environment', settings_data)
Helper to test if needed args are in the settings.
assertSettings
python
inventree/InvenTree
src/backend/InvenTree/web/tests.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/web/tests.py
MIT
def cui_compatibility_urls(base: str) -> list: """Generate a list of URL patterns for compatibility with old (CUI) URLs. These URLs are provided for backwards compatibility with older versions of InvenTree, before we moved to a SPA (Single Page Application) architecture in the 1.0.0 release. At some f...
Generate a list of URL patterns for compatibility with old (CUI) URLs. These URLs are provided for backwards compatibility with older versions of InvenTree, before we moved to a SPA (Single Page Application) architecture in the 1.0.0 release. At some future point these may be removed? Args: b...
cui_compatibility_urls
python
inventree/InvenTree
src/backend/InvenTree/web/urls.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/web/urls.py
MIT
def rddconf(_dummy=_named_only_start, disk_merge=None, sort_merge=None, iter_group=False, ordered_group=None, dump_mem_ratio=None, op=OP_UDF): """ Return new RDDConfig object based on default values. Only takes named arguments. e.g. groupByKey(.., rddc...
Return new RDDConfig object based on default values. Only takes named arguments. e.g. groupByKey(.., rddconf=dpark.conf.rddconf(...))
rddconf
python
douban/dpark
dpark/conf.py
https://github.com/douban/dpark/blob/master/dpark/conf.py
BSD-3-Clause
def enumerate(self): """ enumerate this RDD. >>> dpark.parallelize(["a", "b", "c", "d"], 3).enumerate().collect() [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')] """ starts = [0] if len(self) > 1: nums = self.mapPartitions(lambda it: [sum(1 for _ in it)]).co...
enumerate this RDD. >>> dpark.parallelize(["a", "b", "c", "d"], 3).enumerate().collect() [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
enumerate
python
douban/dpark
dpark/rdd.py
https://github.com/douban/dpark/blob/master/dpark/rdd.py
BSD-3-Clause
def fold(self, zero, f): '''Aggregate the elements of each partition, and then the results for all the partitions, using a given associative function and a neutral "zero value". The function op(t1, t2) is allowed to modify t1 and return it as its result value to avoid object allo...
Aggregate the elements of each partition, and then the results for all the partitions, using a given associative function and a neutral "zero value". The function op(t1, t2) is allowed to modify t1 and return it as its result value to avoid object allocation; however, it should not modif...
fold
python
douban/dpark
dpark/rdd.py
https://github.com/douban/dpark/blob/master/dpark/rdd.py
BSD-3-Clause
def aggregate(self, zero, seqOp, combOp): '''Aggregate the elements of each partition, and then the results for all the partitions, using given combine functions and a neutral "zero value". This function can return a different result type, U, than the type of this RDD, T. Thus, w...
Aggregate the elements of each partition, and then the results for all the partitions, using given combine functions and a neutral "zero value". This function can return a different result type, U, than the type of this RDD, T. Thus, we need one operation for merging a T into an U (seqOp...
aggregate
python
douban/dpark
dpark/rdd.py
https://github.com/douban/dpark/blob/master/dpark/rdd.py
BSD-3-Clause
def saveAsBeansdb(self, path, depth=0, overwrite=True, compress=True, raw=False, valueWithMeta=False): """ save (key, value) pair in beansdb format files Args: depth: choice = [0, 1, 2]. e.g. depth = 2 will write split N to 256 files: ...
save (key, value) pair in beansdb format files Args: depth: choice = [0, 1, 2]. e.g. depth = 2 will write split N to 256 files: 'path/[0-F]/[0-F]/%03d.data' % N MUST use depth == 0 to generate data for rivendb raw: same as in DparkCon...
saveAsBeansdb
python
douban/dpark
dpark/rdd.py
https://github.com/douban/dpark/blob/master/dpark/rdd.py
BSD-3-Clause
def innerJoin(self, smallRdd): """ This is functionally equivalent to `join`, but `innerJoin` assume `smallRdd` is a small Data set, and `innerJoin` will broadcast the `smallRdd` to optimize running time. >>> x = dpark_context.parallelize([("a", 1), ("b", 4)]) >>> y = dpark_cont...
This is functionally equivalent to `join`, but `innerJoin` assume `smallRdd` is a small Data set, and `innerJoin` will broadcast the `smallRdd` to optimize running time. >>> x = dpark_context.parallelize([("a", 1), ("b", 4)]) >>> y = dpark_context.parallelize([("a", 2), ("a", 3)]) ...
innerJoin
python
douban/dpark
dpark/rdd.py
https://github.com/douban/dpark/blob/master/dpark/rdd.py
BSD-3-Clause
def __init__(self, rdd, shuffleDep, parents, pipelines, pipeline_edges, rdd_pipelines): """ :param rdd: output rdd of this stage :param shuffleDep: for mapOutputStage, determine how computing result will be aggregated, partitioned """ self.id = self.new_id() self.num_try...
:param rdd: output rdd of this stage :param shuffleDep: for mapOutputStage, determine how computing result will be aggregated, partitioned
__init__
python
douban/dpark
dpark/schedule.py
https://github.com/douban/dpark/blob/master/dpark/schedule.py
BSD-3-Clause
def newStage(self, output_rdd, shuffleDep): """ A stage may contain multi data pipeline, which form a tree with one final output pipline as root. Zip, CartesianRDD, and Union may commine diff data sources, so lead to a split of the tree. The leaves of the tree may be one of: ...
A stage may contain multi data pipeline, which form a tree with one final output pipline as root. Zip, CartesianRDD, and Union may commine diff data sources, so lead to a split of the tree. The leaves of the tree may be one of: 1. a pipeline start from a source RDD (TextFileRDD,...
newStage
python
douban/dpark
dpark/schedule.py
https://github.com/douban/dpark/blob/master/dpark/schedule.py
BSD-3-Clause
def readchunk(self, inode, index, chunkopflags=0): """ // msgid:32 length:64 chunkid:64 version:32 N*[ ip:32 port:16 ] // msgid:32 protocolid:8 length:64 chunkid:64 version:32 N*[ ip:32 port:16 cs_ver:32 ] (master and client both versions >= 1.7.32 - protocolid==1) // msg...
// msgid:32 length:64 chunkid:64 version:32 N*[ ip:32 port:16 ] // msgid:32 protocolid:8 length:64 chunkid:64 version:32 N*[ ip:32 port:16 cs_ver:32 ] (master and client both versions >= 1.7.32 - protocolid==1) // msgid:32 protocolid:8 length:64 chunkid:64 version:32 N*[ ip:32 p...
readchunk
python
douban/dpark
dpark/file_manager/mfs_proxy.py
https://github.com/douban/dpark/blob/master/dpark/file_manager/mfs_proxy.py
BSD-3-Clause
def write_bucket(self, it, index): """ 0 <= index < 256 yield from it write to "*/%03d.data" % index """ N = 16 ** self.depth if self.depth > 0: fmt = '%%0%dx' % self.depth ds = [os.path.join(self.path, *list(fmt % i)) for i in range(N)] ...
0 <= index < 256 yield from it write to "*/%03d.data" % index
write_bucket
python
douban/dpark
dpark/utils/beansdb.py
https://github.com/douban/dpark/blob/master/dpark/utils/beansdb.py
BSD-3-Clause
def __init__(self, f): """working in func_name, exec code at pos""" self.path = get_path(f.f_code.co_filename) self.lineno = f.f_lineno self.lasti = f.f_lasti self.func_name = f.f_code.co_name
working in func_name, exec code at pos
__init__
python
douban/dpark
dpark/utils/frame.py
https://github.com/douban/dpark/blob/master/dpark/utils/frame.py
BSD-3-Clause
def get_callsite(cls, caller, callee): """ Deal with usage like "rdd.map(_).map(_)", distinguish same dpark api called in one line by lasti. To be comprehensible, replace lasti with order of calling of same api in this line , starts with 0. """ callee = Frame(callee) # the dpa...
Deal with usage like "rdd.map(_).map(_)", distinguish same dpark api called in one line by lasti. To be comprehensible, replace lasti with order of calling of same api in this line , starts with 0.
get_callsite
python
douban/dpark
dpark/utils/frame.py
https://github.com/douban/dpark/blob/master/dpark/utils/frame.py
BSD-3-Clause
def merge(self, iterables, ordered_iters=0): """iterables: each is sorted ordered_iters: when come to equal value, the element in the first iter yields first(last) if ordered_iters >(<) 0 not stable if ordered_iters == 0 """ if not ordered_iters: ...
iterables: each is sorted ordered_iters: when come to equal value, the element in the first iter yields first(last) if ordered_iters >(<) 0 not stable if ordered_iters == 0
merge
python
douban/dpark
dpark/utils/heaponkey.py
https://github.com/douban/dpark/blob/master/dpark/utils/heaponkey.py
BSD-3-Clause
def get_logger(name): """ Always use logging.Logger class. The user code may change the loggerClass (e.g. pyinotify), and will cause exception when format log message. """ old_class = logging.getLoggerClass() logging.setLoggerClass(logging.Logger) logger = logging.getLogger(name) loggin...
Always use logging.Logger class. The user code may change the loggerClass (e.g. pyinotify), and will cause exception when format log message.
get_logger
python
douban/dpark
dpark/utils/log.py
https://github.com/douban/dpark/blob/master/dpark/utils/log.py
BSD-3-Clause
def _next_block_for_key(self, k): """return None when meet a diff key or the end else return and then update _next_block """ if self._next_block is None: # start/end try: self._next_block = next(self._it) except StopIteration: r...
return None when meet a diff key or the end else return and then update _next_block
_next_block_for_key
python
douban/dpark
dpark/utils/nested_groupby.py
https://github.com/douban/dpark/blob/master/dpark/utils/nested_groupby.py
BSD-3-Clause
def __init__(self, cfg: LeggedRobotCfg, sim_params, physics_engine, sim_device, headless): """ Parses the provided config file, calls create_sim() (which creates, simulation and environments), initilizes pytorch buffers used during training Args: cfg (Dict): Environm...
Parses the provided config file, calls create_sim() (which creates, simulation and environments), initilizes pytorch buffers used during training Args: cfg (Dict): Environment config file sim_params (gymapi.SimParams): simulation parameters physics_e...
__init__
python
unitreerobotics/unitree_rl_gym
legged_gym/envs/base/legged_robot.py
https://github.com/unitreerobotics/unitree_rl_gym/blob/master/legged_gym/envs/base/legged_robot.py
BSD-3-Clause
def _resample_commands(self, env_ids): """ Randommly select commands of some environments Args: env_ids (List[int]): Environments ids for which new commands are needed """ self.commands[env_ids, 0] = torch_rand_float(self.command_ranges["lin_vel_x"][0], self.command_ranges["...
Randommly select commands of some environments Args: env_ids (List[int]): Environments ids for which new commands are needed
_resample_commands
python
unitreerobotics/unitree_rl_gym
legged_gym/envs/base/legged_robot.py
https://github.com/unitreerobotics/unitree_rl_gym/blob/master/legged_gym/envs/base/legged_robot.py
BSD-3-Clause
def _push_robots(self): """ Random pushes the robots. Emulates an impulse by setting a randomized base velocity. """ env_ids = torch.arange(self.num_envs, device=self.device) push_env_ids = env_ids[self.episode_length_buf[env_ids] % int(self.cfg.domain_rand.push_interval) == 0] ...
Random pushes the robots. Emulates an impulse by setting a randomized base velocity.
_push_robots
python
unitreerobotics/unitree_rl_gym
legged_gym/envs/base/legged_robot.py
https://github.com/unitreerobotics/unitree_rl_gym/blob/master/legged_gym/envs/base/legged_robot.py
BSD-3-Clause
def update_command_curriculum(self, env_ids): """ Implements a curriculum of increasing commands Args: env_ids (List[int]): ids of environments being reset """ # If the tracking reward is above 80% of the maximum, increase the range of commands if torch.mean(self.epi...
Implements a curriculum of increasing commands Args: env_ids (List[int]): ids of environments being reset
update_command_curriculum
python
unitreerobotics/unitree_rl_gym
legged_gym/envs/base/legged_robot.py
https://github.com/unitreerobotics/unitree_rl_gym/blob/master/legged_gym/envs/base/legged_robot.py
BSD-3-Clause
def make_env(self, name, args=None, env_cfg=None) -> Tuple[VecEnv, LeggedRobotCfg]: """ Creates an environment either from a registered namme or from the provided config file. Args: name (string): Name of a registered env. args (Args, optional): Isaac Gym comand line arguments. ...
Creates an environment either from a registered namme or from the provided config file. Args: name (string): Name of a registered env. args (Args, optional): Isaac Gym comand line arguments. If None get_args() will be called. Defaults to None. env_cfg (Dict, optional): Envi...
make_env
python
unitreerobotics/unitree_rl_gym
legged_gym/utils/task_registry.py
https://github.com/unitreerobotics/unitree_rl_gym/blob/master/legged_gym/utils/task_registry.py
BSD-3-Clause
def make_alg_runner(self, env, name=None, args=None, train_cfg=None, log_root="default") -> Tuple[OnPolicyRunner, LeggedRobotCfgPPO]: """ Creates the training algorithm either from a registered namme or from the provided config file. Args: env (isaacgym.VecTaskPython): The environment to t...
Creates the training algorithm either from a registered namme or from the provided config file. Args: env (isaacgym.VecTaskPython): The environment to train (TODO: remove from within the algorithm) name (string, optional): Name of a registered env. If None, the config file will be use...
make_alg_runner
python
unitreerobotics/unitree_rl_gym
legged_gym/utils/task_registry.py
https://github.com/unitreerobotics/unitree_rl_gym/blob/master/legged_gym/utils/task_registry.py
BSD-3-Clause
def voronoi_finite_polygons_2d(vor, radius=None): """ Credit: https://gist.github.com/pv/8036995 Reconstruct infinite voronoi regions in a 2D diagram to finite regions. Parameters ---------- vor : Voronoi Input diagram radius : float, optional Distance to 'poin...
Credit: https://gist.github.com/pv/8036995 Reconstruct infinite voronoi regions in a 2D diagram to finite regions. Parameters ---------- vor : Voronoi Input diagram radius : float, optional Distance to 'points at infinity'. Returns ------- regions : l...
voronoi_finite_polygons_2d
python
aburkov/theMLbook
kmeans.py
https://github.com/aburkov/theMLbook/blob/master/kmeans.py
MIT
def fig2data(fig): """ @brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it @param fig a matplotlib figure @return a numpy 3D array of RGB values """ # draw the renderer fig.canvas.draw() # Get the RGBA buffer from the figure w,h = fig.canvas.get_...
@brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it @param fig a matplotlib figure @return a numpy 3D array of RGB values
fig2data
python
aburkov/theMLbook
Animated_Illustrations/density_estimation.py
https://github.com/aburkov/theMLbook/blob/master/Animated_Illustrations/density_estimation.py
MIT
def voronoi_finite_polygons_2d(vor, radius=None): """ Reconstruct infinite voronoi regions in a 2D diagram to finite regions. Parameters ---------- vor : Voronoi Input diagram radius : float, optional Distance to 'points at infinity'. Returns ------- regions : l...
Reconstruct infinite voronoi regions in a 2D diagram to finite regions. Parameters ---------- vor : Voronoi Input diagram radius : float, optional Distance to 'points at infinity'. Returns ------- regions : list of tuples Indices of vertices in each revised...
voronoi_finite_polygons_2d
python
aburkov/theMLbook
Animated_Illustrations/kmeans.py
https://github.com/aburkov/theMLbook/blob/master/Animated_Illustrations/kmeans.py
MIT
def search_flights( departure_airport: str, arrival_airport: str, date: str, ) -> list[dict]: """Search flights. Args: departure_airport: 3-letter airport code for the departure airport. If unsure, use the biggest airport in the area arrival_airport: 3-letter airport code for the ar...
Search flights. Args: departure_airport: 3-letter airport code for the departure airport. If unsure, use the biggest airport in the area arrival_airport: 3-letter airport code for the arrival airport. If unsure, use the biggest airport in the area date: YYYY-MM-DD date
search_flights
python
langchain-ai/langgraph-swarm-py
examples/customer_support/src/agent/customer_support.py
https://github.com/langchain-ai/langgraph-swarm-py/blob/master/examples/customer_support/src/agent/customer_support.py
MIT
def fetch_doc(url: str) -> str: """Fetch a document from a URL and return the markdownified text. Args: url (str): The URL of the document to fetch. Returns: str: The markdownified text of the document. """ try: response = httpx_client.get(url, timeout=10) response....
Fetch a document from a URL and return the markdownified text. Args: url (str): The URL of the document to fetch. Returns: str: The markdownified text of the document.
fetch_doc
python
langchain-ai/langgraph-swarm-py
examples/research/src/agent/utils.py
https://github.com/langchain-ai/langgraph-swarm-py/blob/master/examples/research/src/agent/utils.py
MIT
def get_handoff_destinations(agent: CompiledStateGraph, tool_node_name: str = "tools") -> list[str]: """Get a list of destinations from agent's handoff tools.""" nodes = agent.get_graph().nodes if tool_node_name not in nodes: return [] tool_node = nodes[tool_node_name].data if not isinstanc...
Get a list of destinations from agent's handoff tools.
get_handoff_destinations
python
langchain-ai/langgraph-swarm-py
langgraph_swarm/handoff.py
https://github.com/langchain-ai/langgraph-swarm-py/blob/master/langgraph_swarm/handoff.py
MIT
def _update_state_schema_agent_names( state_schema: StateSchemaType, agent_names: list[str] ) -> StateSchemaType: """Update the state schema to use Literal with agent names for 'active_agent'.""" active_agent_annotation = state_schema.__annotations__["active_agent"] # Check if the annotation is str or...
Update the state schema to use Literal with agent names for 'active_agent'.
_update_state_schema_agent_names
python
langchain-ai/langgraph-swarm-py
langgraph_swarm/swarm.py
https://github.com/langchain-ai/langgraph-swarm-py/blob/master/langgraph_swarm/swarm.py
MIT
def add_active_agent_router( builder: StateGraph, *, route_to: list[str], default_active_agent: str, ) -> StateGraph: """Add a router to the currently active agent to the StateGraph. Args: builder: The graph builder (StateGraph) to add the router to. route_to: A list of agent (n...
Add a router to the currently active agent to the StateGraph. Args: builder: The graph builder (StateGraph) to add the router to. route_to: A list of agent (node) names to route to. default_active_agent: Name of the agent to route to by default (if no agents are currently active). Retu...
add_active_agent_router
python
langchain-ai/langgraph-swarm-py
langgraph_swarm/swarm.py
https://github.com/langchain-ai/langgraph-swarm-py/blob/master/langgraph_swarm/swarm.py
MIT
def create_swarm( agents: list[Pregel], *, default_active_agent: str, state_schema: StateSchemaType = SwarmState, config_schema: Type[Any] | None = None, ) -> StateGraph: """Create a multi-agent swarm. Args: agents: List of agents to add to the swarm An agent can be a La...
Create a multi-agent swarm. Args: agents: List of agents to add to the swarm An agent can be a LangGraph [CompiledStateGraph](https://langchain-ai.github.io/langgraph/reference/graphs/#langgraph.graph.state.CompiledStateGraph), a functional API [workflow](https://langchain-ai.github...
create_swarm
python
langchain-ai/langgraph-swarm-py
langgraph_swarm/swarm.py
https://github.com/langchain-ai/langgraph-swarm-py/blob/master/langgraph_swarm/swarm.py
MIT
def test_import() -> None: """Test that the code can be imported""" from langgraph_swarm import ( # noqa: F401 add_active_agent_router, create_handoff_tool, create_swarm, )
Test that the code can be imported
test_import
python
langchain-ai/langgraph-swarm-py
tests/test_import.py
https://github.com/langchain-ai/langgraph-swarm-py/blob/master/tests/test_import.py
MIT
def method_params(doc): """Document the parameters of a method. Args: doc: string, The method's docstring. Returns: The method signature as a string. """ doclines = doc.splitlines() if "Args:" in doclines: begin = doclines.index("Args:") if "Returns:" in doclines[be...
Document the parameters of a method. Args: doc: string, The method's docstring. Returns: The method signature as a string.
method_params
python
googleapis/google-api-python-client
describe.py
https://github.com/googleapis/google-api-python-client/blob/master/describe.py
Apache-2.0
def method(name, doc): """Documents an individual method. Args: name: string, Name of the method. doc: string, The methods docstring. """ import html params = method_params(doc) doc = html.escape(doc) return string.Template(METHOD_TEMPLATE).substitute( name=name, params...
Documents an individual method. Args: name: string, Name of the method. doc: string, The methods docstring.
method
python
googleapis/google-api-python-client
describe.py
https://github.com/googleapis/google-api-python-client/blob/master/describe.py
Apache-2.0
def breadcrumbs(path, root_discovery): """Create the breadcrumb trail to this page of documentation. Args: path: string, Dot separated name of the resource. root_discovery: Deserialized discovery document. Returns: HTML with links to each of the parent resources of this resource. """...
Create the breadcrumb trail to this page of documentation. Args: path: string, Dot separated name of the resource. root_discovery: Deserialized discovery document. Returns: HTML with links to each of the parent resources of this resource.
breadcrumbs
python
googleapis/google-api-python-client
describe.py
https://github.com/googleapis/google-api-python-client/blob/master/describe.py
Apache-2.0
def document_collection(resource, path, root_discovery, discovery, css=CSS): """Document a single collection in an API. Args: resource: Collection or service being documented. path: string, Dot separated name of the resource. root_discovery: Deserialized discovery document. discovery: D...
Document a single collection in an API. Args: resource: Collection or service being documented. path: string, Dot separated name of the resource. root_discovery: Deserialized discovery document. discovery: Deserialized discovery document, but just the portion that describes the reso...
document_collection
python
googleapis/google-api-python-client
describe.py
https://github.com/googleapis/google-api-python-client/blob/master/describe.py
Apache-2.0
def document_api( name, version, uri, doc_destination_dir, artifact_destination_dir=DISCOVERY_DOC_DIR, ): """Document the given API. Args: name (str): Name of the API. version (str): Version of the API. uri (str): URI of the API's discovery document doc_desti...
Document the given API. Args: name (str): Name of the API. version (str): Version of the API. uri (str): URI of the API's discovery document doc_destination_dir (str): relative path where the reference documentation should be saved. artifact_destination_dir (Opti...
document_api
python
googleapis/google-api-python-client
describe.py
https://github.com/googleapis/google-api-python-client/blob/master/describe.py
Apache-2.0
def document_api_from_discovery_document( discovery_url, doc_destination_dir, artifact_destination_dir=DISCOVERY_DOC_DIR ): """Document the given API. Args: discovery_url (str): URI of discovery document. doc_destination_dir (str): relative path where the reference documentation shoul...
Document the given API. Args: discovery_url (str): URI of discovery document. doc_destination_dir (str): relative path where the reference documentation should be saved. artifact_destination_dir (str): relative path where the discovery artifacts should be saved.
document_api_from_discovery_document
python
googleapis/google-api-python-client
describe.py
https://github.com/googleapis/google-api-python-client/blob/master/describe.py
Apache-2.0
def generate_all_api_documents( directory_uri=DIRECTORY_URI, doc_destination_dir=BASE, artifact_destination_dir=DISCOVERY_DOC_DIR, discovery_uri_template=DISCOVERY_URI_TEMPLATE, ): """Retrieve discovery artifacts and fetch reference documentations for all apis listed in the public discovery dire...
Retrieve discovery artifacts and fetch reference documentations for all apis listed in the public discovery directory. args: directory_uri (Optional[str]): uri of the public discovery directory. doc_destination_dir (Optional[str]): relative path where the reference documentation shou...
generate_all_api_documents
python
googleapis/google-api-python-client
describe.py
https://github.com/googleapis/google-api-python-client/blob/master/describe.py
Apache-2.0
def get_lines(name, lines): """Return lines that begin with name. Lines are expected to look like: name: space separated values Args: name: string, parameter name. lines: iterable of string, lines in the file. Returns: List of values in the lines that match. """ retval = [] matc...
Return lines that begin with name. Lines are expected to look like: name: space separated values Args: name: string, parameter name. lines: iterable of string, lines in the file. Returns: List of values in the lines that match.
get_lines
python
googleapis/google-api-python-client
samples-index.py
https://github.com/googleapis/google-api-python-client/blob/master/samples-index.py
Apache-2.0
def wiki_escape(s): """Detect WikiSyntax (i.e. InterCaps, a.k.a. CamelCase) and escape it.""" ret = [] for word in s.split(): if re.match(r"[A-Z]+[a-z]+[A-Z]", word): word = "!%s" % word ret.append(word) return " ".join(ret)
Detect WikiSyntax (i.e. InterCaps, a.k.a. CamelCase) and escape it.
wiki_escape
python
googleapis/google-api-python-client
samples-index.py
https://github.com/googleapis/google-api-python-client/blob/master/samples-index.py
Apache-2.0
def context_from_sample(api, keywords, dirname, desc, uri): """Return info for expanding a sample into a template. Args: api: string, name of api. keywords: list of string, list of keywords for the given api. dirname: string, directory name of the sample. desc: string, long description of the sam...
Return info for expanding a sample into a template. Args: api: string, name of api. keywords: list of string, list of keywords for the given api. dirname: string, directory name of the sample. desc: string, long description of the sample. uri: string, uri of the sample code if provided in the REA...
context_from_sample
python
googleapis/google-api-python-client
samples-index.py
https://github.com/googleapis/google-api-python-client/blob/master/samples-index.py
Apache-2.0
def keyword_context_from_sample(keywords, dirname, desc, uri): """Return info for expanding a sample into a template. Sample may not be about a specific api. Args: keywords: list of string, list of keywords for the given api. dirname: string, directory name of the sample. desc: string, long descri...
Return info for expanding a sample into a template. Sample may not be about a specific api. Args: keywords: list of string, list of keywords for the given api. dirname: string, directory name of the sample. desc: string, long description of the sample. uri: string, uri of the sample code if provid...
keyword_context_from_sample
python
googleapis/google-api-python-client
samples-index.py
https://github.com/googleapis/google-api-python-client/blob/master/samples-index.py
Apache-2.0
def scan_readme_files(dirname): """Scans all subdirs of dirname for README files. Args: dirname: string, name of directory to walk. Returns: (samples, keyword_set): list of information about all samples, the union of all keywords found. """ samples = [] keyword_set = set() for roo...
Scans all subdirs of dirname for README files. Args: dirname: string, name of directory to walk. Returns: (samples, keyword_set): list of information about all samples, the union of all keywords found.
scan_readme_files
python
googleapis/google-api-python-client
samples-index.py
https://github.com/googleapis/google-api-python-client/blob/master/samples-index.py
Apache-2.0
def init( argv, name, version, doc, filename, scope=None, parents=[], discovery_filename=None ): """A common initialization routine for samples. Many of the sample applications do the same initialization, which has now been consolidated into this function. This function uses common idioms found in ...
A common initialization routine for samples. Many of the sample applications do the same initialization, which has now been consolidated into this function. This function uses common idioms found in almost all the samples, i.e. for an API with name 'apiname', the credentials are stored in a file named ...
init
python
googleapis/google-api-python-client
googleapiclient/sample_tools.py
https://github.com/googleapis/google-api-python-client/blob/master/googleapiclient/sample_tools.py
Apache-2.0
def get_api_query(service, table_id): """Returns a query object to retrieve data from the Core Reporting API. Args: service: The service object built by the Google API Python client library. table_id: str The table ID form which to retrieve data. """ return ( service.data() ...
Returns a query object to retrieve data from the Core Reporting API. Args: service: The service object built by the Google API Python client library. table_id: str The table ID form which to retrieve data.
get_api_query
python
googleapis/google-api-python-client
samples/analytics/core_reporting_v3_reference.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/analytics/core_reporting_v3_reference.py
Apache-2.0
def print_results(results): """Prints all the results in the Core Reporting API Response. Args: results: The response returned from the Core Reporting API. """ print_report_info(results) print_pagination_info(results) print_profile_info(results) print_query(results) print_column_...
Prints all the results in the Core Reporting API Response. Args: results: The response returned from the Core Reporting API.
print_results
python
googleapis/google-api-python-client
samples/analytics/core_reporting_v3_reference.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/analytics/core_reporting_v3_reference.py
Apache-2.0
def print_report_info(results): """Prints general information about this report. Args: results: The response returned from the Core Reporting API. """ print("Report Infos:") print("Contains Sampled Data = %s" % results.get("containsSampledData")) print("Kind = %s" % resu...
Prints general information about this report. Args: results: The response returned from the Core Reporting API.
print_report_info
python
googleapis/google-api-python-client
samples/analytics/core_reporting_v3_reference.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/analytics/core_reporting_v3_reference.py
Apache-2.0
def print_pagination_info(results): """Prints common pagination details. Args: results: The response returned from the Core Reporting API. """ print("Pagination Infos:") print("Items per page = %s" % results.get("itemsPerPage")) print("Total Results = %s" % results.get("totalResults")) ...
Prints common pagination details. Args: results: The response returned from the Core Reporting API.
print_pagination_info
python
googleapis/google-api-python-client
samples/analytics/core_reporting_v3_reference.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/analytics/core_reporting_v3_reference.py
Apache-2.0
def print_profile_info(results): """Prints information about the profile. Args: results: The response returned from the Core Reporting API. """ print("Profile Infos:") info = results.get("profileInfo") print("Account Id = %s" % info.get("accountId")) print("Web Property Id = %s"...
Prints information about the profile. Args: results: The response returned from the Core Reporting API.
print_profile_info
python
googleapis/google-api-python-client
samples/analytics/core_reporting_v3_reference.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/analytics/core_reporting_v3_reference.py
Apache-2.0
def print_query(results): """The query returns the original report query as a dict. Args: results: The response returned from the Core Reporting API. """ print("Query Parameters:") query = results.get("query") for key, value in query.iteritems(): print("%s = %s" % (key, value)) ...
The query returns the original report query as a dict. Args: results: The response returned from the Core Reporting API.
print_query
python
googleapis/google-api-python-client
samples/analytics/core_reporting_v3_reference.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/analytics/core_reporting_v3_reference.py
Apache-2.0
def print_column_headers(results): """Prints the information for each column. The main data from the API is returned as rows of data. The column headers describe the names and types of each column in rows. Args: results: The response returned from the Core Reporting API. """ print("Col...
Prints the information for each column. The main data from the API is returned as rows of data. The column headers describe the names and types of each column in rows. Args: results: The response returned from the Core Reporting API.
print_column_headers
python
googleapis/google-api-python-client
samples/analytics/core_reporting_v3_reference.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/analytics/core_reporting_v3_reference.py
Apache-2.0
def print_totals_for_all_results(results): """Prints the total metric value for all pages the query matched. Args: results: The response returned from the Core Reporting API. """ print("Total Metrics For All Results:") print("This query returned %s rows." % len(results.get("rows"))) prin...
Prints the total metric value for all pages the query matched. Args: results: The response returned from the Core Reporting API.
print_totals_for_all_results
python
googleapis/google-api-python-client
samples/analytics/core_reporting_v3_reference.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/analytics/core_reporting_v3_reference.py
Apache-2.0
def print_rows(results): """Prints all the rows of data returned by the API. Args: results: The response returned from the Core Reporting API. """ print("Rows:") if results.get("rows", []): for row in results.get("rows"): print("\t".join(row)) else: print("No ...
Prints all the rows of data returned by the API. Args: results: The response returned from the Core Reporting API.
print_rows
python
googleapis/google-api-python-client
samples/analytics/core_reporting_v3_reference.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/analytics/core_reporting_v3_reference.py
Apache-2.0
def get_first_profile_id(service): """Traverses Management API to return the first profile id. This first queries the Accounts collection to get the first account ID. This ID is used to query the Webproperties collection to retrieve the first webproperty ID. And both account and webproperty IDs are use...
Traverses Management API to return the first profile id. This first queries the Accounts collection to get the first account ID. This ID is used to query the Webproperties collection to retrieve the first webproperty ID. And both account and webproperty IDs are used to query the Profile collection to g...
get_first_profile_id
python
googleapis/google-api-python-client
samples/analytics/hello_analytics_api_v3.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/analytics/hello_analytics_api_v3.py
Apache-2.0
def get_top_keywords(service, profile_id): """Executes and returns data from the Core Reporting API. This queries the API for the top 25 organic search terms by visits. Args: service: The service object built by the Google API Python client library. profile_id: String The profile ID from which...
Executes and returns data from the Core Reporting API. This queries the API for the top 25 organic search terms by visits. Args: service: The service object built by the Google API Python client library. profile_id: String The profile ID from which to retrieve analytics data. Returns: T...
get_top_keywords
python
googleapis/google-api-python-client
samples/analytics/hello_analytics_api_v3.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/analytics/hello_analytics_api_v3.py
Apache-2.0
def print_results(results): """Prints out the results. This prints out the profile name, the column headers, and all the rows of data. Args: results: The response returned from the Core Reporting API. """ print() print("Profile Name: %s" % results.get("profileInfo").get("profileName...
Prints out the results. This prints out the profile name, the column headers, and all the rows of data. Args: results: The response returned from the Core Reporting API.
print_results
python
googleapis/google-api-python-client
samples/analytics/hello_analytics_api_v3.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/analytics/hello_analytics_api_v3.py
Apache-2.0
def traverse_hierarchy(service): """Traverses the management API hierarchy and prints results. This retrieves and prints the authorized user's accounts. It then retrieves and prints all the web properties for the first account, retrieves and prints all the profiles for the first web property, and r...
Traverses the management API hierarchy and prints results. This retrieves and prints the authorized user's accounts. It then retrieves and prints all the web properties for the first account, retrieves and prints all the profiles for the first web property, and retrieves and prints all the goals for th...
traverse_hierarchy
python
googleapis/google-api-python-client
samples/analytics/management_v3_reference.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/analytics/management_v3_reference.py
Apache-2.0
def print_accounts(accounts_response): """Prints all the account info in the Accounts Collection. Args: accounts_response: The response object returned from querying the Accounts collection. """ print("------ Account Collection -------") print_pagination_info(accounts_response) ...
Prints all the account info in the Accounts Collection. Args: accounts_response: The response object returned from querying the Accounts collection.
print_accounts
python
googleapis/google-api-python-client
samples/analytics/management_v3_reference.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/analytics/management_v3_reference.py
Apache-2.0
def print_webproperties(webproperties_response): """Prints all the web property info in the WebProperties collection. Args: webproperties_response: The response object returned from querying the Webproperties collection. """ print("------ Web Properties Collection -------") print_p...
Prints all the web property info in the WebProperties collection. Args: webproperties_response: The response object returned from querying the Webproperties collection.
print_webproperties
python
googleapis/google-api-python-client
samples/analytics/management_v3_reference.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/analytics/management_v3_reference.py
Apache-2.0
def print_profiles(profiles_response): """Prints all the profile info in the Profiles Collection. Args: profiles_response: The response object returned from querying the Profiles collection. """ print("------ Profiles Collection -------") print_pagination_info(profiles_response) ...
Prints all the profile info in the Profiles Collection. Args: profiles_response: The response object returned from querying the Profiles collection.
print_profiles
python
googleapis/google-api-python-client
samples/analytics/management_v3_reference.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/analytics/management_v3_reference.py
Apache-2.0
def print_goals(goals_response): """Prints all the goal info in the Goals collection. Args: goals_response: The response object returned from querying the Goals collection """ print("------ Goals Collection -------") print_pagination_info(goals_response) print() for goal i...
Prints all the goal info in the Goals collection. Args: goals_response: The response object returned from querying the Goals collection
print_goals
python
googleapis/google-api-python-client
samples/analytics/management_v3_reference.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/analytics/management_v3_reference.py
Apache-2.0
def print_url_destination_goal_details(goal_details): """Prints all the URL Destination goal type info. Args: goal_details: The details portion of the goal response. """ print("------ Url Destination Goal -------") print("Goal URL = %s" % goal_details.get("url")) print("Case S...
Prints all the URL Destination goal type info. Args: goal_details: The details portion of the goal response.
print_url_destination_goal_details
python
googleapis/google-api-python-client
samples/analytics/management_v3_reference.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/analytics/management_v3_reference.py
Apache-2.0
def print_visit_time_on_site_goal_details(goal_details): """Prints all the Visit Time On Site goal type info. Args: goal_details: The details portion of the goal response. """ print("------ Visit Time On Site Goal -------") print("Comparison Type = %s" % goal_details.get("comparisonType")) ...
Prints all the Visit Time On Site goal type info. Args: goal_details: The details portion of the goal response.
print_visit_time_on_site_goal_details
python
googleapis/google-api-python-client
samples/analytics/management_v3_reference.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/analytics/management_v3_reference.py
Apache-2.0
def print_visit_num_pages_goal_details(goal_details): """Prints all the Visit Num Pages goal type info. Args: goal_details: The details portion of the goal response. """ print("------ Visit Num Pages Goal -------") print("Comparison Type = %s" % goal_details.get("comparisonType")) print...
Prints all the Visit Num Pages goal type info. Args: goal_details: The details portion of the goal response.
print_visit_num_pages_goal_details
python
googleapis/google-api-python-client
samples/analytics/management_v3_reference.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/analytics/management_v3_reference.py
Apache-2.0
def print_event_goal_details(goal_details): """Prints all the Event goal type info. Args: goal_details: The details portion of the goal response. """ print("------ Event Goal -------") print("Use Event Value = %s" % goal_details.get("useEventValue")) for event_condition in goal_details...
Prints all the Event goal type info. Args: goal_details: The details portion of the goal response.
print_event_goal_details
python
googleapis/google-api-python-client
samples/analytics/management_v3_reference.py
https://github.com/googleapis/google-api-python-client/blob/master/samples/analytics/management_v3_reference.py
Apache-2.0