file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
city.rs
use iron::prelude::*; use hyper::status::StatusCode; use super::request_body; use ::proto::response::*; use ::proto::schema::NewCity; use ::db::schema::*; use ::db::*; pub fn get_cities(_: &mut Request) -> IronResult<Response> { let query = City::select_builder().build(); let conn = get_db_connection(); info!("request GET /city");
Ok(cities.as_response()) } pub fn put_city(req: &mut Request) -> IronResult<Response> { let new_city: NewCity = request_body(req)?; info!("request PUT /city {{ {:?} }}", new_city); let conn = get_db_connection(); let query = City::insert_query(); conn.execute(&query, &[&new_city.Name]).unwrap(); Ok(Response::with(StatusCode::Ok)) }
let rows = conn.query(&query, &[]).unwrap(); let cities = rows.into_iter() .map(City::from) .collect::<Vec<City>>();
random_line_split
city.rs
use iron::prelude::*; use hyper::status::StatusCode; use super::request_body; use ::proto::response::*; use ::proto::schema::NewCity; use ::db::schema::*; use ::db::*; pub fn get_cities(_: &mut Request) -> IronResult<Response>
pub fn put_city(req: &mut Request) -> IronResult<Response> { let new_city: NewCity = request_body(req)?; info!("request PUT /city {{ {:?} }}", new_city); let conn = get_db_connection(); let query = City::insert_query(); conn.execute(&query, &[&new_city.Name]).unwrap(); Ok(Response::with(StatusCode::Ok)) }
{ let query = City::select_builder().build(); let conn = get_db_connection(); info!("request GET /city"); let rows = conn.query(&query, &[]).unwrap(); let cities = rows.into_iter() .map(City::from) .collect::<Vec<City>>(); Ok(cities.as_response()) }
identifier_body
roles.py
""" Classes used to model the roles used in the courseware. Each role is responsible for checking membership, adding users, removing users, and listing members """ import logging from abc import ABCMeta, abstractmethod from collections import defaultdict from django.contrib.auth.models import User from opaque_keys.edx.django.models import CourseKeyField from openedx.core.lib.cache_utils import get_cache from student.models import CourseAccessRole log = logging.getLogger(__name__) # A list of registered access roles. REGISTERED_ACCESS_ROLES = {} def register_access_role(cls): """ Decorator that allows access roles to be registered within the roles module and referenced by their string values. Assumes that the decorated class has a "ROLE" attribute, defining its type. """ try: role_name = cls.ROLE REGISTERED_ACCESS_ROLES[role_name] = cls except AttributeError: log.exception(u"Unable to register Access Role with attribute 'ROLE'.") return cls class BulkRoleCache(object): CACHE_NAMESPACE = u"student.roles.BulkRoleCache" CACHE_KEY = u'roles_by_user' @classmethod def prefetch(cls, users): roles_by_user = defaultdict(set) get_cache(cls.CACHE_NAMESPACE)[cls.CACHE_KEY] = roles_by_user for role in CourseAccessRole.objects.filter(user__in=users).select_related('user'): roles_by_user[role.user.id].add(role) users_without_roles = filter(lambda u: u.id not in roles_by_user, users) for user in users_without_roles: roles_by_user[user.id] = set() @classmethod def get_user_roles(cls, user): return get_cache(cls.CACHE_NAMESPACE)[cls.CACHE_KEY][user.id] class RoleCache(object): """ A cache of the CourseAccessRoles held by a particular user """ def __init__(self, user): try: self._roles = BulkRoleCache.get_user_roles(user) except KeyError: self._roles = set( CourseAccessRole.objects.filter(user=user).all() ) def has_role(self, role, course_id, org): """ Return whether this RoleCache contains a role with the specified role, course_id, and org """ return any( access_role.role == role and access_role.course_id == course_id and access_role.org == org for access_role in self._roles ) class AccessRole(object): """ Object representing a role with particular access to a resource """ __metaclass__ = ABCMeta @abstractmethod def has_user(self, user): """ Return whether the supplied django user has access to this role. """ return False @abstractmethod def add_users(self, *users): """ Add the role to the supplied django users. """ pass @abstractmethod def remove_users(self, *users): """ Remove the role from the supplied django users. """ pass @abstractmethod def users_with_role(self): """ Return a django QuerySet for all of the users with this role """ return User.objects.none() class GlobalStaff(AccessRole): """ The global staff role """ def has_user(self, user): return user.is_staff def add_users(self, *users): for user in users: if user.is_authenticated and user.is_active: user.is_staff = True user.save() def remove_users(self, *users): for user in users: # don't check is_authenticated nor is_active on purpose user.is_staff = False user.save() def users_with_role(self):
class RoleBase(AccessRole): """ Roles by type (e.g., instructor, beta_user) and optionally org, course_key """ def __init__(self, role_name, org='', course_key=None): """ Create role from required role_name w/ optional org and course_key. You may just provide a role name if it's a global role (not constrained to an org or course). Provide org if constrained to an org. Provide org and course if constrained to a course. Although, you should use the subclasses for all of these. """ super(RoleBase, self).__init__() self.org = org self.course_key = course_key self._role_name = role_name # pylint: disable=arguments-differ def has_user(self, user, check_user_activation=True): """ Check if the supplied django user has access to this role. Arguments: user: user to check against access to role check_user_activation: Indicating whether or not we need to check user activation while checking user roles Return: bool identifying if user has that particular role or not """ if check_user_activation and not (user.is_authenticated and user.is_active): return False # pylint: disable=protected-access if not hasattr(user, '_roles'): # Cache a list of tuples identifying the particular roles that a user has # Stored as tuples, rather than django models, to make it cheaper to construct objects for comparison user._roles = RoleCache(user) return user._roles.has_role(self._role_name, self.course_key, self.org) def add_users(self, *users): """ Add the supplied django users to this role. """ # silently ignores anonymous and inactive users so that any that are # legit get updated. from student.models import CourseAccessRole for user in users: if user.is_authenticated and user.is_active and not self.has_user(user): entry = CourseAccessRole(user=user, role=self._role_name, course_id=self.course_key, org=self.org) entry.save() if hasattr(user, '_roles'): del user._roles def remove_users(self, *users): """ Remove the supplied django users from this role. """ entries = CourseAccessRole.objects.filter( user__in=users, role=self._role_name, org=self.org, course_id=self.course_key ) entries.delete() for user in users: if hasattr(user, '_roles'): del user._roles def users_with_role(self): """ Return a django QuerySet for all of the users with this role """ # Org roles don't query by CourseKey, so use CourseKeyField.Empty for that query if self.course_key is None: self.course_key = CourseKeyField.Empty entries = User.objects.filter( courseaccessrole__role=self._role_name, courseaccessrole__org=self.org, courseaccessrole__course_id=self.course_key ) return entries class CourseRole(RoleBase): """ A named role in a particular course """ def __init__(self, role, course_key): """ Args: course_key (CourseKey) """ super(CourseRole, self).__init__(role, course_key.org, course_key) @classmethod def course_group_already_exists(self, course_key): return CourseAccessRole.objects.filter(org=course_key.org, course_id=course_key).exists() def __repr__(self): return '<{}: course_key={}>'.format(self.__class__.__name__, self.course_key) class OrgRole(RoleBase): """ A named role in a particular org independent of course """ def __repr__(self): return '<{}>'.format(self.__class__.__name__) @register_access_role class CourseStaffRole(CourseRole): """A Staff member of a course""" ROLE = 'staff' def __init__(self, *args, **kwargs): super(CourseStaffRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class CourseInstructorRole(CourseRole): """A course Instructor""" ROLE = 'instructor' def __init__(self, *args, **kwargs): super(CourseInstructorRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class CourseFinanceAdminRole(CourseRole): """A course staff member with privileges to review financial data.""" ROLE = 'finance_admin' def __init__(self, *args, **kwargs): super(CourseFinanceAdminRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class CourseSalesAdminRole(CourseRole): """A course staff member with privileges to perform sales operations. """ ROLE = 'sales_admin' def __init__(self, *args, **kwargs): super(CourseSalesAdminRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class CourseBetaTesterRole(CourseRole): """A course Beta Tester""" ROLE = 'beta_testers' def __init__(self, *args, **kwargs): super(CourseBetaTesterRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class LibraryUserRole(CourseRole): """ A user who can view a library and import content from it, but not edit it. Used in Studio only. """ ROLE = 'library_user' def __init__(self, *args, **kwargs): super(LibraryUserRole, self).__init__(self.ROLE, *args, **kwargs) class CourseCcxCoachRole(CourseRole): """A CCX Coach""" ROLE = 'ccx_coach' def __init__(self, *args, **kwargs): super(CourseCcxCoachRole, self).__init__(self.ROLE, *args, **kwargs) class OrgStaffRole(OrgRole): """An organization staff member""" def __init__(self, *args, **kwargs): super(OrgStaffRole, self).__init__('staff', *args, **kwargs) class OrgInstructorRole(OrgRole): """An organization instructor""" def __init__(self, *args, **kwargs): super(OrgInstructorRole, self).__init__('instructor', *args, **kwargs) class OrgLibraryUserRole(OrgRole): """ A user who can view any libraries in an org and import content from them, but not edit them. Used in Studio only. """ ROLE = LibraryUserRole.ROLE def __init__(self, *args, **kwargs): super(OrgLibraryUserRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class CourseCreatorRole(RoleBase): """ This is the group of people who have permission to create new courses (we may want to eventually make this an org based role). """ ROLE = "course_creator_group" def __init__(self, *args, **kwargs): super(CourseCreatorRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class SupportStaffRole(RoleBase): """ Student support team members. """ ROLE = "support" def __init__(self, *args, **kwargs): super(SupportStaffRole, self).__init__(self.ROLE, *args, **kwargs) class UserBasedRole(object): """ Backward mapping: given a user, manipulate the courses and roles """ def __init__(self, user, role): """ Create a UserBasedRole accessor: for a given user and role (e.g., "instructor") """ self.user = user self.role = role def has_course(self, course_key): """ Return whether the role's user has the configured role access to the passed course """ if not (self.user.is_authenticated and self.user.is_active): return False # pylint: disable=protected-access if not hasattr(self.user, '_roles'): self.user._roles = RoleCache(self.user) return self.user._roles.has_role(self.role, course_key, course_key.org) def add_course(self, *course_keys): """ Grant this object's user the object's role for the supplied courses """ if self.user.is_authenticated and self.user.is_active: for course_key in course_keys: entry = CourseAccessRole(user=self.user, role=self.role, course_id=course_key, org=course_key.org) entry.save() if hasattr(self.user, '_roles'): del self.user._roles else: raise ValueError("user is not active. Cannot grant access to courses") def remove_courses(self, *course_keys): """ Remove the supplied courses from this user's configured role. """ entries = CourseAccessRole.objects.filter(user=self.user, role=self.role, course_id__in=course_keys) entries.delete() if hasattr(self.user, '_roles'): del self.user._roles def courses_with_role(self): """ Return a django QuerySet for all of the courses with this user x role. You can access any of these properties on each result record: * user (will be self.user--thus uninteresting) * org * course_id * role (will be self.role--thus uninteresting) """ return CourseAccessRole.objects.filter(role=self.role, user=self.user)
raise Exception("This operation is un-indexed, and shouldn't be used")
identifier_body
roles.py
""" Classes used to model the roles used in the courseware. Each role is responsible for checking membership, adding users, removing users, and listing members """ import logging from abc import ABCMeta, abstractmethod from collections import defaultdict from django.contrib.auth.models import User from opaque_keys.edx.django.models import CourseKeyField from openedx.core.lib.cache_utils import get_cache from student.models import CourseAccessRole log = logging.getLogger(__name__) # A list of registered access roles. REGISTERED_ACCESS_ROLES = {} def register_access_role(cls): """ Decorator that allows access roles to be registered within the roles module and referenced by their string values. Assumes that the decorated class has a "ROLE" attribute, defining its type. """ try: role_name = cls.ROLE REGISTERED_ACCESS_ROLES[role_name] = cls except AttributeError: log.exception(u"Unable to register Access Role with attribute 'ROLE'.") return cls class BulkRoleCache(object): CACHE_NAMESPACE = u"student.roles.BulkRoleCache" CACHE_KEY = u'roles_by_user' @classmethod def prefetch(cls, users): roles_by_user = defaultdict(set) get_cache(cls.CACHE_NAMESPACE)[cls.CACHE_KEY] = roles_by_user for role in CourseAccessRole.objects.filter(user__in=users).select_related('user'): roles_by_user[role.user.id].add(role) users_without_roles = filter(lambda u: u.id not in roles_by_user, users) for user in users_without_roles: roles_by_user[user.id] = set() @classmethod def get_user_roles(cls, user): return get_cache(cls.CACHE_NAMESPACE)[cls.CACHE_KEY][user.id] class RoleCache(object): """ A cache of the CourseAccessRoles held by a particular user """ def __init__(self, user): try: self._roles = BulkRoleCache.get_user_roles(user) except KeyError: self._roles = set( CourseAccessRole.objects.filter(user=user).all() ) def has_role(self, role, course_id, org): """ Return whether this RoleCache contains a role with the specified role, course_id, and org """ return any( access_role.role == role and access_role.course_id == course_id and access_role.org == org for access_role in self._roles ) class AccessRole(object): """ Object representing a role with particular access to a resource """ __metaclass__ = ABCMeta @abstractmethod def has_user(self, user): """ Return whether the supplied django user has access to this role. """ return False @abstractmethod def add_users(self, *users): """ Add the role to the supplied django users. """ pass @abstractmethod def remove_users(self, *users): """ Remove the role from the supplied django users. """ pass @abstractmethod def users_with_role(self): """ Return a django QuerySet for all of the users with this role """ return User.objects.none() class GlobalStaff(AccessRole): """ The global staff role """ def has_user(self, user): return user.is_staff def add_users(self, *users): for user in users: if user.is_authenticated and user.is_active: user.is_staff = True user.save() def remove_users(self, *users): for user in users: # don't check is_authenticated nor is_active on purpose user.is_staff = False user.save() def users_with_role(self): raise Exception("This operation is un-indexed, and shouldn't be used") class RoleBase(AccessRole): """ Roles by type (e.g., instructor, beta_user) and optionally org, course_key """ def __init__(self, role_name, org='', course_key=None): """ Create role from required role_name w/ optional org and course_key. You may just provide a role name if it's a global role (not constrained to an org or course). Provide org if constrained to an org. Provide org and course if constrained to a course. Although, you should use the subclasses for all of these. """ super(RoleBase, self).__init__() self.org = org self.course_key = course_key self._role_name = role_name # pylint: disable=arguments-differ def has_user(self, user, check_user_activation=True): """ Check if the supplied django user has access to this role. Arguments: user: user to check against access to role check_user_activation: Indicating whether or not we need to check user activation while checking user roles Return: bool identifying if user has that particular role or not """ if check_user_activation and not (user.is_authenticated and user.is_active): return False # pylint: disable=protected-access if not hasattr(user, '_roles'): # Cache a list of tuples identifying the particular roles that a user has # Stored as tuples, rather than django models, to make it cheaper to construct objects for comparison user._roles = RoleCache(user) return user._roles.has_role(self._role_name, self.course_key, self.org) def add_users(self, *users): """ Add the supplied django users to this role. """ # silently ignores anonymous and inactive users so that any that are # legit get updated. from student.models import CourseAccessRole for user in users: if user.is_authenticated and user.is_active and not self.has_user(user): entry = CourseAccessRole(user=user, role=self._role_name, course_id=self.course_key, org=self.org) entry.save() if hasattr(user, '_roles'): del user._roles def remove_users(self, *users): """ Remove the supplied django users from this role. """ entries = CourseAccessRole.objects.filter( user__in=users, role=self._role_name, org=self.org, course_id=self.course_key ) entries.delete() for user in users: if hasattr(user, '_roles'): del user._roles def users_with_role(self): """ Return a django QuerySet for all of the users with this role """ # Org roles don't query by CourseKey, so use CourseKeyField.Empty for that query if self.course_key is None: self.course_key = CourseKeyField.Empty entries = User.objects.filter( courseaccessrole__role=self._role_name, courseaccessrole__org=self.org, courseaccessrole__course_id=self.course_key ) return entries class CourseRole(RoleBase): """ A named role in a particular course """ def __init__(self, role, course_key): """ Args: course_key (CourseKey) """ super(CourseRole, self).__init__(role, course_key.org, course_key) @classmethod def course_group_already_exists(self, course_key): return CourseAccessRole.objects.filter(org=course_key.org, course_id=course_key).exists() def __repr__(self): return '<{}: course_key={}>'.format(self.__class__.__name__, self.course_key) class OrgRole(RoleBase): """ A named role in a particular org independent of course """ def __repr__(self): return '<{}>'.format(self.__class__.__name__) @register_access_role class CourseStaffRole(CourseRole): """A Staff member of a course""" ROLE = 'staff' def __init__(self, *args, **kwargs): super(CourseStaffRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class CourseInstructorRole(CourseRole): """A course Instructor""" ROLE = 'instructor' def __init__(self, *args, **kwargs): super(CourseInstructorRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class CourseFinanceAdminRole(CourseRole): """A course staff member with privileges to review financial data.""" ROLE = 'finance_admin' def __init__(self, *args, **kwargs): super(CourseFinanceAdminRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class CourseSalesAdminRole(CourseRole): """A course staff member with privileges to perform sales operations. """ ROLE = 'sales_admin' def __init__(self, *args, **kwargs): super(CourseSalesAdminRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class CourseBetaTesterRole(CourseRole): """A course Beta Tester""" ROLE = 'beta_testers' def __init__(self, *args, **kwargs): super(CourseBetaTesterRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class LibraryUserRole(CourseRole): """ A user who can view a library and import content from it, but not edit it. Used in Studio only. """ ROLE = 'library_user' def __init__(self, *args, **kwargs): super(LibraryUserRole, self).__init__(self.ROLE, *args, **kwargs) class CourseCcxCoachRole(CourseRole): """A CCX Coach""" ROLE = 'ccx_coach' def __init__(self, *args, **kwargs): super(CourseCcxCoachRole, self).__init__(self.ROLE, *args, **kwargs)
class OrgInstructorRole(OrgRole): """An organization instructor""" def __init__(self, *args, **kwargs): super(OrgInstructorRole, self).__init__('instructor', *args, **kwargs) class OrgLibraryUserRole(OrgRole): """ A user who can view any libraries in an org and import content from them, but not edit them. Used in Studio only. """ ROLE = LibraryUserRole.ROLE def __init__(self, *args, **kwargs): super(OrgLibraryUserRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class CourseCreatorRole(RoleBase): """ This is the group of people who have permission to create new courses (we may want to eventually make this an org based role). """ ROLE = "course_creator_group" def __init__(self, *args, **kwargs): super(CourseCreatorRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class SupportStaffRole(RoleBase): """ Student support team members. """ ROLE = "support" def __init__(self, *args, **kwargs): super(SupportStaffRole, self).__init__(self.ROLE, *args, **kwargs) class UserBasedRole(object): """ Backward mapping: given a user, manipulate the courses and roles """ def __init__(self, user, role): """ Create a UserBasedRole accessor: for a given user and role (e.g., "instructor") """ self.user = user self.role = role def has_course(self, course_key): """ Return whether the role's user has the configured role access to the passed course """ if not (self.user.is_authenticated and self.user.is_active): return False # pylint: disable=protected-access if not hasattr(self.user, '_roles'): self.user._roles = RoleCache(self.user) return self.user._roles.has_role(self.role, course_key, course_key.org) def add_course(self, *course_keys): """ Grant this object's user the object's role for the supplied courses """ if self.user.is_authenticated and self.user.is_active: for course_key in course_keys: entry = CourseAccessRole(user=self.user, role=self.role, course_id=course_key, org=course_key.org) entry.save() if hasattr(self.user, '_roles'): del self.user._roles else: raise ValueError("user is not active. Cannot grant access to courses") def remove_courses(self, *course_keys): """ Remove the supplied courses from this user's configured role. """ entries = CourseAccessRole.objects.filter(user=self.user, role=self.role, course_id__in=course_keys) entries.delete() if hasattr(self.user, '_roles'): del self.user._roles def courses_with_role(self): """ Return a django QuerySet for all of the courses with this user x role. You can access any of these properties on each result record: * user (will be self.user--thus uninteresting) * org * course_id * role (will be self.role--thus uninteresting) """ return CourseAccessRole.objects.filter(role=self.role, user=self.user)
class OrgStaffRole(OrgRole): """An organization staff member""" def __init__(self, *args, **kwargs): super(OrgStaffRole, self).__init__('staff', *args, **kwargs)
random_line_split
roles.py
""" Classes used to model the roles used in the courseware. Each role is responsible for checking membership, adding users, removing users, and listing members """ import logging from abc import ABCMeta, abstractmethod from collections import defaultdict from django.contrib.auth.models import User from opaque_keys.edx.django.models import CourseKeyField from openedx.core.lib.cache_utils import get_cache from student.models import CourseAccessRole log = logging.getLogger(__name__) # A list of registered access roles. REGISTERED_ACCESS_ROLES = {} def register_access_role(cls): """ Decorator that allows access roles to be registered within the roles module and referenced by their string values. Assumes that the decorated class has a "ROLE" attribute, defining its type. """ try: role_name = cls.ROLE REGISTERED_ACCESS_ROLES[role_name] = cls except AttributeError: log.exception(u"Unable to register Access Role with attribute 'ROLE'.") return cls class BulkRoleCache(object): CACHE_NAMESPACE = u"student.roles.BulkRoleCache" CACHE_KEY = u'roles_by_user' @classmethod def prefetch(cls, users): roles_by_user = defaultdict(set) get_cache(cls.CACHE_NAMESPACE)[cls.CACHE_KEY] = roles_by_user for role in CourseAccessRole.objects.filter(user__in=users).select_related('user'): roles_by_user[role.user.id].add(role) users_without_roles = filter(lambda u: u.id not in roles_by_user, users) for user in users_without_roles: roles_by_user[user.id] = set() @classmethod def get_user_roles(cls, user): return get_cache(cls.CACHE_NAMESPACE)[cls.CACHE_KEY][user.id] class RoleCache(object): """ A cache of the CourseAccessRoles held by a particular user """ def __init__(self, user): try: self._roles = BulkRoleCache.get_user_roles(user) except KeyError: self._roles = set( CourseAccessRole.objects.filter(user=user).all() ) def has_role(self, role, course_id, org): """ Return whether this RoleCache contains a role with the specified role, course_id, and org """ return any( access_role.role == role and access_role.course_id == course_id and access_role.org == org for access_role in self._roles ) class AccessRole(object): """ Object representing a role with particular access to a resource """ __metaclass__ = ABCMeta @abstractmethod def has_user(self, user): """ Return whether the supplied django user has access to this role. """ return False @abstractmethod def add_users(self, *users): """ Add the role to the supplied django users. """ pass @abstractmethod def remove_users(self, *users): """ Remove the role from the supplied django users. """ pass @abstractmethod def users_with_role(self): """ Return a django QuerySet for all of the users with this role """ return User.objects.none() class GlobalStaff(AccessRole): """ The global staff role """ def has_user(self, user): return user.is_staff def add_users(self, *users): for user in users: if user.is_authenticated and user.is_active: user.is_staff = True user.save() def remove_users(self, *users): for user in users: # don't check is_authenticated nor is_active on purpose user.is_staff = False user.save() def users_with_role(self): raise Exception("This operation is un-indexed, and shouldn't be used") class RoleBase(AccessRole): """ Roles by type (e.g., instructor, beta_user) and optionally org, course_key """ def __init__(self, role_name, org='', course_key=None): """ Create role from required role_name w/ optional org and course_key. You may just provide a role name if it's a global role (not constrained to an org or course). Provide org if constrained to an org. Provide org and course if constrained to a course. Although, you should use the subclasses for all of these. """ super(RoleBase, self).__init__() self.org = org self.course_key = course_key self._role_name = role_name # pylint: disable=arguments-differ def has_user(self, user, check_user_activation=True): """ Check if the supplied django user has access to this role. Arguments: user: user to check against access to role check_user_activation: Indicating whether or not we need to check user activation while checking user roles Return: bool identifying if user has that particular role or not """ if check_user_activation and not (user.is_authenticated and user.is_active): return False # pylint: disable=protected-access if not hasattr(user, '_roles'): # Cache a list of tuples identifying the particular roles that a user has # Stored as tuples, rather than django models, to make it cheaper to construct objects for comparison user._roles = RoleCache(user) return user._roles.has_role(self._role_name, self.course_key, self.org) def add_users(self, *users): """ Add the supplied django users to this role. """ # silently ignores anonymous and inactive users so that any that are # legit get updated. from student.models import CourseAccessRole for user in users: if user.is_authenticated and user.is_active and not self.has_user(user): entry = CourseAccessRole(user=user, role=self._role_name, course_id=self.course_key, org=self.org) entry.save() if hasattr(user, '_roles'): del user._roles def remove_users(self, *users): """ Remove the supplied django users from this role. """ entries = CourseAccessRole.objects.filter( user__in=users, role=self._role_name, org=self.org, course_id=self.course_key ) entries.delete() for user in users:
def users_with_role(self): """ Return a django QuerySet for all of the users with this role """ # Org roles don't query by CourseKey, so use CourseKeyField.Empty for that query if self.course_key is None: self.course_key = CourseKeyField.Empty entries = User.objects.filter( courseaccessrole__role=self._role_name, courseaccessrole__org=self.org, courseaccessrole__course_id=self.course_key ) return entries class CourseRole(RoleBase): """ A named role in a particular course """ def __init__(self, role, course_key): """ Args: course_key (CourseKey) """ super(CourseRole, self).__init__(role, course_key.org, course_key) @classmethod def course_group_already_exists(self, course_key): return CourseAccessRole.objects.filter(org=course_key.org, course_id=course_key).exists() def __repr__(self): return '<{}: course_key={}>'.format(self.__class__.__name__, self.course_key) class OrgRole(RoleBase): """ A named role in a particular org independent of course """ def __repr__(self): return '<{}>'.format(self.__class__.__name__) @register_access_role class CourseStaffRole(CourseRole): """A Staff member of a course""" ROLE = 'staff' def __init__(self, *args, **kwargs): super(CourseStaffRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class CourseInstructorRole(CourseRole): """A course Instructor""" ROLE = 'instructor' def __init__(self, *args, **kwargs): super(CourseInstructorRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class CourseFinanceAdminRole(CourseRole): """A course staff member with privileges to review financial data.""" ROLE = 'finance_admin' def __init__(self, *args, **kwargs): super(CourseFinanceAdminRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class CourseSalesAdminRole(CourseRole): """A course staff member with privileges to perform sales operations. """ ROLE = 'sales_admin' def __init__(self, *args, **kwargs): super(CourseSalesAdminRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class CourseBetaTesterRole(CourseRole): """A course Beta Tester""" ROLE = 'beta_testers' def __init__(self, *args, **kwargs): super(CourseBetaTesterRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class LibraryUserRole(CourseRole): """ A user who can view a library and import content from it, but not edit it. Used in Studio only. """ ROLE = 'library_user' def __init__(self, *args, **kwargs): super(LibraryUserRole, self).__init__(self.ROLE, *args, **kwargs) class CourseCcxCoachRole(CourseRole): """A CCX Coach""" ROLE = 'ccx_coach' def __init__(self, *args, **kwargs): super(CourseCcxCoachRole, self).__init__(self.ROLE, *args, **kwargs) class OrgStaffRole(OrgRole): """An organization staff member""" def __init__(self, *args, **kwargs): super(OrgStaffRole, self).__init__('staff', *args, **kwargs) class OrgInstructorRole(OrgRole): """An organization instructor""" def __init__(self, *args, **kwargs): super(OrgInstructorRole, self).__init__('instructor', *args, **kwargs) class OrgLibraryUserRole(OrgRole): """ A user who can view any libraries in an org and import content from them, but not edit them. Used in Studio only. """ ROLE = LibraryUserRole.ROLE def __init__(self, *args, **kwargs): super(OrgLibraryUserRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class CourseCreatorRole(RoleBase): """ This is the group of people who have permission to create new courses (we may want to eventually make this an org based role). """ ROLE = "course_creator_group" def __init__(self, *args, **kwargs): super(CourseCreatorRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class SupportStaffRole(RoleBase): """ Student support team members. """ ROLE = "support" def __init__(self, *args, **kwargs): super(SupportStaffRole, self).__init__(self.ROLE, *args, **kwargs) class UserBasedRole(object): """ Backward mapping: given a user, manipulate the courses and roles """ def __init__(self, user, role): """ Create a UserBasedRole accessor: for a given user and role (e.g., "instructor") """ self.user = user self.role = role def has_course(self, course_key): """ Return whether the role's user has the configured role access to the passed course """ if not (self.user.is_authenticated and self.user.is_active): return False # pylint: disable=protected-access if not hasattr(self.user, '_roles'): self.user._roles = RoleCache(self.user) return self.user._roles.has_role(self.role, course_key, course_key.org) def add_course(self, *course_keys): """ Grant this object's user the object's role for the supplied courses """ if self.user.is_authenticated and self.user.is_active: for course_key in course_keys: entry = CourseAccessRole(user=self.user, role=self.role, course_id=course_key, org=course_key.org) entry.save() if hasattr(self.user, '_roles'): del self.user._roles else: raise ValueError("user is not active. Cannot grant access to courses") def remove_courses(self, *course_keys): """ Remove the supplied courses from this user's configured role. """ entries = CourseAccessRole.objects.filter(user=self.user, role=self.role, course_id__in=course_keys) entries.delete() if hasattr(self.user, '_roles'): del self.user._roles def courses_with_role(self): """ Return a django QuerySet for all of the courses with this user x role. You can access any of these properties on each result record: * user (will be self.user--thus uninteresting) * org * course_id * role (will be self.role--thus uninteresting) """ return CourseAccessRole.objects.filter(role=self.role, user=self.user)
if hasattr(user, '_roles'): del user._roles
conditional_block
roles.py
""" Classes used to model the roles used in the courseware. Each role is responsible for checking membership, adding users, removing users, and listing members """ import logging from abc import ABCMeta, abstractmethod from collections import defaultdict from django.contrib.auth.models import User from opaque_keys.edx.django.models import CourseKeyField from openedx.core.lib.cache_utils import get_cache from student.models import CourseAccessRole log = logging.getLogger(__name__) # A list of registered access roles. REGISTERED_ACCESS_ROLES = {} def register_access_role(cls): """ Decorator that allows access roles to be registered within the roles module and referenced by their string values. Assumes that the decorated class has a "ROLE" attribute, defining its type. """ try: role_name = cls.ROLE REGISTERED_ACCESS_ROLES[role_name] = cls except AttributeError: log.exception(u"Unable to register Access Role with attribute 'ROLE'.") return cls class BulkRoleCache(object): CACHE_NAMESPACE = u"student.roles.BulkRoleCache" CACHE_KEY = u'roles_by_user' @classmethod def prefetch(cls, users): roles_by_user = defaultdict(set) get_cache(cls.CACHE_NAMESPACE)[cls.CACHE_KEY] = roles_by_user for role in CourseAccessRole.objects.filter(user__in=users).select_related('user'): roles_by_user[role.user.id].add(role) users_without_roles = filter(lambda u: u.id not in roles_by_user, users) for user in users_without_roles: roles_by_user[user.id] = set() @classmethod def get_user_roles(cls, user): return get_cache(cls.CACHE_NAMESPACE)[cls.CACHE_KEY][user.id] class RoleCache(object): """ A cache of the CourseAccessRoles held by a particular user """ def __init__(self, user): try: self._roles = BulkRoleCache.get_user_roles(user) except KeyError: self._roles = set( CourseAccessRole.objects.filter(user=user).all() ) def has_role(self, role, course_id, org): """ Return whether this RoleCache contains a role with the specified role, course_id, and org """ return any( access_role.role == role and access_role.course_id == course_id and access_role.org == org for access_role in self._roles ) class AccessRole(object): """ Object representing a role with particular access to a resource """ __metaclass__ = ABCMeta @abstractmethod def has_user(self, user): """ Return whether the supplied django user has access to this role. """ return False @abstractmethod def add_users(self, *users): """ Add the role to the supplied django users. """ pass @abstractmethod def remove_users(self, *users): """ Remove the role from the supplied django users. """ pass @abstractmethod def users_with_role(self): """ Return a django QuerySet for all of the users with this role """ return User.objects.none() class GlobalStaff(AccessRole): """ The global staff role """ def has_user(self, user): return user.is_staff def add_users(self, *users): for user in users: if user.is_authenticated and user.is_active: user.is_staff = True user.save() def remove_users(self, *users): for user in users: # don't check is_authenticated nor is_active on purpose user.is_staff = False user.save() def users_with_role(self): raise Exception("This operation is un-indexed, and shouldn't be used") class RoleBase(AccessRole): """ Roles by type (e.g., instructor, beta_user) and optionally org, course_key """ def __init__(self, role_name, org='', course_key=None): """ Create role from required role_name w/ optional org and course_key. You may just provide a role name if it's a global role (not constrained to an org or course). Provide org if constrained to an org. Provide org and course if constrained to a course. Although, you should use the subclasses for all of these. """ super(RoleBase, self).__init__() self.org = org self.course_key = course_key self._role_name = role_name # pylint: disable=arguments-differ def has_user(self, user, check_user_activation=True): """ Check if the supplied django user has access to this role. Arguments: user: user to check against access to role check_user_activation: Indicating whether or not we need to check user activation while checking user roles Return: bool identifying if user has that particular role or not """ if check_user_activation and not (user.is_authenticated and user.is_active): return False # pylint: disable=protected-access if not hasattr(user, '_roles'): # Cache a list of tuples identifying the particular roles that a user has # Stored as tuples, rather than django models, to make it cheaper to construct objects for comparison user._roles = RoleCache(user) return user._roles.has_role(self._role_name, self.course_key, self.org) def add_users(self, *users): """ Add the supplied django users to this role. """ # silently ignores anonymous and inactive users so that any that are # legit get updated. from student.models import CourseAccessRole for user in users: if user.is_authenticated and user.is_active and not self.has_user(user): entry = CourseAccessRole(user=user, role=self._role_name, course_id=self.course_key, org=self.org) entry.save() if hasattr(user, '_roles'): del user._roles def remove_users(self, *users): """ Remove the supplied django users from this role. """ entries = CourseAccessRole.objects.filter( user__in=users, role=self._role_name, org=self.org, course_id=self.course_key ) entries.delete() for user in users: if hasattr(user, '_roles'): del user._roles def users_with_role(self): """ Return a django QuerySet for all of the users with this role """ # Org roles don't query by CourseKey, so use CourseKeyField.Empty for that query if self.course_key is None: self.course_key = CourseKeyField.Empty entries = User.objects.filter( courseaccessrole__role=self._role_name, courseaccessrole__org=self.org, courseaccessrole__course_id=self.course_key ) return entries class CourseRole(RoleBase): """ A named role in a particular course """ def __init__(self, role, course_key): """ Args: course_key (CourseKey) """ super(CourseRole, self).__init__(role, course_key.org, course_key) @classmethod def course_group_already_exists(self, course_key): return CourseAccessRole.objects.filter(org=course_key.org, course_id=course_key).exists() def __repr__(self): return '<{}: course_key={}>'.format(self.__class__.__name__, self.course_key) class OrgRole(RoleBase): """ A named role in a particular org independent of course """ def __repr__(self): return '<{}>'.format(self.__class__.__name__) @register_access_role class CourseStaffRole(CourseRole): """A Staff member of a course""" ROLE = 'staff' def __init__(self, *args, **kwargs): super(CourseStaffRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class CourseInstructorRole(CourseRole): """A course Instructor""" ROLE = 'instructor' def __init__(self, *args, **kwargs): super(CourseInstructorRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class CourseFinanceAdminRole(CourseRole): """A course staff member with privileges to review financial data.""" ROLE = 'finance_admin' def __init__(self, *args, **kwargs): super(CourseFinanceAdminRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class
(CourseRole): """A course staff member with privileges to perform sales operations. """ ROLE = 'sales_admin' def __init__(self, *args, **kwargs): super(CourseSalesAdminRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class CourseBetaTesterRole(CourseRole): """A course Beta Tester""" ROLE = 'beta_testers' def __init__(self, *args, **kwargs): super(CourseBetaTesterRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class LibraryUserRole(CourseRole): """ A user who can view a library and import content from it, but not edit it. Used in Studio only. """ ROLE = 'library_user' def __init__(self, *args, **kwargs): super(LibraryUserRole, self).__init__(self.ROLE, *args, **kwargs) class CourseCcxCoachRole(CourseRole): """A CCX Coach""" ROLE = 'ccx_coach' def __init__(self, *args, **kwargs): super(CourseCcxCoachRole, self).__init__(self.ROLE, *args, **kwargs) class OrgStaffRole(OrgRole): """An organization staff member""" def __init__(self, *args, **kwargs): super(OrgStaffRole, self).__init__('staff', *args, **kwargs) class OrgInstructorRole(OrgRole): """An organization instructor""" def __init__(self, *args, **kwargs): super(OrgInstructorRole, self).__init__('instructor', *args, **kwargs) class OrgLibraryUserRole(OrgRole): """ A user who can view any libraries in an org and import content from them, but not edit them. Used in Studio only. """ ROLE = LibraryUserRole.ROLE def __init__(self, *args, **kwargs): super(OrgLibraryUserRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class CourseCreatorRole(RoleBase): """ This is the group of people who have permission to create new courses (we may want to eventually make this an org based role). """ ROLE = "course_creator_group" def __init__(self, *args, **kwargs): super(CourseCreatorRole, self).__init__(self.ROLE, *args, **kwargs) @register_access_role class SupportStaffRole(RoleBase): """ Student support team members. """ ROLE = "support" def __init__(self, *args, **kwargs): super(SupportStaffRole, self).__init__(self.ROLE, *args, **kwargs) class UserBasedRole(object): """ Backward mapping: given a user, manipulate the courses and roles """ def __init__(self, user, role): """ Create a UserBasedRole accessor: for a given user and role (e.g., "instructor") """ self.user = user self.role = role def has_course(self, course_key): """ Return whether the role's user has the configured role access to the passed course """ if not (self.user.is_authenticated and self.user.is_active): return False # pylint: disable=protected-access if not hasattr(self.user, '_roles'): self.user._roles = RoleCache(self.user) return self.user._roles.has_role(self.role, course_key, course_key.org) def add_course(self, *course_keys): """ Grant this object's user the object's role for the supplied courses """ if self.user.is_authenticated and self.user.is_active: for course_key in course_keys: entry = CourseAccessRole(user=self.user, role=self.role, course_id=course_key, org=course_key.org) entry.save() if hasattr(self.user, '_roles'): del self.user._roles else: raise ValueError("user is not active. Cannot grant access to courses") def remove_courses(self, *course_keys): """ Remove the supplied courses from this user's configured role. """ entries = CourseAccessRole.objects.filter(user=self.user, role=self.role, course_id__in=course_keys) entries.delete() if hasattr(self.user, '_roles'): del self.user._roles def courses_with_role(self): """ Return a django QuerySet for all of the courses with this user x role. You can access any of these properties on each result record: * user (will be self.user--thus uninteresting) * org * course_id * role (will be self.role--thus uninteresting) """ return CourseAccessRole.objects.filter(role=self.role, user=self.user)
CourseSalesAdminRole
identifier_name
dj.js
$(document).ready(function () { }); var play = function () { mopidy.playback.play({ "tl_track": null }).then(function (data) { }); } var pause = function () { mopidy.playback.pause({}).then(function (data) { }); } var resume = function () { mopidy.playback.resume({}).then(function (data) { }); } var stop = function () { mopidy.playback.stop({}).then(function (data) { }); } var skip = function () { mopidy.playback.next({}).then(function (data) { }); } function Ch
ewVol) { window.mopidy.playback.getVolume().then(function (vol) { var currentVolume = vol; console.log('curent vol: ' + currentVolume); currentVolume = currentVolume + newVol; mopidy.mixer.setVolume({ "volume": currentVolume }).then(function (data) { console.log(data); }); }); }; var shuffleTracklist = function () { window.mopidy.tracklist.getTracks() // => tracklist .then(function (tracklist) { mopidy.playback.getCurrentTlTrack({}).then(function (currentTlTrack) { mopidy.tracklist.index({ "tl_track": currentTlTrack }).then(function (currentTlTrackIndex) { //shuffle tracklist starting from 4 after the current track so: // currentTlTrackIndex = current track (dont shuffle) // currentTlTrackIndex +1 = next track (dont shuffle) // currentTlTrackIndex +2 = 2nd next track (dont shuffle) // currentTlTrackIndex +3 = 3rd next track (can be shuffled) if ((tracklist.length - currentTlTrackIndex) > 4) { mopidy.tracklist.shuffle({ "start": (currentTlTrackIndex + 4), "end": tracklist.length }).then(function (data) { }); } }); }); }); } var PrintTracklist = function () { window.mopidy.tracklist.getTracks() .then(function (tracklist) { $("#tblTracklist").find("tr:gt(0)").remove(); for (var i = 0; i < tracklist.length; ++i) { if (tracklist[i].artists != null) { $('#tblTracklist tr:last').after('<tr><td>' + tracklist[i].name + '</td><td>' + tracklist[i].artists[0].name + '</td><td><input type="button" value="X" style="font-size:10px" onclick=RemoveTrackFromTracklist(' + i + ') /></td></tr>'); } else { $('#tblTracklist tr:last').after('<tr><td>' + tracklist[i].name + '</td><td>&nbsp</td><td><input type="button" value="X" style="font-size:10px" onclick=RemoveTrackFromTracklist(' + i + ') /></td></tr>'); } } }); }
angeVolume(n
identifier_name
dj.js
$(document).ready(function () { }); var play = function () { mopidy.playback.play({ "tl_track": null }).then(function (data) { }); } var pause = function () { mopidy.playback.pause({}).then(function (data) { }); } var resume = function () { mopidy.playback.resume({}).then(function (data) { }); } var stop = function () { mopidy.playback.stop({}).then(function (data) { }); } var skip = function () { mopidy.playback.next({}).then(function (data) { }); } function ChangeVolume(newVol) {
var shuffleTracklist = function () { window.mopidy.tracklist.getTracks() // => tracklist .then(function (tracklist) { mopidy.playback.getCurrentTlTrack({}).then(function (currentTlTrack) { mopidy.tracklist.index({ "tl_track": currentTlTrack }).then(function (currentTlTrackIndex) { //shuffle tracklist starting from 4 after the current track so: // currentTlTrackIndex = current track (dont shuffle) // currentTlTrackIndex +1 = next track (dont shuffle) // currentTlTrackIndex +2 = 2nd next track (dont shuffle) // currentTlTrackIndex +3 = 3rd next track (can be shuffled) if ((tracklist.length - currentTlTrackIndex) > 4) { mopidy.tracklist.shuffle({ "start": (currentTlTrackIndex + 4), "end": tracklist.length }).then(function (data) { }); } }); }); }); } var PrintTracklist = function () { window.mopidy.tracklist.getTracks() .then(function (tracklist) { $("#tblTracklist").find("tr:gt(0)").remove(); for (var i = 0; i < tracklist.length; ++i) { if (tracklist[i].artists != null) { $('#tblTracklist tr:last').after('<tr><td>' + tracklist[i].name + '</td><td>' + tracklist[i].artists[0].name + '</td><td><input type="button" value="X" style="font-size:10px" onclick=RemoveTrackFromTracklist(' + i + ') /></td></tr>'); } else { $('#tblTracklist tr:last').after('<tr><td>' + tracklist[i].name + '</td><td>&nbsp</td><td><input type="button" value="X" style="font-size:10px" onclick=RemoveTrackFromTracklist(' + i + ') /></td></tr>'); } } }); }
window.mopidy.playback.getVolume().then(function (vol) { var currentVolume = vol; console.log('curent vol: ' + currentVolume); currentVolume = currentVolume + newVol; mopidy.mixer.setVolume({ "volume": currentVolume }).then(function (data) { console.log(data); }); }); };
identifier_body
dj.js
$(document).ready(function () { }); var play = function () { mopidy.playback.play({ "tl_track": null }).then(function (data) { }); } var pause = function () { mopidy.playback.pause({}).then(function (data) { }); } var resume = function () { mopidy.playback.resume({}).then(function (data) { }); } var stop = function () { mopidy.playback.stop({}).then(function (data) { }); } var skip = function () { mopidy.playback.next({}).then(function (data) { }); } function ChangeVolume(newVol) { window.mopidy.playback.getVolume().then(function (vol) { var currentVolume = vol; console.log('curent vol: ' + currentVolume); currentVolume = currentVolume + newVol; mopidy.mixer.setVolume({ "volume": currentVolume }).then(function (data) { console.log(data); }); }); }; var shuffleTracklist = function () { window.mopidy.tracklist.getTracks() // => tracklist .then(function (tracklist) { mopidy.playback.getCurrentTlTrack({}).then(function (currentTlTrack) { mopidy.tracklist.index({ "tl_track": currentTlTrack }).then(function (currentTlTrackIndex) {
// currentTlTrackIndex +1 = next track (dont shuffle) // currentTlTrackIndex +2 = 2nd next track (dont shuffle) // currentTlTrackIndex +3 = 3rd next track (can be shuffled) if ((tracklist.length - currentTlTrackIndex) > 4) { mopidy.tracklist.shuffle({ "start": (currentTlTrackIndex + 4), "end": tracklist.length }).then(function (data) { }); } }); }); }); } var PrintTracklist = function () { window.mopidy.tracklist.getTracks() .then(function (tracklist) { $("#tblTracklist").find("tr:gt(0)").remove(); for (var i = 0; i < tracklist.length; ++i) { if (tracklist[i].artists != null) { $('#tblTracklist tr:last').after('<tr><td>' + tracklist[i].name + '</td><td>' + tracklist[i].artists[0].name + '</td><td><input type="button" value="X" style="font-size:10px" onclick=RemoveTrackFromTracklist(' + i + ') /></td></tr>'); } else { $('#tblTracklist tr:last').after('<tr><td>' + tracklist[i].name + '</td><td>&nbsp</td><td><input type="button" value="X" style="font-size:10px" onclick=RemoveTrackFromTracklist(' + i + ') /></td></tr>'); } } }); }
//shuffle tracklist starting from 4 after the current track so: // currentTlTrackIndex = current track (dont shuffle)
random_line_split
dj.js
$(document).ready(function () { }); var play = function () { mopidy.playback.play({ "tl_track": null }).then(function (data) { }); } var pause = function () { mopidy.playback.pause({}).then(function (data) { }); } var resume = function () { mopidy.playback.resume({}).then(function (data) { }); } var stop = function () { mopidy.playback.stop({}).then(function (data) { }); } var skip = function () { mopidy.playback.next({}).then(function (data) { }); } function ChangeVolume(newVol) { window.mopidy.playback.getVolume().then(function (vol) { var currentVolume = vol; console.log('curent vol: ' + currentVolume); currentVolume = currentVolume + newVol; mopidy.mixer.setVolume({ "volume": currentVolume }).then(function (data) { console.log(data); }); }); }; var shuffleTracklist = function () { window.mopidy.tracklist.getTracks() // => tracklist .then(function (tracklist) { mopidy.playback.getCurrentTlTrack({}).then(function (currentTlTrack) { mopidy.tracklist.index({ "tl_track": currentTlTrack }).then(function (currentTlTrackIndex) { //shuffle tracklist starting from 4 after the current track so: // currentTlTrackIndex = current track (dont shuffle) // currentTlTrackIndex +1 = next track (dont shuffle) // currentTlTrackIndex +2 = 2nd next track (dont shuffle) // currentTlTrackIndex +3 = 3rd next track (can be shuffled) if ((tracklist.length - currentTlTrackIndex) > 4) { mopidy.tracklist.shuffle({ "start": (currentTlTrackIndex + 4), "end": tracklist.length }).then(function (data) { }); } }); }); }); } var PrintTracklist = function () { window.mopidy.tracklist.getTracks() .then(function (tracklist) { $("#tblTracklist").find("tr:gt(0)").remove(); for (var i = 0; i < tracklist.length; ++i) { if (tracklist[i].artists != null) { $('#tblTracklist tr:last').after('<tr><td>' + tracklist[i].name + '</td><td>' + tracklist[i].artists[0].name + '</td><td><input type="button" value="X" style="font-size:10px" onclick=RemoveTrackFromTracklist(' + i + ') /></td></tr>'); } else {
} }); }
$('#tblTracklist tr:last').after('<tr><td>' + tracklist[i].name + '</td><td>&nbsp</td><td><input type="button" value="X" style="font-size:10px" onclick=RemoveTrackFromTracklist(' + i + ') /></td></tr>'); }
conditional_block
error_handler_spec.ts
/** * @license
* * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ERROR_DEBUG_CONTEXT} from '@angular/core/src/errors'; import {DebugContext} from '@angular/core/src/linker/debug_context'; import {viewWrappedError} from '@angular/core/src/linker/errors'; import {ErrorHandler, wrappedError} from '../src/error_handler'; class MockConsole { res: any[] = []; error(s: any): void { this.res.push(s); } } export function main() { function errorToString(error: any) { const logger = new MockConsole(); const errorHandler = new ErrorHandler(false); errorHandler._console = logger as any; errorHandler.handleError(error); return logger.res.join('\n'); } function getStack(error: Error): string { try { throw error; } catch (e) { return e.stack; } } describe('ErrorHandler', () => { it('should output exception', () => { const e = errorToString(new Error('message!')); expect(e).toContain('message!'); }); it('should output stackTrace', () => { const error = new Error('message!'); const stack = getStack(error); if (stack) { const e = errorToString(error); expect(e).toContain(stack); } }); describe('context', () => { it('should print nested context', () => { const cause = new Error('message!'); const stack = getStack(cause); const context = { source: 'context!', toString() { return 'Context'; } } as any; const original = viewWrappedError(cause, context); const e = errorToString(wrappedError('message', original)); expect(e).toEqual( stack ? `EXCEPTION: message caused by: Error in context! caused by: message! ORIGINAL EXCEPTION: message! ORIGINAL STACKTRACE: ${stack} ERROR CONTEXT: Context` : `EXCEPTION: message caused by: Error in context! caused by: message! ORIGINAL EXCEPTION: message! ERROR CONTEXT: Context`); }); }); describe('original exception', () => { it('should print original exception message if available (original is Error)', () => { const realOriginal = new Error('inner'); const original = wrappedError('wrapped', realOriginal); const e = errorToString(wrappedError('wrappedwrapped', original)); expect(e).toContain('inner'); }); it('should print original exception message if available (original is not Error)', () => { const realOriginal = new Error('custom'); const original = wrappedError('wrapped', realOriginal); const e = errorToString(wrappedError('wrappedwrapped', original)); expect(e).toContain('custom'); }); }); describe('original stack', () => { it('should print original stack if available', () => { const realOriginal = new Error('inner'); const stack = getStack(realOriginal); if (stack) { const original = wrappedError('wrapped', realOriginal); const e = errorToString(wrappedError('wrappedwrapped', original)); expect(e).toContain(stack); } }); }); }); }
* Copyright Google Inc. All Rights Reserved.
random_line_split
error_handler_spec.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ERROR_DEBUG_CONTEXT} from '@angular/core/src/errors'; import {DebugContext} from '@angular/core/src/linker/debug_context'; import {viewWrappedError} from '@angular/core/src/linker/errors'; import {ErrorHandler, wrappedError} from '../src/error_handler'; class MockConsole { res: any[] = []; error(s: any): void { this.res.push(s); } } export function
() { function errorToString(error: any) { const logger = new MockConsole(); const errorHandler = new ErrorHandler(false); errorHandler._console = logger as any; errorHandler.handleError(error); return logger.res.join('\n'); } function getStack(error: Error): string { try { throw error; } catch (e) { return e.stack; } } describe('ErrorHandler', () => { it('should output exception', () => { const e = errorToString(new Error('message!')); expect(e).toContain('message!'); }); it('should output stackTrace', () => { const error = new Error('message!'); const stack = getStack(error); if (stack) { const e = errorToString(error); expect(e).toContain(stack); } }); describe('context', () => { it('should print nested context', () => { const cause = new Error('message!'); const stack = getStack(cause); const context = { source: 'context!', toString() { return 'Context'; } } as any; const original = viewWrappedError(cause, context); const e = errorToString(wrappedError('message', original)); expect(e).toEqual( stack ? `EXCEPTION: message caused by: Error in context! caused by: message! ORIGINAL EXCEPTION: message! ORIGINAL STACKTRACE: ${stack} ERROR CONTEXT: Context` : `EXCEPTION: message caused by: Error in context! caused by: message! ORIGINAL EXCEPTION: message! ERROR CONTEXT: Context`); }); }); describe('original exception', () => { it('should print original exception message if available (original is Error)', () => { const realOriginal = new Error('inner'); const original = wrappedError('wrapped', realOriginal); const e = errorToString(wrappedError('wrappedwrapped', original)); expect(e).toContain('inner'); }); it('should print original exception message if available (original is not Error)', () => { const realOriginal = new Error('custom'); const original = wrappedError('wrapped', realOriginal); const e = errorToString(wrappedError('wrappedwrapped', original)); expect(e).toContain('custom'); }); }); describe('original stack', () => { it('should print original stack if available', () => { const realOriginal = new Error('inner'); const stack = getStack(realOriginal); if (stack) { const original = wrappedError('wrapped', realOriginal); const e = errorToString(wrappedError('wrappedwrapped', original)); expect(e).toContain(stack); } }); }); }); }
main
identifier_name
error_handler_spec.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ERROR_DEBUG_CONTEXT} from '@angular/core/src/errors'; import {DebugContext} from '@angular/core/src/linker/debug_context'; import {viewWrappedError} from '@angular/core/src/linker/errors'; import {ErrorHandler, wrappedError} from '../src/error_handler'; class MockConsole { res: any[] = []; error(s: any): void { this.res.push(s); } } export function main() { function errorToString(error: any) { const logger = new MockConsole(); const errorHandler = new ErrorHandler(false); errorHandler._console = logger as any; errorHandler.handleError(error); return logger.res.join('\n'); } function getStack(error: Error): string { try { throw error; } catch (e) { return e.stack; } } describe('ErrorHandler', () => { it('should output exception', () => { const e = errorToString(new Error('message!')); expect(e).toContain('message!'); }); it('should output stackTrace', () => { const error = new Error('message!'); const stack = getStack(error); if (stack) { const e = errorToString(error); expect(e).toContain(stack); } }); describe('context', () => { it('should print nested context', () => { const cause = new Error('message!'); const stack = getStack(cause); const context = { source: 'context!', toString() { return 'Context'; } } as any; const original = viewWrappedError(cause, context); const e = errorToString(wrappedError('message', original)); expect(e).toEqual( stack ? `EXCEPTION: message caused by: Error in context! caused by: message! ORIGINAL EXCEPTION: message! ORIGINAL STACKTRACE: ${stack} ERROR CONTEXT: Context` : `EXCEPTION: message caused by: Error in context! caused by: message! ORIGINAL EXCEPTION: message! ERROR CONTEXT: Context`); }); }); describe('original exception', () => { it('should print original exception message if available (original is Error)', () => { const realOriginal = new Error('inner'); const original = wrappedError('wrapped', realOriginal); const e = errorToString(wrappedError('wrappedwrapped', original)); expect(e).toContain('inner'); }); it('should print original exception message if available (original is not Error)', () => { const realOriginal = new Error('custom'); const original = wrappedError('wrapped', realOriginal); const e = errorToString(wrappedError('wrappedwrapped', original)); expect(e).toContain('custom'); }); }); describe('original stack', () => { it('should print original stack if available', () => { const realOriginal = new Error('inner'); const stack = getStack(realOriginal); if (stack)
}); }); }); }
{ const original = wrappedError('wrapped', realOriginal); const e = errorToString(wrappedError('wrappedwrapped', original)); expect(e).toContain(stack); }
conditional_block
error_handler_spec.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ERROR_DEBUG_CONTEXT} from '@angular/core/src/errors'; import {DebugContext} from '@angular/core/src/linker/debug_context'; import {viewWrappedError} from '@angular/core/src/linker/errors'; import {ErrorHandler, wrappedError} from '../src/error_handler'; class MockConsole { res: any[] = []; error(s: any): void
} export function main() { function errorToString(error: any) { const logger = new MockConsole(); const errorHandler = new ErrorHandler(false); errorHandler._console = logger as any; errorHandler.handleError(error); return logger.res.join('\n'); } function getStack(error: Error): string { try { throw error; } catch (e) { return e.stack; } } describe('ErrorHandler', () => { it('should output exception', () => { const e = errorToString(new Error('message!')); expect(e).toContain('message!'); }); it('should output stackTrace', () => { const error = new Error('message!'); const stack = getStack(error); if (stack) { const e = errorToString(error); expect(e).toContain(stack); } }); describe('context', () => { it('should print nested context', () => { const cause = new Error('message!'); const stack = getStack(cause); const context = { source: 'context!', toString() { return 'Context'; } } as any; const original = viewWrappedError(cause, context); const e = errorToString(wrappedError('message', original)); expect(e).toEqual( stack ? `EXCEPTION: message caused by: Error in context! caused by: message! ORIGINAL EXCEPTION: message! ORIGINAL STACKTRACE: ${stack} ERROR CONTEXT: Context` : `EXCEPTION: message caused by: Error in context! caused by: message! ORIGINAL EXCEPTION: message! ERROR CONTEXT: Context`); }); }); describe('original exception', () => { it('should print original exception message if available (original is Error)', () => { const realOriginal = new Error('inner'); const original = wrappedError('wrapped', realOriginal); const e = errorToString(wrappedError('wrappedwrapped', original)); expect(e).toContain('inner'); }); it('should print original exception message if available (original is not Error)', () => { const realOriginal = new Error('custom'); const original = wrappedError('wrapped', realOriginal); const e = errorToString(wrappedError('wrappedwrapped', original)); expect(e).toContain('custom'); }); }); describe('original stack', () => { it('should print original stack if available', () => { const realOriginal = new Error('inner'); const stack = getStack(realOriginal); if (stack) { const original = wrappedError('wrapped', realOriginal); const e = errorToString(wrappedError('wrappedwrapped', original)); expect(e).toContain(stack); } }); }); }); }
{ this.res.push(s); }
identifier_body
.eslintrc.js
module.exports = { env: { browser: true, es2020: true, greasemonkey: true, jquery: true, node: true, webextensions: true, }, rules: {}, overrides: [ { files: ['**/*.{js,jsx}'], parserOptions: { sourceType: 'module', }, extends: [ 'eslint:recommended', 'plugin:react/recommended', 'plugin:prettier/recommended', // Displays Prettier errors as ESLint errors. **Make sure this is always the last configuration.** ], rules: { quotes: [ 'error', 'single', { avoidEscape: true, allowTemplateLiterals: false, }, ], 'react/react-in-jsx-scope': 'off',
plugins: ['prefer-arrow'], extends: [ 'eslint:recommended', 'plugin:react/recommended', 'plugin:@typescript-eslint/recommended', 'prettier/@typescript-eslint', // Disables TypeScript rules that conflict with Prettier. 'plugin:prettier/recommended', // Displays Prettier errors as ESLint errors. **Make sure this is always the last configuration.** ], rules: { quotes: 'off', '@typescript-eslint/quotes': [ 'error', 'single', { avoidEscape: true, allowTemplateLiterals: false, }, ], 'prefer-arrow/prefer-arrow-functions': [ 'error', { disallowPrototype: true, classPropertiesAllowed: true, }, ], 'react/react-in-jsx-scope': 'off', }, }, ], settings: { react: { version: 'detect', }, }, };
}, }, { files: ['**/*.{ts,tsx}'],
random_line_split
sample_test.py
# Copyright 2014 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from perfkitbenchmarker import sample class SampleTestCase(unittest.TestCase): def testMetadataOptional(self):
def testProvidedMetadataSet(self): metadata = {'origin': 'unit test'} instance = sample.Sample(metric='Test', value=1.0, unit='Mbps', metadata=metadata.copy()) self.assertDictEqual(metadata, instance.metadata)
instance = sample.Sample(metric='Test', value=1.0, unit='Mbps') self.assertDictEqual({}, instance.metadata)
identifier_body
sample_test.py
# Copyright 2014 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from perfkitbenchmarker import sample class SampleTestCase(unittest.TestCase): def testMetadataOptional(self): instance = sample.Sample(metric='Test', value=1.0, unit='Mbps') self.assertDictEqual({}, instance.metadata) def
(self): metadata = {'origin': 'unit test'} instance = sample.Sample(metric='Test', value=1.0, unit='Mbps', metadata=metadata.copy()) self.assertDictEqual(metadata, instance.metadata)
testProvidedMetadataSet
identifier_name
sample_test.py
# Copyright 2014 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from perfkitbenchmarker import sample class SampleTestCase(unittest.TestCase): def testMetadataOptional(self): instance = sample.Sample(metric='Test', value=1.0, unit='Mbps')
def testProvidedMetadataSet(self): metadata = {'origin': 'unit test'} instance = sample.Sample(metric='Test', value=1.0, unit='Mbps', metadata=metadata.copy()) self.assertDictEqual(metadata, instance.metadata)
self.assertDictEqual({}, instance.metadata)
random_line_split
runTask.js
/*jshint node:true */ "use strict"; var extend = require('util')._extend; module.exports = function (task, args, done) { var that = this, params, finish, cb, isDone = false, start, r, streamReturn = []; finish = function (err, results, runMethod) { var hrDuration = process.hrtime(start); if (isDone) { return; } isDone = true; var duration = hrDuration[0] + (hrDuration[1] / 1e9); // seconds done.call(that, err, results, { duration: duration, // seconds hrDuration: hrDuration, // [seconds,nanoseconds] runMethod: runMethod }); }; cb = function (err, results) { finish(err, results, 'callback'); }; params = extend([], args);
try { start = process.hrtime(); r = task.apply(this, params); } catch (err) { finish(err, null, 'catch'); } if (r && typeof r.done === 'function') { // wait for promise to resolve // FRAGILE: ASSUME: Promises/A+, see http://promises-aplus.github.io/promises-spec/ r.done(function (results) { finish(null, results, 'promise'); }, function(err) { finish(err, null, 'promise'); }); } else if (r && typeof r.on === 'function' && typeof r.once === 'function' && typeof r.end === 'function' && r.pipe) { // wait for stream to end r.on('data', function (results) { // return an array of results because we must listen to all the traffic through the stream if (typeof results !== 'undefined') { streamReturn.push(results); } }); r.once('error', function (err) { finish(err, null, 'stream'); }); r.once('end', function () { finish(null, streamReturn, 'stream'); }); // start stream if (typeof args !== 'undefined' && args !== null) { r.write.apply(that, args); } } else if (task.length < params.length) { // synchronous, function took in args.length parameters, and the callback was extra finish(null, r, 'sync'); //} else { // FRAGILE: ASSUME: callback } };
params.push(cb);
random_line_split
findARestaurant.py
# -*- coding: utf-8 -*- import json import httplib2 import sys import codecs sys.stdout = codecs.getwriter('utf8')(sys.stdout) sys.stderr = codecs.getwriter('utf8')(sys.stderr) foursquare_client_id = 'SMQNYZFVCIOYIRAIXND2D5SYBLQUOPDB4HZTV13TT22AGACD' foursquare_client_secret = 'IHBS4VBHYWJL53NLIY2HSVI5A1144GJ3MDTYYY1KLKTMC4BV' google_api_key = 'AIzaSyBz7r2Kz6x7wO1zV9_O5Rcxmt8NahJ6kos' def getGeocodeLocation(inputString): #Replace Spaces with '+' in URL locationString = inputString.replace(" ", "+") url = ('https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=%s'% (locationString, google_api_key)) h = httplib2.Http() result = json.loads(h.request(url,'GET')[1]) #print response latitude = result['results'][0]['geometry']['location']['lat'] longitude = result['results'][0]['geometry']['location']['lng'] return (latitude,longitude) #This function takes in a string representation of a location and cuisine type, geocodes the location, and then pass in the latitude and longitude coordinates to the Foursquare API def findARestaurant(mealType, location): latitude, longitude = getGeocodeLocation(location) url = ('https://api.foursquare.com/v2/venues/search?client_id=%s&client_secret=%s&v=20130815&ll=%s,%s&query=%s' % (foursquare_client_id, foursquare_client_secret,latitude,longitude,mealType)) h = httplib2.Http() result = json.loads(h.request(url,'GET')[1]) if result['response']['venues']: #Grab the first restaurant restaurant = result['response']['venues'][0] venue_id = restaurant['id'] restaurant_name = restaurant['name'] restaurant_address = restaurant['location']['formattedAddress'] #Format the Restaurant Address into one string address = "" for i in restaurant_address: address += i + " " restaurant_address = address #Get a 300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture url = ('https://api.foursquare.com/v2/venues/%s/photos?client_id=%s&v=20150603&client_secret=%s' % ((venue_id,foursquare_client_id,foursquare_client_secret))) result = json.loads(h.request(url,'GET')[1]) #Grab the first image #if no image available, insert default image url if result['response']['photos']['items']: firstpic = result['response']['photos']['items'][0] prefix = firstpic['prefix'] suffix = firstpic['suffix'] imageURL = prefix + "300x300" + suffix
#print "Restaurant Address: %s " % restaurantInfo['address'] #print "Image: %s \n " % restaurantInfo['image'] return restaurantInfo else: #print "No Restaurants Found for %s" % location return "No Restaurants Found" if __name__ == '__main__': findARestaurant("Pizza", "Tokyo, Japan") findARestaurant("Tacos", "Jakarta, Indonesia") findARestaurant("Tapas", "Maputo, Mozambique") findARestaurant("Falafel", "Cairo, Egypt") findARestaurant("Spaghetti", "New Delhi, India") findARestaurant("Cappuccino", "Geneva, Switzerland") findARestaurant("Sushi", "Los Angeles, California") findARestaurant("Steak", "La Paz, Bolivia") findARestaurant("Gyros", "Sydney Austrailia")
else: imageURL = "http://pixabay.com/get/8926af5eb597ca51ca4c/1433440765/cheeseburger-34314_1280.png?direct" restaurantInfo = {'name':restaurant_name, 'address':restaurant_address, 'image':imageURL} #print "Restaurant Name: %s " % restaurantInfo['name']
random_line_split
findARestaurant.py
# -*- coding: utf-8 -*- import json import httplib2 import sys import codecs sys.stdout = codecs.getwriter('utf8')(sys.stdout) sys.stderr = codecs.getwriter('utf8')(sys.stderr) foursquare_client_id = 'SMQNYZFVCIOYIRAIXND2D5SYBLQUOPDB4HZTV13TT22AGACD' foursquare_client_secret = 'IHBS4VBHYWJL53NLIY2HSVI5A1144GJ3MDTYYY1KLKTMC4BV' google_api_key = 'AIzaSyBz7r2Kz6x7wO1zV9_O5Rcxmt8NahJ6kos' def getGeocodeLocation(inputString): #Replace Spaces with '+' in URL
#This function takes in a string representation of a location and cuisine type, geocodes the location, and then pass in the latitude and longitude coordinates to the Foursquare API def findARestaurant(mealType, location): latitude, longitude = getGeocodeLocation(location) url = ('https://api.foursquare.com/v2/venues/search?client_id=%s&client_secret=%s&v=20130815&ll=%s,%s&query=%s' % (foursquare_client_id, foursquare_client_secret,latitude,longitude,mealType)) h = httplib2.Http() result = json.loads(h.request(url,'GET')[1]) if result['response']['venues']: #Grab the first restaurant restaurant = result['response']['venues'][0] venue_id = restaurant['id'] restaurant_name = restaurant['name'] restaurant_address = restaurant['location']['formattedAddress'] #Format the Restaurant Address into one string address = "" for i in restaurant_address: address += i + " " restaurant_address = address #Get a 300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture url = ('https://api.foursquare.com/v2/venues/%s/photos?client_id=%s&v=20150603&client_secret=%s' % ((venue_id,foursquare_client_id,foursquare_client_secret))) result = json.loads(h.request(url,'GET')[1]) #Grab the first image #if no image available, insert default image url if result['response']['photos']['items']: firstpic = result['response']['photos']['items'][0] prefix = firstpic['prefix'] suffix = firstpic['suffix'] imageURL = prefix + "300x300" + suffix else: imageURL = "http://pixabay.com/get/8926af5eb597ca51ca4c/1433440765/cheeseburger-34314_1280.png?direct" restaurantInfo = {'name':restaurant_name, 'address':restaurant_address, 'image':imageURL} #print "Restaurant Name: %s " % restaurantInfo['name'] #print "Restaurant Address: %s " % restaurantInfo['address'] #print "Image: %s \n " % restaurantInfo['image'] return restaurantInfo else: #print "No Restaurants Found for %s" % location return "No Restaurants Found" if __name__ == '__main__': findARestaurant("Pizza", "Tokyo, Japan") findARestaurant("Tacos", "Jakarta, Indonesia") findARestaurant("Tapas", "Maputo, Mozambique") findARestaurant("Falafel", "Cairo, Egypt") findARestaurant("Spaghetti", "New Delhi, India") findARestaurant("Cappuccino", "Geneva, Switzerland") findARestaurant("Sushi", "Los Angeles, California") findARestaurant("Steak", "La Paz, Bolivia") findARestaurant("Gyros", "Sydney Austrailia")
locationString = inputString.replace(" ", "+") url = ('https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=%s'% (locationString, google_api_key)) h = httplib2.Http() result = json.loads(h.request(url,'GET')[1]) #print response latitude = result['results'][0]['geometry']['location']['lat'] longitude = result['results'][0]['geometry']['location']['lng'] return (latitude,longitude)
identifier_body
findARestaurant.py
# -*- coding: utf-8 -*- import json import httplib2 import sys import codecs sys.stdout = codecs.getwriter('utf8')(sys.stdout) sys.stderr = codecs.getwriter('utf8')(sys.stderr) foursquare_client_id = 'SMQNYZFVCIOYIRAIXND2D5SYBLQUOPDB4HZTV13TT22AGACD' foursquare_client_secret = 'IHBS4VBHYWJL53NLIY2HSVI5A1144GJ3MDTYYY1KLKTMC4BV' google_api_key = 'AIzaSyBz7r2Kz6x7wO1zV9_O5Rcxmt8NahJ6kos' def getGeocodeLocation(inputString): #Replace Spaces with '+' in URL locationString = inputString.replace(" ", "+") url = ('https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=%s'% (locationString, google_api_key)) h = httplib2.Http() result = json.loads(h.request(url,'GET')[1]) #print response latitude = result['results'][0]['geometry']['location']['lat'] longitude = result['results'][0]['geometry']['location']['lng'] return (latitude,longitude) #This function takes in a string representation of a location and cuisine type, geocodes the location, and then pass in the latitude and longitude coordinates to the Foursquare API def findARestaurant(mealType, location): latitude, longitude = getGeocodeLocation(location) url = ('https://api.foursquare.com/v2/venues/search?client_id=%s&client_secret=%s&v=20130815&ll=%s,%s&query=%s' % (foursquare_client_id, foursquare_client_secret,latitude,longitude,mealType)) h = httplib2.Http() result = json.loads(h.request(url,'GET')[1]) if result['response']['venues']: #Grab the first restaurant restaurant = result['response']['venues'][0] venue_id = restaurant['id'] restaurant_name = restaurant['name'] restaurant_address = restaurant['location']['formattedAddress'] #Format the Restaurant Address into one string address = "" for i in restaurant_address: address += i + " " restaurant_address = address #Get a 300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture url = ('https://api.foursquare.com/v2/venues/%s/photos?client_id=%s&v=20150603&client_secret=%s' % ((venue_id,foursquare_client_id,foursquare_client_secret))) result = json.loads(h.request(url,'GET')[1]) #Grab the first image #if no image available, insert default image url if result['response']['photos']['items']: firstpic = result['response']['photos']['items'][0] prefix = firstpic['prefix'] suffix = firstpic['suffix'] imageURL = prefix + "300x300" + suffix else:
restaurantInfo = {'name':restaurant_name, 'address':restaurant_address, 'image':imageURL} #print "Restaurant Name: %s " % restaurantInfo['name'] #print "Restaurant Address: %s " % restaurantInfo['address'] #print "Image: %s \n " % restaurantInfo['image'] return restaurantInfo else: #print "No Restaurants Found for %s" % location return "No Restaurants Found" if __name__ == '__main__': findARestaurant("Pizza", "Tokyo, Japan") findARestaurant("Tacos", "Jakarta, Indonesia") findARestaurant("Tapas", "Maputo, Mozambique") findARestaurant("Falafel", "Cairo, Egypt") findARestaurant("Spaghetti", "New Delhi, India") findARestaurant("Cappuccino", "Geneva, Switzerland") findARestaurant("Sushi", "Los Angeles, California") findARestaurant("Steak", "La Paz, Bolivia") findARestaurant("Gyros", "Sydney Austrailia")
imageURL = "http://pixabay.com/get/8926af5eb597ca51ca4c/1433440765/cheeseburger-34314_1280.png?direct"
conditional_block
findARestaurant.py
# -*- coding: utf-8 -*- import json import httplib2 import sys import codecs sys.stdout = codecs.getwriter('utf8')(sys.stdout) sys.stderr = codecs.getwriter('utf8')(sys.stderr) foursquare_client_id = 'SMQNYZFVCIOYIRAIXND2D5SYBLQUOPDB4HZTV13TT22AGACD' foursquare_client_secret = 'IHBS4VBHYWJL53NLIY2HSVI5A1144GJ3MDTYYY1KLKTMC4BV' google_api_key = 'AIzaSyBz7r2Kz6x7wO1zV9_O5Rcxmt8NahJ6kos' def getGeocodeLocation(inputString): #Replace Spaces with '+' in URL locationString = inputString.replace(" ", "+") url = ('https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=%s'% (locationString, google_api_key)) h = httplib2.Http() result = json.loads(h.request(url,'GET')[1]) #print response latitude = result['results'][0]['geometry']['location']['lat'] longitude = result['results'][0]['geometry']['location']['lng'] return (latitude,longitude) #This function takes in a string representation of a location and cuisine type, geocodes the location, and then pass in the latitude and longitude coordinates to the Foursquare API def
(mealType, location): latitude, longitude = getGeocodeLocation(location) url = ('https://api.foursquare.com/v2/venues/search?client_id=%s&client_secret=%s&v=20130815&ll=%s,%s&query=%s' % (foursquare_client_id, foursquare_client_secret,latitude,longitude,mealType)) h = httplib2.Http() result = json.loads(h.request(url,'GET')[1]) if result['response']['venues']: #Grab the first restaurant restaurant = result['response']['venues'][0] venue_id = restaurant['id'] restaurant_name = restaurant['name'] restaurant_address = restaurant['location']['formattedAddress'] #Format the Restaurant Address into one string address = "" for i in restaurant_address: address += i + " " restaurant_address = address #Get a 300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture url = ('https://api.foursquare.com/v2/venues/%s/photos?client_id=%s&v=20150603&client_secret=%s' % ((venue_id,foursquare_client_id,foursquare_client_secret))) result = json.loads(h.request(url,'GET')[1]) #Grab the first image #if no image available, insert default image url if result['response']['photos']['items']: firstpic = result['response']['photos']['items'][0] prefix = firstpic['prefix'] suffix = firstpic['suffix'] imageURL = prefix + "300x300" + suffix else: imageURL = "http://pixabay.com/get/8926af5eb597ca51ca4c/1433440765/cheeseburger-34314_1280.png?direct" restaurantInfo = {'name':restaurant_name, 'address':restaurant_address, 'image':imageURL} #print "Restaurant Name: %s " % restaurantInfo['name'] #print "Restaurant Address: %s " % restaurantInfo['address'] #print "Image: %s \n " % restaurantInfo['image'] return restaurantInfo else: #print "No Restaurants Found for %s" % location return "No Restaurants Found" if __name__ == '__main__': findARestaurant("Pizza", "Tokyo, Japan") findARestaurant("Tacos", "Jakarta, Indonesia") findARestaurant("Tapas", "Maputo, Mozambique") findARestaurant("Falafel", "Cairo, Egypt") findARestaurant("Spaghetti", "New Delhi, India") findARestaurant("Cappuccino", "Geneva, Switzerland") findARestaurant("Sushi", "Los Angeles, California") findARestaurant("Steak", "La Paz, Bolivia") findARestaurant("Gyros", "Sydney Austrailia")
findARestaurant
identifier_name
mouse.rs
// The MIT License (MIT) // // Copyright (c) 2014 Jeremy Letang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. use imp::ffi; use imp::window::WindowImpl; pub fn
(window: &WindowImpl) -> (i32, i32) { let point = ffi::ve_mouse_get_location(window.window_handler); (point.x as i32, point.y as i32) } pub fn screen_location() -> (i32, i32) { let point = ffi::ve_mouse_get_global_location(); (point.x as i32, point.y as i32) }
location
identifier_name
mouse.rs
// The MIT License (MIT) // // Copyright (c) 2014 Jeremy Letang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. use imp::ffi; use imp::window::WindowImpl; pub fn location(window: &WindowImpl) -> (i32, i32) { let point = ffi::ve_mouse_get_location(window.window_handler); (point.x as i32, point.y as i32) } pub fn screen_location() -> (i32, i32)
{ let point = ffi::ve_mouse_get_global_location(); (point.x as i32, point.y as i32) }
identifier_body
mouse.rs
// The MIT License (MIT) // // Copyright (c) 2014 Jeremy Letang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. use imp::ffi; use imp::window::WindowImpl; pub fn location(window: &WindowImpl) -> (i32, i32) { let point = ffi::ve_mouse_get_location(window.window_handler); (point.x as i32, point.y as i32) } pub fn screen_location() -> (i32, i32) { let point = ffi::ve_mouse_get_global_location();
(point.x as i32, point.y as i32) }
random_line_split
tips.js
angular.module('tips.tips').controller('TipsController', ['$scope', '$routeParams', '$location', 'Global', 'Tips', function ($scope, $routeParams, $location, Global, Tips) { $scope.global = Global; $scope.createTip = function () { var tips = new Tips({ text: this.text, likes: this.likes, category: this.category }); tips.$save(function (response) { $location.path("/"); }); this.title = ""; }; $scope.showTip = function () { Tips.query(function (tips) { $scope.tips = tips; tips.linkEdit = 'tips/edit/'; // show tips size function Settings (minLikes, maxLikes)
function startIsotope(){ var el = $('#isotope-container'); el.isotope({ itemSelector: '.isotope-element', layoutMode: 'fitRows', sortBy: 'number', sortAscending: true, }); return el; } var maxLikes = 0; var minLikes = 0; for (var i = 0; i < tips.length; i++) { if(maxLikes <= tips[i].likes)maxLikes = tips[i].likes; if(minLikes >= tips[i].likes)minLikes = tips[i].likes; }; tips.settingsView = new Settings(minLikes, maxLikes); $scope.$watch('tips', function () { $scope.$evalAsync(function () { var isotope = startIsotope(); }); }) }); }; $scope.updateTip = function (tip) { var tip = new Tips(tip); tip.$update(tip, function(){ console.log("update updateTip: ", tip._id); }, function(){ console.warn("error updateTip:", tip._id); }); }; $scope.getTip = function () { Tips.query(function (tip) { $scope.tip = tip; console.log(tip); }); }; $scope.editTip = function(tip){ console.log("edit tip"); }; }])
{ var that = this; that.size = { min: 26, max: 300 }; that.maxLikes = maxLikes; that.minLikes = tips[0].likes; that.valueOfdivision = (function(){ return (that.size.max - that.size.min)/that.maxLikes })() }
identifier_body
tips.js
angular.module('tips.tips').controller('TipsController', ['$scope', '$routeParams', '$location', 'Global', 'Tips', function ($scope, $routeParams, $location, Global, Tips) { $scope.global = Global; $scope.createTip = function () { var tips = new Tips({ text: this.text, likes: this.likes, category: this.category }); tips.$save(function (response) { $location.path("/"); }); this.title = ""; }; $scope.showTip = function () { Tips.query(function (tips) { $scope.tips = tips; tips.linkEdit = 'tips/edit/'; // show tips size function Settings (minLikes, maxLikes) { var that = this; that.size = { min: 26, max: 300 }; that.maxLikes = maxLikes; that.minLikes = tips[0].likes; that.valueOfdivision = (function(){ return (that.size.max - that.size.min)/that.maxLikes })() } function startIsotope(){ var el = $('#isotope-container'); el.isotope({ itemSelector: '.isotope-element', layoutMode: 'fitRows', sortBy: 'number', sortAscending: true, }); return el; } var maxLikes = 0; var minLikes = 0; for (var i = 0; i < tips.length; i++) {
tips.settingsView = new Settings(minLikes, maxLikes); $scope.$watch('tips', function () { $scope.$evalAsync(function () { var isotope = startIsotope(); }); }) }); }; $scope.updateTip = function (tip) { var tip = new Tips(tip); tip.$update(tip, function(){ console.log("update updateTip: ", tip._id); }, function(){ console.warn("error updateTip:", tip._id); }); }; $scope.getTip = function () { Tips.query(function (tip) { $scope.tip = tip; console.log(tip); }); }; $scope.editTip = function(tip){ console.log("edit tip"); }; }])
if(maxLikes <= tips[i].likes)maxLikes = tips[i].likes; if(minLikes >= tips[i].likes)minLikes = tips[i].likes; };
random_line_split
tips.js
angular.module('tips.tips').controller('TipsController', ['$scope', '$routeParams', '$location', 'Global', 'Tips', function ($scope, $routeParams, $location, Global, Tips) { $scope.global = Global; $scope.createTip = function () { var tips = new Tips({ text: this.text, likes: this.likes, category: this.category }); tips.$save(function (response) { $location.path("/"); }); this.title = ""; }; $scope.showTip = function () { Tips.query(function (tips) { $scope.tips = tips; tips.linkEdit = 'tips/edit/'; // show tips size function Settings (minLikes, maxLikes) { var that = this; that.size = { min: 26, max: 300 }; that.maxLikes = maxLikes; that.minLikes = tips[0].likes; that.valueOfdivision = (function(){ return (that.size.max - that.size.min)/that.maxLikes })() } function
(){ var el = $('#isotope-container'); el.isotope({ itemSelector: '.isotope-element', layoutMode: 'fitRows', sortBy: 'number', sortAscending: true, }); return el; } var maxLikes = 0; var minLikes = 0; for (var i = 0; i < tips.length; i++) { if(maxLikes <= tips[i].likes)maxLikes = tips[i].likes; if(minLikes >= tips[i].likes)minLikes = tips[i].likes; }; tips.settingsView = new Settings(minLikes, maxLikes); $scope.$watch('tips', function () { $scope.$evalAsync(function () { var isotope = startIsotope(); }); }) }); }; $scope.updateTip = function (tip) { var tip = new Tips(tip); tip.$update(tip, function(){ console.log("update updateTip: ", tip._id); }, function(){ console.warn("error updateTip:", tip._id); }); }; $scope.getTip = function () { Tips.query(function (tip) { $scope.tip = tip; console.log(tip); }); }; $scope.editTip = function(tip){ console.log("edit tip"); }; }])
startIsotope
identifier_name
helloworld_grpc_pb.js
// GENERATED CODE -- DO NOT EDIT! // Original file comments: // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // 'use strict'; var grpc = require('grpc'); var helloworld_pb = require('./helloworld_pb.js'); function serialize_HelloReply(arg) { if (!(arg instanceof helloworld_pb.HelloReply)) { throw new Error('Expected argument of type HelloReply'); } return new Buffer(arg.serializeBinary()); } function
(buffer_arg) { return helloworld_pb.HelloReply.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_HelloRequest(arg) { if (!(arg instanceof helloworld_pb.HelloRequest)) { throw new Error('Expected argument of type HelloRequest'); } return new Buffer(arg.serializeBinary()); } function deserialize_HelloRequest(buffer_arg) { return helloworld_pb.HelloRequest.deserializeBinary(new Uint8Array(buffer_arg)); } // The greeting service definition. var GreeterService = exports.GreeterService = { // Sends a greeting sayHello: { path: '/helloworld.Greeter/SayHello', requestStream: false, responseStream: false, requestType: helloworld_pb.HelloRequest, responseType: helloworld_pb.HelloReply, requestSerialize: serialize_HelloRequest, requestDeserialize: deserialize_HelloRequest, responseSerialize: serialize_HelloReply, responseDeserialize: deserialize_HelloReply, }, }; exports.GreeterClient = grpc.makeGenericClientConstructor(GreeterService);
deserialize_HelloReply
identifier_name
helloworld_grpc_pb.js
// GENERATED CODE -- DO NOT EDIT! // Original file comments: // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // 'use strict'; var grpc = require('grpc'); var helloworld_pb = require('./helloworld_pb.js'); function serialize_HelloReply(arg) { if (!(arg instanceof helloworld_pb.HelloReply)) { throw new Error('Expected argument of type HelloReply'); } return new Buffer(arg.serializeBinary()); } function deserialize_HelloReply(buffer_arg) { return helloworld_pb.HelloReply.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_HelloRequest(arg) { if (!(arg instanceof helloworld_pb.HelloRequest)) { throw new Error('Expected argument of type HelloRequest'); } return new Buffer(arg.serializeBinary()); } function deserialize_HelloRequest(buffer_arg) { return helloworld_pb.HelloRequest.deserializeBinary(new Uint8Array(buffer_arg)); }
sayHello: { path: '/helloworld.Greeter/SayHello', requestStream: false, responseStream: false, requestType: helloworld_pb.HelloRequest, responseType: helloworld_pb.HelloReply, requestSerialize: serialize_HelloRequest, requestDeserialize: deserialize_HelloRequest, responseSerialize: serialize_HelloReply, responseDeserialize: deserialize_HelloReply, }, }; exports.GreeterClient = grpc.makeGenericClientConstructor(GreeterService);
// The greeting service definition. var GreeterService = exports.GreeterService = { // Sends a greeting
random_line_split
helloworld_grpc_pb.js
// GENERATED CODE -- DO NOT EDIT! // Original file comments: // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // 'use strict'; var grpc = require('grpc'); var helloworld_pb = require('./helloworld_pb.js'); function serialize_HelloReply(arg) { if (!(arg instanceof helloworld_pb.HelloReply))
return new Buffer(arg.serializeBinary()); } function deserialize_HelloReply(buffer_arg) { return helloworld_pb.HelloReply.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_HelloRequest(arg) { if (!(arg instanceof helloworld_pb.HelloRequest)) { throw new Error('Expected argument of type HelloRequest'); } return new Buffer(arg.serializeBinary()); } function deserialize_HelloRequest(buffer_arg) { return helloworld_pb.HelloRequest.deserializeBinary(new Uint8Array(buffer_arg)); } // The greeting service definition. var GreeterService = exports.GreeterService = { // Sends a greeting sayHello: { path: '/helloworld.Greeter/SayHello', requestStream: false, responseStream: false, requestType: helloworld_pb.HelloRequest, responseType: helloworld_pb.HelloReply, requestSerialize: serialize_HelloRequest, requestDeserialize: deserialize_HelloRequest, responseSerialize: serialize_HelloReply, responseDeserialize: deserialize_HelloReply, }, }; exports.GreeterClient = grpc.makeGenericClientConstructor(GreeterService);
{ throw new Error('Expected argument of type HelloReply'); }
conditional_block
helloworld_grpc_pb.js
// GENERATED CODE -- DO NOT EDIT! // Original file comments: // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // 'use strict'; var grpc = require('grpc'); var helloworld_pb = require('./helloworld_pb.js'); function serialize_HelloReply(arg) { if (!(arg instanceof helloworld_pb.HelloReply)) { throw new Error('Expected argument of type HelloReply'); } return new Buffer(arg.serializeBinary()); } function deserialize_HelloReply(buffer_arg) { return helloworld_pb.HelloReply.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_HelloRequest(arg) { if (!(arg instanceof helloworld_pb.HelloRequest)) { throw new Error('Expected argument of type HelloRequest'); } return new Buffer(arg.serializeBinary()); } function deserialize_HelloRequest(buffer_arg)
// The greeting service definition. var GreeterService = exports.GreeterService = { // Sends a greeting sayHello: { path: '/helloworld.Greeter/SayHello', requestStream: false, responseStream: false, requestType: helloworld_pb.HelloRequest, responseType: helloworld_pb.HelloReply, requestSerialize: serialize_HelloRequest, requestDeserialize: deserialize_HelloRequest, responseSerialize: serialize_HelloReply, responseDeserialize: deserialize_HelloReply, }, }; exports.GreeterClient = grpc.makeGenericClientConstructor(GreeterService);
{ return helloworld_pb.HelloRequest.deserializeBinary(new Uint8Array(buffer_arg)); }
identifier_body
extshadertexturelod.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use super::{WebGLExtension, WebGLExtensionSpec, WebGLExtensions}; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::webglrenderingcontext::WebGLRenderingContext; use canvas_traits::webgl::WebGLVersion; use dom_struct::dom_struct; #[dom_struct] pub struct EXTShaderTextureLod { reflector_: Reflector, } impl EXTShaderTextureLod { fn new_inherited() -> Self { Self { reflector_: Reflector::new(), } } } impl WebGLExtension for EXTShaderTextureLod { type Extension = Self; fn new(ctx: &WebGLRenderingContext) -> DomRoot<Self> { reflect_dom_object(Box::new(Self::new_inherited()), &*ctx.global()) } fn spec() -> WebGLExtensionSpec { WebGLExtensionSpec::Specific(WebGLVersion::WebGL1) } fn is_supported(ext: &WebGLExtensions) -> bool { // This extension is always available on desktop GL.
fn enable(_ext: &WebGLExtensions) {} fn name() -> &'static str { "EXT_shader_texture_lod" } }
!ext.is_gles() || ext.supports_gl_extension("GL_EXT_shader_texture_lod") }
random_line_split
extshadertexturelod.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use super::{WebGLExtension, WebGLExtensionSpec, WebGLExtensions}; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::webglrenderingcontext::WebGLRenderingContext; use canvas_traits::webgl::WebGLVersion; use dom_struct::dom_struct; #[dom_struct] pub struct EXTShaderTextureLod { reflector_: Reflector, } impl EXTShaderTextureLod { fn new_inherited() -> Self { Self { reflector_: Reflector::new(), } } } impl WebGLExtension for EXTShaderTextureLod { type Extension = Self; fn new(ctx: &WebGLRenderingContext) -> DomRoot<Self> { reflect_dom_object(Box::new(Self::new_inherited()), &*ctx.global()) } fn spec() -> WebGLExtensionSpec { WebGLExtensionSpec::Specific(WebGLVersion::WebGL1) } fn is_supported(ext: &WebGLExtensions) -> bool { // This extension is always available on desktop GL. !ext.is_gles() || ext.supports_gl_extension("GL_EXT_shader_texture_lod") } fn enable(_ext: &WebGLExtensions) {} fn name() -> &'static str
}
{ "EXT_shader_texture_lod" }
identifier_body
extshadertexturelod.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use super::{WebGLExtension, WebGLExtensionSpec, WebGLExtensions}; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::webglrenderingcontext::WebGLRenderingContext; use canvas_traits::webgl::WebGLVersion; use dom_struct::dom_struct; #[dom_struct] pub struct EXTShaderTextureLod { reflector_: Reflector, } impl EXTShaderTextureLod { fn new_inherited() -> Self { Self { reflector_: Reflector::new(), } } } impl WebGLExtension for EXTShaderTextureLod { type Extension = Self; fn new(ctx: &WebGLRenderingContext) -> DomRoot<Self> { reflect_dom_object(Box::new(Self::new_inherited()), &*ctx.global()) } fn spec() -> WebGLExtensionSpec { WebGLExtensionSpec::Specific(WebGLVersion::WebGL1) } fn
(ext: &WebGLExtensions) -> bool { // This extension is always available on desktop GL. !ext.is_gles() || ext.supports_gl_extension("GL_EXT_shader_texture_lod") } fn enable(_ext: &WebGLExtensions) {} fn name() -> &'static str { "EXT_shader_texture_lod" } }
is_supported
identifier_name
home.py
""" This page is in the table of contents. Plugin to home the tool at beginning of each layer. The home manual page is at: http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Home ==Operation== The default 'Activate Home' checkbox is on. When it is on, the functions described below will work, when it is off, nothing will be done. ==Settings== ===Name of Home File=== Default: home.gcode At the beginning of a each layer, home will add the commands of a gcode script with the name of the "Name of Home File" setting, if one exists. Home does not care if the text file names are capitalized, but some file systems do not handle file name cases properly, so to be on the safe side you should give them lower case names. Home looks for those files in the alterations folder in the .skeinforge folder in the home directory. If it doesn't find the file it then looks in the alterations folder in the skeinforge_plugins folder. ==Examples== The following examples home the file Screw Holder Bottom.stl. The examples are run in a terminal in the folder which contains Screw Holder Bottom.stl and home.py. > python home.py This brings up the home dialog. > python home.py Screw Holder Bottom.stl The home tool is parsing the file: Screw Holder Bottom.stl .. The home tool has created the file: .. Screw Holder Bottom_home.gcode """ from __future__ import absolute_import #Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module. import __init__ from fabmetheus_utilities.fabmetheus_tools import fabmetheus_interpret from fabmetheus_utilities.vector3 import Vector3 from fabmetheus_utilities import archive from fabmetheus_utilities import euclidean from fabmetheus_utilities import gcodec from fabmetheus_utilities import settings from skeinforge_application.skeinforge_utilities import skeinforge_craft from skeinforge_application.skeinforge_utilities import skeinforge_polyfile from skeinforge_application.skeinforge_utilities import skeinforge_profile import math import os import sys __author__ = 'Enrique Perez (perez_enrique@yahoo.com)' __date__ = '$Date: 2008/21/04 $' __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' def getCraftedText( fileName, text, repository = None ): "Home a gcode linear move file or text." return getCraftedTextFromText(archive.getTextIfEmpty(fileName, text), repository) def getCraftedTextFromText( gcodeText, repository = None ): "Home a gcode linear move text." if gcodec.isProcedureDoneOrFileIsEmpty( gcodeText, 'home'): return gcodeText if repository == None: repository = settings.getReadRepository( HomeRepository() ) if not repository.activateHome.value: return gcodeText return HomeSkein().getCraftedGcode(gcodeText, repository) def getNewRepository(): 'Get new repository.' return HomeRepository() def writeOutput(fileName, shouldAnalyze=True): "Home a gcode linear move file. Chain home the gcode if it is not already homed." skeinforge_craft.writeChainTextWithNounMessage(fileName, 'home', shouldAnalyze) class HomeRepository: "A class to handle the home settings." def __init__(self): "Set the default settings, execute title & settings fileName." skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_plugins.craft_plugins.home.html', self) self.fileNameInput = settings.FileNameInput().getFromFileName( fabmetheus_interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Home', self, '') self.openWikiManualHelpPage = settings.HelpPage().getOpenFromAbsolute('http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Home') self.activateHome = settings.BooleanSetting().getFromValue('Activate Home', self, True ) self.nameOfHomeFile = settings.StringSetting().getFromValue('Name of Home File:', self, 'home.gcode') self.executeTitle = 'Home' def execute(self): "Home button has been clicked." fileNames = skeinforge_polyfile.getFileOrDirectoryTypesUnmodifiedGcode(self.fileNameInput.value, fabmetheus_interpret.getImportPluginFileNames(), self.fileNameInput.wasCancelled) for fileName in fileNames: writeOutput(fileName) class HomeSkein: "A class to home a skein of extrusions." def __init__(self): self.distanceFeedRate = gcodec.DistanceFeedRate() self.extruderActive = False self.highestZ = None self.homeLines = [] self.layerCount = settings.LayerCount() self.lineIndex = 0 self.lines = None self.oldLocation = None self.shouldHome = False self.travelFeedRateMinute = 957.0 def addFloat( self, begin, end ): "Add dive to the original height." beginEndDistance = begin.distance(end) alongWay = self.absolutePerimeterWidth / beginEndDistance closeToEnd = euclidean.getIntermediateLocation( alongWay, end, begin ) closeToEnd.z = self.highestZ self.distanceFeedRate.addLine( self.distanceFeedRate.getLinearGcodeMovementWithFeedRate( self.travelFeedRateMinute, closeToEnd.dropAxis(), closeToEnd.z ) ) def addHomeTravel( self, splitLine ): "Add the home travel gcode." location = gcodec.getLocationFromSplitLine(self.oldLocation, splitLine) self.highestZ = max( self.highestZ, location.z ) if not self.shouldHome: return self.shouldHome = False if self.oldLocation == None: return if self.extruderActive: self.distanceFeedRate.addLine('M103') self.addHopUp( self.oldLocation ) self.distanceFeedRate.addLinesSetAbsoluteDistanceMode(self.homeLines) self.addHopUp( self.oldLocation ) self.addFloat( self.oldLocation, location ) if self.extruderActive: self.distanceFeedRate.addLine('M101') def addHopUp(self, location): "Add hop to highest point." locationUp = Vector3( location.x, location.y, self.highestZ ) self.distanceFeedRate.addLine( self.distanceFeedRate.getLinearGcodeMovementWithFeedRate( self.travelFeedRateMinute, locationUp.dropAxis(), locationUp.z ) ) def getCraftedGcode( self, gcodeText, repository ): "Parse gcode text and store the home gcode." self.repository = repository self.homeLines = settings.getAlterationFileLines(repository.nameOfHomeFile.value) if len(self.homeLines) < 1: return gcodeText self.lines = archive.getTextLines(gcodeText) self.parseInitialization( repository ) for self.lineIndex in xrange(self.lineIndex, len(self.lines)): line = self.lines[self.lineIndex] self.parseLine(line) return self.distanceFeedRate.output.getvalue() def parseInitialization( self, repository ): 'Parse gcode initialization and store the parameters.' for self.lineIndex in xrange(len(self.lines)): line = self.lines[self.lineIndex] splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line) firstWord = gcodec.getFirstWord(splitLine) self.distanceFeedRate.parseSplitLine(firstWord, splitLine) if firstWord == '(</extruderInitialization>)': self.distanceFeedRate.addTagBracketedProcedure('home') return elif firstWord == '(<perimeterWidth>': self.absolutePerimeterWidth = abs(float(splitLine[1])) elif firstWord == '(<travelFeedRatePerSecond>': self.travelFeedRateMinute = 60.0 * float(splitLine[1]) self.distanceFeedRate.addLine(line) def parseLine(self, line): "Parse a gcode line and add it to the bevel gcode." splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line) if len(splitLine) < 1: return firstWord = splitLine[0] if firstWord == 'G1': self.addHomeTravel(splitLine) self.oldLocation = gcodec.getLocationFromSplitLine(self.oldLocation, splitLine) elif firstWord == '(<layer>': self.layerCount.printProgressIncrement('home') if len(self.homeLines) > 0: self.shouldHome = True elif firstWord == 'M101': self.extruderActive = True elif firstWord == 'M103': self.extruderActive = False self.distanceFeedRate.addLine(line) def main(): "Display the home dialog." if len(sys.argv) > 1: writeOutput(' '.join(sys.argv[1 :])) else: settings.startMainLoopFromConstructor(getNewRepository())
if __name__ == "__main__": main()
random_line_split
home.py
""" This page is in the table of contents. Plugin to home the tool at beginning of each layer. The home manual page is at: http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Home ==Operation== The default 'Activate Home' checkbox is on. When it is on, the functions described below will work, when it is off, nothing will be done. ==Settings== ===Name of Home File=== Default: home.gcode At the beginning of a each layer, home will add the commands of a gcode script with the name of the "Name of Home File" setting, if one exists. Home does not care if the text file names are capitalized, but some file systems do not handle file name cases properly, so to be on the safe side you should give them lower case names. Home looks for those files in the alterations folder in the .skeinforge folder in the home directory. If it doesn't find the file it then looks in the alterations folder in the skeinforge_plugins folder. ==Examples== The following examples home the file Screw Holder Bottom.stl. The examples are run in a terminal in the folder which contains Screw Holder Bottom.stl and home.py. > python home.py This brings up the home dialog. > python home.py Screw Holder Bottom.stl The home tool is parsing the file: Screw Holder Bottom.stl .. The home tool has created the file: .. Screw Holder Bottom_home.gcode """ from __future__ import absolute_import #Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module. import __init__ from fabmetheus_utilities.fabmetheus_tools import fabmetheus_interpret from fabmetheus_utilities.vector3 import Vector3 from fabmetheus_utilities import archive from fabmetheus_utilities import euclidean from fabmetheus_utilities import gcodec from fabmetheus_utilities import settings from skeinforge_application.skeinforge_utilities import skeinforge_craft from skeinforge_application.skeinforge_utilities import skeinforge_polyfile from skeinforge_application.skeinforge_utilities import skeinforge_profile import math import os import sys __author__ = 'Enrique Perez (perez_enrique@yahoo.com)' __date__ = '$Date: 2008/21/04 $' __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' def getCraftedText( fileName, text, repository = None ): "Home a gcode linear move file or text." return getCraftedTextFromText(archive.getTextIfEmpty(fileName, text), repository) def getCraftedTextFromText( gcodeText, repository = None ): "Home a gcode linear move text." if gcodec.isProcedureDoneOrFileIsEmpty( gcodeText, 'home'): return gcodeText if repository == None: repository = settings.getReadRepository( HomeRepository() ) if not repository.activateHome.value: return gcodeText return HomeSkein().getCraftedGcode(gcodeText, repository) def getNewRepository(): 'Get new repository.' return HomeRepository() def writeOutput(fileName, shouldAnalyze=True): "Home a gcode linear move file. Chain home the gcode if it is not already homed." skeinforge_craft.writeChainTextWithNounMessage(fileName, 'home', shouldAnalyze) class HomeRepository: "A class to handle the home settings." def __init__(self): "Set the default settings, execute title & settings fileName." skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_plugins.craft_plugins.home.html', self) self.fileNameInput = settings.FileNameInput().getFromFileName( fabmetheus_interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Home', self, '') self.openWikiManualHelpPage = settings.HelpPage().getOpenFromAbsolute('http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Home') self.activateHome = settings.BooleanSetting().getFromValue('Activate Home', self, True ) self.nameOfHomeFile = settings.StringSetting().getFromValue('Name of Home File:', self, 'home.gcode') self.executeTitle = 'Home' def execute(self): "Home button has been clicked." fileNames = skeinforge_polyfile.getFileOrDirectoryTypesUnmodifiedGcode(self.fileNameInput.value, fabmetheus_interpret.getImportPluginFileNames(), self.fileNameInput.wasCancelled) for fileName in fileNames: writeOutput(fileName) class HomeSkein: "A class to home a skein of extrusions." def __init__(self): self.distanceFeedRate = gcodec.DistanceFeedRate() self.extruderActive = False self.highestZ = None self.homeLines = [] self.layerCount = settings.LayerCount() self.lineIndex = 0 self.lines = None self.oldLocation = None self.shouldHome = False self.travelFeedRateMinute = 957.0 def addFloat( self, begin, end ): "Add dive to the original height." beginEndDistance = begin.distance(end) alongWay = self.absolutePerimeterWidth / beginEndDistance closeToEnd = euclidean.getIntermediateLocation( alongWay, end, begin ) closeToEnd.z = self.highestZ self.distanceFeedRate.addLine( self.distanceFeedRate.getLinearGcodeMovementWithFeedRate( self.travelFeedRateMinute, closeToEnd.dropAxis(), closeToEnd.z ) ) def addHomeTravel( self, splitLine ): "Add the home travel gcode." location = gcodec.getLocationFromSplitLine(self.oldLocation, splitLine) self.highestZ = max( self.highestZ, location.z ) if not self.shouldHome: return self.shouldHome = False if self.oldLocation == None: return if self.extruderActive: self.distanceFeedRate.addLine('M103') self.addHopUp( self.oldLocation ) self.distanceFeedRate.addLinesSetAbsoluteDistanceMode(self.homeLines) self.addHopUp( self.oldLocation ) self.addFloat( self.oldLocation, location ) if self.extruderActive: self.distanceFeedRate.addLine('M101') def addHopUp(self, location): "Add hop to highest point." locationUp = Vector3( location.x, location.y, self.highestZ ) self.distanceFeedRate.addLine( self.distanceFeedRate.getLinearGcodeMovementWithFeedRate( self.travelFeedRateMinute, locationUp.dropAxis(), locationUp.z ) ) def getCraftedGcode( self, gcodeText, repository ):
def parseInitialization( self, repository ): 'Parse gcode initialization and store the parameters.' for self.lineIndex in xrange(len(self.lines)): line = self.lines[self.lineIndex] splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line) firstWord = gcodec.getFirstWord(splitLine) self.distanceFeedRate.parseSplitLine(firstWord, splitLine) if firstWord == '(</extruderInitialization>)': self.distanceFeedRate.addTagBracketedProcedure('home') return elif firstWord == '(<perimeterWidth>': self.absolutePerimeterWidth = abs(float(splitLine[1])) elif firstWord == '(<travelFeedRatePerSecond>': self.travelFeedRateMinute = 60.0 * float(splitLine[1]) self.distanceFeedRate.addLine(line) def parseLine(self, line): "Parse a gcode line and add it to the bevel gcode." splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line) if len(splitLine) < 1: return firstWord = splitLine[0] if firstWord == 'G1': self.addHomeTravel(splitLine) self.oldLocation = gcodec.getLocationFromSplitLine(self.oldLocation, splitLine) elif firstWord == '(<layer>': self.layerCount.printProgressIncrement('home') if len(self.homeLines) > 0: self.shouldHome = True elif firstWord == 'M101': self.extruderActive = True elif firstWord == 'M103': self.extruderActive = False self.distanceFeedRate.addLine(line) def main(): "Display the home dialog." if len(sys.argv) > 1: writeOutput(' '.join(sys.argv[1 :])) else: settings.startMainLoopFromConstructor(getNewRepository()) if __name__ == "__main__": main()
"Parse gcode text and store the home gcode." self.repository = repository self.homeLines = settings.getAlterationFileLines(repository.nameOfHomeFile.value) if len(self.homeLines) < 1: return gcodeText self.lines = archive.getTextLines(gcodeText) self.parseInitialization( repository ) for self.lineIndex in xrange(self.lineIndex, len(self.lines)): line = self.lines[self.lineIndex] self.parseLine(line) return self.distanceFeedRate.output.getvalue()
identifier_body
home.py
""" This page is in the table of contents. Plugin to home the tool at beginning of each layer. The home manual page is at: http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Home ==Operation== The default 'Activate Home' checkbox is on. When it is on, the functions described below will work, when it is off, nothing will be done. ==Settings== ===Name of Home File=== Default: home.gcode At the beginning of a each layer, home will add the commands of a gcode script with the name of the "Name of Home File" setting, if one exists. Home does not care if the text file names are capitalized, but some file systems do not handle file name cases properly, so to be on the safe side you should give them lower case names. Home looks for those files in the alterations folder in the .skeinforge folder in the home directory. If it doesn't find the file it then looks in the alterations folder in the skeinforge_plugins folder. ==Examples== The following examples home the file Screw Holder Bottom.stl. The examples are run in a terminal in the folder which contains Screw Holder Bottom.stl and home.py. > python home.py This brings up the home dialog. > python home.py Screw Holder Bottom.stl The home tool is parsing the file: Screw Holder Bottom.stl .. The home tool has created the file: .. Screw Holder Bottom_home.gcode """ from __future__ import absolute_import #Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module. import __init__ from fabmetheus_utilities.fabmetheus_tools import fabmetheus_interpret from fabmetheus_utilities.vector3 import Vector3 from fabmetheus_utilities import archive from fabmetheus_utilities import euclidean from fabmetheus_utilities import gcodec from fabmetheus_utilities import settings from skeinforge_application.skeinforge_utilities import skeinforge_craft from skeinforge_application.skeinforge_utilities import skeinforge_polyfile from skeinforge_application.skeinforge_utilities import skeinforge_profile import math import os import sys __author__ = 'Enrique Perez (perez_enrique@yahoo.com)' __date__ = '$Date: 2008/21/04 $' __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' def getCraftedText( fileName, text, repository = None ): "Home a gcode linear move file or text." return getCraftedTextFromText(archive.getTextIfEmpty(fileName, text), repository) def getCraftedTextFromText( gcodeText, repository = None ): "Home a gcode linear move text." if gcodec.isProcedureDoneOrFileIsEmpty( gcodeText, 'home'): return gcodeText if repository == None: repository = settings.getReadRepository( HomeRepository() ) if not repository.activateHome.value: return gcodeText return HomeSkein().getCraftedGcode(gcodeText, repository) def getNewRepository(): 'Get new repository.' return HomeRepository() def writeOutput(fileName, shouldAnalyze=True): "Home a gcode linear move file. Chain home the gcode if it is not already homed." skeinforge_craft.writeChainTextWithNounMessage(fileName, 'home', shouldAnalyze) class HomeRepository: "A class to handle the home settings." def __init__(self): "Set the default settings, execute title & settings fileName." skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_plugins.craft_plugins.home.html', self) self.fileNameInput = settings.FileNameInput().getFromFileName( fabmetheus_interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Home', self, '') self.openWikiManualHelpPage = settings.HelpPage().getOpenFromAbsolute('http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Home') self.activateHome = settings.BooleanSetting().getFromValue('Activate Home', self, True ) self.nameOfHomeFile = settings.StringSetting().getFromValue('Name of Home File:', self, 'home.gcode') self.executeTitle = 'Home' def execute(self): "Home button has been clicked." fileNames = skeinforge_polyfile.getFileOrDirectoryTypesUnmodifiedGcode(self.fileNameInput.value, fabmetheus_interpret.getImportPluginFileNames(), self.fileNameInput.wasCancelled) for fileName in fileNames: writeOutput(fileName) class HomeSkein: "A class to home a skein of extrusions." def __init__(self): self.distanceFeedRate = gcodec.DistanceFeedRate() self.extruderActive = False self.highestZ = None self.homeLines = [] self.layerCount = settings.LayerCount() self.lineIndex = 0 self.lines = None self.oldLocation = None self.shouldHome = False self.travelFeedRateMinute = 957.0 def addFloat( self, begin, end ): "Add dive to the original height." beginEndDistance = begin.distance(end) alongWay = self.absolutePerimeterWidth / beginEndDistance closeToEnd = euclidean.getIntermediateLocation( alongWay, end, begin ) closeToEnd.z = self.highestZ self.distanceFeedRate.addLine( self.distanceFeedRate.getLinearGcodeMovementWithFeedRate( self.travelFeedRateMinute, closeToEnd.dropAxis(), closeToEnd.z ) ) def addHomeTravel( self, splitLine ): "Add the home travel gcode." location = gcodec.getLocationFromSplitLine(self.oldLocation, splitLine) self.highestZ = max( self.highestZ, location.z ) if not self.shouldHome: return self.shouldHome = False if self.oldLocation == None: return if self.extruderActive: self.distanceFeedRate.addLine('M103') self.addHopUp( self.oldLocation ) self.distanceFeedRate.addLinesSetAbsoluteDistanceMode(self.homeLines) self.addHopUp( self.oldLocation ) self.addFloat( self.oldLocation, location ) if self.extruderActive: self.distanceFeedRate.addLine('M101') def addHopUp(self, location): "Add hop to highest point." locationUp = Vector3( location.x, location.y, self.highestZ ) self.distanceFeedRate.addLine( self.distanceFeedRate.getLinearGcodeMovementWithFeedRate( self.travelFeedRateMinute, locationUp.dropAxis(), locationUp.z ) ) def getCraftedGcode( self, gcodeText, repository ): "Parse gcode text and store the home gcode." self.repository = repository self.homeLines = settings.getAlterationFileLines(repository.nameOfHomeFile.value) if len(self.homeLines) < 1: return gcodeText self.lines = archive.getTextLines(gcodeText) self.parseInitialization( repository ) for self.lineIndex in xrange(self.lineIndex, len(self.lines)): line = self.lines[self.lineIndex] self.parseLine(line) return self.distanceFeedRate.output.getvalue() def parseInitialization( self, repository ): 'Parse gcode initialization and store the parameters.' for self.lineIndex in xrange(len(self.lines)): line = self.lines[self.lineIndex] splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line) firstWord = gcodec.getFirstWord(splitLine) self.distanceFeedRate.parseSplitLine(firstWord, splitLine) if firstWord == '(</extruderInitialization>)': self.distanceFeedRate.addTagBracketedProcedure('home') return elif firstWord == '(<perimeterWidth>': self.absolutePerimeterWidth = abs(float(splitLine[1])) elif firstWord == '(<travelFeedRatePerSecond>': self.travelFeedRateMinute = 60.0 * float(splitLine[1]) self.distanceFeedRate.addLine(line) def parseLine(self, line): "Parse a gcode line and add it to the bevel gcode." splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line) if len(splitLine) < 1: return firstWord = splitLine[0] if firstWord == 'G1': self.addHomeTravel(splitLine) self.oldLocation = gcodec.getLocationFromSplitLine(self.oldLocation, splitLine) elif firstWord == '(<layer>': self.layerCount.printProgressIncrement('home') if len(self.homeLines) > 0: self.shouldHome = True elif firstWord == 'M101':
elif firstWord == 'M103': self.extruderActive = False self.distanceFeedRate.addLine(line) def main(): "Display the home dialog." if len(sys.argv) > 1: writeOutput(' '.join(sys.argv[1 :])) else: settings.startMainLoopFromConstructor(getNewRepository()) if __name__ == "__main__": main()
self.extruderActive = True
conditional_block
home.py
""" This page is in the table of contents. Plugin to home the tool at beginning of each layer. The home manual page is at: http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Home ==Operation== The default 'Activate Home' checkbox is on. When it is on, the functions described below will work, when it is off, nothing will be done. ==Settings== ===Name of Home File=== Default: home.gcode At the beginning of a each layer, home will add the commands of a gcode script with the name of the "Name of Home File" setting, if one exists. Home does not care if the text file names are capitalized, but some file systems do not handle file name cases properly, so to be on the safe side you should give them lower case names. Home looks for those files in the alterations folder in the .skeinforge folder in the home directory. If it doesn't find the file it then looks in the alterations folder in the skeinforge_plugins folder. ==Examples== The following examples home the file Screw Holder Bottom.stl. The examples are run in a terminal in the folder which contains Screw Holder Bottom.stl and home.py. > python home.py This brings up the home dialog. > python home.py Screw Holder Bottom.stl The home tool is parsing the file: Screw Holder Bottom.stl .. The home tool has created the file: .. Screw Holder Bottom_home.gcode """ from __future__ import absolute_import #Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module. import __init__ from fabmetheus_utilities.fabmetheus_tools import fabmetheus_interpret from fabmetheus_utilities.vector3 import Vector3 from fabmetheus_utilities import archive from fabmetheus_utilities import euclidean from fabmetheus_utilities import gcodec from fabmetheus_utilities import settings from skeinforge_application.skeinforge_utilities import skeinforge_craft from skeinforge_application.skeinforge_utilities import skeinforge_polyfile from skeinforge_application.skeinforge_utilities import skeinforge_profile import math import os import sys __author__ = 'Enrique Perez (perez_enrique@yahoo.com)' __date__ = '$Date: 2008/21/04 $' __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' def getCraftedText( fileName, text, repository = None ): "Home a gcode linear move file or text." return getCraftedTextFromText(archive.getTextIfEmpty(fileName, text), repository) def getCraftedTextFromText( gcodeText, repository = None ): "Home a gcode linear move text." if gcodec.isProcedureDoneOrFileIsEmpty( gcodeText, 'home'): return gcodeText if repository == None: repository = settings.getReadRepository( HomeRepository() ) if not repository.activateHome.value: return gcodeText return HomeSkein().getCraftedGcode(gcodeText, repository) def getNewRepository(): 'Get new repository.' return HomeRepository() def writeOutput(fileName, shouldAnalyze=True): "Home a gcode linear move file. Chain home the gcode if it is not already homed." skeinforge_craft.writeChainTextWithNounMessage(fileName, 'home', shouldAnalyze) class HomeRepository: "A class to handle the home settings." def __init__(self): "Set the default settings, execute title & settings fileName." skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_plugins.craft_plugins.home.html', self) self.fileNameInput = settings.FileNameInput().getFromFileName( fabmetheus_interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Home', self, '') self.openWikiManualHelpPage = settings.HelpPage().getOpenFromAbsolute('http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Home') self.activateHome = settings.BooleanSetting().getFromValue('Activate Home', self, True ) self.nameOfHomeFile = settings.StringSetting().getFromValue('Name of Home File:', self, 'home.gcode') self.executeTitle = 'Home' def execute(self): "Home button has been clicked." fileNames = skeinforge_polyfile.getFileOrDirectoryTypesUnmodifiedGcode(self.fileNameInput.value, fabmetheus_interpret.getImportPluginFileNames(), self.fileNameInput.wasCancelled) for fileName in fileNames: writeOutput(fileName) class HomeSkein: "A class to home a skein of extrusions." def __init__(self): self.distanceFeedRate = gcodec.DistanceFeedRate() self.extruderActive = False self.highestZ = None self.homeLines = [] self.layerCount = settings.LayerCount() self.lineIndex = 0 self.lines = None self.oldLocation = None self.shouldHome = False self.travelFeedRateMinute = 957.0 def addFloat( self, begin, end ): "Add dive to the original height." beginEndDistance = begin.distance(end) alongWay = self.absolutePerimeterWidth / beginEndDistance closeToEnd = euclidean.getIntermediateLocation( alongWay, end, begin ) closeToEnd.z = self.highestZ self.distanceFeedRate.addLine( self.distanceFeedRate.getLinearGcodeMovementWithFeedRate( self.travelFeedRateMinute, closeToEnd.dropAxis(), closeToEnd.z ) ) def
( self, splitLine ): "Add the home travel gcode." location = gcodec.getLocationFromSplitLine(self.oldLocation, splitLine) self.highestZ = max( self.highestZ, location.z ) if not self.shouldHome: return self.shouldHome = False if self.oldLocation == None: return if self.extruderActive: self.distanceFeedRate.addLine('M103') self.addHopUp( self.oldLocation ) self.distanceFeedRate.addLinesSetAbsoluteDistanceMode(self.homeLines) self.addHopUp( self.oldLocation ) self.addFloat( self.oldLocation, location ) if self.extruderActive: self.distanceFeedRate.addLine('M101') def addHopUp(self, location): "Add hop to highest point." locationUp = Vector3( location.x, location.y, self.highestZ ) self.distanceFeedRate.addLine( self.distanceFeedRate.getLinearGcodeMovementWithFeedRate( self.travelFeedRateMinute, locationUp.dropAxis(), locationUp.z ) ) def getCraftedGcode( self, gcodeText, repository ): "Parse gcode text and store the home gcode." self.repository = repository self.homeLines = settings.getAlterationFileLines(repository.nameOfHomeFile.value) if len(self.homeLines) < 1: return gcodeText self.lines = archive.getTextLines(gcodeText) self.parseInitialization( repository ) for self.lineIndex in xrange(self.lineIndex, len(self.lines)): line = self.lines[self.lineIndex] self.parseLine(line) return self.distanceFeedRate.output.getvalue() def parseInitialization( self, repository ): 'Parse gcode initialization and store the parameters.' for self.lineIndex in xrange(len(self.lines)): line = self.lines[self.lineIndex] splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line) firstWord = gcodec.getFirstWord(splitLine) self.distanceFeedRate.parseSplitLine(firstWord, splitLine) if firstWord == '(</extruderInitialization>)': self.distanceFeedRate.addTagBracketedProcedure('home') return elif firstWord == '(<perimeterWidth>': self.absolutePerimeterWidth = abs(float(splitLine[1])) elif firstWord == '(<travelFeedRatePerSecond>': self.travelFeedRateMinute = 60.0 * float(splitLine[1]) self.distanceFeedRate.addLine(line) def parseLine(self, line): "Parse a gcode line and add it to the bevel gcode." splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line) if len(splitLine) < 1: return firstWord = splitLine[0] if firstWord == 'G1': self.addHomeTravel(splitLine) self.oldLocation = gcodec.getLocationFromSplitLine(self.oldLocation, splitLine) elif firstWord == '(<layer>': self.layerCount.printProgressIncrement('home') if len(self.homeLines) > 0: self.shouldHome = True elif firstWord == 'M101': self.extruderActive = True elif firstWord == 'M103': self.extruderActive = False self.distanceFeedRate.addLine(line) def main(): "Display the home dialog." if len(sys.argv) > 1: writeOutput(' '.join(sys.argv[1 :])) else: settings.startMainLoopFromConstructor(getNewRepository()) if __name__ == "__main__": main()
addHomeTravel
identifier_name
iconDirective.js
angular .module('material.components.icon') .directive('mdIcon', ['$mdIcon', '$mdTheming', '$mdAria', '$sce', mdIconDirective]); /** * @ngdoc directive * @name mdIcon * @module material.components.icon * * @restrict E * * @description * The `md-icon` directive makes it easier to use vector-based icons in your app (as opposed to * raster-based icons types like PNG). The directive supports both icon fonts and SVG icons. * * Icons should be considered view-only elements that should not be used directly as buttons; instead nest a `<md-icon>` * inside a `md-button` to add hover and click features. * * ### Icon fonts * Icon fonts are a technique in which you use a font where the glyphs in the font are * your icons instead of text. Benefits include a straightforward way to bundle everything into a * single HTTP request, simple scaling, easy color changing, and more. * * `md-icon` lets you consume an icon font by letting you reference specific icons in that font * by name rather than character code. * * ### SVG * For SVGs, the problem with using `<img>` or a CSS `background-image` is that you can't take * advantage of some SVG features, such as styling specific parts of the icon with CSS or SVG * animation. * * `md-icon` makes it easier to use SVG icons by *inlining* the SVG into an `<svg>` element in the * document. The most straightforward way of referencing an SVG icon is via URL, just like a * traditional `<img>`. `$mdIconProvider`, as a convenience, lets you _name_ an icon so you can * reference it by name instead of URL throughout your templates. * * Additionally, you may not want to make separate HTTP requests for every icon, so you can bundle * your SVG icons together and pre-load them with $mdIconProvider as an icon set. An icon set can * also be given a name, which acts as a namespace for individual icons, so you can reference them
* When using SVGs, both external SVGs (via URLs) or sets of SVGs [from icon sets] can be * easily loaded and used. When using font-icons, developers must follow three (3) simple steps: * * <ol> * <li>Load the font library. e.g.<br/> * `<link href="https://fonts.googleapis.com/icon?family=Material+Icons" * rel="stylesheet">` * </li> * <li> * Use either (a) font-icon class names or (b) a fontset and a font ligature to render the font glyph by * using its textual name _or_ numerical character reference. Note that `material-icons` is the default fontset when * none is specified. * </li> * <li> Use any of the following templates: <br/> * <ul> * <li>`<md-icon md-font-icon="classname"></md-icon>`</li> * <li>`<md-icon md-font-set="font library classname or alias">textual_name</md-icon>`</li> * <li>`<md-icon> numerical_character_reference </md-icon>`</li> * <li>`<md-icon ng_bind="'textual_name'"></md-icon>`</li> * <li>`<md-icon ng-bind="scopeVariable"></md-icon>`</li> * </ul> * </li> * </ol> * * Full details for these steps can be found: * * <ul> * <li>http://google.github.io/material-design-icons/</li> * <li>http://google.github.io/material-design-icons/#icon-font-for-the-web</li> * </ul> * * The Material Design icon style <code>.material-icons</code> and the icon font references are published in * Material Design Icons: * * <ul> * <li>https://design.google.com/icons/</li> * <li>https://design.google.com/icons/#ic_accessibility</li> * </ul> * * ### Localization * * Because an `md-icon` element's text content is not intended to translated, it is recommended to declare the text * content for an `md-icon` element in its start tag. Instead of using the HTML text content, consider using `ng-bind` * with a scope variable or literal string. * * Examples: * * <ul> * <li>`<md-icon ng-bind="myIconVariable"></md-icon>`</li> * <li>`<md-icon ng-bind="'menu'"></md-icon>` * </ul> * * <h2 id="material_design_icons">Material Design Icons</h2> * Using the Material Design Icon-Selector, developers can easily and quickly search for a Material Design font-icon and * determine its textual name and character reference code. Click on any icon to see the slide-up information * panel with details regarding a SVG download or information on the font-icon usage. * * <a href="https://www.google.com/design/icons/#ic_accessibility" target="_blank" style="border-bottom:none;"> * <img src="https://cloud.githubusercontent.com/assets/210413/7902490/fe8dd14c-0780-11e5-98fb-c821cc6475e6.png" * aria-label="Material Design Icon-Selector" style="max-width:75%;padding-left:10%"> * </a> * * <span class="image_caption"> * Click on the image above to link to the * <a href="https://design.google.com/icons/#ic_accessibility" target="_blank">Material Design Icon-Selector</a>. * </span> * * @param {string} md-font-icon String name of CSS icon associated with the font-face will be used * to render the icon. Requires the fonts and the named CSS styles to be preloaded. * @param {string} md-font-set CSS style name associated with the font library; which will be assigned as * the class for the font-icon ligature. This value may also be an alias that is used to lookup the classname; * internally use `$mdIconProvider.fontSet(<alias>)` to determine the style name. * @param {string} md-svg-src String URL (or expression) used to load, cache, and display an * external SVG. * @param {string} md-svg-icon md-svg-icon String name used for lookup of the icon from the internal cache; * interpolated strings or expressions may also be used. Specific set names can be used with * the syntax `<set name>:<icon name>`.<br/><br/> * To use icon sets, developers are required to pre-register the sets using the `$mdIconProvider` service. * @param {string=} aria-label Labels icon for accessibility. If an empty string is provided, icon * will be hidden from accessibility layer with `aria-hidden="true"`. If there's no aria-label on the icon * nor a label on the parent element, a warning will be logged to the console. * @param {string=} alt Labels icon for accessibility. If an empty string is provided, icon * will be hidden from accessibility layer with `aria-hidden="true"`. If there's no alt on the icon * nor a label on the parent element, a warning will be logged to the console. * * @usage * When using SVGs: * <hljs lang="html"> * * <!-- Icon ID; may contain optional icon set prefix; icons must registered using $mdIconProvider --> * <md-icon md-svg-icon="social:android" aria-label="android " ></md-icon> * * <!-- Icon urls; may be preloaded in templateCache --> * <md-icon md-svg-src="/android.svg" aria-label="android " ></md-icon> * <md-icon md-svg-src="{{ getAndroid() }}" aria-label="android " ></md-icon> * * </hljs> * * Use the <code>$mdIconProvider</code> to configure your application with * svg iconsets. * * <hljs lang="js"> * angular.module('appSvgIconSets', ['ngMaterial']) * .controller('DemoCtrl', function($scope) {}) * .config(function($mdIconProvider) { * $mdIconProvider * .iconSet('social', 'img/icons/sets/social-icons.svg', 24) * .defaultIconSet('img/icons/sets/core-icons.svg', 24); * }); * </hljs> * * * When using Font Icons with classnames: * <hljs lang="html"> * * <md-icon md-font-icon="android" aria-label="android" ></md-icon> * <md-icon class="icon_home" aria-label="Home" ></md-icon> * * </hljs> * * When using Material Font Icons with ligatures: * <hljs lang="html"> * <!-- * For Material Design Icons * The class '.material-icons' is auto-added if a style has NOT been specified * since `material-icons` is the default fontset. So your markup: * --> * <md-icon> face </md-icon> * <!-- becomes this at runtime: --> * <md-icon md-font-set="material-icons"> face </md-icon> * <!-- If the fontset does not support ligature names, then we need to use the ligature unicode.--> * <md-icon> &#xE87C; </md-icon> * <!-- The class '.material-icons' must be manually added if other styles are also specified--> * <md-icon class="material-icons md-light md-48"> face </md-icon> * </hljs> * * When using other Font-Icon libraries: * * <hljs lang="js"> * // Specify a font-icon style alias * angular.config(function($mdIconProvider) { * $mdIconProvider.fontSet('md', 'material-icons'); * }); * </hljs> * * <hljs lang="html"> * <md-icon md-font-set="md">favorite</md-icon> * </hljs> * */ function mdIconDirective($mdIcon, $mdTheming, $mdAria, $sce) { return { restrict: 'E', link : postLink }; /** * Directive postLink * Supports embedded SVGs, font-icons, & external SVGs */ function postLink(scope, element, attr) { $mdTheming(element); var lastFontIcon = attr.mdFontIcon; var lastFontSet = $mdIcon.fontSet(attr.mdFontSet); prepareForFontIcon(); attr.$observe('mdFontIcon', fontIconChanged); attr.$observe('mdFontSet', fontIconChanged); // Keep track of the content of the svg src so we can compare against it later to see if the // attribute is static (and thus safe). var originalSvgSrc = element[0].getAttribute(attr.$attr.mdSvgSrc); // If using a font-icon, then the textual name of the icon itself // provides the aria-label. var label = attr.alt || attr.mdFontIcon || attr.mdSvgIcon || element.text(); var attrName = attr.$normalize(attr.$attr.mdSvgIcon || attr.$attr.mdSvgSrc || ''); if ( !attr['aria-label'] ) { if (label !== '' && !parentsHaveText() ) { $mdAria.expect(element, 'aria-label', label); $mdAria.expect(element, 'role', 'img'); } else if ( !element.text() ) { // If not a font-icon with ligature, then // hide from the accessibility layer. $mdAria.expect(element, 'aria-hidden', 'true'); } } if (attrName) { // Use either pre-configured SVG or URL source, respectively. attr.$observe(attrName, function(attrVal) { element.empty(); if (attrVal) { $mdIcon(attrVal) .then(function(svg) { element.empty(); element.append(svg); }); } }); } function parentsHaveText() { var parent = element.parent(); if (parent.attr('aria-label') || parent.text()) { return true; } else if(parent.parent().attr('aria-label') || parent.parent().text()) { return true; } return false; } function prepareForFontIcon() { if (!attr.mdSvgIcon && !attr.mdSvgSrc) { if (attr.mdFontIcon) { element.addClass('md-font ' + attr.mdFontIcon); } element.addClass(lastFontSet); } } function fontIconChanged() { if (!attr.mdSvgIcon && !attr.mdSvgSrc) { if (attr.mdFontIcon) { element.removeClass(lastFontIcon); element.addClass(attr.mdFontIcon); lastFontIcon = attr.mdFontIcon; } var fontSet = $mdIcon.fontSet(attr.mdFontSet); if (lastFontSet !== fontSet) { element.removeClass(lastFontSet); element.addClass(fontSet); lastFontSet = fontSet; } } } } }
* like `"social:cake"`. *
random_line_split
iconDirective.js
angular .module('material.components.icon') .directive('mdIcon', ['$mdIcon', '$mdTheming', '$mdAria', '$sce', mdIconDirective]); /** * @ngdoc directive * @name mdIcon * @module material.components.icon * * @restrict E * * @description * The `md-icon` directive makes it easier to use vector-based icons in your app (as opposed to * raster-based icons types like PNG). The directive supports both icon fonts and SVG icons. * * Icons should be considered view-only elements that should not be used directly as buttons; instead nest a `<md-icon>` * inside a `md-button` to add hover and click features. * * ### Icon fonts * Icon fonts are a technique in which you use a font where the glyphs in the font are * your icons instead of text. Benefits include a straightforward way to bundle everything into a * single HTTP request, simple scaling, easy color changing, and more. * * `md-icon` lets you consume an icon font by letting you reference specific icons in that font * by name rather than character code. * * ### SVG * For SVGs, the problem with using `<img>` or a CSS `background-image` is that you can't take * advantage of some SVG features, such as styling specific parts of the icon with CSS or SVG * animation. * * `md-icon` makes it easier to use SVG icons by *inlining* the SVG into an `<svg>` element in the * document. The most straightforward way of referencing an SVG icon is via URL, just like a * traditional `<img>`. `$mdIconProvider`, as a convenience, lets you _name_ an icon so you can * reference it by name instead of URL throughout your templates. * * Additionally, you may not want to make separate HTTP requests for every icon, so you can bundle * your SVG icons together and pre-load them with $mdIconProvider as an icon set. An icon set can * also be given a name, which acts as a namespace for individual icons, so you can reference them * like `"social:cake"`. * * When using SVGs, both external SVGs (via URLs) or sets of SVGs [from icon sets] can be * easily loaded and used. When using font-icons, developers must follow three (3) simple steps: * * <ol> * <li>Load the font library. e.g.<br/> * `<link href="https://fonts.googleapis.com/icon?family=Material+Icons" * rel="stylesheet">` * </li> * <li> * Use either (a) font-icon class names or (b) a fontset and a font ligature to render the font glyph by * using its textual name _or_ numerical character reference. Note that `material-icons` is the default fontset when * none is specified. * </li> * <li> Use any of the following templates: <br/> * <ul> * <li>`<md-icon md-font-icon="classname"></md-icon>`</li> * <li>`<md-icon md-font-set="font library classname or alias">textual_name</md-icon>`</li> * <li>`<md-icon> numerical_character_reference </md-icon>`</li> * <li>`<md-icon ng_bind="'textual_name'"></md-icon>`</li> * <li>`<md-icon ng-bind="scopeVariable"></md-icon>`</li> * </ul> * </li> * </ol> * * Full details for these steps can be found: * * <ul> * <li>http://google.github.io/material-design-icons/</li> * <li>http://google.github.io/material-design-icons/#icon-font-for-the-web</li> * </ul> * * The Material Design icon style <code>.material-icons</code> and the icon font references are published in * Material Design Icons: * * <ul> * <li>https://design.google.com/icons/</li> * <li>https://design.google.com/icons/#ic_accessibility</li> * </ul> * * ### Localization * * Because an `md-icon` element's text content is not intended to translated, it is recommended to declare the text * content for an `md-icon` element in its start tag. Instead of using the HTML text content, consider using `ng-bind` * with a scope variable or literal string. * * Examples: * * <ul> * <li>`<md-icon ng-bind="myIconVariable"></md-icon>`</li> * <li>`<md-icon ng-bind="'menu'"></md-icon>` * </ul> * * <h2 id="material_design_icons">Material Design Icons</h2> * Using the Material Design Icon-Selector, developers can easily and quickly search for a Material Design font-icon and * determine its textual name and character reference code. Click on any icon to see the slide-up information * panel with details regarding a SVG download or information on the font-icon usage. * * <a href="https://www.google.com/design/icons/#ic_accessibility" target="_blank" style="border-bottom:none;"> * <img src="https://cloud.githubusercontent.com/assets/210413/7902490/fe8dd14c-0780-11e5-98fb-c821cc6475e6.png" * aria-label="Material Design Icon-Selector" style="max-width:75%;padding-left:10%"> * </a> * * <span class="image_caption"> * Click on the image above to link to the * <a href="https://design.google.com/icons/#ic_accessibility" target="_blank">Material Design Icon-Selector</a>. * </span> * * @param {string} md-font-icon String name of CSS icon associated with the font-face will be used * to render the icon. Requires the fonts and the named CSS styles to be preloaded. * @param {string} md-font-set CSS style name associated with the font library; which will be assigned as * the class for the font-icon ligature. This value may also be an alias that is used to lookup the classname; * internally use `$mdIconProvider.fontSet(<alias>)` to determine the style name. * @param {string} md-svg-src String URL (or expression) used to load, cache, and display an * external SVG. * @param {string} md-svg-icon md-svg-icon String name used for lookup of the icon from the internal cache; * interpolated strings or expressions may also be used. Specific set names can be used with * the syntax `<set name>:<icon name>`.<br/><br/> * To use icon sets, developers are required to pre-register the sets using the `$mdIconProvider` service. * @param {string=} aria-label Labels icon for accessibility. If an empty string is provided, icon * will be hidden from accessibility layer with `aria-hidden="true"`. If there's no aria-label on the icon * nor a label on the parent element, a warning will be logged to the console. * @param {string=} alt Labels icon for accessibility. If an empty string is provided, icon * will be hidden from accessibility layer with `aria-hidden="true"`. If there's no alt on the icon * nor a label on the parent element, a warning will be logged to the console. * * @usage * When using SVGs: * <hljs lang="html"> * * <!-- Icon ID; may contain optional icon set prefix; icons must registered using $mdIconProvider --> * <md-icon md-svg-icon="social:android" aria-label="android " ></md-icon> * * <!-- Icon urls; may be preloaded in templateCache --> * <md-icon md-svg-src="/android.svg" aria-label="android " ></md-icon> * <md-icon md-svg-src="{{ getAndroid() }}" aria-label="android " ></md-icon> * * </hljs> * * Use the <code>$mdIconProvider</code> to configure your application with * svg iconsets. * * <hljs lang="js"> * angular.module('appSvgIconSets', ['ngMaterial']) * .controller('DemoCtrl', function($scope) {}) * .config(function($mdIconProvider) { * $mdIconProvider * .iconSet('social', 'img/icons/sets/social-icons.svg', 24) * .defaultIconSet('img/icons/sets/core-icons.svg', 24); * }); * </hljs> * * * When using Font Icons with classnames: * <hljs lang="html"> * * <md-icon md-font-icon="android" aria-label="android" ></md-icon> * <md-icon class="icon_home" aria-label="Home" ></md-icon> * * </hljs> * * When using Material Font Icons with ligatures: * <hljs lang="html"> * <!-- * For Material Design Icons * The class '.material-icons' is auto-added if a style has NOT been specified * since `material-icons` is the default fontset. So your markup: * --> * <md-icon> face </md-icon> * <!-- becomes this at runtime: --> * <md-icon md-font-set="material-icons"> face </md-icon> * <!-- If the fontset does not support ligature names, then we need to use the ligature unicode.--> * <md-icon> &#xE87C; </md-icon> * <!-- The class '.material-icons' must be manually added if other styles are also specified--> * <md-icon class="material-icons md-light md-48"> face </md-icon> * </hljs> * * When using other Font-Icon libraries: * * <hljs lang="js"> * // Specify a font-icon style alias * angular.config(function($mdIconProvider) { * $mdIconProvider.fontSet('md', 'material-icons'); * }); * </hljs> * * <hljs lang="html"> * <md-icon md-font-set="md">favorite</md-icon> * </hljs> * */ function mdIconDirective($mdIcon, $mdTheming, $mdAria, $sce) { return { restrict: 'E', link : postLink }; /** * Directive postLink * Supports embedded SVGs, font-icons, & external SVGs */ function postLink(scope, element, attr) { $mdTheming(element); var lastFontIcon = attr.mdFontIcon; var lastFontSet = $mdIcon.fontSet(attr.mdFontSet); prepareForFontIcon(); attr.$observe('mdFontIcon', fontIconChanged); attr.$observe('mdFontSet', fontIconChanged); // Keep track of the content of the svg src so we can compare against it later to see if the // attribute is static (and thus safe). var originalSvgSrc = element[0].getAttribute(attr.$attr.mdSvgSrc); // If using a font-icon, then the textual name of the icon itself // provides the aria-label. var label = attr.alt || attr.mdFontIcon || attr.mdSvgIcon || element.text(); var attrName = attr.$normalize(attr.$attr.mdSvgIcon || attr.$attr.mdSvgSrc || ''); if ( !attr['aria-label'] ) { if (label !== '' && !parentsHaveText() ) { $mdAria.expect(element, 'aria-label', label); $mdAria.expect(element, 'role', 'img'); } else if ( !element.text() ) { // If not a font-icon with ligature, then // hide from the accessibility layer. $mdAria.expect(element, 'aria-hidden', 'true'); } } if (attrName) { // Use either pre-configured SVG or URL source, respectively. attr.$observe(attrName, function(attrVal) { element.empty(); if (attrVal) { $mdIcon(attrVal) .then(function(svg) { element.empty(); element.append(svg); }); } }); } function
() { var parent = element.parent(); if (parent.attr('aria-label') || parent.text()) { return true; } else if(parent.parent().attr('aria-label') || parent.parent().text()) { return true; } return false; } function prepareForFontIcon() { if (!attr.mdSvgIcon && !attr.mdSvgSrc) { if (attr.mdFontIcon) { element.addClass('md-font ' + attr.mdFontIcon); } element.addClass(lastFontSet); } } function fontIconChanged() { if (!attr.mdSvgIcon && !attr.mdSvgSrc) { if (attr.mdFontIcon) { element.removeClass(lastFontIcon); element.addClass(attr.mdFontIcon); lastFontIcon = attr.mdFontIcon; } var fontSet = $mdIcon.fontSet(attr.mdFontSet); if (lastFontSet !== fontSet) { element.removeClass(lastFontSet); element.addClass(fontSet); lastFontSet = fontSet; } } } } }
parentsHaveText
identifier_name
iconDirective.js
angular .module('material.components.icon') .directive('mdIcon', ['$mdIcon', '$mdTheming', '$mdAria', '$sce', mdIconDirective]); /** * @ngdoc directive * @name mdIcon * @module material.components.icon * * @restrict E * * @description * The `md-icon` directive makes it easier to use vector-based icons in your app (as opposed to * raster-based icons types like PNG). The directive supports both icon fonts and SVG icons. * * Icons should be considered view-only elements that should not be used directly as buttons; instead nest a `<md-icon>` * inside a `md-button` to add hover and click features. * * ### Icon fonts * Icon fonts are a technique in which you use a font where the glyphs in the font are * your icons instead of text. Benefits include a straightforward way to bundle everything into a * single HTTP request, simple scaling, easy color changing, and more. * * `md-icon` lets you consume an icon font by letting you reference specific icons in that font * by name rather than character code. * * ### SVG * For SVGs, the problem with using `<img>` or a CSS `background-image` is that you can't take * advantage of some SVG features, such as styling specific parts of the icon with CSS or SVG * animation. * * `md-icon` makes it easier to use SVG icons by *inlining* the SVG into an `<svg>` element in the * document. The most straightforward way of referencing an SVG icon is via URL, just like a * traditional `<img>`. `$mdIconProvider`, as a convenience, lets you _name_ an icon so you can * reference it by name instead of URL throughout your templates. * * Additionally, you may not want to make separate HTTP requests for every icon, so you can bundle * your SVG icons together and pre-load them with $mdIconProvider as an icon set. An icon set can * also be given a name, which acts as a namespace for individual icons, so you can reference them * like `"social:cake"`. * * When using SVGs, both external SVGs (via URLs) or sets of SVGs [from icon sets] can be * easily loaded and used. When using font-icons, developers must follow three (3) simple steps: * * <ol> * <li>Load the font library. e.g.<br/> * `<link href="https://fonts.googleapis.com/icon?family=Material+Icons" * rel="stylesheet">` * </li> * <li> * Use either (a) font-icon class names or (b) a fontset and a font ligature to render the font glyph by * using its textual name _or_ numerical character reference. Note that `material-icons` is the default fontset when * none is specified. * </li> * <li> Use any of the following templates: <br/> * <ul> * <li>`<md-icon md-font-icon="classname"></md-icon>`</li> * <li>`<md-icon md-font-set="font library classname or alias">textual_name</md-icon>`</li> * <li>`<md-icon> numerical_character_reference </md-icon>`</li> * <li>`<md-icon ng_bind="'textual_name'"></md-icon>`</li> * <li>`<md-icon ng-bind="scopeVariable"></md-icon>`</li> * </ul> * </li> * </ol> * * Full details for these steps can be found: * * <ul> * <li>http://google.github.io/material-design-icons/</li> * <li>http://google.github.io/material-design-icons/#icon-font-for-the-web</li> * </ul> * * The Material Design icon style <code>.material-icons</code> and the icon font references are published in * Material Design Icons: * * <ul> * <li>https://design.google.com/icons/</li> * <li>https://design.google.com/icons/#ic_accessibility</li> * </ul> * * ### Localization * * Because an `md-icon` element's text content is not intended to translated, it is recommended to declare the text * content for an `md-icon` element in its start tag. Instead of using the HTML text content, consider using `ng-bind` * with a scope variable or literal string. * * Examples: * * <ul> * <li>`<md-icon ng-bind="myIconVariable"></md-icon>`</li> * <li>`<md-icon ng-bind="'menu'"></md-icon>` * </ul> * * <h2 id="material_design_icons">Material Design Icons</h2> * Using the Material Design Icon-Selector, developers can easily and quickly search for a Material Design font-icon and * determine its textual name and character reference code. Click on any icon to see the slide-up information * panel with details regarding a SVG download or information on the font-icon usage. * * <a href="https://www.google.com/design/icons/#ic_accessibility" target="_blank" style="border-bottom:none;"> * <img src="https://cloud.githubusercontent.com/assets/210413/7902490/fe8dd14c-0780-11e5-98fb-c821cc6475e6.png" * aria-label="Material Design Icon-Selector" style="max-width:75%;padding-left:10%"> * </a> * * <span class="image_caption"> * Click on the image above to link to the * <a href="https://design.google.com/icons/#ic_accessibility" target="_blank">Material Design Icon-Selector</a>. * </span> * * @param {string} md-font-icon String name of CSS icon associated with the font-face will be used * to render the icon. Requires the fonts and the named CSS styles to be preloaded. * @param {string} md-font-set CSS style name associated with the font library; which will be assigned as * the class for the font-icon ligature. This value may also be an alias that is used to lookup the classname; * internally use `$mdIconProvider.fontSet(<alias>)` to determine the style name. * @param {string} md-svg-src String URL (or expression) used to load, cache, and display an * external SVG. * @param {string} md-svg-icon md-svg-icon String name used for lookup of the icon from the internal cache; * interpolated strings or expressions may also be used. Specific set names can be used with * the syntax `<set name>:<icon name>`.<br/><br/> * To use icon sets, developers are required to pre-register the sets using the `$mdIconProvider` service. * @param {string=} aria-label Labels icon for accessibility. If an empty string is provided, icon * will be hidden from accessibility layer with `aria-hidden="true"`. If there's no aria-label on the icon * nor a label on the parent element, a warning will be logged to the console. * @param {string=} alt Labels icon for accessibility. If an empty string is provided, icon * will be hidden from accessibility layer with `aria-hidden="true"`. If there's no alt on the icon * nor a label on the parent element, a warning will be logged to the console. * * @usage * When using SVGs: * <hljs lang="html"> * * <!-- Icon ID; may contain optional icon set prefix; icons must registered using $mdIconProvider --> * <md-icon md-svg-icon="social:android" aria-label="android " ></md-icon> * * <!-- Icon urls; may be preloaded in templateCache --> * <md-icon md-svg-src="/android.svg" aria-label="android " ></md-icon> * <md-icon md-svg-src="{{ getAndroid() }}" aria-label="android " ></md-icon> * * </hljs> * * Use the <code>$mdIconProvider</code> to configure your application with * svg iconsets. * * <hljs lang="js"> * angular.module('appSvgIconSets', ['ngMaterial']) * .controller('DemoCtrl', function($scope) {}) * .config(function($mdIconProvider) { * $mdIconProvider * .iconSet('social', 'img/icons/sets/social-icons.svg', 24) * .defaultIconSet('img/icons/sets/core-icons.svg', 24); * }); * </hljs> * * * When using Font Icons with classnames: * <hljs lang="html"> * * <md-icon md-font-icon="android" aria-label="android" ></md-icon> * <md-icon class="icon_home" aria-label="Home" ></md-icon> * * </hljs> * * When using Material Font Icons with ligatures: * <hljs lang="html"> * <!-- * For Material Design Icons * The class '.material-icons' is auto-added if a style has NOT been specified * since `material-icons` is the default fontset. So your markup: * --> * <md-icon> face </md-icon> * <!-- becomes this at runtime: --> * <md-icon md-font-set="material-icons"> face </md-icon> * <!-- If the fontset does not support ligature names, then we need to use the ligature unicode.--> * <md-icon> &#xE87C; </md-icon> * <!-- The class '.material-icons' must be manually added if other styles are also specified--> * <md-icon class="material-icons md-light md-48"> face </md-icon> * </hljs> * * When using other Font-Icon libraries: * * <hljs lang="js"> * // Specify a font-icon style alias * angular.config(function($mdIconProvider) { * $mdIconProvider.fontSet('md', 'material-icons'); * }); * </hljs> * * <hljs lang="html"> * <md-icon md-font-set="md">favorite</md-icon> * </hljs> * */ function mdIconDirective($mdIcon, $mdTheming, $mdAria, $sce) { return { restrict: 'E', link : postLink }; /** * Directive postLink * Supports embedded SVGs, font-icons, & external SVGs */ function postLink(scope, element, attr) { $mdTheming(element); var lastFontIcon = attr.mdFontIcon; var lastFontSet = $mdIcon.fontSet(attr.mdFontSet); prepareForFontIcon(); attr.$observe('mdFontIcon', fontIconChanged); attr.$observe('mdFontSet', fontIconChanged); // Keep track of the content of the svg src so we can compare against it later to see if the // attribute is static (and thus safe). var originalSvgSrc = element[0].getAttribute(attr.$attr.mdSvgSrc); // If using a font-icon, then the textual name of the icon itself // provides the aria-label. var label = attr.alt || attr.mdFontIcon || attr.mdSvgIcon || element.text(); var attrName = attr.$normalize(attr.$attr.mdSvgIcon || attr.$attr.mdSvgSrc || ''); if ( !attr['aria-label'] ) { if (label !== '' && !parentsHaveText() ) { $mdAria.expect(element, 'aria-label', label); $mdAria.expect(element, 'role', 'img'); } else if ( !element.text() ) { // If not a font-icon with ligature, then // hide from the accessibility layer. $mdAria.expect(element, 'aria-hidden', 'true'); } } if (attrName) { // Use either pre-configured SVG or URL source, respectively. attr.$observe(attrName, function(attrVal) { element.empty(); if (attrVal) { $mdIcon(attrVal) .then(function(svg) { element.empty(); element.append(svg); }); } }); } function parentsHaveText() { var parent = element.parent(); if (parent.attr('aria-label') || parent.text()) { return true; } else if(parent.parent().attr('aria-label') || parent.parent().text()) { return true; } return false; } function prepareForFontIcon()
function fontIconChanged() { if (!attr.mdSvgIcon && !attr.mdSvgSrc) { if (attr.mdFontIcon) { element.removeClass(lastFontIcon); element.addClass(attr.mdFontIcon); lastFontIcon = attr.mdFontIcon; } var fontSet = $mdIcon.fontSet(attr.mdFontSet); if (lastFontSet !== fontSet) { element.removeClass(lastFontSet); element.addClass(fontSet); lastFontSet = fontSet; } } } } }
{ if (!attr.mdSvgIcon && !attr.mdSvgSrc) { if (attr.mdFontIcon) { element.addClass('md-font ' + attr.mdFontIcon); } element.addClass(lastFontSet); } }
identifier_body
iconDirective.js
angular .module('material.components.icon') .directive('mdIcon', ['$mdIcon', '$mdTheming', '$mdAria', '$sce', mdIconDirective]); /** * @ngdoc directive * @name mdIcon * @module material.components.icon * * @restrict E * * @description * The `md-icon` directive makes it easier to use vector-based icons in your app (as opposed to * raster-based icons types like PNG). The directive supports both icon fonts and SVG icons. * * Icons should be considered view-only elements that should not be used directly as buttons; instead nest a `<md-icon>` * inside a `md-button` to add hover and click features. * * ### Icon fonts * Icon fonts are a technique in which you use a font where the glyphs in the font are * your icons instead of text. Benefits include a straightforward way to bundle everything into a * single HTTP request, simple scaling, easy color changing, and more. * * `md-icon` lets you consume an icon font by letting you reference specific icons in that font * by name rather than character code. * * ### SVG * For SVGs, the problem with using `<img>` or a CSS `background-image` is that you can't take * advantage of some SVG features, such as styling specific parts of the icon with CSS or SVG * animation. * * `md-icon` makes it easier to use SVG icons by *inlining* the SVG into an `<svg>` element in the * document. The most straightforward way of referencing an SVG icon is via URL, just like a * traditional `<img>`. `$mdIconProvider`, as a convenience, lets you _name_ an icon so you can * reference it by name instead of URL throughout your templates. * * Additionally, you may not want to make separate HTTP requests for every icon, so you can bundle * your SVG icons together and pre-load them with $mdIconProvider as an icon set. An icon set can * also be given a name, which acts as a namespace for individual icons, so you can reference them * like `"social:cake"`. * * When using SVGs, both external SVGs (via URLs) or sets of SVGs [from icon sets] can be * easily loaded and used. When using font-icons, developers must follow three (3) simple steps: * * <ol> * <li>Load the font library. e.g.<br/> * `<link href="https://fonts.googleapis.com/icon?family=Material+Icons" * rel="stylesheet">` * </li> * <li> * Use either (a) font-icon class names or (b) a fontset and a font ligature to render the font glyph by * using its textual name _or_ numerical character reference. Note that `material-icons` is the default fontset when * none is specified. * </li> * <li> Use any of the following templates: <br/> * <ul> * <li>`<md-icon md-font-icon="classname"></md-icon>`</li> * <li>`<md-icon md-font-set="font library classname or alias">textual_name</md-icon>`</li> * <li>`<md-icon> numerical_character_reference </md-icon>`</li> * <li>`<md-icon ng_bind="'textual_name'"></md-icon>`</li> * <li>`<md-icon ng-bind="scopeVariable"></md-icon>`</li> * </ul> * </li> * </ol> * * Full details for these steps can be found: * * <ul> * <li>http://google.github.io/material-design-icons/</li> * <li>http://google.github.io/material-design-icons/#icon-font-for-the-web</li> * </ul> * * The Material Design icon style <code>.material-icons</code> and the icon font references are published in * Material Design Icons: * * <ul> * <li>https://design.google.com/icons/</li> * <li>https://design.google.com/icons/#ic_accessibility</li> * </ul> * * ### Localization * * Because an `md-icon` element's text content is not intended to translated, it is recommended to declare the text * content for an `md-icon` element in its start tag. Instead of using the HTML text content, consider using `ng-bind` * with a scope variable or literal string. * * Examples: * * <ul> * <li>`<md-icon ng-bind="myIconVariable"></md-icon>`</li> * <li>`<md-icon ng-bind="'menu'"></md-icon>` * </ul> * * <h2 id="material_design_icons">Material Design Icons</h2> * Using the Material Design Icon-Selector, developers can easily and quickly search for a Material Design font-icon and * determine its textual name and character reference code. Click on any icon to see the slide-up information * panel with details regarding a SVG download or information on the font-icon usage. * * <a href="https://www.google.com/design/icons/#ic_accessibility" target="_blank" style="border-bottom:none;"> * <img src="https://cloud.githubusercontent.com/assets/210413/7902490/fe8dd14c-0780-11e5-98fb-c821cc6475e6.png" * aria-label="Material Design Icon-Selector" style="max-width:75%;padding-left:10%"> * </a> * * <span class="image_caption"> * Click on the image above to link to the * <a href="https://design.google.com/icons/#ic_accessibility" target="_blank">Material Design Icon-Selector</a>. * </span> * * @param {string} md-font-icon String name of CSS icon associated with the font-face will be used * to render the icon. Requires the fonts and the named CSS styles to be preloaded. * @param {string} md-font-set CSS style name associated with the font library; which will be assigned as * the class for the font-icon ligature. This value may also be an alias that is used to lookup the classname; * internally use `$mdIconProvider.fontSet(<alias>)` to determine the style name. * @param {string} md-svg-src String URL (or expression) used to load, cache, and display an * external SVG. * @param {string} md-svg-icon md-svg-icon String name used for lookup of the icon from the internal cache; * interpolated strings or expressions may also be used. Specific set names can be used with * the syntax `<set name>:<icon name>`.<br/><br/> * To use icon sets, developers are required to pre-register the sets using the `$mdIconProvider` service. * @param {string=} aria-label Labels icon for accessibility. If an empty string is provided, icon * will be hidden from accessibility layer with `aria-hidden="true"`. If there's no aria-label on the icon * nor a label on the parent element, a warning will be logged to the console. * @param {string=} alt Labels icon for accessibility. If an empty string is provided, icon * will be hidden from accessibility layer with `aria-hidden="true"`. If there's no alt on the icon * nor a label on the parent element, a warning will be logged to the console. * * @usage * When using SVGs: * <hljs lang="html"> * * <!-- Icon ID; may contain optional icon set prefix; icons must registered using $mdIconProvider --> * <md-icon md-svg-icon="social:android" aria-label="android " ></md-icon> * * <!-- Icon urls; may be preloaded in templateCache --> * <md-icon md-svg-src="/android.svg" aria-label="android " ></md-icon> * <md-icon md-svg-src="{{ getAndroid() }}" aria-label="android " ></md-icon> * * </hljs> * * Use the <code>$mdIconProvider</code> to configure your application with * svg iconsets. * * <hljs lang="js"> * angular.module('appSvgIconSets', ['ngMaterial']) * .controller('DemoCtrl', function($scope) {}) * .config(function($mdIconProvider) { * $mdIconProvider * .iconSet('social', 'img/icons/sets/social-icons.svg', 24) * .defaultIconSet('img/icons/sets/core-icons.svg', 24); * }); * </hljs> * * * When using Font Icons with classnames: * <hljs lang="html"> * * <md-icon md-font-icon="android" aria-label="android" ></md-icon> * <md-icon class="icon_home" aria-label="Home" ></md-icon> * * </hljs> * * When using Material Font Icons with ligatures: * <hljs lang="html"> * <!-- * For Material Design Icons * The class '.material-icons' is auto-added if a style has NOT been specified * since `material-icons` is the default fontset. So your markup: * --> * <md-icon> face </md-icon> * <!-- becomes this at runtime: --> * <md-icon md-font-set="material-icons"> face </md-icon> * <!-- If the fontset does not support ligature names, then we need to use the ligature unicode.--> * <md-icon> &#xE87C; </md-icon> * <!-- The class '.material-icons' must be manually added if other styles are also specified--> * <md-icon class="material-icons md-light md-48"> face </md-icon> * </hljs> * * When using other Font-Icon libraries: * * <hljs lang="js"> * // Specify a font-icon style alias * angular.config(function($mdIconProvider) { * $mdIconProvider.fontSet('md', 'material-icons'); * }); * </hljs> * * <hljs lang="html"> * <md-icon md-font-set="md">favorite</md-icon> * </hljs> * */ function mdIconDirective($mdIcon, $mdTheming, $mdAria, $sce) { return { restrict: 'E', link : postLink }; /** * Directive postLink * Supports embedded SVGs, font-icons, & external SVGs */ function postLink(scope, element, attr) { $mdTheming(element); var lastFontIcon = attr.mdFontIcon; var lastFontSet = $mdIcon.fontSet(attr.mdFontSet); prepareForFontIcon(); attr.$observe('mdFontIcon', fontIconChanged); attr.$observe('mdFontSet', fontIconChanged); // Keep track of the content of the svg src so we can compare against it later to see if the // attribute is static (and thus safe). var originalSvgSrc = element[0].getAttribute(attr.$attr.mdSvgSrc); // If using a font-icon, then the textual name of the icon itself // provides the aria-label. var label = attr.alt || attr.mdFontIcon || attr.mdSvgIcon || element.text(); var attrName = attr.$normalize(attr.$attr.mdSvgIcon || attr.$attr.mdSvgSrc || ''); if ( !attr['aria-label'] ) { if (label !== '' && !parentsHaveText() ) { $mdAria.expect(element, 'aria-label', label); $mdAria.expect(element, 'role', 'img'); } else if ( !element.text() )
} if (attrName) { // Use either pre-configured SVG or URL source, respectively. attr.$observe(attrName, function(attrVal) { element.empty(); if (attrVal) { $mdIcon(attrVal) .then(function(svg) { element.empty(); element.append(svg); }); } }); } function parentsHaveText() { var parent = element.parent(); if (parent.attr('aria-label') || parent.text()) { return true; } else if(parent.parent().attr('aria-label') || parent.parent().text()) { return true; } return false; } function prepareForFontIcon() { if (!attr.mdSvgIcon && !attr.mdSvgSrc) { if (attr.mdFontIcon) { element.addClass('md-font ' + attr.mdFontIcon); } element.addClass(lastFontSet); } } function fontIconChanged() { if (!attr.mdSvgIcon && !attr.mdSvgSrc) { if (attr.mdFontIcon) { element.removeClass(lastFontIcon); element.addClass(attr.mdFontIcon); lastFontIcon = attr.mdFontIcon; } var fontSet = $mdIcon.fontSet(attr.mdFontSet); if (lastFontSet !== fontSet) { element.removeClass(lastFontSet); element.addClass(fontSet); lastFontSet = fontSet; } } } } }
{ // If not a font-icon with ligature, then // hide from the accessibility layer. $mdAria.expect(element, 'aria-hidden', 'true'); }
conditional_block
admin.py
from django.contrib import admin from .models import Lesson, Course, CourseLead, QA # from django.utils.translation import ugettext_lazy as _ from ordered_model.admin import OrderedModelAdmin from core.models import User # from adminfilters.models import Species, Breed class UserAdminInline(admin.TabularInline): model = User @admin.register(Lesson) class LessonAdmin(admin.ModelAdmin): ordering = ['-start'] list_filter = ('student', ) list_display = ('start', 'student') save_as = True # raw_id_fields = ("student",) # inlines = [UserAdminInline] @admin.register(Course) class CourseAdmin(admin.ModelAdmin): list_display = ('name', 'slug', 'published', ) ordering = ['id'] @admin.register(CourseLead) class CourseLeadAdmin(admin.ModelAdmin): list_display = ( 'name', 'contact', 'course', 'status', 'student', ) list_filter = ('status', ) ordering = ['status'] @admin.register(QA) class
(OrderedModelAdmin): list_display = ( 'order', 'question', 'move_up_down_links', ) # list_filter = ('status', ) list_display_links = ('question', ) ordering = ['order']
QAAdmin
identifier_name
admin.py
from django.contrib import admin from .models import Lesson, Course, CourseLead, QA # from django.utils.translation import ugettext_lazy as _ from ordered_model.admin import OrderedModelAdmin from core.models import User # from adminfilters.models import Species, Breed class UserAdminInline(admin.TabularInline): model = User @admin.register(Lesson) class LessonAdmin(admin.ModelAdmin): ordering = ['-start'] list_filter = ('student', ) list_display = ('start', 'student') save_as = True # raw_id_fields = ("student",) # inlines = [UserAdminInline] @admin.register(Course) class CourseAdmin(admin.ModelAdmin): list_display = ('name', 'slug', 'published', ) ordering = ['id'] @admin.register(CourseLead) class CourseLeadAdmin(admin.ModelAdmin): list_display = ( 'name', 'contact', 'course', 'status', 'student',
@admin.register(QA) class QAAdmin(OrderedModelAdmin): list_display = ( 'order', 'question', 'move_up_down_links', ) # list_filter = ('status', ) list_display_links = ('question', ) ordering = ['order']
) list_filter = ('status', ) ordering = ['status']
random_line_split
admin.py
from django.contrib import admin from .models import Lesson, Course, CourseLead, QA # from django.utils.translation import ugettext_lazy as _ from ordered_model.admin import OrderedModelAdmin from core.models import User # from adminfilters.models import Species, Breed class UserAdminInline(admin.TabularInline): model = User @admin.register(Lesson) class LessonAdmin(admin.ModelAdmin): ordering = ['-start'] list_filter = ('student', ) list_display = ('start', 'student') save_as = True # raw_id_fields = ("student",) # inlines = [UserAdminInline] @admin.register(Course) class CourseAdmin(admin.ModelAdmin): list_display = ('name', 'slug', 'published', ) ordering = ['id'] @admin.register(CourseLead) class CourseLeadAdmin(admin.ModelAdmin): list_display = ( 'name', 'contact', 'course', 'status', 'student', ) list_filter = ('status', ) ordering = ['status'] @admin.register(QA) class QAAdmin(OrderedModelAdmin):
list_display = ( 'order', 'question', 'move_up_down_links', ) # list_filter = ('status', ) list_display_links = ('question', ) ordering = ['order']
identifier_body
structured-compare.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[deriving(Show)] enum foo { large, small, } impl Copy for foo {} impl PartialEq for foo { fn eq(&self, other: &foo) -> bool { ((*self) as uint) == ((*other) as uint) } fn ne(&self, other: &foo) -> bool
} pub fn main() { let a = (1i, 2i, 3i); let b = (1i, 2i, 3i); assert_eq!(a, b); assert!((a != (1, 2, 4))); assert!((a < (1, 2, 4))); assert!((a <= (1, 2, 4))); assert!(((1i, 2i, 4i) > a)); assert!(((1i, 2i, 4i) >= a)); let x = foo::large; let y = foo::small; assert!((x != y)); assert_eq!(x, foo::large); assert!((x != foo::small)); }
{ !(*self).eq(other) }
identifier_body
structured-compare.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[deriving(Show)] enum foo { large, small, } impl Copy for foo {} impl PartialEq for foo { fn eq(&self, other: &foo) -> bool { ((*self) as uint) == ((*other) as uint) } fn ne(&self, other: &foo) -> bool { !(*self).eq(other) } } pub fn
() { let a = (1i, 2i, 3i); let b = (1i, 2i, 3i); assert_eq!(a, b); assert!((a != (1, 2, 4))); assert!((a < (1, 2, 4))); assert!((a <= (1, 2, 4))); assert!(((1i, 2i, 4i) > a)); assert!(((1i, 2i, 4i) >= a)); let x = foo::large; let y = foo::small; assert!((x != y)); assert_eq!(x, foo::large); assert!((x != foo::small)); }
main
identifier_name
structured-compare.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[deriving(Show)] enum foo { large, small, } impl Copy for foo {} impl PartialEq for foo { fn eq(&self, other: &foo) -> bool { ((*self) as uint) == ((*other) as uint)
pub fn main() { let a = (1i, 2i, 3i); let b = (1i, 2i, 3i); assert_eq!(a, b); assert!((a != (1, 2, 4))); assert!((a < (1, 2, 4))); assert!((a <= (1, 2, 4))); assert!(((1i, 2i, 4i) > a)); assert!(((1i, 2i, 4i) >= a)); let x = foo::large; let y = foo::small; assert!((x != y)); assert_eq!(x, foo::large); assert!((x != foo::small)); }
} fn ne(&self, other: &foo) -> bool { !(*self).eq(other) } }
random_line_split
utils.py
from __future__ import print_function, unicode_literals, division, absolute_import import os import sys import string import random import hashlib import logging import subprocess from io import StringIO import config def valid_path(path): """ Returns an expanded, absolute path, or None if the path does not exist. """ path = os.path.expanduser(path) if not os.path.exists(path): return None return os.path.abspath(path) def get_paths(args):
def split_path(path): """ Returns a normalized list of the path's components. """ path = os.path.normpath(path) return [x for x in path.split(os.path.sep) if x] def generate_id(size=10, chars=string.ascii_uppercase + string.digits): """ Generate a string of random alphanumeric characters. """ return ''.join(random.choice(chars) for i in range(size)) def list_contents(rar_file_path): """ Returns a list of the archive's contents. """ assert os.path.isfile(rar_file_path) and rar_file_path.endswith('.rar') contents = [] count = 0 command = '"{unrar}" v -- "{file}"' command = command.format(unrar=config.UNRAR_PATH, file=rar_file_path) try: output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True) except subprocess.CalledProcessError as e: output = e.output.decode(encoding='utf-8') msg = 'Error while listing archive contents: "{error_string}"' raise FileUtilsError(msg.format(error_string=output.strip())) else: output = StringIO(output.decode(encoding='utf-8')) parse = False for line in output.readlines(): line_list = line.strip().split() # If the line is not empty... if line_list: # This marks the start and end of the section we want to parse if line_list[0] == '-------------------------------------------------------------------------------': parse = not parse count = 0 # If we're in the section of the output we want to parse... elif parse: # Parse every other line (only the file paths) if count % 2 == 0: contents.append(line_list[0]) count += 1 return contents def unrar(rar_file_path, destination_dir=None): """ Get a list of the archive's contents, then extract the archive and return the list. """ assert os.path.isfile(rar_file_path) and rar_file_path.endswith('.rar') if not destination_dir: destination_dir = os.path.split(rar_file_path)[0] # Get a list of the archive's contents contents = list_contents(rar_file_path) extracted_files = [] # Extract the archive command = '"{unrar}" x -o+ -- "{file}" "{destination}"' command = command.format(unrar=config.UNRAR_PATH, file=rar_file_path, destination=destination_dir) logging.debug(command) try: subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True) except subprocess.CalledProcessError as e: output = e.output.decode(encoding='utf-8') msg = 'Error while extracting!\n{error_string}' raise FileUtilsError(msg.format(error_string=output.strip())) for relative_path in contents: path = os.path.join(destination_dir, relative_path) # Recursively extract until there are no RAR files left if path.endswith('.rar'): extracted_files += unrar(path) else: extracted_files.append(path) # Return the list of paths return extracted_files def sha1(data): """ Return the SHA-1 hash of the given data. """ assert isinstance(data, (bytes, bytearray)) sha1_hash = hashlib.sha1() sha1_hash.update(data) return sha1_hash.digest() def set_log_file_name(file_name): """ Set the file name for log output. """ # Remove all logging handlers from the root logger logger = logging.getLogger('') for handler in list(logger.handlers): logger.removeHandler(handler) handler.flush() handler.close() # Configure console logging console_log_format = logging.Formatter('%(module)-15s: %(levelname)-8s %(message)s') console_log_handler = logging.StreamHandler(sys.stdout) console_log_handler.setFormatter(console_log_format) console_log_handler.setLevel(logging.INFO) logger.addHandler(console_log_handler) # Configure disk logging if file_name: log_path = os.path.join(config.LOG_DIR, file_name) disk_log_format = logging.Formatter('%(asctime)s %(module)-15s: %(levelname)-8s %(message)s') disk_log_handler = logging.FileHandler(filename=log_path, mode='w', encoding='utf-8') disk_log_handler.setFormatter(disk_log_format) disk_log_handler.setLevel(logging.DEBUG) logger.addHandler(disk_log_handler) logger.setLevel(logging.DEBUG) # Set logging level for the requests lib to warning+ requests_log = logging.getLogger('requests') requests_log.setLevel(logging.WARNING) # Log system info and Python version for debugging purposes logging.debug('Python {version}'.format(version=sys.version)) logging.debug('System platform: {platform}'.format(platform=sys.platform)) class FileUtilsError(Exception): pass
""" Returns expanded, absolute paths for all valid paths in a list of arguments. """ assert isinstance(args, list) valid_paths = [] for path in args: abs_path = valid_path(path) if abs_path is not None: valid_paths.append(abs_path) return valid_paths
identifier_body
utils.py
from __future__ import print_function, unicode_literals, division, absolute_import import os import sys import string import random import hashlib import logging import subprocess from io import StringIO import config def valid_path(path): """ Returns an expanded, absolute path, or None if the path does not exist. """ path = os.path.expanduser(path) if not os.path.exists(path): return None return os.path.abspath(path) def get_paths(args): """ Returns expanded, absolute paths for all valid paths in a list of arguments. """ assert isinstance(args, list) valid_paths = [] for path in args: abs_path = valid_path(path) if abs_path is not None: valid_paths.append(abs_path) return valid_paths def split_path(path): """ Returns a normalized list of the path's components. """ path = os.path.normpath(path) return [x for x in path.split(os.path.sep) if x] def generate_id(size=10, chars=string.ascii_uppercase + string.digits): """ Generate a string of random alphanumeric characters. """ return ''.join(random.choice(chars) for i in range(size)) def list_contents(rar_file_path): """ Returns a list of the archive's contents. """ assert os.path.isfile(rar_file_path) and rar_file_path.endswith('.rar') contents = [] count = 0 command = '"{unrar}" v -- "{file}"' command = command.format(unrar=config.UNRAR_PATH, file=rar_file_path) try: output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True) except subprocess.CalledProcessError as e: output = e.output.decode(encoding='utf-8') msg = 'Error while listing archive contents: "{error_string}"' raise FileUtilsError(msg.format(error_string=output.strip())) else: output = StringIO(output.decode(encoding='utf-8')) parse = False for line in output.readlines(): line_list = line.strip().split() # If the line is not empty... if line_list: # This marks the start and end of the section we want to parse if line_list[0] == '-------------------------------------------------------------------------------': parse = not parse count = 0 # If we're in the section of the output we want to parse... elif parse: # Parse every other line (only the file paths) if count % 2 == 0: contents.append(line_list[0]) count += 1 return contents def unrar(rar_file_path, destination_dir=None): """ Get a list of the archive's contents, then extract the archive and return the list. """ assert os.path.isfile(rar_file_path) and rar_file_path.endswith('.rar') if not destination_dir:
# Get a list of the archive's contents contents = list_contents(rar_file_path) extracted_files = [] # Extract the archive command = '"{unrar}" x -o+ -- "{file}" "{destination}"' command = command.format(unrar=config.UNRAR_PATH, file=rar_file_path, destination=destination_dir) logging.debug(command) try: subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True) except subprocess.CalledProcessError as e: output = e.output.decode(encoding='utf-8') msg = 'Error while extracting!\n{error_string}' raise FileUtilsError(msg.format(error_string=output.strip())) for relative_path in contents: path = os.path.join(destination_dir, relative_path) # Recursively extract until there are no RAR files left if path.endswith('.rar'): extracted_files += unrar(path) else: extracted_files.append(path) # Return the list of paths return extracted_files def sha1(data): """ Return the SHA-1 hash of the given data. """ assert isinstance(data, (bytes, bytearray)) sha1_hash = hashlib.sha1() sha1_hash.update(data) return sha1_hash.digest() def set_log_file_name(file_name): """ Set the file name for log output. """ # Remove all logging handlers from the root logger logger = logging.getLogger('') for handler in list(logger.handlers): logger.removeHandler(handler) handler.flush() handler.close() # Configure console logging console_log_format = logging.Formatter('%(module)-15s: %(levelname)-8s %(message)s') console_log_handler = logging.StreamHandler(sys.stdout) console_log_handler.setFormatter(console_log_format) console_log_handler.setLevel(logging.INFO) logger.addHandler(console_log_handler) # Configure disk logging if file_name: log_path = os.path.join(config.LOG_DIR, file_name) disk_log_format = logging.Formatter('%(asctime)s %(module)-15s: %(levelname)-8s %(message)s') disk_log_handler = logging.FileHandler(filename=log_path, mode='w', encoding='utf-8') disk_log_handler.setFormatter(disk_log_format) disk_log_handler.setLevel(logging.DEBUG) logger.addHandler(disk_log_handler) logger.setLevel(logging.DEBUG) # Set logging level for the requests lib to warning+ requests_log = logging.getLogger('requests') requests_log.setLevel(logging.WARNING) # Log system info and Python version for debugging purposes logging.debug('Python {version}'.format(version=sys.version)) logging.debug('System platform: {platform}'.format(platform=sys.platform)) class FileUtilsError(Exception): pass
destination_dir = os.path.split(rar_file_path)[0]
conditional_block
utils.py
from __future__ import print_function, unicode_literals, division, absolute_import import os import sys import string import random import hashlib import logging import subprocess from io import StringIO import config def valid_path(path): """ Returns an expanded, absolute path, or None if the path does not exist. """ path = os.path.expanduser(path) if not os.path.exists(path): return None return os.path.abspath(path) def
(args): """ Returns expanded, absolute paths for all valid paths in a list of arguments. """ assert isinstance(args, list) valid_paths = [] for path in args: abs_path = valid_path(path) if abs_path is not None: valid_paths.append(abs_path) return valid_paths def split_path(path): """ Returns a normalized list of the path's components. """ path = os.path.normpath(path) return [x for x in path.split(os.path.sep) if x] def generate_id(size=10, chars=string.ascii_uppercase + string.digits): """ Generate a string of random alphanumeric characters. """ return ''.join(random.choice(chars) for i in range(size)) def list_contents(rar_file_path): """ Returns a list of the archive's contents. """ assert os.path.isfile(rar_file_path) and rar_file_path.endswith('.rar') contents = [] count = 0 command = '"{unrar}" v -- "{file}"' command = command.format(unrar=config.UNRAR_PATH, file=rar_file_path) try: output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True) except subprocess.CalledProcessError as e: output = e.output.decode(encoding='utf-8') msg = 'Error while listing archive contents: "{error_string}"' raise FileUtilsError(msg.format(error_string=output.strip())) else: output = StringIO(output.decode(encoding='utf-8')) parse = False for line in output.readlines(): line_list = line.strip().split() # If the line is not empty... if line_list: # This marks the start and end of the section we want to parse if line_list[0] == '-------------------------------------------------------------------------------': parse = not parse count = 0 # If we're in the section of the output we want to parse... elif parse: # Parse every other line (only the file paths) if count % 2 == 0: contents.append(line_list[0]) count += 1 return contents def unrar(rar_file_path, destination_dir=None): """ Get a list of the archive's contents, then extract the archive and return the list. """ assert os.path.isfile(rar_file_path) and rar_file_path.endswith('.rar') if not destination_dir: destination_dir = os.path.split(rar_file_path)[0] # Get a list of the archive's contents contents = list_contents(rar_file_path) extracted_files = [] # Extract the archive command = '"{unrar}" x -o+ -- "{file}" "{destination}"' command = command.format(unrar=config.UNRAR_PATH, file=rar_file_path, destination=destination_dir) logging.debug(command) try: subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True) except subprocess.CalledProcessError as e: output = e.output.decode(encoding='utf-8') msg = 'Error while extracting!\n{error_string}' raise FileUtilsError(msg.format(error_string=output.strip())) for relative_path in contents: path = os.path.join(destination_dir, relative_path) # Recursively extract until there are no RAR files left if path.endswith('.rar'): extracted_files += unrar(path) else: extracted_files.append(path) # Return the list of paths return extracted_files def sha1(data): """ Return the SHA-1 hash of the given data. """ assert isinstance(data, (bytes, bytearray)) sha1_hash = hashlib.sha1() sha1_hash.update(data) return sha1_hash.digest() def set_log_file_name(file_name): """ Set the file name for log output. """ # Remove all logging handlers from the root logger logger = logging.getLogger('') for handler in list(logger.handlers): logger.removeHandler(handler) handler.flush() handler.close() # Configure console logging console_log_format = logging.Formatter('%(module)-15s: %(levelname)-8s %(message)s') console_log_handler = logging.StreamHandler(sys.stdout) console_log_handler.setFormatter(console_log_format) console_log_handler.setLevel(logging.INFO) logger.addHandler(console_log_handler) # Configure disk logging if file_name: log_path = os.path.join(config.LOG_DIR, file_name) disk_log_format = logging.Formatter('%(asctime)s %(module)-15s: %(levelname)-8s %(message)s') disk_log_handler = logging.FileHandler(filename=log_path, mode='w', encoding='utf-8') disk_log_handler.setFormatter(disk_log_format) disk_log_handler.setLevel(logging.DEBUG) logger.addHandler(disk_log_handler) logger.setLevel(logging.DEBUG) # Set logging level for the requests lib to warning+ requests_log = logging.getLogger('requests') requests_log.setLevel(logging.WARNING) # Log system info and Python version for debugging purposes logging.debug('Python {version}'.format(version=sys.version)) logging.debug('System platform: {platform}'.format(platform=sys.platform)) class FileUtilsError(Exception): pass
get_paths
identifier_name
utils.py
from __future__ import print_function, unicode_literals, division, absolute_import import os import sys import string import random import hashlib import logging import subprocess from io import StringIO import config def valid_path(path): """ Returns an expanded, absolute path, or None if the path does not exist. """ path = os.path.expanduser(path) if not os.path.exists(path): return None return os.path.abspath(path) def get_paths(args): """ Returns expanded, absolute paths for all valid paths in a list of arguments. """ assert isinstance(args, list) valid_paths = [] for path in args: abs_path = valid_path(path) if abs_path is not None: valid_paths.append(abs_path) return valid_paths def split_path(path): """ Returns a normalized list of the path's components. """ path = os.path.normpath(path) return [x for x in path.split(os.path.sep) if x] def generate_id(size=10, chars=string.ascii_uppercase + string.digits): """ Generate a string of random alphanumeric characters. """ return ''.join(random.choice(chars) for i in range(size)) def list_contents(rar_file_path): """ Returns a list of the archive's contents. """ assert os.path.isfile(rar_file_path) and rar_file_path.endswith('.rar') contents = [] count = 0 command = '"{unrar}" v -- "{file}"' command = command.format(unrar=config.UNRAR_PATH, file=rar_file_path) try: output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True) except subprocess.CalledProcessError as e: output = e.output.decode(encoding='utf-8') msg = 'Error while listing archive contents: "{error_string}"' raise FileUtilsError(msg.format(error_string=output.strip())) else: output = StringIO(output.decode(encoding='utf-8')) parse = False for line in output.readlines(): line_list = line.strip().split() # If the line is not empty... if line_list: # This marks the start and end of the section we want to parse if line_list[0] == '-------------------------------------------------------------------------------': parse = not parse
elif parse: # Parse every other line (only the file paths) if count % 2 == 0: contents.append(line_list[0]) count += 1 return contents def unrar(rar_file_path, destination_dir=None): """ Get a list of the archive's contents, then extract the archive and return the list. """ assert os.path.isfile(rar_file_path) and rar_file_path.endswith('.rar') if not destination_dir: destination_dir = os.path.split(rar_file_path)[0] # Get a list of the archive's contents contents = list_contents(rar_file_path) extracted_files = [] # Extract the archive command = '"{unrar}" x -o+ -- "{file}" "{destination}"' command = command.format(unrar=config.UNRAR_PATH, file=rar_file_path, destination=destination_dir) logging.debug(command) try: subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True) except subprocess.CalledProcessError as e: output = e.output.decode(encoding='utf-8') msg = 'Error while extracting!\n{error_string}' raise FileUtilsError(msg.format(error_string=output.strip())) for relative_path in contents: path = os.path.join(destination_dir, relative_path) # Recursively extract until there are no RAR files left if path.endswith('.rar'): extracted_files += unrar(path) else: extracted_files.append(path) # Return the list of paths return extracted_files def sha1(data): """ Return the SHA-1 hash of the given data. """ assert isinstance(data, (bytes, bytearray)) sha1_hash = hashlib.sha1() sha1_hash.update(data) return sha1_hash.digest() def set_log_file_name(file_name): """ Set the file name for log output. """ # Remove all logging handlers from the root logger logger = logging.getLogger('') for handler in list(logger.handlers): logger.removeHandler(handler) handler.flush() handler.close() # Configure console logging console_log_format = logging.Formatter('%(module)-15s: %(levelname)-8s %(message)s') console_log_handler = logging.StreamHandler(sys.stdout) console_log_handler.setFormatter(console_log_format) console_log_handler.setLevel(logging.INFO) logger.addHandler(console_log_handler) # Configure disk logging if file_name: log_path = os.path.join(config.LOG_DIR, file_name) disk_log_format = logging.Formatter('%(asctime)s %(module)-15s: %(levelname)-8s %(message)s') disk_log_handler = logging.FileHandler(filename=log_path, mode='w', encoding='utf-8') disk_log_handler.setFormatter(disk_log_format) disk_log_handler.setLevel(logging.DEBUG) logger.addHandler(disk_log_handler) logger.setLevel(logging.DEBUG) # Set logging level for the requests lib to warning+ requests_log = logging.getLogger('requests') requests_log.setLevel(logging.WARNING) # Log system info and Python version for debugging purposes logging.debug('Python {version}'.format(version=sys.version)) logging.debug('System platform: {platform}'.format(platform=sys.platform)) class FileUtilsError(Exception): pass
count = 0 # If we're in the section of the output we want to parse...
random_line_split
symbol_analysis.rs
use tokens::*; use symbols::*; use support::*; use plp::PLPWriter; use symbols::commons::*; use symbols::symbol_table::*; pub fn get_accessor_namespace(symbol: &Symbol, symbol_table: &StaticSymbolTable) -> Option<String> { match symbol.symbol_class { SymbolClass::Variable(ref variable_type) => { let potential_matches = symbol_table.lookup_by_name(&*variable_type); if potential_matches.is_empty() { return None; } let type_symbol = potential_matches[0]; let namespace = concatenate_namespace(&*type_symbol.namespace, &*type_symbol.name); return Some(namespace); }, SymbolClass::Structure(_, _) => { panic!("get_accessor_namespace: Structure access not currently supported"); }, SymbolClass::Function(_, _, _, _) => { panic!("Expected Variable or Structure, found Function"); }, }; } /// @return: (static_memory_label, static_init_label, local_init_label) pub fn get_class_labels(class_symbol: &Symbol) -> (String, String, String) { let mut namespace_label = class_symbol.namespace.clone(); if !namespace_label.is_empty() { namespace_label.push_str("_"); } namespace_label.push_str(&*class_symbol.name.clone()); let mut static_memory_label = namespace_label.clone(); static_memory_label.push_str("_static"); let mut static_init_label = static_memory_label.to_string(); static_init_label.push_str("_init"); let mut local_init_label = namespace_label.clone(); local_init_label.push_str("_local_init"); (static_memory_label, static_init_label, local_init_label) } /// @return: (method_label, return_label) pub fn get_method_labels(method_symbol: &Symbol) -> (String, String) { let method_label = match method_symbol.location { SymbolLocation::Memory(ref address) => address.label_name.clone(), _ => { panic!("compile_method_body: Expected Memory address for method"); }, }; let mut return_label = method_label.clone(); return_label.push_str("_return"); (method_label, return_label) } /// @return (memory_label, memory_size) pub fn get_static_allocation(method_symbol: &Symbol) -> (String, u16) { match method_symbol.symbol_class { SymbolClass::Variable(_) => { panic!("Expected Function found Variable"); }, SymbolClass::Function(_, _, ref label_name, var_count) => (label_name.clone(), var_count as u16), SymbolClass::Structure(ref subtype, _) => { panic!("Expected Function found {}", subtype); } } } /// @return (memory_label, memory_size) pub fn get_return_type_of(method_symbol: &Symbol) -> String { match method_symbol.symbol_class { SymbolClass::Variable(_) => { panic!("Expected Function found Variable"); }, SymbolClass::Function(ref return_type, _, _, _) => return_type.clone(), SymbolClass::Structure(ref subtype, _) =>
} } /// @return ([arg1] [, arg2] {, arg3..}) pub fn get_arg_signature_of(method_symbol: &Symbol) -> String { let types: &Vec<String> = match method_symbol.symbol_class { SymbolClass::Variable(_) => { panic!("Expected Function found Variable"); }, SymbolClass::Function(_, ref arg_types, _, _) => arg_types, SymbolClass::Structure(ref subtype, _) => { panic!("Expected Function found {}", subtype); } }; let mut arg_signature = "(".to_string(); // Handle first arg type if types.len() > 0 { arg_signature.push_str(&*types[0]); for ref arg_type in types[1..].iter() { arg_signature.push_str(","); arg_signature.push_str(&*arg_type); } } arg_signature.push_str(")"); arg_signature }
{ panic!("Expected Function found {}", subtype); }
conditional_block
symbol_analysis.rs
use tokens::*; use symbols::*; use support::*; use plp::PLPWriter; use symbols::commons::*; use symbols::symbol_table::*; pub fn get_accessor_namespace(symbol: &Symbol, symbol_table: &StaticSymbolTable) -> Option<String> { match symbol.symbol_class { SymbolClass::Variable(ref variable_type) => { let potential_matches = symbol_table.lookup_by_name(&*variable_type);
let namespace = concatenate_namespace(&*type_symbol.namespace, &*type_symbol.name); return Some(namespace); }, SymbolClass::Structure(_, _) => { panic!("get_accessor_namespace: Structure access not currently supported"); }, SymbolClass::Function(_, _, _, _) => { panic!("Expected Variable or Structure, found Function"); }, }; } /// @return: (static_memory_label, static_init_label, local_init_label) pub fn get_class_labels(class_symbol: &Symbol) -> (String, String, String) { let mut namespace_label = class_symbol.namespace.clone(); if !namespace_label.is_empty() { namespace_label.push_str("_"); } namespace_label.push_str(&*class_symbol.name.clone()); let mut static_memory_label = namespace_label.clone(); static_memory_label.push_str("_static"); let mut static_init_label = static_memory_label.to_string(); static_init_label.push_str("_init"); let mut local_init_label = namespace_label.clone(); local_init_label.push_str("_local_init"); (static_memory_label, static_init_label, local_init_label) } /// @return: (method_label, return_label) pub fn get_method_labels(method_symbol: &Symbol) -> (String, String) { let method_label = match method_symbol.location { SymbolLocation::Memory(ref address) => address.label_name.clone(), _ => { panic!("compile_method_body: Expected Memory address for method"); }, }; let mut return_label = method_label.clone(); return_label.push_str("_return"); (method_label, return_label) } /// @return (memory_label, memory_size) pub fn get_static_allocation(method_symbol: &Symbol) -> (String, u16) { match method_symbol.symbol_class { SymbolClass::Variable(_) => { panic!("Expected Function found Variable"); }, SymbolClass::Function(_, _, ref label_name, var_count) => (label_name.clone(), var_count as u16), SymbolClass::Structure(ref subtype, _) => { panic!("Expected Function found {}", subtype); } } } /// @return (memory_label, memory_size) pub fn get_return_type_of(method_symbol: &Symbol) -> String { match method_symbol.symbol_class { SymbolClass::Variable(_) => { panic!("Expected Function found Variable"); }, SymbolClass::Function(ref return_type, _, _, _) => return_type.clone(), SymbolClass::Structure(ref subtype, _) => { panic!("Expected Function found {}", subtype); } } } /// @return ([arg1] [, arg2] {, arg3..}) pub fn get_arg_signature_of(method_symbol: &Symbol) -> String { let types: &Vec<String> = match method_symbol.symbol_class { SymbolClass::Variable(_) => { panic!("Expected Function found Variable"); }, SymbolClass::Function(_, ref arg_types, _, _) => arg_types, SymbolClass::Structure(ref subtype, _) => { panic!("Expected Function found {}", subtype); } }; let mut arg_signature = "(".to_string(); // Handle first arg type if types.len() > 0 { arg_signature.push_str(&*types[0]); for ref arg_type in types[1..].iter() { arg_signature.push_str(","); arg_signature.push_str(&*arg_type); } } arg_signature.push_str(")"); arg_signature }
if potential_matches.is_empty() { return None; } let type_symbol = potential_matches[0];
random_line_split
symbol_analysis.rs
use tokens::*; use symbols::*; use support::*; use plp::PLPWriter; use symbols::commons::*; use symbols::symbol_table::*; pub fn get_accessor_namespace(symbol: &Symbol, symbol_table: &StaticSymbolTable) -> Option<String> { match symbol.symbol_class { SymbolClass::Variable(ref variable_type) => { let potential_matches = symbol_table.lookup_by_name(&*variable_type); if potential_matches.is_empty() { return None; } let type_symbol = potential_matches[0]; let namespace = concatenate_namespace(&*type_symbol.namespace, &*type_symbol.name); return Some(namespace); }, SymbolClass::Structure(_, _) => { panic!("get_accessor_namespace: Structure access not currently supported"); }, SymbolClass::Function(_, _, _, _) => { panic!("Expected Variable or Structure, found Function"); }, }; } /// @return: (static_memory_label, static_init_label, local_init_label) pub fn get_class_labels(class_symbol: &Symbol) -> (String, String, String) { let mut namespace_label = class_symbol.namespace.clone(); if !namespace_label.is_empty() { namespace_label.push_str("_"); } namespace_label.push_str(&*class_symbol.name.clone()); let mut static_memory_label = namespace_label.clone(); static_memory_label.push_str("_static"); let mut static_init_label = static_memory_label.to_string(); static_init_label.push_str("_init"); let mut local_init_label = namespace_label.clone(); local_init_label.push_str("_local_init"); (static_memory_label, static_init_label, local_init_label) } /// @return: (method_label, return_label) pub fn get_method_labels(method_symbol: &Symbol) -> (String, String) { let method_label = match method_symbol.location { SymbolLocation::Memory(ref address) => address.label_name.clone(), _ => { panic!("compile_method_body: Expected Memory address for method"); }, }; let mut return_label = method_label.clone(); return_label.push_str("_return"); (method_label, return_label) } /// @return (memory_label, memory_size) pub fn
(method_symbol: &Symbol) -> (String, u16) { match method_symbol.symbol_class { SymbolClass::Variable(_) => { panic!("Expected Function found Variable"); }, SymbolClass::Function(_, _, ref label_name, var_count) => (label_name.clone(), var_count as u16), SymbolClass::Structure(ref subtype, _) => { panic!("Expected Function found {}", subtype); } } } /// @return (memory_label, memory_size) pub fn get_return_type_of(method_symbol: &Symbol) -> String { match method_symbol.symbol_class { SymbolClass::Variable(_) => { panic!("Expected Function found Variable"); }, SymbolClass::Function(ref return_type, _, _, _) => return_type.clone(), SymbolClass::Structure(ref subtype, _) => { panic!("Expected Function found {}", subtype); } } } /// @return ([arg1] [, arg2] {, arg3..}) pub fn get_arg_signature_of(method_symbol: &Symbol) -> String { let types: &Vec<String> = match method_symbol.symbol_class { SymbolClass::Variable(_) => { panic!("Expected Function found Variable"); }, SymbolClass::Function(_, ref arg_types, _, _) => arg_types, SymbolClass::Structure(ref subtype, _) => { panic!("Expected Function found {}", subtype); } }; let mut arg_signature = "(".to_string(); // Handle first arg type if types.len() > 0 { arg_signature.push_str(&*types[0]); for ref arg_type in types[1..].iter() { arg_signature.push_str(","); arg_signature.push_str(&*arg_type); } } arg_signature.push_str(")"); arg_signature }
get_static_allocation
identifier_name
symbol_analysis.rs
use tokens::*; use symbols::*; use support::*; use plp::PLPWriter; use symbols::commons::*; use symbols::symbol_table::*; pub fn get_accessor_namespace(symbol: &Symbol, symbol_table: &StaticSymbolTable) -> Option<String> { match symbol.symbol_class { SymbolClass::Variable(ref variable_type) => { let potential_matches = symbol_table.lookup_by_name(&*variable_type); if potential_matches.is_empty() { return None; } let type_symbol = potential_matches[0]; let namespace = concatenate_namespace(&*type_symbol.namespace, &*type_symbol.name); return Some(namespace); }, SymbolClass::Structure(_, _) => { panic!("get_accessor_namespace: Structure access not currently supported"); }, SymbolClass::Function(_, _, _, _) => { panic!("Expected Variable or Structure, found Function"); }, }; } /// @return: (static_memory_label, static_init_label, local_init_label) pub fn get_class_labels(class_symbol: &Symbol) -> (String, String, String) { let mut namespace_label = class_symbol.namespace.clone(); if !namespace_label.is_empty() { namespace_label.push_str("_"); } namespace_label.push_str(&*class_symbol.name.clone()); let mut static_memory_label = namespace_label.clone(); static_memory_label.push_str("_static"); let mut static_init_label = static_memory_label.to_string(); static_init_label.push_str("_init"); let mut local_init_label = namespace_label.clone(); local_init_label.push_str("_local_init"); (static_memory_label, static_init_label, local_init_label) } /// @return: (method_label, return_label) pub fn get_method_labels(method_symbol: &Symbol) -> (String, String) { let method_label = match method_symbol.location { SymbolLocation::Memory(ref address) => address.label_name.clone(), _ => { panic!("compile_method_body: Expected Memory address for method"); }, }; let mut return_label = method_label.clone(); return_label.push_str("_return"); (method_label, return_label) } /// @return (memory_label, memory_size) pub fn get_static_allocation(method_symbol: &Symbol) -> (String, u16) { match method_symbol.symbol_class { SymbolClass::Variable(_) => { panic!("Expected Function found Variable"); }, SymbolClass::Function(_, _, ref label_name, var_count) => (label_name.clone(), var_count as u16), SymbolClass::Structure(ref subtype, _) => { panic!("Expected Function found {}", subtype); } } } /// @return (memory_label, memory_size) pub fn get_return_type_of(method_symbol: &Symbol) -> String
/// @return ([arg1] [, arg2] {, arg3..}) pub fn get_arg_signature_of(method_symbol: &Symbol) -> String { let types: &Vec<String> = match method_symbol.symbol_class { SymbolClass::Variable(_) => { panic!("Expected Function found Variable"); }, SymbolClass::Function(_, ref arg_types, _, _) => arg_types, SymbolClass::Structure(ref subtype, _) => { panic!("Expected Function found {}", subtype); } }; let mut arg_signature = "(".to_string(); // Handle first arg type if types.len() > 0 { arg_signature.push_str(&*types[0]); for ref arg_type in types[1..].iter() { arg_signature.push_str(","); arg_signature.push_str(&*arg_type); } } arg_signature.push_str(")"); arg_signature }
{ match method_symbol.symbol_class { SymbolClass::Variable(_) => { panic!("Expected Function found Variable"); }, SymbolClass::Function(ref return_type, _, _, _) => return_type.clone(), SymbolClass::Structure(ref subtype, _) => { panic!("Expected Function found {}", subtype); } } }
identifier_body
configure.py
#!/usr/bin/env python import glob, os, sys import sipconfig from PyQt4 import pyqtconfig def get_diana_version(): depends = filter(lambda line: line.startswith("Depends:"), open("debian/control").readlines()) for line in depends: pieces = line.split() for piece in pieces: name_pieces = piece.strip(",").split("-") if len(name_pieces) == 2 and name_pieces[0] == "diana": return name_pieces[1] return None def get_python_diana_version(): line = open("debian/changelog").readline() pieces = line.split() return pieces[1][1:-1] if __name__ == "__main__": if len(sys.argv) not in (1, 3, 5): sys.stderr.write("Usage: %s [<directory containing diana headers> <directory containing libdiana>] " "[<directory containing metlibs headers> <directory containing metlibs libraries>]\n" % sys.argv[0]) sys.exit(1) if len(sys.argv) == 5: metlibs_inc_dir = sys.argv[3] metlibs_lib_dir = sys.argv[4] else: metlibs_inc_dir = "/usr/include/metlibs" metlibs_lib_dir = "/usr/lib" if len(sys.argv) >= 3: diana_inc_dir = sys.argv[1] diana_lib_dir = sys.argv[2] else: diana_inc_dir = "/usr/include/diana" diana_lib_dir = "/usr/lib" qt_pkg_dir = os.getenv("qt_pkg_dir") python_diana_pkg_dir = os.getenv("python_diana_pkg_dir") dest_pkg_dir = os.path.join(python_diana_pkg_dir, "metno") config = pyqtconfig.Configuration() # The name of the SIP build file generated by SIP and used by the build # system. sip_files_dir = "sip" modules = ["std", "metlibs", "diana"] if not os.path.exists("modules"): os.mkdir("modules") # Run SIP to generate the code. output_dirs = [] for module in modules: output_dir = os.path.join("modules", module) build_file = module + ".sbf" build_path = os.path.join(output_dir, build_file) if not os.path.exists(output_dir): os.mkdir(output_dir) sip_file = os.path.join("sip", module, module+".sip") command = " ".join([config.sip_bin, "-c", output_dir, "-b", build_path, "-I"+config.sip_inc_dir, "-I"+config.pyqt_sip_dir, "-I"+diana_inc_dir, "-I/usr/include", "-I"+metlibs_inc_dir, "-I"+qt_pkg_dir+"/include", "-I"+qt_pkg_dir+"/share/sip/PyQt4", "-Isip", config.pyqt_sip_flags, "-w", "-o", # generate docstrings for signatures sip_file]) sys.stdout.write(command+"\n") sys.stdout.flush() if os.system(command) != 0: sys.exit(1) # Create the Makefile (within the diana directory). makefile = pyqtconfig.QtGuiModuleMakefile( config, build_file, dir=output_dir, install_dir=dest_pkg_dir, qt=["QtCore", "QtGui", "QtNetwork", "QtXml", "QtXmlPatterns"] ) if module == "diana": makefile.extra_include_dirs += [ diana_inc_dir, os.path.join(diana_inc_dir, "PaintGL"), metlibs_inc_dir, qt_pkg_dir+"/include" ] makefile.extra_lib_dirs += [diana_lib_dir, qt_pkg_dir+"/lib"] makefile.extra_lflags += ["-Wl,-rpath="+diana_lib_dir, "-Wl,-fPIC"] makefile.extra_libs += ["diana"] if module == "metlibs": makefile.extra_include_dirs.append(diana_inc_dir) makefile.extra_include_dirs.append("/usr/include/metlibs") makefile.extra_lib_dirs += [diana_lib_dir, "/usr/lib", metlibs_lib_dir, qt_pkg_dir+"/lib"] makefile.extra_lflags += ["-Wl,-rpath="+diana_lib_dir, "-Wl,-fPIC"] makefile.extra_libs += ["miLogger", "coserver", "diana"] makefile.generate() output_dirs.append(output_dir) # Update the metno package version. diana_version = get_diana_version() python_diana_version = get_python_diana_version() if not diana_version or not python_diana_version: sys.stderr.write("Failed to find version information for Diana (%s) " "or python-diana (%s)\n" % (repr(diana_version), repr(python_diana_version))) sys.exit(1) f = open("python/metno/versions.py", "w") f.write('\ndiana_version = "%s"\npython_diana_version = "%s"\n' % ( diana_version, python_diana_version)) # Generate the top-level Makefile. python_files = glob.glob(os.path.join("python", "metno", "*.py"))
installs = [(python_files, dest_pkg_dir)] ).generate() sys.exit()
sipconfig.ParentMakefile( configuration = config, subdirs = output_dirs,
random_line_split
configure.py
#!/usr/bin/env python import glob, os, sys import sipconfig from PyQt4 import pyqtconfig def get_diana_version(): depends = filter(lambda line: line.startswith("Depends:"), open("debian/control").readlines()) for line in depends: pieces = line.split() for piece in pieces: name_pieces = piece.strip(",").split("-") if len(name_pieces) == 2 and name_pieces[0] == "diana": return name_pieces[1] return None def get_python_diana_version(): line = open("debian/changelog").readline() pieces = line.split() return pieces[1][1:-1] if __name__ == "__main__":
if len(sys.argv) not in (1, 3, 5): sys.stderr.write("Usage: %s [<directory containing diana headers> <directory containing libdiana>] " "[<directory containing metlibs headers> <directory containing metlibs libraries>]\n" % sys.argv[0]) sys.exit(1) if len(sys.argv) == 5: metlibs_inc_dir = sys.argv[3] metlibs_lib_dir = sys.argv[4] else: metlibs_inc_dir = "/usr/include/metlibs" metlibs_lib_dir = "/usr/lib" if len(sys.argv) >= 3: diana_inc_dir = sys.argv[1] diana_lib_dir = sys.argv[2] else: diana_inc_dir = "/usr/include/diana" diana_lib_dir = "/usr/lib" qt_pkg_dir = os.getenv("qt_pkg_dir") python_diana_pkg_dir = os.getenv("python_diana_pkg_dir") dest_pkg_dir = os.path.join(python_diana_pkg_dir, "metno") config = pyqtconfig.Configuration() # The name of the SIP build file generated by SIP and used by the build # system. sip_files_dir = "sip" modules = ["std", "metlibs", "diana"] if not os.path.exists("modules"): os.mkdir("modules") # Run SIP to generate the code. output_dirs = [] for module in modules: output_dir = os.path.join("modules", module) build_file = module + ".sbf" build_path = os.path.join(output_dir, build_file) if not os.path.exists(output_dir): os.mkdir(output_dir) sip_file = os.path.join("sip", module, module+".sip") command = " ".join([config.sip_bin, "-c", output_dir, "-b", build_path, "-I"+config.sip_inc_dir, "-I"+config.pyqt_sip_dir, "-I"+diana_inc_dir, "-I/usr/include", "-I"+metlibs_inc_dir, "-I"+qt_pkg_dir+"/include", "-I"+qt_pkg_dir+"/share/sip/PyQt4", "-Isip", config.pyqt_sip_flags, "-w", "-o", # generate docstrings for signatures sip_file]) sys.stdout.write(command+"\n") sys.stdout.flush() if os.system(command) != 0: sys.exit(1) # Create the Makefile (within the diana directory). makefile = pyqtconfig.QtGuiModuleMakefile( config, build_file, dir=output_dir, install_dir=dest_pkg_dir, qt=["QtCore", "QtGui", "QtNetwork", "QtXml", "QtXmlPatterns"] ) if module == "diana": makefile.extra_include_dirs += [ diana_inc_dir, os.path.join(diana_inc_dir, "PaintGL"), metlibs_inc_dir, qt_pkg_dir+"/include" ] makefile.extra_lib_dirs += [diana_lib_dir, qt_pkg_dir+"/lib"] makefile.extra_lflags += ["-Wl,-rpath="+diana_lib_dir, "-Wl,-fPIC"] makefile.extra_libs += ["diana"] if module == "metlibs": makefile.extra_include_dirs.append(diana_inc_dir) makefile.extra_include_dirs.append("/usr/include/metlibs") makefile.extra_lib_dirs += [diana_lib_dir, "/usr/lib", metlibs_lib_dir, qt_pkg_dir+"/lib"] makefile.extra_lflags += ["-Wl,-rpath="+diana_lib_dir, "-Wl,-fPIC"] makefile.extra_libs += ["miLogger", "coserver", "diana"] makefile.generate() output_dirs.append(output_dir) # Update the metno package version. diana_version = get_diana_version() python_diana_version = get_python_diana_version() if not diana_version or not python_diana_version: sys.stderr.write("Failed to find version information for Diana (%s) " "or python-diana (%s)\n" % (repr(diana_version), repr(python_diana_version))) sys.exit(1) f = open("python/metno/versions.py", "w") f.write('\ndiana_version = "%s"\npython_diana_version = "%s"\n' % ( diana_version, python_diana_version)) # Generate the top-level Makefile. python_files = glob.glob(os.path.join("python", "metno", "*.py")) sipconfig.ParentMakefile( configuration = config, subdirs = output_dirs, installs = [(python_files, dest_pkg_dir)] ).generate() sys.exit()
conditional_block
configure.py
#!/usr/bin/env python import glob, os, sys import sipconfig from PyQt4 import pyqtconfig def get_diana_version(): depends = filter(lambda line: line.startswith("Depends:"), open("debian/control").readlines()) for line in depends: pieces = line.split() for piece in pieces: name_pieces = piece.strip(",").split("-") if len(name_pieces) == 2 and name_pieces[0] == "diana": return name_pieces[1] return None def get_python_diana_version():
if __name__ == "__main__": if len(sys.argv) not in (1, 3, 5): sys.stderr.write("Usage: %s [<directory containing diana headers> <directory containing libdiana>] " "[<directory containing metlibs headers> <directory containing metlibs libraries>]\n" % sys.argv[0]) sys.exit(1) if len(sys.argv) == 5: metlibs_inc_dir = sys.argv[3] metlibs_lib_dir = sys.argv[4] else: metlibs_inc_dir = "/usr/include/metlibs" metlibs_lib_dir = "/usr/lib" if len(sys.argv) >= 3: diana_inc_dir = sys.argv[1] diana_lib_dir = sys.argv[2] else: diana_inc_dir = "/usr/include/diana" diana_lib_dir = "/usr/lib" qt_pkg_dir = os.getenv("qt_pkg_dir") python_diana_pkg_dir = os.getenv("python_diana_pkg_dir") dest_pkg_dir = os.path.join(python_diana_pkg_dir, "metno") config = pyqtconfig.Configuration() # The name of the SIP build file generated by SIP and used by the build # system. sip_files_dir = "sip" modules = ["std", "metlibs", "diana"] if not os.path.exists("modules"): os.mkdir("modules") # Run SIP to generate the code. output_dirs = [] for module in modules: output_dir = os.path.join("modules", module) build_file = module + ".sbf" build_path = os.path.join(output_dir, build_file) if not os.path.exists(output_dir): os.mkdir(output_dir) sip_file = os.path.join("sip", module, module+".sip") command = " ".join([config.sip_bin, "-c", output_dir, "-b", build_path, "-I"+config.sip_inc_dir, "-I"+config.pyqt_sip_dir, "-I"+diana_inc_dir, "-I/usr/include", "-I"+metlibs_inc_dir, "-I"+qt_pkg_dir+"/include", "-I"+qt_pkg_dir+"/share/sip/PyQt4", "-Isip", config.pyqt_sip_flags, "-w", "-o", # generate docstrings for signatures sip_file]) sys.stdout.write(command+"\n") sys.stdout.flush() if os.system(command) != 0: sys.exit(1) # Create the Makefile (within the diana directory). makefile = pyqtconfig.QtGuiModuleMakefile( config, build_file, dir=output_dir, install_dir=dest_pkg_dir, qt=["QtCore", "QtGui", "QtNetwork", "QtXml", "QtXmlPatterns"] ) if module == "diana": makefile.extra_include_dirs += [ diana_inc_dir, os.path.join(diana_inc_dir, "PaintGL"), metlibs_inc_dir, qt_pkg_dir+"/include" ] makefile.extra_lib_dirs += [diana_lib_dir, qt_pkg_dir+"/lib"] makefile.extra_lflags += ["-Wl,-rpath="+diana_lib_dir, "-Wl,-fPIC"] makefile.extra_libs += ["diana"] if module == "metlibs": makefile.extra_include_dirs.append(diana_inc_dir) makefile.extra_include_dirs.append("/usr/include/metlibs") makefile.extra_lib_dirs += [diana_lib_dir, "/usr/lib", metlibs_lib_dir, qt_pkg_dir+"/lib"] makefile.extra_lflags += ["-Wl,-rpath="+diana_lib_dir, "-Wl,-fPIC"] makefile.extra_libs += ["miLogger", "coserver", "diana"] makefile.generate() output_dirs.append(output_dir) # Update the metno package version. diana_version = get_diana_version() python_diana_version = get_python_diana_version() if not diana_version or not python_diana_version: sys.stderr.write("Failed to find version information for Diana (%s) " "or python-diana (%s)\n" % (repr(diana_version), repr(python_diana_version))) sys.exit(1) f = open("python/metno/versions.py", "w") f.write('\ndiana_version = "%s"\npython_diana_version = "%s"\n' % ( diana_version, python_diana_version)) # Generate the top-level Makefile. python_files = glob.glob(os.path.join("python", "metno", "*.py")) sipconfig.ParentMakefile( configuration = config, subdirs = output_dirs, installs = [(python_files, dest_pkg_dir)] ).generate() sys.exit()
line = open("debian/changelog").readline() pieces = line.split() return pieces[1][1:-1]
identifier_body
configure.py
#!/usr/bin/env python import glob, os, sys import sipconfig from PyQt4 import pyqtconfig def
(): depends = filter(lambda line: line.startswith("Depends:"), open("debian/control").readlines()) for line in depends: pieces = line.split() for piece in pieces: name_pieces = piece.strip(",").split("-") if len(name_pieces) == 2 and name_pieces[0] == "diana": return name_pieces[1] return None def get_python_diana_version(): line = open("debian/changelog").readline() pieces = line.split() return pieces[1][1:-1] if __name__ == "__main__": if len(sys.argv) not in (1, 3, 5): sys.stderr.write("Usage: %s [<directory containing diana headers> <directory containing libdiana>] " "[<directory containing metlibs headers> <directory containing metlibs libraries>]\n" % sys.argv[0]) sys.exit(1) if len(sys.argv) == 5: metlibs_inc_dir = sys.argv[3] metlibs_lib_dir = sys.argv[4] else: metlibs_inc_dir = "/usr/include/metlibs" metlibs_lib_dir = "/usr/lib" if len(sys.argv) >= 3: diana_inc_dir = sys.argv[1] diana_lib_dir = sys.argv[2] else: diana_inc_dir = "/usr/include/diana" diana_lib_dir = "/usr/lib" qt_pkg_dir = os.getenv("qt_pkg_dir") python_diana_pkg_dir = os.getenv("python_diana_pkg_dir") dest_pkg_dir = os.path.join(python_diana_pkg_dir, "metno") config = pyqtconfig.Configuration() # The name of the SIP build file generated by SIP and used by the build # system. sip_files_dir = "sip" modules = ["std", "metlibs", "diana"] if not os.path.exists("modules"): os.mkdir("modules") # Run SIP to generate the code. output_dirs = [] for module in modules: output_dir = os.path.join("modules", module) build_file = module + ".sbf" build_path = os.path.join(output_dir, build_file) if not os.path.exists(output_dir): os.mkdir(output_dir) sip_file = os.path.join("sip", module, module+".sip") command = " ".join([config.sip_bin, "-c", output_dir, "-b", build_path, "-I"+config.sip_inc_dir, "-I"+config.pyqt_sip_dir, "-I"+diana_inc_dir, "-I/usr/include", "-I"+metlibs_inc_dir, "-I"+qt_pkg_dir+"/include", "-I"+qt_pkg_dir+"/share/sip/PyQt4", "-Isip", config.pyqt_sip_flags, "-w", "-o", # generate docstrings for signatures sip_file]) sys.stdout.write(command+"\n") sys.stdout.flush() if os.system(command) != 0: sys.exit(1) # Create the Makefile (within the diana directory). makefile = pyqtconfig.QtGuiModuleMakefile( config, build_file, dir=output_dir, install_dir=dest_pkg_dir, qt=["QtCore", "QtGui", "QtNetwork", "QtXml", "QtXmlPatterns"] ) if module == "diana": makefile.extra_include_dirs += [ diana_inc_dir, os.path.join(diana_inc_dir, "PaintGL"), metlibs_inc_dir, qt_pkg_dir+"/include" ] makefile.extra_lib_dirs += [diana_lib_dir, qt_pkg_dir+"/lib"] makefile.extra_lflags += ["-Wl,-rpath="+diana_lib_dir, "-Wl,-fPIC"] makefile.extra_libs += ["diana"] if module == "metlibs": makefile.extra_include_dirs.append(diana_inc_dir) makefile.extra_include_dirs.append("/usr/include/metlibs") makefile.extra_lib_dirs += [diana_lib_dir, "/usr/lib", metlibs_lib_dir, qt_pkg_dir+"/lib"] makefile.extra_lflags += ["-Wl,-rpath="+diana_lib_dir, "-Wl,-fPIC"] makefile.extra_libs += ["miLogger", "coserver", "diana"] makefile.generate() output_dirs.append(output_dir) # Update the metno package version. diana_version = get_diana_version() python_diana_version = get_python_diana_version() if not diana_version or not python_diana_version: sys.stderr.write("Failed to find version information for Diana (%s) " "or python-diana (%s)\n" % (repr(diana_version), repr(python_diana_version))) sys.exit(1) f = open("python/metno/versions.py", "w") f.write('\ndiana_version = "%s"\npython_diana_version = "%s"\n' % ( diana_version, python_diana_version)) # Generate the top-level Makefile. python_files = glob.glob(os.path.join("python", "metno", "*.py")) sipconfig.ParentMakefile( configuration = config, subdirs = output_dirs, installs = [(python_files, dest_pkg_dir)] ).generate() sys.exit()
get_diana_version
identifier_name
SvgIcon.d.ts
import * as React from 'react'; import { OverridableComponent, OverrideProps } from '../OverridableComponent'; export interface SvgIconTypeMap<P = {}, D extends React.ElementType = 'svg'> { props: P & { /** * Node passed into the SVG element. */ children?: React.ReactNode; /** * The color of the component. It supports those theme colors that make sense for this component. * You can use the `htmlColor` prop to apply a color attribute to the SVG element. */ color?: 'inherit' | 'primary' | 'secondary' | 'action' | 'disabled' | 'error'; /** * The fontSize applied to the icon. Defaults to 24px, but can be configure to inherit font size. */ fontSize?: 'inherit' | 'default' | 'small' | 'large'; /** * Applies a color attribute to the SVG element. */ htmlColor?: string; /** * The shape-rendering attribute. The behavior of the different options is described on the * [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/shape-rendering). * If you are having issues with blurry icons you should investigate this prop. */ shapeRendering?: string; /** * Provides a human-readable title for the element that contains it. * https://www.w3.org/TR/SVG-access/#Equivalent */ titleAccess?: string; /** * Allows you to redefine what the coordinates without units mean inside an SVG element. * For example, if the SVG element is 500 (width) by 200 (height), * and you pass viewBox="0 0 50 20", * this means that the coordinates inside the SVG will go from the top left corner (0,0) * to bottom right (50,20) and each unit will be worth 10px. */ viewBox?: string; }; defaultComponent: D; classKey: SvgIconClassKey; } /** * * Demos: * * - [Icons](https://material-ui.com/components/icons/) * - [Material Icons](https://material-ui.com/components/material-icons/) * * API: * * - [SvgIcon API](https://material-ui.com/api/svg-icon/) */ declare const SvgIcon: OverridableComponent<SvgIconTypeMap>; export type SvgIconClassKey = | 'root' | 'colorSecondary' | 'colorAction' | 'colorDisabled' | 'colorError' | 'colorPrimary' | 'fontSizeInherit' | 'fontSizeSmall' | 'fontSizeLarge'; export type SvgIconProps< D extends React.ElementType = SvgIconTypeMap['defaultComponent'],
> = OverrideProps<SvgIconTypeMap<P, D>, D>; export default SvgIcon;
P = {}
random_line_split
torrentz.py
#VERSION: 2.14 #AUTHORS: Diego de las Heras (diegodelasheras@gmail.com) # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the author nor the names of its contributors may be # used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. from novaprinter import prettyPrinter from helpers import retrieve_url, download_file from HTMLParser import HTMLParser from urllib import urlencode class torrentz(object): # mandatory properties url = 'https://torrentz.eu' name = 'Torrentz' supported_categories = {'all': ''} trackers_list = ['udp://open.demonii.com:1337/announce', 'udp://tracker.leechers-paradise.org:6969', 'udp://exodus.desync.com:6969', 'udp://tracker.coppersurfer.tk:6969', 'udp://9.rarbg.com:2710/announce'] class MyHtmlParser(HTMLParser): def __init__(self, results, url, trackers): HTMLParser.__init__(self) self.results = results self.url = url self.trackers = trackers self.td_counter = None self.current_item = None def handle_starttag(self, tag, attrs): if tag == 'a': params = dict(attrs) if 'href' in params: self.current_item = {} self.td_counter = 0 self.current_item['link'] = 'magnet:?xt=urn:btih:' + \ params['href'].strip(' /') + self.trackers self.current_item['desc_link'] = self.url + params['href'].strip() elif tag == 'span': if isinstance(self.td_counter,int): self.td_counter += 1 if self.td_counter > 6: # safety self.td_counter = None def handle_data(self, data): if self.td_counter == 0: if 'name' not in self.current_item: self.current_item['name'] = '' self.current_item['name'] += data elif self.td_counter == 4: if 'size' not in self.current_item: self.current_item['size'] = data.strip() elif self.td_counter == 5: if 'seeds' not in self.current_item: self.current_item['seeds'] = data.strip().replace(',', '') elif self.td_counter == 6: if 'leech' not in self.current_item:
self.current_item['leech'] = data.strip().replace(',', '') # display item self.td_counter = None self.current_item['engine_url'] = self.url if self.current_item['name'].find(' \xc2'): self.current_item['name'] = self.current_item['name'].split(' \xc2')[0] self.current_item['link'] += '&' + urlencode({'dn' : self.current_item['name']}) if not self.current_item['seeds'].isdigit(): self.current_item['seeds'] = 0 if not self.current_item['leech'].isdigit(): self.current_item['leech'] = 0 prettyPrinter(self.current_item) self.results.append('a') def download_torrent(self, info): print(download_file(info)) def search(self, what, cat='all'): # initialize trackers for magnet links trackers = '&' + '&'.join(urlencode({'tr' : tracker}) for tracker in self.trackers_list) i = 0 while i < 6: results_list = [] # "what" is already urlencoded html = retrieve_url('%s/any?f=%s&p=%d' % (self.url, what, i)) parser = self.MyHtmlParser(results_list, self.url, trackers) parser.feed(html) parser.close() if len(results_list) < 1: break i += 1
random_line_split
torrentz.py
#VERSION: 2.14 #AUTHORS: Diego de las Heras (diegodelasheras@gmail.com) # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the author nor the names of its contributors may be # used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. from novaprinter import prettyPrinter from helpers import retrieve_url, download_file from HTMLParser import HTMLParser from urllib import urlencode class torrentz(object): # mandatory properties url = 'https://torrentz.eu' name = 'Torrentz' supported_categories = {'all': ''} trackers_list = ['udp://open.demonii.com:1337/announce', 'udp://tracker.leechers-paradise.org:6969', 'udp://exodus.desync.com:6969', 'udp://tracker.coppersurfer.tk:6969', 'udp://9.rarbg.com:2710/announce'] class MyHtmlParser(HTMLParser): def __init__(self, results, url, trackers): HTMLParser.__init__(self) self.results = results self.url = url self.trackers = trackers self.td_counter = None self.current_item = None def handle_starttag(self, tag, attrs): if tag == 'a': params = dict(attrs) if 'href' in params: self.current_item = {} self.td_counter = 0 self.current_item['link'] = 'magnet:?xt=urn:btih:' + \ params['href'].strip(' /') + self.trackers self.current_item['desc_link'] = self.url + params['href'].strip() elif tag == 'span': if isinstance(self.td_counter,int): self.td_counter += 1 if self.td_counter > 6: # safety self.td_counter = None def handle_data(self, data): if self.td_counter == 0: if 'name' not in self.current_item: self.current_item['name'] = '' self.current_item['name'] += data elif self.td_counter == 4: if 'size' not in self.current_item: self.current_item['size'] = data.strip() elif self.td_counter == 5: if 'seeds' not in self.current_item: self.current_item['seeds'] = data.strip().replace(',', '') elif self.td_counter == 6: if 'leech' not in self.current_item: self.current_item['leech'] = data.strip().replace(',', '') # display item self.td_counter = None self.current_item['engine_url'] = self.url if self.current_item['name'].find(' \xc2'):
self.current_item['link'] += '&' + urlencode({'dn' : self.current_item['name']}) if not self.current_item['seeds'].isdigit(): self.current_item['seeds'] = 0 if not self.current_item['leech'].isdigit(): self.current_item['leech'] = 0 prettyPrinter(self.current_item) self.results.append('a') def download_torrent(self, info): print(download_file(info)) def search(self, what, cat='all'): # initialize trackers for magnet links trackers = '&' + '&'.join(urlencode({'tr' : tracker}) for tracker in self.trackers_list) i = 0 while i < 6: results_list = [] # "what" is already urlencoded html = retrieve_url('%s/any?f=%s&p=%d' % (self.url, what, i)) parser = self.MyHtmlParser(results_list, self.url, trackers) parser.feed(html) parser.close() if len(results_list) < 1: break i += 1
self.current_item['name'] = self.current_item['name'].split(' \xc2')[0]
conditional_block
torrentz.py
#VERSION: 2.14 #AUTHORS: Diego de las Heras (diegodelasheras@gmail.com) # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the author nor the names of its contributors may be # used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. from novaprinter import prettyPrinter from helpers import retrieve_url, download_file from HTMLParser import HTMLParser from urllib import urlencode class torrentz(object): # mandatory properties url = 'https://torrentz.eu' name = 'Torrentz' supported_categories = {'all': ''} trackers_list = ['udp://open.demonii.com:1337/announce', 'udp://tracker.leechers-paradise.org:6969', 'udp://exodus.desync.com:6969', 'udp://tracker.coppersurfer.tk:6969', 'udp://9.rarbg.com:2710/announce'] class MyHtmlParser(HTMLParser): def __init__(self, results, url, trackers): HTMLParser.__init__(self) self.results = results self.url = url self.trackers = trackers self.td_counter = None self.current_item = None def handle_starttag(self, tag, attrs): if tag == 'a': params = dict(attrs) if 'href' in params: self.current_item = {} self.td_counter = 0 self.current_item['link'] = 'magnet:?xt=urn:btih:' + \ params['href'].strip(' /') + self.trackers self.current_item['desc_link'] = self.url + params['href'].strip() elif tag == 'span': if isinstance(self.td_counter,int): self.td_counter += 1 if self.td_counter > 6: # safety self.td_counter = None def handle_data(self, data): if self.td_counter == 0: if 'name' not in self.current_item: self.current_item['name'] = '' self.current_item['name'] += data elif self.td_counter == 4: if 'size' not in self.current_item: self.current_item['size'] = data.strip() elif self.td_counter == 5: if 'seeds' not in self.current_item: self.current_item['seeds'] = data.strip().replace(',', '') elif self.td_counter == 6: if 'leech' not in self.current_item: self.current_item['leech'] = data.strip().replace(',', '') # display item self.td_counter = None self.current_item['engine_url'] = self.url if self.current_item['name'].find(' \xc2'): self.current_item['name'] = self.current_item['name'].split(' \xc2')[0] self.current_item['link'] += '&' + urlencode({'dn' : self.current_item['name']}) if not self.current_item['seeds'].isdigit(): self.current_item['seeds'] = 0 if not self.current_item['leech'].isdigit(): self.current_item['leech'] = 0 prettyPrinter(self.current_item) self.results.append('a') def download_torrent(self, info): print(download_file(info)) def
(self, what, cat='all'): # initialize trackers for magnet links trackers = '&' + '&'.join(urlencode({'tr' : tracker}) for tracker in self.trackers_list) i = 0 while i < 6: results_list = [] # "what" is already urlencoded html = retrieve_url('%s/any?f=%s&p=%d' % (self.url, what, i)) parser = self.MyHtmlParser(results_list, self.url, trackers) parser.feed(html) parser.close() if len(results_list) < 1: break i += 1
search
identifier_name
torrentz.py
#VERSION: 2.14 #AUTHORS: Diego de las Heras (diegodelasheras@gmail.com) # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the author nor the names of its contributors may be # used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. from novaprinter import prettyPrinter from helpers import retrieve_url, download_file from HTMLParser import HTMLParser from urllib import urlencode class torrentz(object): # mandatory properties url = 'https://torrentz.eu' name = 'Torrentz' supported_categories = {'all': ''} trackers_list = ['udp://open.demonii.com:1337/announce', 'udp://tracker.leechers-paradise.org:6969', 'udp://exodus.desync.com:6969', 'udp://tracker.coppersurfer.tk:6969', 'udp://9.rarbg.com:2710/announce'] class MyHtmlParser(HTMLParser): def __init__(self, results, url, trackers): HTMLParser.__init__(self) self.results = results self.url = url self.trackers = trackers self.td_counter = None self.current_item = None def handle_starttag(self, tag, attrs): if tag == 'a': params = dict(attrs) if 'href' in params: self.current_item = {} self.td_counter = 0 self.current_item['link'] = 'magnet:?xt=urn:btih:' + \ params['href'].strip(' /') + self.trackers self.current_item['desc_link'] = self.url + params['href'].strip() elif tag == 'span': if isinstance(self.td_counter,int): self.td_counter += 1 if self.td_counter > 6: # safety self.td_counter = None def handle_data(self, data): if self.td_counter == 0: if 'name' not in self.current_item: self.current_item['name'] = '' self.current_item['name'] += data elif self.td_counter == 4: if 'size' not in self.current_item: self.current_item['size'] = data.strip() elif self.td_counter == 5: if 'seeds' not in self.current_item: self.current_item['seeds'] = data.strip().replace(',', '') elif self.td_counter == 6: if 'leech' not in self.current_item: self.current_item['leech'] = data.strip().replace(',', '') # display item self.td_counter = None self.current_item['engine_url'] = self.url if self.current_item['name'].find(' \xc2'): self.current_item['name'] = self.current_item['name'].split(' \xc2')[0] self.current_item['link'] += '&' + urlencode({'dn' : self.current_item['name']}) if not self.current_item['seeds'].isdigit(): self.current_item['seeds'] = 0 if not self.current_item['leech'].isdigit(): self.current_item['leech'] = 0 prettyPrinter(self.current_item) self.results.append('a') def download_torrent(self, info):
def search(self, what, cat='all'): # initialize trackers for magnet links trackers = '&' + '&'.join(urlencode({'tr' : tracker}) for tracker in self.trackers_list) i = 0 while i < 6: results_list = [] # "what" is already urlencoded html = retrieve_url('%s/any?f=%s&p=%d' % (self.url, what, i)) parser = self.MyHtmlParser(results_list, self.url, trackers) parser.feed(html) parser.close() if len(results_list) < 1: break i += 1
print(download_file(info))
identifier_body
config.rs
//! The configuration format for the program container use typedef::*; pub const DEFAULT_SCALE: f64 = 4.0; pub const DEFAULT_SCREEN_WIDTH: usize = 160; pub const DEFAULT_SCREEN_HEIGHT: usize = 100; pub const DEFAULT_WINDOW_TITLE: &str = "bakerVM"; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct DisplayConfig { #[serde(default)] pub resolution: DisplayResolution, pub default_scale: Float, #[serde(default)] pub hide_cursor: bool, } impl Default for DisplayConfig { fn default() -> Self { DisplayConfig { resolution: Default::default(), default_scale: DEFAULT_SCALE, hide_cursor: true, } } } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct DisplayResolution { pub width: usize, pub height: usize, } impl Default for DisplayResolution { fn default() -> Self { DisplayResolution { width: DEFAULT_SCREEN_WIDTH, height: DEFAULT_SCREEN_HEIGHT, } } } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Config { #[serde(default)] pub title: String, #[serde(default)] pub display: DisplayConfig, #[serde(default)] pub input_enabled: bool, } impl Default for Config { fn default() -> Self
}
{ Config { title: DEFAULT_WINDOW_TITLE.into(), display: Default::default(), input_enabled: true, } }
identifier_body
config.rs
//! The configuration format for the program container use typedef::*; pub const DEFAULT_SCALE: f64 = 4.0; pub const DEFAULT_SCREEN_WIDTH: usize = 160; pub const DEFAULT_SCREEN_HEIGHT: usize = 100; pub const DEFAULT_WINDOW_TITLE: &str = "bakerVM"; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct DisplayConfig { #[serde(default)] pub resolution: DisplayResolution, pub default_scale: Float, #[serde(default)] pub hide_cursor: bool, } impl Default for DisplayConfig { fn
() -> Self { DisplayConfig { resolution: Default::default(), default_scale: DEFAULT_SCALE, hide_cursor: true, } } } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct DisplayResolution { pub width: usize, pub height: usize, } impl Default for DisplayResolution { fn default() -> Self { DisplayResolution { width: DEFAULT_SCREEN_WIDTH, height: DEFAULT_SCREEN_HEIGHT, } } } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Config { #[serde(default)] pub title: String, #[serde(default)] pub display: DisplayConfig, #[serde(default)] pub input_enabled: bool, } impl Default for Config { fn default() -> Self { Config { title: DEFAULT_WINDOW_TITLE.into(), display: Default::default(), input_enabled: true, } } }
default
identifier_name
config.rs
//! The configuration format for the program container use typedef::*;
pub const DEFAULT_SCREEN_HEIGHT: usize = 100; pub const DEFAULT_WINDOW_TITLE: &str = "bakerVM"; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct DisplayConfig { #[serde(default)] pub resolution: DisplayResolution, pub default_scale: Float, #[serde(default)] pub hide_cursor: bool, } impl Default for DisplayConfig { fn default() -> Self { DisplayConfig { resolution: Default::default(), default_scale: DEFAULT_SCALE, hide_cursor: true, } } } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct DisplayResolution { pub width: usize, pub height: usize, } impl Default for DisplayResolution { fn default() -> Self { DisplayResolution { width: DEFAULT_SCREEN_WIDTH, height: DEFAULT_SCREEN_HEIGHT, } } } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Config { #[serde(default)] pub title: String, #[serde(default)] pub display: DisplayConfig, #[serde(default)] pub input_enabled: bool, } impl Default for Config { fn default() -> Self { Config { title: DEFAULT_WINDOW_TITLE.into(), display: Default::default(), input_enabled: true, } } }
pub const DEFAULT_SCALE: f64 = 4.0; pub const DEFAULT_SCREEN_WIDTH: usize = 160;
random_line_split
web.dom.iterable.js
var $iterators = require('./es6.array.iterator') , redefine = require('./_redefine') , global = require('./_global') , hide = require('./_hide') , Iterators = require('./_iterators') , wks = require('./_wks') , CORRECT_SYMBOL = require('./_correct-symbol') , ITERATOR = wks('iterator') , TO_STRING_TAG = wks('toStringTag') , ArrayValues = Iterators.Array;
'MimeTypeArray,NamedNodeMap,NodeList,NodeListOf,Plugin,PluginArray,StyleSheetList,TouchList' ).split(','), function(NAME){ var Collection = global[NAME] , proto = Collection && Collection.prototype , key; if(proto){ if(!proto[ITERATOR])hide(proto, ITERATOR, ArrayValues); if(!proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME); Iterators[NAME] = ArrayValues; for(key in $iterators){ if(!CORRECT_SYMBOL || !proto[key])redefine(proto, key, $iterators[key], true); } } });
require('./_').each.call(( 'CSSRuleList,CSSStyleDeclaration,DOMStringList,DOMTokenList,FileList,HTMLCollection,MediaList,' +
random_line_split
imgupload_ostest.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # ================================================================= # ================================================================= import httplib import json import logging import sys import requests import os import hashlib def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) return type('Enum', (), enums) XFER_TYPE = enum('URL', 'FILE') def
(): """ Test file upload """ # setup logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) debug_stream = logging.StreamHandler() logger.addHandler(debug_stream) ############################################################## # common paxes_ip = "9.5.126.255" # Sadek # paxes_ip = "9.5.127.146" # Harish # keystone --insecure token-get tenant_id = "36d6476ee75945a0bb47e6b08c0ae050" # Sadek # tenant_id = "affc458e94c843119d8f0f442408faad" # Harish x_auth_token = "b649417985b74582a969bc853871a810" # Sadek # x_auth_token = "74447c39d56c4598970a2dc58a652d7e" # Harish hmc_id = '2fa9da84-12d1-3256-af87-1b1b1c0134a8' # Sadek # hmc_id="07247992-444c-3e08-9820-3b5c426174ca" # Harish # to create a volume: # paxes-devcli cinder volume-create json scovolume42 42 # use "id", eg "id": "b769d931-0346-4265-a7a4-5bfe9ae22e4f", x_imgupload_cinder_volume_id = \ "78ec5b63-893a-4274-ac33-6ef3257bc9d2" # billsco001 # "83a167d6-3d9e-4f14-bdcc-5f87e2361cee" # Bill 1 # x_imgupload_cinder_volume_id = \ # "5b4d33c0-b2fb-414c-bfbf-5023add3ad99" # Sadek 2 # x_imgupload_cinder_volume_id = \ # "81107edc-06c9-4c8b-9706-214809ea97d7" # Harish ############################################################## # xfer specifics # vios = "2B74BDF1-7CC8-439E-A7D7-15C2B5864DA8" # Sadek # N23 vios = "1BC0CB5E-15BF-492A-8D06-25B69833B54E" # Sadek # N24 # vios = None # Harish #### # STANDARD TESTS # set xfer type # xfer_type = XFER_TYPE.FILE xfer_type = XFER_TYPE.URL # set xfer test xfer_test = "2MB" sha256 = {} if xfer_type == XFER_TYPE.URL: url = "http://9.47.161.56:8080/SHA256SUM" r = requests.get(url) for line in r.content.strip().split("\n"): print line ws = line.split() sha256[ws[0]] = ws[1] elif xfer_type == XFER_TYPE.FILE: with open("/tmp/SHA256SUM", "r") as f: content = f.readlines() for line in content: ws = line.split() sha256[ws[0]] = ws[1] else: raise Exception("Programming error") image_file = {} image_size = {} # for image_file only copy_from = {} # 2MB image_file["2MB"] = "/tmp/testfile2MB.txt" image_size["2MB"] = os.path.getsize(image_file["2MB"]) copy_from["2MB"] = 'http://9.47.161.56:8080/testfile2MB.txt' # checksum = \ # 'e025e4f9d3ccf1a9b25202304d4a3d4822cd6e76843a51b803623f740bc03e66' # 1GB image_file["1GB"] = "/tmp/testfile1GB.txt" image_size["1GB"] = os.path.getsize(image_file["1GB"]) copy_from["1GB"] = 'http://9.47.161.56:8080/testfile1GB.txt' # checksum = \ # '6e86684bdba30e8f1997a652dcb2ba5a199880c44c2c9110b325cd4ca5f48152' # 2GB image_file["2GB"] = "/tmp/testfile2GB.txt" image_size["2GB"] = os.path.getsize(image_file["2GB"]) copy_from["2GB"] = 'http://9.47.161.56:8080/testfile2GB.txt' # checksum = \ # '067002c822d7b7f0a826c6bbd53d30b70b13048f25f10be2e9aacc8056bbc4cc' # PAVEL image_file["PAVEL"] = "/tmp/testfilePAVEL.txt" image_size["PAVEL"] = os.path.getsize(image_file["PAVEL"]) copy_from["PAVEL"] = 'http://9.47.161.56:8080/testfilePAVEL.txt' # checksum = \ # 'b8bbde7ba106d0f6e6cd1c6e033bfa4e6e11d5b4b944aa3e6d08b5a7d3a4252e' # 3GB image_file["3GB"] = "/tmp/testfile3GB.txt" image_size["3GB"] = os.path.getsize(image_file["3GB"]) copy_from["3GB"] = 'http://9.47.161.56:8080/testfile3GB.txt' # checksum = \ # '18c0f13594702add11573ad72ed9baa42facad5ba5fe9a7194465a246a31e000' #### # Images # copy_from = 'http://9.47.161.56:8080/cirros-0.3.0-x86_64-disk.img' # checksum = None # copy_from = 'http://9.47.161.56:8080/IBM_SCE_3.2_PPC64_App-disk3.raw' # checksum = None # copy_from = ('http://pokgsa.ibm.com/home/g/j/gjromano/web/public/' # 'ZippedImagesAndOVFs242/RHEL62/rhel6_2_ds6_21.gz') # Harish # checksum = None # image_size = None # if xfer_type == XFER_TYPE.FILE: # image_size = os.path.getsize(image_file) # if checksum: # assert checksum == _sha256sum(image_file) ############################################################## # test cinder w/ simple get print "test cinder w/ simple GET" method = "GET" simple_apiurl = 'http://%s:9000/v1/%s' % (paxes_ip, tenant_id, ) # simple_apiurl = ('https://%s/paxes/openstack/volume/v1/%s/imgupload' % # (paxes_ip, tenant_id, )) headers = {'X-Auth-Project-Id': 'demo', 'User-Agent': 'python-cinderclient', 'Accept': 'application/json', 'X-Auth-Token': x_auth_token} url = "%s/types" % (simple_apiurl,) resp = requests.request(method, url, headers=headers) if resp.text: try: body = json.loads(resp.text) except ValueError: pass body = None else: body = None if resp.status_code >= 400: raise Exception("status_code: >%s<" % (resp.status_code,)) print body ############################################################## # headers headers = {'X-Auth-Token': x_auth_token, 'Content-Type': 'application/octet-stream', 'User-Agent': 'python-cinderclient', 'x-imgupload-cinder-volume-id': x_imgupload_cinder_volume_id, 'x-imgupload-hmc-id': hmc_id} # add vios header if vios is not None: print "VIOS specified: >%s<" % (vios,) headers['x-imgupload-vios-id'] = vios # optional if xfer_type == XFER_TYPE.FILE: headers['x-imgupload-file-size'] = image_size[xfer_test] headers['Transfer-Encoding'] = 'chunked' if xfer_type == XFER_TYPE.FILE: k = image_file[xfer_test].rsplit("/")[-1] elif xfer_type == XFER_TYPE.URL: k = copy_from[xfer_test].rsplit("/")[-1] else: raise Exception("Programming error") headers['x-imgupload-file-checksum'] = sha256[k] ############################################################## # request url = 'http://%s:9000/v1/%s/imgupload' % (paxes_ip, tenant_id, ) if xfer_type == XFER_TYPE.URL: # url specific headers headers['x-imgupload-copy-from'] = copy_from[xfer_test] print "Upload w/ URL" resp = requests.request("POST", url, headers=headers) if resp.text: try: body = json.loads(resp.text) except ValueError: pass body = None else: body = None print resp if resp.status_code >= 400: print resp.json() raise Exception("status._code: >%s<, reason: >%s<" % (resp.status_code, resp.reason)) print body elif xfer_type == XFER_TYPE.FILE: # local file specific headers print "Upload file" cinder_conn = httplib.HTTPConnection(paxes_ip, '9000', {'timeout': 600.0}) cinder_conn.putrequest("POST", url) for header, value in headers.items(): cinder_conn.putheader(header, value) cinder_conn.endheaders() CHUNKSIZE = 1024 * 64 # 64kB f = open(image_file[xfer_test]) chunk = f.read(CHUNKSIZE) # Chunk it, baby... while chunk: cinder_conn.send('%x\r\n%s\r\n' % (len(chunk), chunk)) chunk = f.read(CHUNKSIZE) cinder_conn.send('0\r\n\r\n') f.close() response = cinder_conn.getresponse() response_read = response.read() print response if response.status != httplib.OK: logger.error(("from cinder, unexpected response.status: >%s<," " response.read: >%s<, post for new image from " "file failed, quitting ..."), response.status, response_read) if response.status == httplib.OK: # 200 datajson = json.loads(response_read) print datajson cinder_conn.close() else: raise ValueError("bad type") logger.info("all done") ######## # upload stuff def _sha256sum(filename): sha256 = hashlib.sha256() with open(filename, 'rb') as f: for chunk in iter(lambda: f.read(128 * sha256.block_size), b''): sha256.update(chunk) return sha256.hexdigest() def _createtestfile(fspec='/tmp/testfile.txt', size=1024 * 1024 * 1024 * 3): start = "start" end = "end" with open(fspec, 'wb') as f: f.write(start) f.seek(size - len(start) + 2) f.write(end) f.close() size = os.path.getsize(fspec) sha256 = _sha256sum(fspec) print ("Created: >%s<, with size: >%d<, with sha256: >%s<" % (fspec, size, sha256)) return (fspec, size, sha256) def createtestfiles(): # 2 MB f2mb = _createtestfile(fspec='/tmp/testfile2MB.txt', size=1024 * 1024 * 2) d2mb = ("dd if=/dev/hdisk6 of=/UPLOAD-TESTS/testfile2MB.txt." "2MB bs=1048576 count=2") # 1 GB f1gb = _createtestfile(fspec='/tmp/testfile1GB.txt', size=1024 * 1024 * 1024 * 1) d1gb = ("dd if=/dev/hdiskx of=/UPLOAD-TESTS/testfile1GB.txt." "1GB bs=1048576 count=1024") # 2 GB f2gb = _createtestfile(fspec='/tmp/testfile2GB.txt', size=1024 * 1024 * 1024 * 2) d2gb = ("dd if=/dev/hdiskx of=/UPLOAD-TESTS/testfile2GB.txt." "2GB bs=1048576 count=2048") # Pavel's number fpavel = _createtestfile(fspec='/tmp/testfilePAVEL.txt', size=1024 * 1024 * 2052) dpavel = ("dd if=/dev/hdiskx of=/UPLOAD-TESTS/testfilePAVEL.txt." "PAVEL bs=1048576 count=2051") # 3 GB f3gb = _createtestfile(fspec='/tmp/testfile3GB.txt', size=1024 * 1024 * 1024 * 3) d3gb = ("dd if=/dev/hdiskx of=/UPLOAD-TESTS/testfile3GB.txt." "3GB bs=1048576 count=3072") kfspec = "/tmp/SHA256SUM" with open(kfspec, "w") as f: for i in [f2mb, f1gb, f2gb, fpavel, f3gb]: (fspec, size, sha256) = i fspec = fspec.rsplit("/")[-1] f.write("%s %s\n" % (fspec, sha256)) print "Output sha256 keys: >%s<" % (kfspec,) for i in [d2mb, d1gb, d2gb, dpavel, d3gb]: print i with open("/tmp/SHA256SUM", "r") as f: content = f.readlines() for line in content: ws = line.split() print ws[0], ws[1] if __name__ == '__main__': # to generate test files # sys.exit(createtestfiles()) # to runtest sys.exit(runtest())
runtest
identifier_name
imgupload_ostest.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # ================================================================= # ================================================================= import httplib import json import logging import sys import requests import os import hashlib def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) return type('Enum', (), enums) XFER_TYPE = enum('URL', 'FILE') def runtest(): """ Test file upload """ # setup logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) debug_stream = logging.StreamHandler() logger.addHandler(debug_stream) ############################################################## # common paxes_ip = "9.5.126.255" # Sadek # paxes_ip = "9.5.127.146" # Harish # keystone --insecure token-get tenant_id = "36d6476ee75945a0bb47e6b08c0ae050" # Sadek # tenant_id = "affc458e94c843119d8f0f442408faad" # Harish x_auth_token = "b649417985b74582a969bc853871a810" # Sadek # x_auth_token = "74447c39d56c4598970a2dc58a652d7e" # Harish hmc_id = '2fa9da84-12d1-3256-af87-1b1b1c0134a8' # Sadek # hmc_id="07247992-444c-3e08-9820-3b5c426174ca" # Harish # to create a volume: # paxes-devcli cinder volume-create json scovolume42 42 # use "id", eg "id": "b769d931-0346-4265-a7a4-5bfe9ae22e4f", x_imgupload_cinder_volume_id = \ "78ec5b63-893a-4274-ac33-6ef3257bc9d2" # billsco001 # "83a167d6-3d9e-4f14-bdcc-5f87e2361cee" # Bill 1 # x_imgupload_cinder_volume_id = \ # "5b4d33c0-b2fb-414c-bfbf-5023add3ad99" # Sadek 2 # x_imgupload_cinder_volume_id = \ # "81107edc-06c9-4c8b-9706-214809ea97d7" # Harish ############################################################## # xfer specifics # vios = "2B74BDF1-7CC8-439E-A7D7-15C2B5864DA8" # Sadek # N23 vios = "1BC0CB5E-15BF-492A-8D06-25B69833B54E" # Sadek # N24 # vios = None # Harish #### # STANDARD TESTS # set xfer type # xfer_type = XFER_TYPE.FILE xfer_type = XFER_TYPE.URL # set xfer test xfer_test = "2MB" sha256 = {} if xfer_type == XFER_TYPE.URL: url = "http://9.47.161.56:8080/SHA256SUM" r = requests.get(url) for line in r.content.strip().split("\n"): print line ws = line.split() sha256[ws[0]] = ws[1] elif xfer_type == XFER_TYPE.FILE: with open("/tmp/SHA256SUM", "r") as f: content = f.readlines() for line in content:
else: raise Exception("Programming error") image_file = {} image_size = {} # for image_file only copy_from = {} # 2MB image_file["2MB"] = "/tmp/testfile2MB.txt" image_size["2MB"] = os.path.getsize(image_file["2MB"]) copy_from["2MB"] = 'http://9.47.161.56:8080/testfile2MB.txt' # checksum = \ # 'e025e4f9d3ccf1a9b25202304d4a3d4822cd6e76843a51b803623f740bc03e66' # 1GB image_file["1GB"] = "/tmp/testfile1GB.txt" image_size["1GB"] = os.path.getsize(image_file["1GB"]) copy_from["1GB"] = 'http://9.47.161.56:8080/testfile1GB.txt' # checksum = \ # '6e86684bdba30e8f1997a652dcb2ba5a199880c44c2c9110b325cd4ca5f48152' # 2GB image_file["2GB"] = "/tmp/testfile2GB.txt" image_size["2GB"] = os.path.getsize(image_file["2GB"]) copy_from["2GB"] = 'http://9.47.161.56:8080/testfile2GB.txt' # checksum = \ # '067002c822d7b7f0a826c6bbd53d30b70b13048f25f10be2e9aacc8056bbc4cc' # PAVEL image_file["PAVEL"] = "/tmp/testfilePAVEL.txt" image_size["PAVEL"] = os.path.getsize(image_file["PAVEL"]) copy_from["PAVEL"] = 'http://9.47.161.56:8080/testfilePAVEL.txt' # checksum = \ # 'b8bbde7ba106d0f6e6cd1c6e033bfa4e6e11d5b4b944aa3e6d08b5a7d3a4252e' # 3GB image_file["3GB"] = "/tmp/testfile3GB.txt" image_size["3GB"] = os.path.getsize(image_file["3GB"]) copy_from["3GB"] = 'http://9.47.161.56:8080/testfile3GB.txt' # checksum = \ # '18c0f13594702add11573ad72ed9baa42facad5ba5fe9a7194465a246a31e000' #### # Images # copy_from = 'http://9.47.161.56:8080/cirros-0.3.0-x86_64-disk.img' # checksum = None # copy_from = 'http://9.47.161.56:8080/IBM_SCE_3.2_PPC64_App-disk3.raw' # checksum = None # copy_from = ('http://pokgsa.ibm.com/home/g/j/gjromano/web/public/' # 'ZippedImagesAndOVFs242/RHEL62/rhel6_2_ds6_21.gz') # Harish # checksum = None # image_size = None # if xfer_type == XFER_TYPE.FILE: # image_size = os.path.getsize(image_file) # if checksum: # assert checksum == _sha256sum(image_file) ############################################################## # test cinder w/ simple get print "test cinder w/ simple GET" method = "GET" simple_apiurl = 'http://%s:9000/v1/%s' % (paxes_ip, tenant_id, ) # simple_apiurl = ('https://%s/paxes/openstack/volume/v1/%s/imgupload' % # (paxes_ip, tenant_id, )) headers = {'X-Auth-Project-Id': 'demo', 'User-Agent': 'python-cinderclient', 'Accept': 'application/json', 'X-Auth-Token': x_auth_token} url = "%s/types" % (simple_apiurl,) resp = requests.request(method, url, headers=headers) if resp.text: try: body = json.loads(resp.text) except ValueError: pass body = None else: body = None if resp.status_code >= 400: raise Exception("status_code: >%s<" % (resp.status_code,)) print body ############################################################## # headers headers = {'X-Auth-Token': x_auth_token, 'Content-Type': 'application/octet-stream', 'User-Agent': 'python-cinderclient', 'x-imgupload-cinder-volume-id': x_imgupload_cinder_volume_id, 'x-imgupload-hmc-id': hmc_id} # add vios header if vios is not None: print "VIOS specified: >%s<" % (vios,) headers['x-imgupload-vios-id'] = vios # optional if xfer_type == XFER_TYPE.FILE: headers['x-imgupload-file-size'] = image_size[xfer_test] headers['Transfer-Encoding'] = 'chunked' if xfer_type == XFER_TYPE.FILE: k = image_file[xfer_test].rsplit("/")[-1] elif xfer_type == XFER_TYPE.URL: k = copy_from[xfer_test].rsplit("/")[-1] else: raise Exception("Programming error") headers['x-imgupload-file-checksum'] = sha256[k] ############################################################## # request url = 'http://%s:9000/v1/%s/imgupload' % (paxes_ip, tenant_id, ) if xfer_type == XFER_TYPE.URL: # url specific headers headers['x-imgupload-copy-from'] = copy_from[xfer_test] print "Upload w/ URL" resp = requests.request("POST", url, headers=headers) if resp.text: try: body = json.loads(resp.text) except ValueError: pass body = None else: body = None print resp if resp.status_code >= 400: print resp.json() raise Exception("status._code: >%s<, reason: >%s<" % (resp.status_code, resp.reason)) print body elif xfer_type == XFER_TYPE.FILE: # local file specific headers print "Upload file" cinder_conn = httplib.HTTPConnection(paxes_ip, '9000', {'timeout': 600.0}) cinder_conn.putrequest("POST", url) for header, value in headers.items(): cinder_conn.putheader(header, value) cinder_conn.endheaders() CHUNKSIZE = 1024 * 64 # 64kB f = open(image_file[xfer_test]) chunk = f.read(CHUNKSIZE) # Chunk it, baby... while chunk: cinder_conn.send('%x\r\n%s\r\n' % (len(chunk), chunk)) chunk = f.read(CHUNKSIZE) cinder_conn.send('0\r\n\r\n') f.close() response = cinder_conn.getresponse() response_read = response.read() print response if response.status != httplib.OK: logger.error(("from cinder, unexpected response.status: >%s<," " response.read: >%s<, post for new image from " "file failed, quitting ..."), response.status, response_read) if response.status == httplib.OK: # 200 datajson = json.loads(response_read) print datajson cinder_conn.close() else: raise ValueError("bad type") logger.info("all done") ######## # upload stuff def _sha256sum(filename): sha256 = hashlib.sha256() with open(filename, 'rb') as f: for chunk in iter(lambda: f.read(128 * sha256.block_size), b''): sha256.update(chunk) return sha256.hexdigest() def _createtestfile(fspec='/tmp/testfile.txt', size=1024 * 1024 * 1024 * 3): start = "start" end = "end" with open(fspec, 'wb') as f: f.write(start) f.seek(size - len(start) + 2) f.write(end) f.close() size = os.path.getsize(fspec) sha256 = _sha256sum(fspec) print ("Created: >%s<, with size: >%d<, with sha256: >%s<" % (fspec, size, sha256)) return (fspec, size, sha256) def createtestfiles(): # 2 MB f2mb = _createtestfile(fspec='/tmp/testfile2MB.txt', size=1024 * 1024 * 2) d2mb = ("dd if=/dev/hdisk6 of=/UPLOAD-TESTS/testfile2MB.txt." "2MB bs=1048576 count=2") # 1 GB f1gb = _createtestfile(fspec='/tmp/testfile1GB.txt', size=1024 * 1024 * 1024 * 1) d1gb = ("dd if=/dev/hdiskx of=/UPLOAD-TESTS/testfile1GB.txt." "1GB bs=1048576 count=1024") # 2 GB f2gb = _createtestfile(fspec='/tmp/testfile2GB.txt', size=1024 * 1024 * 1024 * 2) d2gb = ("dd if=/dev/hdiskx of=/UPLOAD-TESTS/testfile2GB.txt." "2GB bs=1048576 count=2048") # Pavel's number fpavel = _createtestfile(fspec='/tmp/testfilePAVEL.txt', size=1024 * 1024 * 2052) dpavel = ("dd if=/dev/hdiskx of=/UPLOAD-TESTS/testfilePAVEL.txt." "PAVEL bs=1048576 count=2051") # 3 GB f3gb = _createtestfile(fspec='/tmp/testfile3GB.txt', size=1024 * 1024 * 1024 * 3) d3gb = ("dd if=/dev/hdiskx of=/UPLOAD-TESTS/testfile3GB.txt." "3GB bs=1048576 count=3072") kfspec = "/tmp/SHA256SUM" with open(kfspec, "w") as f: for i in [f2mb, f1gb, f2gb, fpavel, f3gb]: (fspec, size, sha256) = i fspec = fspec.rsplit("/")[-1] f.write("%s %s\n" % (fspec, sha256)) print "Output sha256 keys: >%s<" % (kfspec,) for i in [d2mb, d1gb, d2gb, dpavel, d3gb]: print i with open("/tmp/SHA256SUM", "r") as f: content = f.readlines() for line in content: ws = line.split() print ws[0], ws[1] if __name__ == '__main__': # to generate test files # sys.exit(createtestfiles()) # to runtest sys.exit(runtest())
ws = line.split() sha256[ws[0]] = ws[1]
conditional_block
imgupload_ostest.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # ================================================================= # ================================================================= import httplib import json import logging import sys import requests import os import hashlib def enum(*sequential, **named):
XFER_TYPE = enum('URL', 'FILE') def runtest(): """ Test file upload """ # setup logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) debug_stream = logging.StreamHandler() logger.addHandler(debug_stream) ############################################################## # common paxes_ip = "9.5.126.255" # Sadek # paxes_ip = "9.5.127.146" # Harish # keystone --insecure token-get tenant_id = "36d6476ee75945a0bb47e6b08c0ae050" # Sadek # tenant_id = "affc458e94c843119d8f0f442408faad" # Harish x_auth_token = "b649417985b74582a969bc853871a810" # Sadek # x_auth_token = "74447c39d56c4598970a2dc58a652d7e" # Harish hmc_id = '2fa9da84-12d1-3256-af87-1b1b1c0134a8' # Sadek # hmc_id="07247992-444c-3e08-9820-3b5c426174ca" # Harish # to create a volume: # paxes-devcli cinder volume-create json scovolume42 42 # use "id", eg "id": "b769d931-0346-4265-a7a4-5bfe9ae22e4f", x_imgupload_cinder_volume_id = \ "78ec5b63-893a-4274-ac33-6ef3257bc9d2" # billsco001 # "83a167d6-3d9e-4f14-bdcc-5f87e2361cee" # Bill 1 # x_imgupload_cinder_volume_id = \ # "5b4d33c0-b2fb-414c-bfbf-5023add3ad99" # Sadek 2 # x_imgupload_cinder_volume_id = \ # "81107edc-06c9-4c8b-9706-214809ea97d7" # Harish ############################################################## # xfer specifics # vios = "2B74BDF1-7CC8-439E-A7D7-15C2B5864DA8" # Sadek # N23 vios = "1BC0CB5E-15BF-492A-8D06-25B69833B54E" # Sadek # N24 # vios = None # Harish #### # STANDARD TESTS # set xfer type # xfer_type = XFER_TYPE.FILE xfer_type = XFER_TYPE.URL # set xfer test xfer_test = "2MB" sha256 = {} if xfer_type == XFER_TYPE.URL: url = "http://9.47.161.56:8080/SHA256SUM" r = requests.get(url) for line in r.content.strip().split("\n"): print line ws = line.split() sha256[ws[0]] = ws[1] elif xfer_type == XFER_TYPE.FILE: with open("/tmp/SHA256SUM", "r") as f: content = f.readlines() for line in content: ws = line.split() sha256[ws[0]] = ws[1] else: raise Exception("Programming error") image_file = {} image_size = {} # for image_file only copy_from = {} # 2MB image_file["2MB"] = "/tmp/testfile2MB.txt" image_size["2MB"] = os.path.getsize(image_file["2MB"]) copy_from["2MB"] = 'http://9.47.161.56:8080/testfile2MB.txt' # checksum = \ # 'e025e4f9d3ccf1a9b25202304d4a3d4822cd6e76843a51b803623f740bc03e66' # 1GB image_file["1GB"] = "/tmp/testfile1GB.txt" image_size["1GB"] = os.path.getsize(image_file["1GB"]) copy_from["1GB"] = 'http://9.47.161.56:8080/testfile1GB.txt' # checksum = \ # '6e86684bdba30e8f1997a652dcb2ba5a199880c44c2c9110b325cd4ca5f48152' # 2GB image_file["2GB"] = "/tmp/testfile2GB.txt" image_size["2GB"] = os.path.getsize(image_file["2GB"]) copy_from["2GB"] = 'http://9.47.161.56:8080/testfile2GB.txt' # checksum = \ # '067002c822d7b7f0a826c6bbd53d30b70b13048f25f10be2e9aacc8056bbc4cc' # PAVEL image_file["PAVEL"] = "/tmp/testfilePAVEL.txt" image_size["PAVEL"] = os.path.getsize(image_file["PAVEL"]) copy_from["PAVEL"] = 'http://9.47.161.56:8080/testfilePAVEL.txt' # checksum = \ # 'b8bbde7ba106d0f6e6cd1c6e033bfa4e6e11d5b4b944aa3e6d08b5a7d3a4252e' # 3GB image_file["3GB"] = "/tmp/testfile3GB.txt" image_size["3GB"] = os.path.getsize(image_file["3GB"]) copy_from["3GB"] = 'http://9.47.161.56:8080/testfile3GB.txt' # checksum = \ # '18c0f13594702add11573ad72ed9baa42facad5ba5fe9a7194465a246a31e000' #### # Images # copy_from = 'http://9.47.161.56:8080/cirros-0.3.0-x86_64-disk.img' # checksum = None # copy_from = 'http://9.47.161.56:8080/IBM_SCE_3.2_PPC64_App-disk3.raw' # checksum = None # copy_from = ('http://pokgsa.ibm.com/home/g/j/gjromano/web/public/' # 'ZippedImagesAndOVFs242/RHEL62/rhel6_2_ds6_21.gz') # Harish # checksum = None # image_size = None # if xfer_type == XFER_TYPE.FILE: # image_size = os.path.getsize(image_file) # if checksum: # assert checksum == _sha256sum(image_file) ############################################################## # test cinder w/ simple get print "test cinder w/ simple GET" method = "GET" simple_apiurl = 'http://%s:9000/v1/%s' % (paxes_ip, tenant_id, ) # simple_apiurl = ('https://%s/paxes/openstack/volume/v1/%s/imgupload' % # (paxes_ip, tenant_id, )) headers = {'X-Auth-Project-Id': 'demo', 'User-Agent': 'python-cinderclient', 'Accept': 'application/json', 'X-Auth-Token': x_auth_token} url = "%s/types" % (simple_apiurl,) resp = requests.request(method, url, headers=headers) if resp.text: try: body = json.loads(resp.text) except ValueError: pass body = None else: body = None if resp.status_code >= 400: raise Exception("status_code: >%s<" % (resp.status_code,)) print body ############################################################## # headers headers = {'X-Auth-Token': x_auth_token, 'Content-Type': 'application/octet-stream', 'User-Agent': 'python-cinderclient', 'x-imgupload-cinder-volume-id': x_imgupload_cinder_volume_id, 'x-imgupload-hmc-id': hmc_id} # add vios header if vios is not None: print "VIOS specified: >%s<" % (vios,) headers['x-imgupload-vios-id'] = vios # optional if xfer_type == XFER_TYPE.FILE: headers['x-imgupload-file-size'] = image_size[xfer_test] headers['Transfer-Encoding'] = 'chunked' if xfer_type == XFER_TYPE.FILE: k = image_file[xfer_test].rsplit("/")[-1] elif xfer_type == XFER_TYPE.URL: k = copy_from[xfer_test].rsplit("/")[-1] else: raise Exception("Programming error") headers['x-imgupload-file-checksum'] = sha256[k] ############################################################## # request url = 'http://%s:9000/v1/%s/imgupload' % (paxes_ip, tenant_id, ) if xfer_type == XFER_TYPE.URL: # url specific headers headers['x-imgupload-copy-from'] = copy_from[xfer_test] print "Upload w/ URL" resp = requests.request("POST", url, headers=headers) if resp.text: try: body = json.loads(resp.text) except ValueError: pass body = None else: body = None print resp if resp.status_code >= 400: print resp.json() raise Exception("status._code: >%s<, reason: >%s<" % (resp.status_code, resp.reason)) print body elif xfer_type == XFER_TYPE.FILE: # local file specific headers print "Upload file" cinder_conn = httplib.HTTPConnection(paxes_ip, '9000', {'timeout': 600.0}) cinder_conn.putrequest("POST", url) for header, value in headers.items(): cinder_conn.putheader(header, value) cinder_conn.endheaders() CHUNKSIZE = 1024 * 64 # 64kB f = open(image_file[xfer_test]) chunk = f.read(CHUNKSIZE) # Chunk it, baby... while chunk: cinder_conn.send('%x\r\n%s\r\n' % (len(chunk), chunk)) chunk = f.read(CHUNKSIZE) cinder_conn.send('0\r\n\r\n') f.close() response = cinder_conn.getresponse() response_read = response.read() print response if response.status != httplib.OK: logger.error(("from cinder, unexpected response.status: >%s<," " response.read: >%s<, post for new image from " "file failed, quitting ..."), response.status, response_read) if response.status == httplib.OK: # 200 datajson = json.loads(response_read) print datajson cinder_conn.close() else: raise ValueError("bad type") logger.info("all done") ######## # upload stuff def _sha256sum(filename): sha256 = hashlib.sha256() with open(filename, 'rb') as f: for chunk in iter(lambda: f.read(128 * sha256.block_size), b''): sha256.update(chunk) return sha256.hexdigest() def _createtestfile(fspec='/tmp/testfile.txt', size=1024 * 1024 * 1024 * 3): start = "start" end = "end" with open(fspec, 'wb') as f: f.write(start) f.seek(size - len(start) + 2) f.write(end) f.close() size = os.path.getsize(fspec) sha256 = _sha256sum(fspec) print ("Created: >%s<, with size: >%d<, with sha256: >%s<" % (fspec, size, sha256)) return (fspec, size, sha256) def createtestfiles(): # 2 MB f2mb = _createtestfile(fspec='/tmp/testfile2MB.txt', size=1024 * 1024 * 2) d2mb = ("dd if=/dev/hdisk6 of=/UPLOAD-TESTS/testfile2MB.txt." "2MB bs=1048576 count=2") # 1 GB f1gb = _createtestfile(fspec='/tmp/testfile1GB.txt', size=1024 * 1024 * 1024 * 1) d1gb = ("dd if=/dev/hdiskx of=/UPLOAD-TESTS/testfile1GB.txt." "1GB bs=1048576 count=1024") # 2 GB f2gb = _createtestfile(fspec='/tmp/testfile2GB.txt', size=1024 * 1024 * 1024 * 2) d2gb = ("dd if=/dev/hdiskx of=/UPLOAD-TESTS/testfile2GB.txt." "2GB bs=1048576 count=2048") # Pavel's number fpavel = _createtestfile(fspec='/tmp/testfilePAVEL.txt', size=1024 * 1024 * 2052) dpavel = ("dd if=/dev/hdiskx of=/UPLOAD-TESTS/testfilePAVEL.txt." "PAVEL bs=1048576 count=2051") # 3 GB f3gb = _createtestfile(fspec='/tmp/testfile3GB.txt', size=1024 * 1024 * 1024 * 3) d3gb = ("dd if=/dev/hdiskx of=/UPLOAD-TESTS/testfile3GB.txt." "3GB bs=1048576 count=3072") kfspec = "/tmp/SHA256SUM" with open(kfspec, "w") as f: for i in [f2mb, f1gb, f2gb, fpavel, f3gb]: (fspec, size, sha256) = i fspec = fspec.rsplit("/")[-1] f.write("%s %s\n" % (fspec, sha256)) print "Output sha256 keys: >%s<" % (kfspec,) for i in [d2mb, d1gb, d2gb, dpavel, d3gb]: print i with open("/tmp/SHA256SUM", "r") as f: content = f.readlines() for line in content: ws = line.split() print ws[0], ws[1] if __name__ == '__main__': # to generate test files # sys.exit(createtestfiles()) # to runtest sys.exit(runtest())
enums = dict(zip(sequential, range(len(sequential))), **named) return type('Enum', (), enums)
identifier_body
imgupload_ostest.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # ================================================================= # ================================================================= import httplib import json import logging import sys import requests import os import hashlib def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) return type('Enum', (), enums) XFER_TYPE = enum('URL', 'FILE')
def runtest(): """ Test file upload """ # setup logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) debug_stream = logging.StreamHandler() logger.addHandler(debug_stream) ############################################################## # common paxes_ip = "9.5.126.255" # Sadek # paxes_ip = "9.5.127.146" # Harish # keystone --insecure token-get tenant_id = "36d6476ee75945a0bb47e6b08c0ae050" # Sadek # tenant_id = "affc458e94c843119d8f0f442408faad" # Harish x_auth_token = "b649417985b74582a969bc853871a810" # Sadek # x_auth_token = "74447c39d56c4598970a2dc58a652d7e" # Harish hmc_id = '2fa9da84-12d1-3256-af87-1b1b1c0134a8' # Sadek # hmc_id="07247992-444c-3e08-9820-3b5c426174ca" # Harish # to create a volume: # paxes-devcli cinder volume-create json scovolume42 42 # use "id", eg "id": "b769d931-0346-4265-a7a4-5bfe9ae22e4f", x_imgupload_cinder_volume_id = \ "78ec5b63-893a-4274-ac33-6ef3257bc9d2" # billsco001 # "83a167d6-3d9e-4f14-bdcc-5f87e2361cee" # Bill 1 # x_imgupload_cinder_volume_id = \ # "5b4d33c0-b2fb-414c-bfbf-5023add3ad99" # Sadek 2 # x_imgupload_cinder_volume_id = \ # "81107edc-06c9-4c8b-9706-214809ea97d7" # Harish ############################################################## # xfer specifics # vios = "2B74BDF1-7CC8-439E-A7D7-15C2B5864DA8" # Sadek # N23 vios = "1BC0CB5E-15BF-492A-8D06-25B69833B54E" # Sadek # N24 # vios = None # Harish #### # STANDARD TESTS # set xfer type # xfer_type = XFER_TYPE.FILE xfer_type = XFER_TYPE.URL # set xfer test xfer_test = "2MB" sha256 = {} if xfer_type == XFER_TYPE.URL: url = "http://9.47.161.56:8080/SHA256SUM" r = requests.get(url) for line in r.content.strip().split("\n"): print line ws = line.split() sha256[ws[0]] = ws[1] elif xfer_type == XFER_TYPE.FILE: with open("/tmp/SHA256SUM", "r") as f: content = f.readlines() for line in content: ws = line.split() sha256[ws[0]] = ws[1] else: raise Exception("Programming error") image_file = {} image_size = {} # for image_file only copy_from = {} # 2MB image_file["2MB"] = "/tmp/testfile2MB.txt" image_size["2MB"] = os.path.getsize(image_file["2MB"]) copy_from["2MB"] = 'http://9.47.161.56:8080/testfile2MB.txt' # checksum = \ # 'e025e4f9d3ccf1a9b25202304d4a3d4822cd6e76843a51b803623f740bc03e66' # 1GB image_file["1GB"] = "/tmp/testfile1GB.txt" image_size["1GB"] = os.path.getsize(image_file["1GB"]) copy_from["1GB"] = 'http://9.47.161.56:8080/testfile1GB.txt' # checksum = \ # '6e86684bdba30e8f1997a652dcb2ba5a199880c44c2c9110b325cd4ca5f48152' # 2GB image_file["2GB"] = "/tmp/testfile2GB.txt" image_size["2GB"] = os.path.getsize(image_file["2GB"]) copy_from["2GB"] = 'http://9.47.161.56:8080/testfile2GB.txt' # checksum = \ # '067002c822d7b7f0a826c6bbd53d30b70b13048f25f10be2e9aacc8056bbc4cc' # PAVEL image_file["PAVEL"] = "/tmp/testfilePAVEL.txt" image_size["PAVEL"] = os.path.getsize(image_file["PAVEL"]) copy_from["PAVEL"] = 'http://9.47.161.56:8080/testfilePAVEL.txt' # checksum = \ # 'b8bbde7ba106d0f6e6cd1c6e033bfa4e6e11d5b4b944aa3e6d08b5a7d3a4252e' # 3GB image_file["3GB"] = "/tmp/testfile3GB.txt" image_size["3GB"] = os.path.getsize(image_file["3GB"]) copy_from["3GB"] = 'http://9.47.161.56:8080/testfile3GB.txt' # checksum = \ # '18c0f13594702add11573ad72ed9baa42facad5ba5fe9a7194465a246a31e000' #### # Images # copy_from = 'http://9.47.161.56:8080/cirros-0.3.0-x86_64-disk.img' # checksum = None # copy_from = 'http://9.47.161.56:8080/IBM_SCE_3.2_PPC64_App-disk3.raw' # checksum = None # copy_from = ('http://pokgsa.ibm.com/home/g/j/gjromano/web/public/' # 'ZippedImagesAndOVFs242/RHEL62/rhel6_2_ds6_21.gz') # Harish # checksum = None # image_size = None # if xfer_type == XFER_TYPE.FILE: # image_size = os.path.getsize(image_file) # if checksum: # assert checksum == _sha256sum(image_file) ############################################################## # test cinder w/ simple get print "test cinder w/ simple GET" method = "GET" simple_apiurl = 'http://%s:9000/v1/%s' % (paxes_ip, tenant_id, ) # simple_apiurl = ('https://%s/paxes/openstack/volume/v1/%s/imgupload' % # (paxes_ip, tenant_id, )) headers = {'X-Auth-Project-Id': 'demo', 'User-Agent': 'python-cinderclient', 'Accept': 'application/json', 'X-Auth-Token': x_auth_token} url = "%s/types" % (simple_apiurl,) resp = requests.request(method, url, headers=headers) if resp.text: try: body = json.loads(resp.text) except ValueError: pass body = None else: body = None if resp.status_code >= 400: raise Exception("status_code: >%s<" % (resp.status_code,)) print body ############################################################## # headers headers = {'X-Auth-Token': x_auth_token, 'Content-Type': 'application/octet-stream', 'User-Agent': 'python-cinderclient', 'x-imgupload-cinder-volume-id': x_imgupload_cinder_volume_id, 'x-imgupload-hmc-id': hmc_id} # add vios header if vios is not None: print "VIOS specified: >%s<" % (vios,) headers['x-imgupload-vios-id'] = vios # optional if xfer_type == XFER_TYPE.FILE: headers['x-imgupload-file-size'] = image_size[xfer_test] headers['Transfer-Encoding'] = 'chunked' if xfer_type == XFER_TYPE.FILE: k = image_file[xfer_test].rsplit("/")[-1] elif xfer_type == XFER_TYPE.URL: k = copy_from[xfer_test].rsplit("/")[-1] else: raise Exception("Programming error") headers['x-imgupload-file-checksum'] = sha256[k] ############################################################## # request url = 'http://%s:9000/v1/%s/imgupload' % (paxes_ip, tenant_id, ) if xfer_type == XFER_TYPE.URL: # url specific headers headers['x-imgupload-copy-from'] = copy_from[xfer_test] print "Upload w/ URL" resp = requests.request("POST", url, headers=headers) if resp.text: try: body = json.loads(resp.text) except ValueError: pass body = None else: body = None print resp if resp.status_code >= 400: print resp.json() raise Exception("status._code: >%s<, reason: >%s<" % (resp.status_code, resp.reason)) print body elif xfer_type == XFER_TYPE.FILE: # local file specific headers print "Upload file" cinder_conn = httplib.HTTPConnection(paxes_ip, '9000', {'timeout': 600.0}) cinder_conn.putrequest("POST", url) for header, value in headers.items(): cinder_conn.putheader(header, value) cinder_conn.endheaders() CHUNKSIZE = 1024 * 64 # 64kB f = open(image_file[xfer_test]) chunk = f.read(CHUNKSIZE) # Chunk it, baby... while chunk: cinder_conn.send('%x\r\n%s\r\n' % (len(chunk), chunk)) chunk = f.read(CHUNKSIZE) cinder_conn.send('0\r\n\r\n') f.close() response = cinder_conn.getresponse() response_read = response.read() print response if response.status != httplib.OK: logger.error(("from cinder, unexpected response.status: >%s<," " response.read: >%s<, post for new image from " "file failed, quitting ..."), response.status, response_read) if response.status == httplib.OK: # 200 datajson = json.loads(response_read) print datajson cinder_conn.close() else: raise ValueError("bad type") logger.info("all done") ######## # upload stuff def _sha256sum(filename): sha256 = hashlib.sha256() with open(filename, 'rb') as f: for chunk in iter(lambda: f.read(128 * sha256.block_size), b''): sha256.update(chunk) return sha256.hexdigest() def _createtestfile(fspec='/tmp/testfile.txt', size=1024 * 1024 * 1024 * 3): start = "start" end = "end" with open(fspec, 'wb') as f: f.write(start) f.seek(size - len(start) + 2) f.write(end) f.close() size = os.path.getsize(fspec) sha256 = _sha256sum(fspec) print ("Created: >%s<, with size: >%d<, with sha256: >%s<" % (fspec, size, sha256)) return (fspec, size, sha256) def createtestfiles(): # 2 MB f2mb = _createtestfile(fspec='/tmp/testfile2MB.txt', size=1024 * 1024 * 2) d2mb = ("dd if=/dev/hdisk6 of=/UPLOAD-TESTS/testfile2MB.txt." "2MB bs=1048576 count=2") # 1 GB f1gb = _createtestfile(fspec='/tmp/testfile1GB.txt', size=1024 * 1024 * 1024 * 1) d1gb = ("dd if=/dev/hdiskx of=/UPLOAD-TESTS/testfile1GB.txt." "1GB bs=1048576 count=1024") # 2 GB f2gb = _createtestfile(fspec='/tmp/testfile2GB.txt', size=1024 * 1024 * 1024 * 2) d2gb = ("dd if=/dev/hdiskx of=/UPLOAD-TESTS/testfile2GB.txt." "2GB bs=1048576 count=2048") # Pavel's number fpavel = _createtestfile(fspec='/tmp/testfilePAVEL.txt', size=1024 * 1024 * 2052) dpavel = ("dd if=/dev/hdiskx of=/UPLOAD-TESTS/testfilePAVEL.txt." "PAVEL bs=1048576 count=2051") # 3 GB f3gb = _createtestfile(fspec='/tmp/testfile3GB.txt', size=1024 * 1024 * 1024 * 3) d3gb = ("dd if=/dev/hdiskx of=/UPLOAD-TESTS/testfile3GB.txt." "3GB bs=1048576 count=3072") kfspec = "/tmp/SHA256SUM" with open(kfspec, "w") as f: for i in [f2mb, f1gb, f2gb, fpavel, f3gb]: (fspec, size, sha256) = i fspec = fspec.rsplit("/")[-1] f.write("%s %s\n" % (fspec, sha256)) print "Output sha256 keys: >%s<" % (kfspec,) for i in [d2mb, d1gb, d2gb, dpavel, d3gb]: print i with open("/tmp/SHA256SUM", "r") as f: content = f.readlines() for line in content: ws = line.split() print ws[0], ws[1] if __name__ == '__main__': # to generate test files # sys.exit(createtestfiles()) # to runtest sys.exit(runtest())
random_line_split
VersionInfo.py
# -*- coding: latin-1 -*- ## ## Copyright (c) 2000, 2001, 2002, 2003 Thomas Heller ## ## Permission is hereby granted, free of charge, to any person obtaining ## a copy of this software and associated documentation files (the ## "Software"), to deal in the Software without restriction, including ## without limitation the rights to use, copy, modify, merge, publish, ## distribute, sublicense, and/or sell copies of the Software, and to ## permit persons to whom the Software is furnished to do so, subject to ## the following conditions: ## ## The above copyright notice and this permission notice shall be ## included in all copies or substantial portions of the Software. ## ## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ## EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ## MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ## NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE ## LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION ## OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION ## WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## # # $Id: VersionInfo.py 392 2004-03-12 17:00:21Z theller $ # # $Log$ # Revision 1.3 2004/01/16 10:45:31 theller # Move py2exe from the sandbox directory up to the root dir. # # Revision 1.3 2003/12/29 13:44:57 theller # Adapt for Python 2.3. # # Revision 1.2 2003/09/18 20:19:57 theller # Remove a 2.3 warning, but mostly this checkin is to test the brand new # py2exe-checkins mailing list. # # Revision 1.1 2003/08/29 12:30:52 mhammond # New py2exe now uses the old resource functions :) # # Revision 1.1 2002/01/29 09:30:55 theller # version 0.3.0 # # Revision 1.2 2002/01/14 19:08:05 theller # Better (?) Unicode handling. # # Revision 1.1 2002/01/07 10:30:32 theller # Create a version resource. # # import struct VOS_NT_WINDOWS32 = 0x00040004 VFT_APP = 0x00000001 RT_VERSION = 16 class VersionError(Exception): pass def w32_uc(text): """convert a string into unicode, then encode it into UTF-16 little endian, ready to use for win32 apis""" if type(text) is str: return unicode(text, "unicode-escape").encode("utf-16-le") return unicode(text).encode("utf-16-le") class VS_FIXEDFILEINFO: dwSignature = 0xFEEF04BDL dwStrucVersion = 0x00010000 dwFileVersionMS = 0x00010000 dwFileVersionLS = 0x00000001 dwProductVersionMS = 0x00010000 dwProductVersionLS = 0x00000001 dwFileFlagsMask = 0x3F dwFileFlags = 0 dwFileOS = VOS_NT_WINDOWS32 dwFileType = VFT_APP dwFileSubtype = 0 dwFileDateMS = 0 dwFileDateLS = 0 fmt = "13L" def __init__(self, version): import string version = string.replace(version, ",", ".") fields = string.split(version + '.0.0.0.0', ".")[:4] fields = map(string.strip, fields) try: self.dwFileVersionMS = int(fields[0]) * 65536 + int(fields[1]) self.dwFileVersionLS = int(fields[2]) * 65536 + int(fields[3]) except ValueError: raise VersionError, "could not parse version number '%s'" % version def __str__(self): return struct.pack(self.fmt, self.dwSignature, self.dwStrucVersion, self.dwFileVersionMS, self.dwFileVersionLS, self.dwProductVersionMS, self.dwProductVersionLS, self.dwFileFlagsMask, self.dwFileFlags, self.dwFileOS, self.dwFileType, self.dwFileSubtype, self.dwFileDateMS, self.dwFileDateLS) def align(data): pad = - len(data) % 4 return data + '\000' * pad class VS_STRUCT: items = () def __str__(self): szKey = w32_uc(self.name) ulen = len(szKey)+2 value = self.get_value() data = struct.pack("h%ss0i" % ulen, self.wType, szKey) + value data = align(data) for item in self.items: data = data + str(item) wLength = len(data) + 4 # 4 bytes for wLength and wValueLength wValueLength = len(value) return self.pack("hh", wLength, wValueLength, data) def pack(self, fmt, len, vlen, data): return struct.pack(fmt, len, vlen) + data def get_value(self): return "" class String(VS_STRUCT): wType = 1 items = () def __init__(self, (name, value)): self.name = name if value: self.value = value + '\000' # strings must be zero terminated else: self.value = value def pack(self, fmt, len, vlen, data): # ValueLength is measured in WORDS, not in BYTES! return struct.pack(fmt, len, vlen/2) + data def get_value(self): return w32_uc(self.value) class StringTable(VS_STRUCT): wType = 1 def __init__(self, name, strings): self.name = name self.items = map(String, strings) class StringFileInfo(VS_STRUCT): wType = 1 name = "StringFileInfo" def __init__(self, name, strings): self.items = [StringTable(name, strings)] class Var(VS_STRUCT): # MSDN says: # If you use the Var structure to list the languages your # application or DLL supports instead of using multiple version # resources, use the Value member to contain an array of DWORD # values indicating the language and code page combinations # supported by this file. The low-order word of each DWORD must # contain a Microsoft language identifier, and the high-order word # must contain the IBM® code page number. Either high-order or # low-order word can be zero, indicating that the file is language # or code page independent. If the Var structure is omitted, the # file will be interpreted as both language and code page # independent. w
class VarFileInfo(VS_STRUCT): wType = 1 name = "VarFileInfo" def __init__(self, *names): self.items = map(Var, names) def get_value(self): return "" class VS_VERSIONINFO(VS_STRUCT): wType = 0 # 0: binary data, 1: text data name = "VS_VERSION_INFO" def __init__(self, version, items): self.value = VS_FIXEDFILEINFO(version) self.items = items def get_value(self): return str(self.value) class Version(object): def __init__(self, version, comments = None, company_name = None, file_description = None, internal_name = None, legal_copyright = None, legal_trademarks = None, original_filename = None, private_build = None, product_name = None, product_version = None, special_build = None): self.version = version strings = [] if comments is not None: strings.append(("Comments", comments)) if company_name is not None: strings.append(("CompanyName", company_name)) if file_description is not None: strings.append(("FileDescription", file_description)) strings.append(("FileVersion", version)) if internal_name is not None: strings.append(("InternalName", internal_name)) if legal_copyright is not None: strings.append(("LegalCopyright", legal_copyright)) if legal_trademarks is not None: strings.append(("LegalTrademarks", legal_trademarks)) if original_filename is not None: strings.append(("OriginalFilename", original_filename)) if private_build is not None: strings.append(("PrivateBuild", private_build)) if product_name is not None: strings.append(("ProductName", product_name)) strings.append(("ProductVersion", product_version or version)) if special_build is not None: strings.append(("SpecialBuild", special_build)) self.strings = strings def resource_bytes(self): vs = VS_VERSIONINFO(self.version, [StringFileInfo("040904B0", self.strings), VarFileInfo(0x04B00409)]) return str(vs) def test(): import sys sys.path.append("c:/tmp") from hexdump import hexdump version = Version("1, 0, 0, 1", comments = "ümläut comments", company_name = "No Company", file_description = "silly application", internal_name = "silly", legal_copyright = u"Copyright © 2003", ## legal_trademark = "", original_filename = "silly.exe", private_build = "test build", product_name = "silly product", product_version = None, ## special_build = "" ) hexdump(version.resource_bytes()) if __name__ == '__main__': import sys sys.path.append("d:/nbalt/tmp") from hexdump import hexdump test()
Type = 0 name = "Translation" def __init__(self, value): self.value = value def get_value(self): return struct.pack("l", self.value)
identifier_body
VersionInfo.py
# -*- coding: latin-1 -*- ## ## Copyright (c) 2000, 2001, 2002, 2003 Thomas Heller ## ## Permission is hereby granted, free of charge, to any person obtaining ## a copy of this software and associated documentation files (the ## "Software"), to deal in the Software without restriction, including ## without limitation the rights to use, copy, modify, merge, publish, ## distribute, sublicense, and/or sell copies of the Software, and to ## permit persons to whom the Software is furnished to do so, subject to ## the following conditions: ## ## The above copyright notice and this permission notice shall be ## included in all copies or substantial portions of the Software. ## ## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ## EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ## MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ## NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE ## LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION ## OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION ## WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## # # $Id: VersionInfo.py 392 2004-03-12 17:00:21Z theller $ # # $Log$ # Revision 1.3 2004/01/16 10:45:31 theller # Move py2exe from the sandbox directory up to the root dir. # # Revision 1.3 2003/12/29 13:44:57 theller # Adapt for Python 2.3. # # Revision 1.2 2003/09/18 20:19:57 theller # Remove a 2.3 warning, but mostly this checkin is to test the brand new # py2exe-checkins mailing list. # # Revision 1.1 2003/08/29 12:30:52 mhammond # New py2exe now uses the old resource functions :) # # Revision 1.1 2002/01/29 09:30:55 theller # version 0.3.0 # # Revision 1.2 2002/01/14 19:08:05 theller # Better (?) Unicode handling. # # Revision 1.1 2002/01/07 10:30:32 theller # Create a version resource. # # import struct VOS_NT_WINDOWS32 = 0x00040004 VFT_APP = 0x00000001 RT_VERSION = 16 class VersionError(Exception): pass def w32_uc(text): """convert a string into unicode, then encode it into UTF-16 little endian, ready to use for win32 apis""" if type(text) is str: return unicode(text, "unicode-escape").encode("utf-16-le") return unicode(text).encode("utf-16-le") class VS_FIXEDFILEINFO: dwSignature = 0xFEEF04BDL dwStrucVersion = 0x00010000 dwFileVersionMS = 0x00010000 dwFileVersionLS = 0x00000001 dwProductVersionMS = 0x00010000 dwProductVersionLS = 0x00000001 dwFileFlagsMask = 0x3F dwFileFlags = 0 dwFileOS = VOS_NT_WINDOWS32 dwFileType = VFT_APP dwFileSubtype = 0 dwFileDateMS = 0 dwFileDateLS = 0 fmt = "13L" def __init__(self, version): import string version = string.replace(version, ",", ".") fields = string.split(version + '.0.0.0.0', ".")[:4] fields = map(string.strip, fields) try: self.dwFileVersionMS = int(fields[0]) * 65536 + int(fields[1]) self.dwFileVersionLS = int(fields[2]) * 65536 + int(fields[3]) except ValueError: raise VersionError, "could not parse version number '%s'" % version def __str__(self): return struct.pack(self.fmt, self.dwSignature, self.dwStrucVersion, self.dwFileVersionMS, self.dwFileVersionLS, self.dwProductVersionMS, self.dwProductVersionLS, self.dwFileFlagsMask, self.dwFileFlags, self.dwFileOS, self.dwFileType, self.dwFileSubtype, self.dwFileDateMS, self.dwFileDateLS) def align(data): pad = - len(data) % 4 return data + '\000' * pad class VS_STRUCT: items = () def __str__(self): szKey = w32_uc(self.name) ulen = len(szKey)+2 value = self.get_value() data = struct.pack("h%ss0i" % ulen, self.wType, szKey) + value data = align(data) for item in self.items: data = data + str(item) wLength = len(data) + 4 # 4 bytes for wLength and wValueLength wValueLength = len(value) return self.pack("hh", wLength, wValueLength, data) def pack(self, fmt, len, vlen, data): return struct.pack(fmt, len, vlen) + data def get_value(self): return "" class String(VS_STRUCT): wType = 1 items = () def __init__(self, (name, value)): self.name = name if value: self.value = value + '\000' # strings must be zero terminated else: self.value = value def pack(self, fmt, len, vlen, data): # ValueLength is measured in WORDS, not in BYTES! return struct.pack(fmt, len, vlen/2) + data def get_value(self): return w32_uc(self.value) class StringTable(VS_STRUCT): wType = 1 def __init__(self, name, strings): self.name = name self.items = map(String, strings) class StringFileInfo(VS_STRUCT): wType = 1 name = "StringFileInfo" def __init__(self, name, strings): self.items = [StringTable(name, strings)] class Var(VS_STRUCT): # MSDN says: # If you use the Var structure to list the languages your # application or DLL supports instead of using multiple version # resources, use the Value member to contain an array of DWORD # values indicating the language and code page combinations # supported by this file. The low-order word of each DWORD must # contain a Microsoft language identifier, and the high-order word # must contain the IBM® code page number. Either high-order or # low-order word can be zero, indicating that the file is language # or code page independent. If the Var structure is omitted, the # file will be interpreted as both language and code page # independent. wType = 0 name = "Translation" def __init__(self, value): self.value = value def get_value(self): return struct.pack("l", self.value) class VarFileInfo(VS_STRUCT): wType = 1 name = "VarFileInfo" def __init__(self, *names): self.items = map(Var, names) def get_value(self): return "" class VS_VERSIONINFO(VS_STRUCT): wType = 0 # 0: binary data, 1: text data name = "VS_VERSION_INFO" def __init__(self, version, items): self.value = VS_FIXEDFILEINFO(version) self.items = items def get_value(self): return str(self.value) class Version(object): def __init__(self, version, comments = None, company_name = None, file_description = None, internal_name = None, legal_copyright = None, legal_trademarks = None, original_filename = None, private_build = None, product_name = None, product_version = None, special_build = None): self.version = version strings = [] if comments is not None: strings.append(("Comments", comments)) if company_name is not None: strings.append(("CompanyName", company_name)) if file_description is not None: strings.append(("FileDescription", file_description)) strings.append(("FileVersion", version)) if internal_name is not None: strings.append(("InternalName", internal_name)) if legal_copyright is not None: strings.append(("LegalCopyright", legal_copyright)) if legal_trademarks is not None: strings.append(("LegalTrademarks", legal_trademarks)) if original_filename is not None: strings.append(("OriginalFilename", original_filename)) if private_build is not None: s
if product_name is not None: strings.append(("ProductName", product_name)) strings.append(("ProductVersion", product_version or version)) if special_build is not None: strings.append(("SpecialBuild", special_build)) self.strings = strings def resource_bytes(self): vs = VS_VERSIONINFO(self.version, [StringFileInfo("040904B0", self.strings), VarFileInfo(0x04B00409)]) return str(vs) def test(): import sys sys.path.append("c:/tmp") from hexdump import hexdump version = Version("1, 0, 0, 1", comments = "ümläut comments", company_name = "No Company", file_description = "silly application", internal_name = "silly", legal_copyright = u"Copyright © 2003", ## legal_trademark = "", original_filename = "silly.exe", private_build = "test build", product_name = "silly product", product_version = None, ## special_build = "" ) hexdump(version.resource_bytes()) if __name__ == '__main__': import sys sys.path.append("d:/nbalt/tmp") from hexdump import hexdump test()
trings.append(("PrivateBuild", private_build))
conditional_block
VersionInfo.py
# -*- coding: latin-1 -*- ## ## Copyright (c) 2000, 2001, 2002, 2003 Thomas Heller ## ## Permission is hereby granted, free of charge, to any person obtaining ## a copy of this software and associated documentation files (the ## "Software"), to deal in the Software without restriction, including ## without limitation the rights to use, copy, modify, merge, publish, ## distribute, sublicense, and/or sell copies of the Software, and to ## permit persons to whom the Software is furnished to do so, subject to
## The above copyright notice and this permission notice shall be ## included in all copies or substantial portions of the Software. ## ## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ## EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ## MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ## NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE ## LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION ## OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION ## WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## # # $Id: VersionInfo.py 392 2004-03-12 17:00:21Z theller $ # # $Log$ # Revision 1.3 2004/01/16 10:45:31 theller # Move py2exe from the sandbox directory up to the root dir. # # Revision 1.3 2003/12/29 13:44:57 theller # Adapt for Python 2.3. # # Revision 1.2 2003/09/18 20:19:57 theller # Remove a 2.3 warning, but mostly this checkin is to test the brand new # py2exe-checkins mailing list. # # Revision 1.1 2003/08/29 12:30:52 mhammond # New py2exe now uses the old resource functions :) # # Revision 1.1 2002/01/29 09:30:55 theller # version 0.3.0 # # Revision 1.2 2002/01/14 19:08:05 theller # Better (?) Unicode handling. # # Revision 1.1 2002/01/07 10:30:32 theller # Create a version resource. # # import struct VOS_NT_WINDOWS32 = 0x00040004 VFT_APP = 0x00000001 RT_VERSION = 16 class VersionError(Exception): pass def w32_uc(text): """convert a string into unicode, then encode it into UTF-16 little endian, ready to use for win32 apis""" if type(text) is str: return unicode(text, "unicode-escape").encode("utf-16-le") return unicode(text).encode("utf-16-le") class VS_FIXEDFILEINFO: dwSignature = 0xFEEF04BDL dwStrucVersion = 0x00010000 dwFileVersionMS = 0x00010000 dwFileVersionLS = 0x00000001 dwProductVersionMS = 0x00010000 dwProductVersionLS = 0x00000001 dwFileFlagsMask = 0x3F dwFileFlags = 0 dwFileOS = VOS_NT_WINDOWS32 dwFileType = VFT_APP dwFileSubtype = 0 dwFileDateMS = 0 dwFileDateLS = 0 fmt = "13L" def __init__(self, version): import string version = string.replace(version, ",", ".") fields = string.split(version + '.0.0.0.0', ".")[:4] fields = map(string.strip, fields) try: self.dwFileVersionMS = int(fields[0]) * 65536 + int(fields[1]) self.dwFileVersionLS = int(fields[2]) * 65536 + int(fields[3]) except ValueError: raise VersionError, "could not parse version number '%s'" % version def __str__(self): return struct.pack(self.fmt, self.dwSignature, self.dwStrucVersion, self.dwFileVersionMS, self.dwFileVersionLS, self.dwProductVersionMS, self.dwProductVersionLS, self.dwFileFlagsMask, self.dwFileFlags, self.dwFileOS, self.dwFileType, self.dwFileSubtype, self.dwFileDateMS, self.dwFileDateLS) def align(data): pad = - len(data) % 4 return data + '\000' * pad class VS_STRUCT: items = () def __str__(self): szKey = w32_uc(self.name) ulen = len(szKey)+2 value = self.get_value() data = struct.pack("h%ss0i" % ulen, self.wType, szKey) + value data = align(data) for item in self.items: data = data + str(item) wLength = len(data) + 4 # 4 bytes for wLength and wValueLength wValueLength = len(value) return self.pack("hh", wLength, wValueLength, data) def pack(self, fmt, len, vlen, data): return struct.pack(fmt, len, vlen) + data def get_value(self): return "" class String(VS_STRUCT): wType = 1 items = () def __init__(self, (name, value)): self.name = name if value: self.value = value + '\000' # strings must be zero terminated else: self.value = value def pack(self, fmt, len, vlen, data): # ValueLength is measured in WORDS, not in BYTES! return struct.pack(fmt, len, vlen/2) + data def get_value(self): return w32_uc(self.value) class StringTable(VS_STRUCT): wType = 1 def __init__(self, name, strings): self.name = name self.items = map(String, strings) class StringFileInfo(VS_STRUCT): wType = 1 name = "StringFileInfo" def __init__(self, name, strings): self.items = [StringTable(name, strings)] class Var(VS_STRUCT): # MSDN says: # If you use the Var structure to list the languages your # application or DLL supports instead of using multiple version # resources, use the Value member to contain an array of DWORD # values indicating the language and code page combinations # supported by this file. The low-order word of each DWORD must # contain a Microsoft language identifier, and the high-order word # must contain the IBM® code page number. Either high-order or # low-order word can be zero, indicating that the file is language # or code page independent. If the Var structure is omitted, the # file will be interpreted as both language and code page # independent. wType = 0 name = "Translation" def __init__(self, value): self.value = value def get_value(self): return struct.pack("l", self.value) class VarFileInfo(VS_STRUCT): wType = 1 name = "VarFileInfo" def __init__(self, *names): self.items = map(Var, names) def get_value(self): return "" class VS_VERSIONINFO(VS_STRUCT): wType = 0 # 0: binary data, 1: text data name = "VS_VERSION_INFO" def __init__(self, version, items): self.value = VS_FIXEDFILEINFO(version) self.items = items def get_value(self): return str(self.value) class Version(object): def __init__(self, version, comments = None, company_name = None, file_description = None, internal_name = None, legal_copyright = None, legal_trademarks = None, original_filename = None, private_build = None, product_name = None, product_version = None, special_build = None): self.version = version strings = [] if comments is not None: strings.append(("Comments", comments)) if company_name is not None: strings.append(("CompanyName", company_name)) if file_description is not None: strings.append(("FileDescription", file_description)) strings.append(("FileVersion", version)) if internal_name is not None: strings.append(("InternalName", internal_name)) if legal_copyright is not None: strings.append(("LegalCopyright", legal_copyright)) if legal_trademarks is not None: strings.append(("LegalTrademarks", legal_trademarks)) if original_filename is not None: strings.append(("OriginalFilename", original_filename)) if private_build is not None: strings.append(("PrivateBuild", private_build)) if product_name is not None: strings.append(("ProductName", product_name)) strings.append(("ProductVersion", product_version or version)) if special_build is not None: strings.append(("SpecialBuild", special_build)) self.strings = strings def resource_bytes(self): vs = VS_VERSIONINFO(self.version, [StringFileInfo("040904B0", self.strings), VarFileInfo(0x04B00409)]) return str(vs) def test(): import sys sys.path.append("c:/tmp") from hexdump import hexdump version = Version("1, 0, 0, 1", comments = "ümläut comments", company_name = "No Company", file_description = "silly application", internal_name = "silly", legal_copyright = u"Copyright © 2003", ## legal_trademark = "", original_filename = "silly.exe", private_build = "test build", product_name = "silly product", product_version = None, ## special_build = "" ) hexdump(version.resource_bytes()) if __name__ == '__main__': import sys sys.path.append("d:/nbalt/tmp") from hexdump import hexdump test()
## the following conditions: ##
random_line_split
VersionInfo.py
# -*- coding: latin-1 -*- ## ## Copyright (c) 2000, 2001, 2002, 2003 Thomas Heller ## ## Permission is hereby granted, free of charge, to any person obtaining ## a copy of this software and associated documentation files (the ## "Software"), to deal in the Software without restriction, including ## without limitation the rights to use, copy, modify, merge, publish, ## distribute, sublicense, and/or sell copies of the Software, and to ## permit persons to whom the Software is furnished to do so, subject to ## the following conditions: ## ## The above copyright notice and this permission notice shall be ## included in all copies or substantial portions of the Software. ## ## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ## EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ## MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ## NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE ## LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION ## OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION ## WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## # # $Id: VersionInfo.py 392 2004-03-12 17:00:21Z theller $ # # $Log$ # Revision 1.3 2004/01/16 10:45:31 theller # Move py2exe from the sandbox directory up to the root dir. # # Revision 1.3 2003/12/29 13:44:57 theller # Adapt for Python 2.3. # # Revision 1.2 2003/09/18 20:19:57 theller # Remove a 2.3 warning, but mostly this checkin is to test the brand new # py2exe-checkins mailing list. # # Revision 1.1 2003/08/29 12:30:52 mhammond # New py2exe now uses the old resource functions :) # # Revision 1.1 2002/01/29 09:30:55 theller # version 0.3.0 # # Revision 1.2 2002/01/14 19:08:05 theller # Better (?) Unicode handling. # # Revision 1.1 2002/01/07 10:30:32 theller # Create a version resource. # # import struct VOS_NT_WINDOWS32 = 0x00040004 VFT_APP = 0x00000001 RT_VERSION = 16 class VersionError(Exception): pass def w32_uc(text): """convert a string into unicode, then encode it into UTF-16 little endian, ready to use for win32 apis""" if type(text) is str: return unicode(text, "unicode-escape").encode("utf-16-le") return unicode(text).encode("utf-16-le") class VS_FIXEDFILEINFO: dwSignature = 0xFEEF04BDL dwStrucVersion = 0x00010000 dwFileVersionMS = 0x00010000 dwFileVersionLS = 0x00000001 dwProductVersionMS = 0x00010000 dwProductVersionLS = 0x00000001 dwFileFlagsMask = 0x3F dwFileFlags = 0 dwFileOS = VOS_NT_WINDOWS32 dwFileType = VFT_APP dwFileSubtype = 0 dwFileDateMS = 0 dwFileDateLS = 0 fmt = "13L" def __init__(self, version): import string version = string.replace(version, ",", ".") fields = string.split(version + '.0.0.0.0', ".")[:4] fields = map(string.strip, fields) try: self.dwFileVersionMS = int(fields[0]) * 65536 + int(fields[1]) self.dwFileVersionLS = int(fields[2]) * 65536 + int(fields[3]) except ValueError: raise VersionError, "could not parse version number '%s'" % version def __str__(self): return struct.pack(self.fmt, self.dwSignature, self.dwStrucVersion, self.dwFileVersionMS, self.dwFileVersionLS, self.dwProductVersionMS, self.dwProductVersionLS, self.dwFileFlagsMask, self.dwFileFlags, self.dwFileOS, self.dwFileType, self.dwFileSubtype, self.dwFileDateMS, self.dwFileDateLS) def align(data): pad = - len(data) % 4 return data + '\000' * pad class VS_STRUCT: items = () def __str__(self): szKey = w32_uc(self.name) ulen = len(szKey)+2 value = self.get_value() data = struct.pack("h%ss0i" % ulen, self.wType, szKey) + value data = align(data) for item in self.items: data = data + str(item) wLength = len(data) + 4 # 4 bytes for wLength and wValueLength wValueLength = len(value) return self.pack("hh", wLength, wValueLength, data) def pack(self, fmt, len, vlen, data): return struct.pack(fmt, len, vlen) + data def get_value(self): return "" class String(VS_STRUCT): wType = 1 items = () def __init__(self, (name, value)): self.name = name if value: self.value = value + '\000' # strings must be zero terminated else: self.value = value def pack(self, fmt, len, vlen, data): # ValueLength is measured in WORDS, not in BYTES! return struct.pack(fmt, len, vlen/2) + data def get_value(self): return w32_uc(self.value) class StringTable(VS_STRUCT): wType = 1 def __init__(self, name, strings): self.name = name self.items = map(String, strings) class StringFileInfo(VS_STRUCT): wType = 1 name = "StringFileInfo" def __init__(self, name, strings): self.items = [StringTable(name, strings)] class Var(VS_STRUCT): # MSDN says: # If you use the Var structure to list the languages your # application or DLL supports instead of using multiple version # resources, use the Value member to contain an array of DWORD # values indicating the language and code page combinations # supported by this file. The low-order word of each DWORD must # contain a Microsoft language identifier, and the high-order word # must contain the IBM® code page number. Either high-order or # low-order word can be zero, indicating that the file is language # or code page independent. If the Var structure is omitted, the # file will be interpreted as both language and code page # independent. wType = 0 name = "Translation" def __init__(self, value): self.value = value def g
self): return struct.pack("l", self.value) class VarFileInfo(VS_STRUCT): wType = 1 name = "VarFileInfo" def __init__(self, *names): self.items = map(Var, names) def get_value(self): return "" class VS_VERSIONINFO(VS_STRUCT): wType = 0 # 0: binary data, 1: text data name = "VS_VERSION_INFO" def __init__(self, version, items): self.value = VS_FIXEDFILEINFO(version) self.items = items def get_value(self): return str(self.value) class Version(object): def __init__(self, version, comments = None, company_name = None, file_description = None, internal_name = None, legal_copyright = None, legal_trademarks = None, original_filename = None, private_build = None, product_name = None, product_version = None, special_build = None): self.version = version strings = [] if comments is not None: strings.append(("Comments", comments)) if company_name is not None: strings.append(("CompanyName", company_name)) if file_description is not None: strings.append(("FileDescription", file_description)) strings.append(("FileVersion", version)) if internal_name is not None: strings.append(("InternalName", internal_name)) if legal_copyright is not None: strings.append(("LegalCopyright", legal_copyright)) if legal_trademarks is not None: strings.append(("LegalTrademarks", legal_trademarks)) if original_filename is not None: strings.append(("OriginalFilename", original_filename)) if private_build is not None: strings.append(("PrivateBuild", private_build)) if product_name is not None: strings.append(("ProductName", product_name)) strings.append(("ProductVersion", product_version or version)) if special_build is not None: strings.append(("SpecialBuild", special_build)) self.strings = strings def resource_bytes(self): vs = VS_VERSIONINFO(self.version, [StringFileInfo("040904B0", self.strings), VarFileInfo(0x04B00409)]) return str(vs) def test(): import sys sys.path.append("c:/tmp") from hexdump import hexdump version = Version("1, 0, 0, 1", comments = "ümläut comments", company_name = "No Company", file_description = "silly application", internal_name = "silly", legal_copyright = u"Copyright © 2003", ## legal_trademark = "", original_filename = "silly.exe", private_build = "test build", product_name = "silly product", product_version = None, ## special_build = "" ) hexdump(version.resource_bytes()) if __name__ == '__main__': import sys sys.path.append("d:/nbalt/tmp") from hexdump import hexdump test()
et_value(
identifier_name
info.py
# DFF -- An Open Source Digital Forensics Framework # Copyright (C) 2009-2011 ArxSys # This program is free software, distributed under the terms of # the GNU General Public License Version 2. See the LICENSE file # at the top of the source tree. # # See http://www.digital-forensic.org for more information about this # project. Please do not directly contact any of the maintainers of # DFF for assistance; the project provides a web site, mailing lists # and IRC channels for your use. # # Author(s): # Solal Jacob <sja@digital-forensic.org> # __dff_module_info_version__ = "1.0.0" from api.vfs import * from api.module.script import * from api.loader import * from api.module.module import * from api.taskmanager.taskmanager import * from api.types.libtypes import Parameter, Variant, Argument, typeId, ConfigManager from datetime import timedelta, datetime from ui.console.utils import VariantTreePrinter class
(Script, VariantTreePrinter): def __init__(self): Script.__init__(self, "info") VariantTreePrinter.__init__(self) self.loader = loader.loader() self.tm = TaskManager() self.cm = ConfigManager.Get() def show_config(self, modname): conf = self.cm.configByName(modname) res = "\n\tConfig:" arguments = conf.arguments() for argument in arguments: res += "\n\t\tname: " + str(argument.name()) res += "\n\t\tdescription: " + str(argument.description()) if argument.inputType() == Argument.Empty: res += "\n\t\tno input parameters" else: res += "\n\t\ttype: " + str(typeId.Get().typeToName(argument.type())) res += "\n\t\trequirement: " if argument.requirementType() == Argument.Optional: res += "optional" else: res += "mandatory" res += "\n\t\tinput parameters: " if argument.parametersType() == Parameter.NotEditable: res += "not editable " else: res += "editable " if argument.inputType() == Argument.List: res += "list" else: res += "single" pcount = argument.parametersCount() if pcount != 0: parameters = argument.parameters() res += "\n\t\tpredefined parameters: " for parameter in parameters: if argument.type() == typeId.Node: res += str(parameter.value().absolute()) else: res += parameter.toString() pcount -= 1 if pcount != 0: res += ", " res += "\n" constants = conf.constants() if len(constants) > 0: res += "\n\tConstant: \t" for constant in constants: res += "\n\t\tname: " + str(constant.name()) res += "\n\t\tdescription: " + str(constant.description()) res += "\n\t\ttype: " + str(typeId.Get().typeToName(constant.type())) cvalues = constant.values() cvallen = len(cvalues) if cvallen > 0: res += "\n\t\tvalues: " for cvalue in cvalues: if cvalue.type() == typeId.Node: res += str(cvalue.value().absolute()) else: res += cvalue.toString() cvallen -= 1 if cvallen != 0: res += ", " res += "\n" return res def show_arg(self, args): res = "" if len(args): res += "\n\n\t\tArguments: \t" for argname in args.keys(): res += "\n\t\t\tname: " + argname res += "\n\t\t\tparameters: " val = args[argname] if val.type() == typeId.List: vlist = val.value() vlen = len(vlist) for item in vlist: if item.type == typeId.Node: res += str(val.value().absolute()) else: res += item.toString() vlen -= 1 if vlen != 0: res += ", " elif val.type() == typeId.Node: res += str(val.value().absolute()) return res def show_res(self, results): res = self.fillMap(3, results, "\n\n\t\tResults:") return res def c_display(self): print self.info def getmodinfo(self, modname): conf = self.cm.configByName(modname) if conf == None: return self.lproc = self.tm.lprocessus self.info += "\n" + modname + self.show_config(modname) for proc in self.lproc: if proc.mod.name == modname: self.info += "\n\tProcessus " + str(proc.pid) stime = datetime.fromtimestamp(proc.timestart) self.info += "\n\t\texecution started at : " + str(stime) if proc.timeend: etime = datetime.fromtimestamp(proc.timeend) self.info += "\n\t\texecution finished at : " + str(etime) else: etime = datetime.fromtimestamp(time.time()) delta = etime - stime self.info += "\n\t\texecution time: " + str(delta) self.info += self.show_arg(proc.args) self.info += self.show_res(proc.res) def start(self, args): self.info = "" if args.has_key("modules"): modnames = args['modules'].value() for modname in modnames: self.getmodinfo(modname.value()) else: self.modules = self.loader.modules for modname in self.modules: self.getmodinfo(modname) class info(Module): """Show info on loaded drivers: configuration, arguments, results """ def __init__(self): Module.__init__(self, "info", INFO) self.tags = "builtins" self.conf.addArgument({"name": "modules", "description": "Display information concerning provided modules", "input": Argument.Optional|Argument.List|typeId.String})
INFO
identifier_name
info.py
# DFF -- An Open Source Digital Forensics Framework # Copyright (C) 2009-2011 ArxSys # This program is free software, distributed under the terms of # the GNU General Public License Version 2. See the LICENSE file # at the top of the source tree. # # See http://www.digital-forensic.org for more information about this # project. Please do not directly contact any of the maintainers of # DFF for assistance; the project provides a web site, mailing lists # and IRC channels for your use. # # Author(s): # Solal Jacob <sja@digital-forensic.org> # __dff_module_info_version__ = "1.0.0" from api.vfs import * from api.module.script import * from api.loader import * from api.module.module import * from api.taskmanager.taskmanager import * from api.types.libtypes import Parameter, Variant, Argument, typeId, ConfigManager from datetime import timedelta, datetime from ui.console.utils import VariantTreePrinter class INFO(Script, VariantTreePrinter): def __init__(self): Script.__init__(self, "info") VariantTreePrinter.__init__(self) self.loader = loader.loader() self.tm = TaskManager() self.cm = ConfigManager.Get() def show_config(self, modname): conf = self.cm.configByName(modname) res = "\n\tConfig:" arguments = conf.arguments() for argument in arguments: res += "\n\t\tname: " + str(argument.name()) res += "\n\t\tdescription: " + str(argument.description()) if argument.inputType() == Argument.Empty: res += "\n\t\tno input parameters" else: res += "\n\t\ttype: " + str(typeId.Get().typeToName(argument.type())) res += "\n\t\trequirement: " if argument.requirementType() == Argument.Optional: res += "optional" else: res += "mandatory" res += "\n\t\tinput parameters: " if argument.parametersType() == Parameter.NotEditable: res += "not editable " else: res += "editable " if argument.inputType() == Argument.List: res += "list" else: res += "single" pcount = argument.parametersCount() if pcount != 0: parameters = argument.parameters() res += "\n\t\tpredefined parameters: " for parameter in parameters: if argument.type() == typeId.Node: res += str(parameter.value().absolute()) else: res += parameter.toString() pcount -= 1 if pcount != 0: res += ", " res += "\n" constants = conf.constants() if len(constants) > 0: res += "\n\tConstant: \t" for constant in constants: res += "\n\t\tname: " + str(constant.name()) res += "\n\t\tdescription: " + str(constant.description()) res += "\n\t\ttype: " + str(typeId.Get().typeToName(constant.type())) cvalues = constant.values() cvallen = len(cvalues) if cvallen > 0: res += "\n\t\tvalues: " for cvalue in cvalues: if cvalue.type() == typeId.Node: res += str(cvalue.value().absolute()) else: res += cvalue.toString() cvallen -= 1 if cvallen != 0: res += ", " res += "\n" return res def show_arg(self, args): res = "" if len(args): res += "\n\n\t\tArguments: \t" for argname in args.keys(): res += "\n\t\t\tname: " + argname res += "\n\t\t\tparameters: " val = args[argname] if val.type() == typeId.List: vlist = val.value() vlen = len(vlist) for item in vlist: if item.type == typeId.Node: res += str(val.value().absolute()) else: res += item.toString() vlen -= 1 if vlen != 0: res += ", " elif val.type() == typeId.Node: res += str(val.value().absolute()) return res def show_res(self, results): res = self.fillMap(3, results, "\n\n\t\tResults:") return res def c_display(self): print self.info def getmodinfo(self, modname): conf = self.cm.configByName(modname) if conf == None: return self.lproc = self.tm.lprocessus self.info += "\n" + modname + self.show_config(modname) for proc in self.lproc: if proc.mod.name == modname: self.info += "\n\tProcessus " + str(proc.pid) stime = datetime.fromtimestamp(proc.timestart) self.info += "\n\t\texecution started at : " + str(stime) if proc.timeend: etime = datetime.fromtimestamp(proc.timeend) self.info += "\n\t\texecution finished at : " + str(etime) else: etime = datetime.fromtimestamp(time.time()) delta = etime - stime self.info += "\n\t\texecution time: " + str(delta) self.info += self.show_arg(proc.args) self.info += self.show_res(proc.res) def start(self, args): self.info = "" if args.has_key("modules"): modnames = args['modules'].value() for modname in modnames: self.getmodinfo(modname.value()) else: self.modules = self.loader.modules for modname in self.modules: self.getmodinfo(modname) class info(Module): """Show info on loaded drivers: configuration, arguments, results """ def __init__(self):
Module.__init__(self, "info", INFO) self.tags = "builtins" self.conf.addArgument({"name": "modules", "description": "Display information concerning provided modules", "input": Argument.Optional|Argument.List|typeId.String})
random_line_split
info.py
# DFF -- An Open Source Digital Forensics Framework # Copyright (C) 2009-2011 ArxSys # This program is free software, distributed under the terms of # the GNU General Public License Version 2. See the LICENSE file # at the top of the source tree. # # See http://www.digital-forensic.org for more information about this # project. Please do not directly contact any of the maintainers of # DFF for assistance; the project provides a web site, mailing lists # and IRC channels for your use. # # Author(s): # Solal Jacob <sja@digital-forensic.org> # __dff_module_info_version__ = "1.0.0" from api.vfs import * from api.module.script import * from api.loader import * from api.module.module import * from api.taskmanager.taskmanager import * from api.types.libtypes import Parameter, Variant, Argument, typeId, ConfigManager from datetime import timedelta, datetime from ui.console.utils import VariantTreePrinter class INFO(Script, VariantTreePrinter): def __init__(self):
def show_config(self, modname): conf = self.cm.configByName(modname) res = "\n\tConfig:" arguments = conf.arguments() for argument in arguments: res += "\n\t\tname: " + str(argument.name()) res += "\n\t\tdescription: " + str(argument.description()) if argument.inputType() == Argument.Empty: res += "\n\t\tno input parameters" else: res += "\n\t\ttype: " + str(typeId.Get().typeToName(argument.type())) res += "\n\t\trequirement: " if argument.requirementType() == Argument.Optional: res += "optional" else: res += "mandatory" res += "\n\t\tinput parameters: " if argument.parametersType() == Parameter.NotEditable: res += "not editable " else: res += "editable " if argument.inputType() == Argument.List: res += "list" else: res += "single" pcount = argument.parametersCount() if pcount != 0: parameters = argument.parameters() res += "\n\t\tpredefined parameters: " for parameter in parameters: if argument.type() == typeId.Node: res += str(parameter.value().absolute()) else: res += parameter.toString() pcount -= 1 if pcount != 0: res += ", " res += "\n" constants = conf.constants() if len(constants) > 0: res += "\n\tConstant: \t" for constant in constants: res += "\n\t\tname: " + str(constant.name()) res += "\n\t\tdescription: " + str(constant.description()) res += "\n\t\ttype: " + str(typeId.Get().typeToName(constant.type())) cvalues = constant.values() cvallen = len(cvalues) if cvallen > 0: res += "\n\t\tvalues: " for cvalue in cvalues: if cvalue.type() == typeId.Node: res += str(cvalue.value().absolute()) else: res += cvalue.toString() cvallen -= 1 if cvallen != 0: res += ", " res += "\n" return res def show_arg(self, args): res = "" if len(args): res += "\n\n\t\tArguments: \t" for argname in args.keys(): res += "\n\t\t\tname: " + argname res += "\n\t\t\tparameters: " val = args[argname] if val.type() == typeId.List: vlist = val.value() vlen = len(vlist) for item in vlist: if item.type == typeId.Node: res += str(val.value().absolute()) else: res += item.toString() vlen -= 1 if vlen != 0: res += ", " elif val.type() == typeId.Node: res += str(val.value().absolute()) return res def show_res(self, results): res = self.fillMap(3, results, "\n\n\t\tResults:") return res def c_display(self): print self.info def getmodinfo(self, modname): conf = self.cm.configByName(modname) if conf == None: return self.lproc = self.tm.lprocessus self.info += "\n" + modname + self.show_config(modname) for proc in self.lproc: if proc.mod.name == modname: self.info += "\n\tProcessus " + str(proc.pid) stime = datetime.fromtimestamp(proc.timestart) self.info += "\n\t\texecution started at : " + str(stime) if proc.timeend: etime = datetime.fromtimestamp(proc.timeend) self.info += "\n\t\texecution finished at : " + str(etime) else: etime = datetime.fromtimestamp(time.time()) delta = etime - stime self.info += "\n\t\texecution time: " + str(delta) self.info += self.show_arg(proc.args) self.info += self.show_res(proc.res) def start(self, args): self.info = "" if args.has_key("modules"): modnames = args['modules'].value() for modname in modnames: self.getmodinfo(modname.value()) else: self.modules = self.loader.modules for modname in self.modules: self.getmodinfo(modname) class info(Module): """Show info on loaded drivers: configuration, arguments, results """ def __init__(self): Module.__init__(self, "info", INFO) self.tags = "builtins" self.conf.addArgument({"name": "modules", "description": "Display information concerning provided modules", "input": Argument.Optional|Argument.List|typeId.String})
Script.__init__(self, "info") VariantTreePrinter.__init__(self) self.loader = loader.loader() self.tm = TaskManager() self.cm = ConfigManager.Get()
identifier_body
info.py
# DFF -- An Open Source Digital Forensics Framework # Copyright (C) 2009-2011 ArxSys # This program is free software, distributed under the terms of # the GNU General Public License Version 2. See the LICENSE file # at the top of the source tree. # # See http://www.digital-forensic.org for more information about this # project. Please do not directly contact any of the maintainers of # DFF for assistance; the project provides a web site, mailing lists # and IRC channels for your use. # # Author(s): # Solal Jacob <sja@digital-forensic.org> # __dff_module_info_version__ = "1.0.0" from api.vfs import * from api.module.script import * from api.loader import * from api.module.module import * from api.taskmanager.taskmanager import * from api.types.libtypes import Parameter, Variant, Argument, typeId, ConfigManager from datetime import timedelta, datetime from ui.console.utils import VariantTreePrinter class INFO(Script, VariantTreePrinter): def __init__(self): Script.__init__(self, "info") VariantTreePrinter.__init__(self) self.loader = loader.loader() self.tm = TaskManager() self.cm = ConfigManager.Get() def show_config(self, modname): conf = self.cm.configByName(modname) res = "\n\tConfig:" arguments = conf.arguments() for argument in arguments: res += "\n\t\tname: " + str(argument.name()) res += "\n\t\tdescription: " + str(argument.description()) if argument.inputType() == Argument.Empty: res += "\n\t\tno input parameters" else: res += "\n\t\ttype: " + str(typeId.Get().typeToName(argument.type())) res += "\n\t\trequirement: " if argument.requirementType() == Argument.Optional: res += "optional" else: res += "mandatory" res += "\n\t\tinput parameters: " if argument.parametersType() == Parameter.NotEditable: res += "not editable " else: res += "editable " if argument.inputType() == Argument.List: res += "list" else: res += "single" pcount = argument.parametersCount() if pcount != 0: parameters = argument.parameters() res += "\n\t\tpredefined parameters: " for parameter in parameters: if argument.type() == typeId.Node: res += str(parameter.value().absolute()) else: res += parameter.toString() pcount -= 1 if pcount != 0: res += ", " res += "\n" constants = conf.constants() if len(constants) > 0: res += "\n\tConstant: \t" for constant in constants: res += "\n\t\tname: " + str(constant.name()) res += "\n\t\tdescription: " + str(constant.description()) res += "\n\t\ttype: " + str(typeId.Get().typeToName(constant.type())) cvalues = constant.values() cvallen = len(cvalues) if cvallen > 0: res += "\n\t\tvalues: " for cvalue in cvalues: if cvalue.type() == typeId.Node: res += str(cvalue.value().absolute()) else: res += cvalue.toString() cvallen -= 1 if cvallen != 0: res += ", " res += "\n" return res def show_arg(self, args): res = "" if len(args): res += "\n\n\t\tArguments: \t" for argname in args.keys():
return res def show_res(self, results): res = self.fillMap(3, results, "\n\n\t\tResults:") return res def c_display(self): print self.info def getmodinfo(self, modname): conf = self.cm.configByName(modname) if conf == None: return self.lproc = self.tm.lprocessus self.info += "\n" + modname + self.show_config(modname) for proc in self.lproc: if proc.mod.name == modname: self.info += "\n\tProcessus " + str(proc.pid) stime = datetime.fromtimestamp(proc.timestart) self.info += "\n\t\texecution started at : " + str(stime) if proc.timeend: etime = datetime.fromtimestamp(proc.timeend) self.info += "\n\t\texecution finished at : " + str(etime) else: etime = datetime.fromtimestamp(time.time()) delta = etime - stime self.info += "\n\t\texecution time: " + str(delta) self.info += self.show_arg(proc.args) self.info += self.show_res(proc.res) def start(self, args): self.info = "" if args.has_key("modules"): modnames = args['modules'].value() for modname in modnames: self.getmodinfo(modname.value()) else: self.modules = self.loader.modules for modname in self.modules: self.getmodinfo(modname) class info(Module): """Show info on loaded drivers: configuration, arguments, results """ def __init__(self): Module.__init__(self, "info", INFO) self.tags = "builtins" self.conf.addArgument({"name": "modules", "description": "Display information concerning provided modules", "input": Argument.Optional|Argument.List|typeId.String})
res += "\n\t\t\tname: " + argname res += "\n\t\t\tparameters: " val = args[argname] if val.type() == typeId.List: vlist = val.value() vlen = len(vlist) for item in vlist: if item.type == typeId.Node: res += str(val.value().absolute()) else: res += item.toString() vlen -= 1 if vlen != 0: res += ", " elif val.type() == typeId.Node: res += str(val.value().absolute())
conditional_block
svg.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Generic types for CSS values in SVG use cssparser::Parser; use parser::{Parse, ParserContext}; use style_traits::{ParseError, StyleParseErrorKind}; use values::{Either, None_}; use values::computed::NumberOrPercentage; use values::computed::length::LengthOrPercentage; use values::distance::{ComputeSquaredDistance, SquaredDistance}; /// An SVG paint value /// /// <https://www.w3.org/TR/SVG2/painting.html#SpecifyingPaint> #[animation(no_bound(UrlPaintServer))] #[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, ToAnimatedValue, ToComputedValue, ToCss)] pub struct SVGPaint<ColorType, UrlPaintServer> {
/// The paint source pub kind: SVGPaintKind<ColorType, UrlPaintServer>, /// The fallback color. It would be empty, the `none` keyword or <color>. pub fallback: Option<Either<ColorType, None_>>, } /// An SVG paint value without the fallback /// /// Whereas the spec only allows PaintServer /// to have a fallback, Gecko lets the context /// properties have a fallback as well. #[animation(no_bound(UrlPaintServer))] #[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss)] pub enum SVGPaintKind<ColorType, UrlPaintServer> { /// `none` #[animation(error)] None, /// `<color>` Color(ColorType), /// `url(...)` #[animation(error)] PaintServer(UrlPaintServer), /// `context-fill` ContextFill, /// `context-stroke` ContextStroke, } impl<ColorType, UrlPaintServer> SVGPaintKind<ColorType, UrlPaintServer> { /// Parse a keyword value only fn parse_ident<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { try_match_ident_ignore_ascii_case! { input, "none" => Ok(SVGPaintKind::None), "context-fill" => Ok(SVGPaintKind::ContextFill), "context-stroke" => Ok(SVGPaintKind::ContextStroke), } } } /// Parse SVGPaint's fallback. /// fallback is keyword(none), Color or empty. /// <https://svgwg.org/svg2-draft/painting.html#SpecifyingPaint> fn parse_fallback<'i, 't, ColorType: Parse>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Option<Either<ColorType, None_>> { if input.try(|i| i.expect_ident_matching("none")).is_ok() { Some(Either::Second(None_)) } else { if let Ok(color) = input.try(|i| ColorType::parse(context, i)) { Some(Either::First(color)) } else { None } } } impl<ColorType: Parse, UrlPaintServer: Parse> Parse for SVGPaint<ColorType, UrlPaintServer> { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { if let Ok(url) = input.try(|i| UrlPaintServer::parse(context, i)) { Ok(SVGPaint { kind: SVGPaintKind::PaintServer(url), fallback: parse_fallback(context, input), }) } else if let Ok(kind) = input.try(SVGPaintKind::parse_ident) { if let SVGPaintKind::None = kind { Ok(SVGPaint { kind: kind, fallback: None, }) } else { Ok(SVGPaint { kind: kind, fallback: parse_fallback(context, input), }) } } else if let Ok(color) = input.try(|i| ColorType::parse(context, i)) { Ok(SVGPaint { kind: SVGPaintKind::Color(color), fallback: None, }) } else { Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) } } } /// A value of <length> | <percentage> | <number> for svg which allow unitless length. /// <https://www.w3.org/TR/SVG11/painting.html#StrokeProperties> #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss)] pub enum SvgLengthOrPercentageOrNumber<LengthOrPercentage, Number> { /// <length> | <percentage> LengthOrPercentage(LengthOrPercentage), /// <number> Number(Number), } impl<L, N> ComputeSquaredDistance for SvgLengthOrPercentageOrNumber<L, N> where L: ComputeSquaredDistance + Copy + Into<NumberOrPercentage>, N: ComputeSquaredDistance + Copy + Into<NumberOrPercentage>, { #[inline] fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> { match (self, other) { ( &SvgLengthOrPercentageOrNumber::LengthOrPercentage(ref from), &SvgLengthOrPercentageOrNumber::LengthOrPercentage(ref to), ) => from.compute_squared_distance(to), ( &SvgLengthOrPercentageOrNumber::Number(ref from), &SvgLengthOrPercentageOrNumber::Number(ref to), ) => from.compute_squared_distance(to), ( &SvgLengthOrPercentageOrNumber::LengthOrPercentage(from), &SvgLengthOrPercentageOrNumber::Number(to), ) => from.into().compute_squared_distance(&to.into()), ( &SvgLengthOrPercentageOrNumber::Number(from), &SvgLengthOrPercentageOrNumber::LengthOrPercentage(to), ) => from.into().compute_squared_distance(&to.into()), } } } impl<LengthOrPercentageType, NumberType> SvgLengthOrPercentageOrNumber<LengthOrPercentageType, NumberType> where LengthOrPercentage: From<LengthOrPercentageType>, LengthOrPercentageType: Copy, { /// return true if this struct has calc value. pub fn has_calc(&self) -> bool { match self { &SvgLengthOrPercentageOrNumber::LengthOrPercentage(lop) => { match LengthOrPercentage::from(lop) { LengthOrPercentage::Calc(_) => true, _ => false, } }, _ => false, } } } /// Parsing the SvgLengthOrPercentageOrNumber. At first, we need to parse number /// since prevent converting to the length. impl<LengthOrPercentageType: Parse, NumberType: Parse> Parse for SvgLengthOrPercentageOrNumber<LengthOrPercentageType, NumberType> { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { if let Ok(num) = input.try(|i| NumberType::parse(context, i)) { return Ok(SvgLengthOrPercentageOrNumber::Number(num)); } if let Ok(lop) = input.try(|i| LengthOrPercentageType::parse(context, i)) { return Ok(SvgLengthOrPercentageOrNumber::LengthOrPercentage(lop)); } Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) } } /// An SVG length value supports `context-value` in addition to length. #[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss)] pub enum SVGLength<LengthType> { /// `<length> | <percentage> | <number>` Length(LengthType), /// `context-value` ContextValue, } /// Generic value for stroke-dasharray. #[derive(Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, ToAnimatedValue, ToComputedValue, ToCss)] pub enum SVGStrokeDashArray<LengthType> { /// `[ <length> | <percentage> | <number> ]#` #[css(comma)] Values( #[css(if_empty = "none", iterable)] #[distance(field_bound)] Vec<LengthType>, ), /// `context-value` ContextValue, } /// An SVG opacity value accepts `context-{fill,stroke}-opacity` in /// addition to opacity value. #[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToAnimatedZero, ToComputedValue, ToCss)] pub enum SVGOpacity<OpacityType> { /// `<opacity-value>` Opacity(OpacityType), /// `context-fill-opacity` ContextFillOpacity, /// `context-stroke-opacity` ContextStrokeOpacity, }
random_line_split
svg.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Generic types for CSS values in SVG use cssparser::Parser; use parser::{Parse, ParserContext}; use style_traits::{ParseError, StyleParseErrorKind}; use values::{Either, None_}; use values::computed::NumberOrPercentage; use values::computed::length::LengthOrPercentage; use values::distance::{ComputeSquaredDistance, SquaredDistance}; /// An SVG paint value /// /// <https://www.w3.org/TR/SVG2/painting.html#SpecifyingPaint> #[animation(no_bound(UrlPaintServer))] #[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, ToAnimatedValue, ToComputedValue, ToCss)] pub struct SVGPaint<ColorType, UrlPaintServer> { /// The paint source pub kind: SVGPaintKind<ColorType, UrlPaintServer>, /// The fallback color. It would be empty, the `none` keyword or <color>. pub fallback: Option<Either<ColorType, None_>>, } /// An SVG paint value without the fallback /// /// Whereas the spec only allows PaintServer /// to have a fallback, Gecko lets the context /// properties have a fallback as well. #[animation(no_bound(UrlPaintServer))] #[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss)] pub enum SVGPaintKind<ColorType, UrlPaintServer> { /// `none` #[animation(error)] None, /// `<color>` Color(ColorType), /// `url(...)` #[animation(error)] PaintServer(UrlPaintServer), /// `context-fill` ContextFill, /// `context-stroke` ContextStroke, } impl<ColorType, UrlPaintServer> SVGPaintKind<ColorType, UrlPaintServer> { /// Parse a keyword value only fn parse_ident<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { try_match_ident_ignore_ascii_case! { input, "none" => Ok(SVGPaintKind::None), "context-fill" => Ok(SVGPaintKind::ContextFill), "context-stroke" => Ok(SVGPaintKind::ContextStroke), } } } /// Parse SVGPaint's fallback. /// fallback is keyword(none), Color or empty. /// <https://svgwg.org/svg2-draft/painting.html#SpecifyingPaint> fn parse_fallback<'i, 't, ColorType: Parse>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Option<Either<ColorType, None_>> { if input.try(|i| i.expect_ident_matching("none")).is_ok() { Some(Either::Second(None_)) } else { if let Ok(color) = input.try(|i| ColorType::parse(context, i)) { Some(Either::First(color)) } else { None } } } impl<ColorType: Parse, UrlPaintServer: Parse> Parse for SVGPaint<ColorType, UrlPaintServer> { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { if let Ok(url) = input.try(|i| UrlPaintServer::parse(context, i)) { Ok(SVGPaint { kind: SVGPaintKind::PaintServer(url), fallback: parse_fallback(context, input), }) } else if let Ok(kind) = input.try(SVGPaintKind::parse_ident) { if let SVGPaintKind::None = kind { Ok(SVGPaint { kind: kind, fallback: None, }) } else { Ok(SVGPaint { kind: kind, fallback: parse_fallback(context, input), }) } } else if let Ok(color) = input.try(|i| ColorType::parse(context, i)) { Ok(SVGPaint { kind: SVGPaintKind::Color(color), fallback: None, }) } else { Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) } } } /// A value of <length> | <percentage> | <number> for svg which allow unitless length. /// <https://www.w3.org/TR/SVG11/painting.html#StrokeProperties> #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss)] pub enum SvgLengthOrPercentageOrNumber<LengthOrPercentage, Number> { /// <length> | <percentage> LengthOrPercentage(LengthOrPercentage), /// <number> Number(Number), } impl<L, N> ComputeSquaredDistance for SvgLengthOrPercentageOrNumber<L, N> where L: ComputeSquaredDistance + Copy + Into<NumberOrPercentage>, N: ComputeSquaredDistance + Copy + Into<NumberOrPercentage>, { #[inline] fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> { match (self, other) { ( &SvgLengthOrPercentageOrNumber::LengthOrPercentage(ref from), &SvgLengthOrPercentageOrNumber::LengthOrPercentage(ref to), ) => from.compute_squared_distance(to), ( &SvgLengthOrPercentageOrNumber::Number(ref from), &SvgLengthOrPercentageOrNumber::Number(ref to), ) => from.compute_squared_distance(to), ( &SvgLengthOrPercentageOrNumber::LengthOrPercentage(from), &SvgLengthOrPercentageOrNumber::Number(to), ) => from.into().compute_squared_distance(&to.into()), ( &SvgLengthOrPercentageOrNumber::Number(from), &SvgLengthOrPercentageOrNumber::LengthOrPercentage(to), ) => from.into().compute_squared_distance(&to.into()), } } } impl<LengthOrPercentageType, NumberType> SvgLengthOrPercentageOrNumber<LengthOrPercentageType, NumberType> where LengthOrPercentage: From<LengthOrPercentageType>, LengthOrPercentageType: Copy, { /// return true if this struct has calc value. pub fn has_calc(&self) -> bool { match self { &SvgLengthOrPercentageOrNumber::LengthOrPercentage(lop) => { match LengthOrPercentage::from(lop) { LengthOrPercentage::Calc(_) => true, _ => false, } }, _ => false, } } } /// Parsing the SvgLengthOrPercentageOrNumber. At first, we need to parse number /// since prevent converting to the length. impl<LengthOrPercentageType: Parse, NumberType: Parse> Parse for SvgLengthOrPercentageOrNumber<LengthOrPercentageType, NumberType> { fn
<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { if let Ok(num) = input.try(|i| NumberType::parse(context, i)) { return Ok(SvgLengthOrPercentageOrNumber::Number(num)); } if let Ok(lop) = input.try(|i| LengthOrPercentageType::parse(context, i)) { return Ok(SvgLengthOrPercentageOrNumber::LengthOrPercentage(lop)); } Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) } } /// An SVG length value supports `context-value` in addition to length. #[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss)] pub enum SVGLength<LengthType> { /// `<length> | <percentage> | <number>` Length(LengthType), /// `context-value` ContextValue, } /// Generic value for stroke-dasharray. #[derive(Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, ToAnimatedValue, ToComputedValue, ToCss)] pub enum SVGStrokeDashArray<LengthType> { /// `[ <length> | <percentage> | <number> ]#` #[css(comma)] Values( #[css(if_empty = "none", iterable)] #[distance(field_bound)] Vec<LengthType>, ), /// `context-value` ContextValue, } /// An SVG opacity value accepts `context-{fill,stroke}-opacity` in /// addition to opacity value. #[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToAnimatedZero, ToComputedValue, ToCss)] pub enum SVGOpacity<OpacityType> { /// `<opacity-value>` Opacity(OpacityType), /// `context-fill-opacity` ContextFillOpacity, /// `context-stroke-opacity` ContextStrokeOpacity, }
parse
identifier_name
issue-14182.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// ignore-test FIXME(japari) remove test struct Foo { f: for <'b> |&'b isize|: 'b -> &'b isize //~ ERROR use of undeclared lifetime name `'b` } fn main() { let mut x: Vec< for <'a> || :'a //~ ERROR use of undeclared lifetime name `'a` > = Vec::new(); x.push(|| {}); let foo = Foo { f: |x| x }; }
// option. This file may not be copied, modified, or distributed // except according to those terms. // compile-flags: -Z parse-only
random_line_split
issue-14182.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-flags: -Z parse-only // ignore-test FIXME(japari) remove test struct Foo { f: for <'b> |&'b isize|: 'b -> &'b isize //~ ERROR use of undeclared lifetime name `'b` } fn
() { let mut x: Vec< for <'a> || :'a //~ ERROR use of undeclared lifetime name `'a` > = Vec::new(); x.push(|| {}); let foo = Foo { f: |x| x }; }
main
identifier_name
issue-14182.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-flags: -Z parse-only // ignore-test FIXME(japari) remove test struct Foo { f: for <'b> |&'b isize|: 'b -> &'b isize //~ ERROR use of undeclared lifetime name `'b` } fn main()
{ let mut x: Vec< for <'a> || :'a //~ ERROR use of undeclared lifetime name `'a` > = Vec::new(); x.push(|| {}); let foo = Foo { f: |x| x }; }
identifier_body
tasks.py
from invoke import task, run #from fabric.api import local, lcd, get, env #from fabric.operations import require, prompt #from fabric.utils import abort import requests import rdflib import getpass import os.path import os import setlr from os import listdir from rdflib import * import logging CHEAR_DIR='chear.d/' HHEAR_DIR='hhear.d/' SETL_FILE='ontology.setl.ttl' ontology_setl = Namespace('https://hadatac.org/setl/') setl = Namespace('http://purl.org/twc/vocab/setl/') prov = Namespace('http://www.w3.org/ns/prov#') dc = Namespace('http://purl.org/dc/terms/') pv = Namespace('http://purl.org/net/provenance/ns#') logging_level = logging.INFO logging.basicConfig(level=logging_level) @task def buildchear(ctx): setl_graph = Graph() setl_graph.parse(SETL_FILE,format="turtle") cwd = os.getcwd() formats = ['ttl','owl','json'] ontology_output_files = [setl_graph.resource(URIRef('file://'+cwd+'/chear.'+x)) for x in formats] print (len(setl_graph)) for filename in os.listdir(CHEAR_DIR): if not filename.endswith('.ttl') or filename.startswith('#'): continue print('Adding fragment', filename) fragment = setl_graph.resource(BNode()) for ontology_output_file in ontology_output_files: print(ontology_output_file.identifier, list(ontology_output_file[prov.wasGeneratedBy])) ontology_output_file.value(prov.wasGeneratedBy).add(prov.used, fragment) fragment.add(RDF.type, setlr.void.Dataset) fragment_extract = setl_graph.resource(BNode()) fragment.add(prov.wasGeneratedBy, fragment_extract) fragment_extract.add(RDF.type, setl.Extract) fragment_extract.add(prov.used, URIRef('file://'+CHEAR_DIR+filename)) setlr._setl(setl_graph) @task def buildhhear(ctx): setl_graph = Graph() setl_graph.parse('hhear-ontology.setl.ttl',format="turtle") cwd = os.getcwd() formats = ['ttl','owl','json'] ontology_output_files = [setl_graph.resource(URIRef('file://'+cwd+'/hhear.'+x)) for x in formats] print (len(setl_graph)) for filename in os.listdir(HHEAR_DIR): if not filename.endswith('.ttl') or filename.startswith('#'):
print('Adding fragment', filename) fragment = setl_graph.resource(BNode()) for ontology_output_file in ontology_output_files: print(ontology_output_file.identifier, list(ontology_output_file[prov.wasGeneratedBy])) ontology_output_file.value(prov.wasGeneratedBy).add(prov.used, fragment) fragment.add(RDF.type, setlr.void.Dataset) fragment_extract = setl_graph.resource(BNode()) fragment.add(prov.wasGeneratedBy, fragment_extract) fragment_extract.add(RDF.type, setl.Extract) fragment_extract.add(prov.used, URIRef('file://'+HHEAR_DIR+filename)) setlr._setl(setl_graph) @task def chear2hhear(c, inputfile, outputfile): import openpyxl import re import pandas as pd mappings = {} mappings.update(dict([(row['label_uri'], row['numeric_uri']) for i, row in pd.read_csv('sio_mappings.csv').iterrows()])) mappings.update(dict([(row['label_uri'], row['numeric_uri']) for i, row in pd.read_csv('chear2hhear_mappings.csv').iterrows()])) wb = openpyxl.load_workbook(inputfile) for sheet in wb: for row in sheet.rows: for cell in row: if isinstance(cell.value, str): cellValues = [] for c in re.split('\\s*[,&]\\s*', cell.value): if c in mappings: print('Replacing',c,'with',mappings[c]) c = mappings[c] cellValues.append(c) cell.value = ', '.join(cellValues) wb.save(outputfile)
continue
conditional_block
tasks.py
from invoke import task, run #from fabric.api import local, lcd, get, env #from fabric.operations import require, prompt #from fabric.utils import abort import requests import rdflib import getpass import os.path import os import setlr from os import listdir from rdflib import * import logging CHEAR_DIR='chear.d/' HHEAR_DIR='hhear.d/' SETL_FILE='ontology.setl.ttl' ontology_setl = Namespace('https://hadatac.org/setl/') setl = Namespace('http://purl.org/twc/vocab/setl/') prov = Namespace('http://www.w3.org/ns/prov#') dc = Namespace('http://purl.org/dc/terms/') pv = Namespace('http://purl.org/net/provenance/ns#') logging_level = logging.INFO logging.basicConfig(level=logging_level) @task def buildchear(ctx):
@task def buildhhear(ctx): setl_graph = Graph() setl_graph.parse('hhear-ontology.setl.ttl',format="turtle") cwd = os.getcwd() formats = ['ttl','owl','json'] ontology_output_files = [setl_graph.resource(URIRef('file://'+cwd+'/hhear.'+x)) for x in formats] print (len(setl_graph)) for filename in os.listdir(HHEAR_DIR): if not filename.endswith('.ttl') or filename.startswith('#'): continue print('Adding fragment', filename) fragment = setl_graph.resource(BNode()) for ontology_output_file in ontology_output_files: print(ontology_output_file.identifier, list(ontology_output_file[prov.wasGeneratedBy])) ontology_output_file.value(prov.wasGeneratedBy).add(prov.used, fragment) fragment.add(RDF.type, setlr.void.Dataset) fragment_extract = setl_graph.resource(BNode()) fragment.add(prov.wasGeneratedBy, fragment_extract) fragment_extract.add(RDF.type, setl.Extract) fragment_extract.add(prov.used, URIRef('file://'+HHEAR_DIR+filename)) setlr._setl(setl_graph) @task def chear2hhear(c, inputfile, outputfile): import openpyxl import re import pandas as pd mappings = {} mappings.update(dict([(row['label_uri'], row['numeric_uri']) for i, row in pd.read_csv('sio_mappings.csv').iterrows()])) mappings.update(dict([(row['label_uri'], row['numeric_uri']) for i, row in pd.read_csv('chear2hhear_mappings.csv').iterrows()])) wb = openpyxl.load_workbook(inputfile) for sheet in wb: for row in sheet.rows: for cell in row: if isinstance(cell.value, str): cellValues = [] for c in re.split('\\s*[,&]\\s*', cell.value): if c in mappings: print('Replacing',c,'with',mappings[c]) c = mappings[c] cellValues.append(c) cell.value = ', '.join(cellValues) wb.save(outputfile)
setl_graph = Graph() setl_graph.parse(SETL_FILE,format="turtle") cwd = os.getcwd() formats = ['ttl','owl','json'] ontology_output_files = [setl_graph.resource(URIRef('file://'+cwd+'/chear.'+x)) for x in formats] print (len(setl_graph)) for filename in os.listdir(CHEAR_DIR): if not filename.endswith('.ttl') or filename.startswith('#'): continue print('Adding fragment', filename) fragment = setl_graph.resource(BNode()) for ontology_output_file in ontology_output_files: print(ontology_output_file.identifier, list(ontology_output_file[prov.wasGeneratedBy])) ontology_output_file.value(prov.wasGeneratedBy).add(prov.used, fragment) fragment.add(RDF.type, setlr.void.Dataset) fragment_extract = setl_graph.resource(BNode()) fragment.add(prov.wasGeneratedBy, fragment_extract) fragment_extract.add(RDF.type, setl.Extract) fragment_extract.add(prov.used, URIRef('file://'+CHEAR_DIR+filename)) setlr._setl(setl_graph)
identifier_body
tasks.py
from invoke import task, run #from fabric.api import local, lcd, get, env #from fabric.operations import require, prompt #from fabric.utils import abort import requests import rdflib import getpass import os.path import os import setlr from os import listdir from rdflib import * import logging CHEAR_DIR='chear.d/' HHEAR_DIR='hhear.d/'
prov = Namespace('http://www.w3.org/ns/prov#') dc = Namespace('http://purl.org/dc/terms/') pv = Namespace('http://purl.org/net/provenance/ns#') logging_level = logging.INFO logging.basicConfig(level=logging_level) @task def buildchear(ctx): setl_graph = Graph() setl_graph.parse(SETL_FILE,format="turtle") cwd = os.getcwd() formats = ['ttl','owl','json'] ontology_output_files = [setl_graph.resource(URIRef('file://'+cwd+'/chear.'+x)) for x in formats] print (len(setl_graph)) for filename in os.listdir(CHEAR_DIR): if not filename.endswith('.ttl') or filename.startswith('#'): continue print('Adding fragment', filename) fragment = setl_graph.resource(BNode()) for ontology_output_file in ontology_output_files: print(ontology_output_file.identifier, list(ontology_output_file[prov.wasGeneratedBy])) ontology_output_file.value(prov.wasGeneratedBy).add(prov.used, fragment) fragment.add(RDF.type, setlr.void.Dataset) fragment_extract = setl_graph.resource(BNode()) fragment.add(prov.wasGeneratedBy, fragment_extract) fragment_extract.add(RDF.type, setl.Extract) fragment_extract.add(prov.used, URIRef('file://'+CHEAR_DIR+filename)) setlr._setl(setl_graph) @task def buildhhear(ctx): setl_graph = Graph() setl_graph.parse('hhear-ontology.setl.ttl',format="turtle") cwd = os.getcwd() formats = ['ttl','owl','json'] ontology_output_files = [setl_graph.resource(URIRef('file://'+cwd+'/hhear.'+x)) for x in formats] print (len(setl_graph)) for filename in os.listdir(HHEAR_DIR): if not filename.endswith('.ttl') or filename.startswith('#'): continue print('Adding fragment', filename) fragment = setl_graph.resource(BNode()) for ontology_output_file in ontology_output_files: print(ontology_output_file.identifier, list(ontology_output_file[prov.wasGeneratedBy])) ontology_output_file.value(prov.wasGeneratedBy).add(prov.used, fragment) fragment.add(RDF.type, setlr.void.Dataset) fragment_extract = setl_graph.resource(BNode()) fragment.add(prov.wasGeneratedBy, fragment_extract) fragment_extract.add(RDF.type, setl.Extract) fragment_extract.add(prov.used, URIRef('file://'+HHEAR_DIR+filename)) setlr._setl(setl_graph) @task def chear2hhear(c, inputfile, outputfile): import openpyxl import re import pandas as pd mappings = {} mappings.update(dict([(row['label_uri'], row['numeric_uri']) for i, row in pd.read_csv('sio_mappings.csv').iterrows()])) mappings.update(dict([(row['label_uri'], row['numeric_uri']) for i, row in pd.read_csv('chear2hhear_mappings.csv').iterrows()])) wb = openpyxl.load_workbook(inputfile) for sheet in wb: for row in sheet.rows: for cell in row: if isinstance(cell.value, str): cellValues = [] for c in re.split('\\s*[,&]\\s*', cell.value): if c in mappings: print('Replacing',c,'with',mappings[c]) c = mappings[c] cellValues.append(c) cell.value = ', '.join(cellValues) wb.save(outputfile)
SETL_FILE='ontology.setl.ttl' ontology_setl = Namespace('https://hadatac.org/setl/') setl = Namespace('http://purl.org/twc/vocab/setl/')
random_line_split
tasks.py
from invoke import task, run #from fabric.api import local, lcd, get, env #from fabric.operations import require, prompt #from fabric.utils import abort import requests import rdflib import getpass import os.path import os import setlr from os import listdir from rdflib import * import logging CHEAR_DIR='chear.d/' HHEAR_DIR='hhear.d/' SETL_FILE='ontology.setl.ttl' ontology_setl = Namespace('https://hadatac.org/setl/') setl = Namespace('http://purl.org/twc/vocab/setl/') prov = Namespace('http://www.w3.org/ns/prov#') dc = Namespace('http://purl.org/dc/terms/') pv = Namespace('http://purl.org/net/provenance/ns#') logging_level = logging.INFO logging.basicConfig(level=logging_level) @task def
(ctx): setl_graph = Graph() setl_graph.parse(SETL_FILE,format="turtle") cwd = os.getcwd() formats = ['ttl','owl','json'] ontology_output_files = [setl_graph.resource(URIRef('file://'+cwd+'/chear.'+x)) for x in formats] print (len(setl_graph)) for filename in os.listdir(CHEAR_DIR): if not filename.endswith('.ttl') or filename.startswith('#'): continue print('Adding fragment', filename) fragment = setl_graph.resource(BNode()) for ontology_output_file in ontology_output_files: print(ontology_output_file.identifier, list(ontology_output_file[prov.wasGeneratedBy])) ontology_output_file.value(prov.wasGeneratedBy).add(prov.used, fragment) fragment.add(RDF.type, setlr.void.Dataset) fragment_extract = setl_graph.resource(BNode()) fragment.add(prov.wasGeneratedBy, fragment_extract) fragment_extract.add(RDF.type, setl.Extract) fragment_extract.add(prov.used, URIRef('file://'+CHEAR_DIR+filename)) setlr._setl(setl_graph) @task def buildhhear(ctx): setl_graph = Graph() setl_graph.parse('hhear-ontology.setl.ttl',format="turtle") cwd = os.getcwd() formats = ['ttl','owl','json'] ontology_output_files = [setl_graph.resource(URIRef('file://'+cwd+'/hhear.'+x)) for x in formats] print (len(setl_graph)) for filename in os.listdir(HHEAR_DIR): if not filename.endswith('.ttl') or filename.startswith('#'): continue print('Adding fragment', filename) fragment = setl_graph.resource(BNode()) for ontology_output_file in ontology_output_files: print(ontology_output_file.identifier, list(ontology_output_file[prov.wasGeneratedBy])) ontology_output_file.value(prov.wasGeneratedBy).add(prov.used, fragment) fragment.add(RDF.type, setlr.void.Dataset) fragment_extract = setl_graph.resource(BNode()) fragment.add(prov.wasGeneratedBy, fragment_extract) fragment_extract.add(RDF.type, setl.Extract) fragment_extract.add(prov.used, URIRef('file://'+HHEAR_DIR+filename)) setlr._setl(setl_graph) @task def chear2hhear(c, inputfile, outputfile): import openpyxl import re import pandas as pd mappings = {} mappings.update(dict([(row['label_uri'], row['numeric_uri']) for i, row in pd.read_csv('sio_mappings.csv').iterrows()])) mappings.update(dict([(row['label_uri'], row['numeric_uri']) for i, row in pd.read_csv('chear2hhear_mappings.csv').iterrows()])) wb = openpyxl.load_workbook(inputfile) for sheet in wb: for row in sheet.rows: for cell in row: if isinstance(cell.value, str): cellValues = [] for c in re.split('\\s*[,&]\\s*', cell.value): if c in mappings: print('Replacing',c,'with',mappings[c]) c = mappings[c] cellValues.append(c) cell.value = ', '.join(cellValues) wb.save(outputfile)
buildchear
identifier_name
flavor-link.component.ts
import { Component, Input, OnDestroy } from '@angular/core'; import { PopupWidgetComponent } from '@kaltura-ng/kaltura-ui'; import { Flavor } from '../flavor'; import { KalturaStorageProfile } from 'kaltura-ngx-client'; import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms'; import { KalturaLogger } from '@kaltura-ng/kaltura-logger'; import { KalturaClient, KalturaMultiRequest } from 'kaltura-ngx-client'; import { KalturaRemoteStorageResource } from 'kaltura-ngx-client'; import { FlavorAssetSetContentAction } from 'kaltura-ngx-client'; import { EntryFlavoursWidget } from '../entry-flavours-widget.service'; import { BrowserService } from 'app-shared/kmc-shell/providers'; import { Observable } from 'rxjs'; import { KalturaFlavorAsset } from 'kaltura-ngx-client'; import { FlavorAssetAddAction } from 'kaltura-ngx-client'; import { KalturaConversionProfileAssetParams } from 'kaltura-ngx-client'; import { KalturaFlavorReadyBehaviorType } from 'kaltura-ngx-client'; import { KalturaAssetParamsOrigin } from 'kaltura-ngx-client'; import { AppLocalization } from '@kaltura-ng/mc-shared'; import { cancelOnDestroy, tag } from '@kaltura-ng/kaltura-common'; @Component({ selector: 'kFlavorLink', templateUrl: './flavor-link.component.html', styleUrls: ['./flavor-link.component.scss'], providers: [KalturaLogger.createLogger('FlavorLinkComponent')] }) export class FlavorLinkComponent implements OnDestroy { @Input() flavor: Flavor; @Input() storageProfile: KalturaStorageProfile; @Input() conversionProfileAsset: KalturaConversionProfileAssetParams; @Input() parentPopupWidget: PopupWidgetComponent; public _form: FormGroup; public _filePathField: AbstractControl; constructor(private _appLocalization: AppLocalization, private _logger: KalturaLogger, private _widgetService: EntryFlavoursWidget, private _kalturaClient: KalturaClient, private _browserService: BrowserService, private _fb: FormBuilder) { this._buildForm(); } ngOnDestroy() { } private _buildForm(): void { this._form = this._fb.group({ filePath: ['', Validators.required] }); this._filePathField = this._form.controls['filePath']; } private _updateFlavorAction(): Observable<void> { this._logger.info(`handle update flavor request`, { fileUrl: this._form.value.filePath, flavorAssetId: this.flavor.flavorAsset.id }); return this._kalturaClient .request(new FlavorAssetSetContentAction({ id: this.flavor.flavorAsset.id, contentResource: new KalturaRemoteStorageResource({ url: this._form.value.filePath, storageProfileId: this.storageProfile.id }) })) .map(() => { }); } private _uploadFlavorAction(): Observable<void> { this._logger.info(`handle upload flavor request, create asset and set its content`, { fileUrl: this._form.value.filePath, }); const entryId = this._widgetService.data.id; const flavorAsset = new KalturaFlavorAsset({ flavorParamsId: this.flavor.flavorParams.id }); const flavorAssetAddAction = new FlavorAssetAddAction({ entryId, flavorAsset }); const flavorAssetSetContentAction = new FlavorAssetSetContentAction({ id: '0', contentResource: new KalturaRemoteStorageResource({ storageProfileId: this.storageProfile.id, url: this._form.value.filePath }) }).setDependency(['id', 0, 'id']); return this._kalturaClient .multiRequest(new KalturaMultiRequest(flavorAssetAddAction, flavorAssetSetContentAction)) .map(responses => { if (responses.hasErrors()) { throw new Error(responses.reduce((acc, val) => `${acc}\n${val.error ? val.error.message : ''}`, '')); } return undefined; }); } private _validate(): boolean { const asset = this.conversionProfileAsset; if (!asset || asset.readyBehavior !== KalturaFlavorReadyBehaviorType.required || asset.origin !== KalturaAssetParamsOrigin.ingest)
return asset.assetParamsId === this.flavor.flavorParams.id; } private _performAction(): void { const linkAction = this.flavor.flavorAsset && this.flavor.flavorAsset.id ? this._updateFlavorAction() : this._uploadFlavorAction(); linkAction .pipe(tag('block-shell')) .pipe(cancelOnDestroy(this)) .subscribe( () => { this._logger.info(`handle successful link action, reload flavors data`); this.parentPopupWidget.close(); this._widgetService.refresh(); }, error => { this._logger.warn(`handle failed link action, show alert`, { errorMessage: error.message }); this._browserService.alert({ header: this._appLocalization.get('app.common.error'), message: error.message, accept: () => { this._logger.info(`user dismissed alert, reload flavors data`); this.parentPopupWidget.close(); this._widgetService.refresh(); } }); }); } public _link(): void { this._logger.info(`handle link action by user`); if (this._form.valid) { this._logger.info(`validate asset params`, { asset: this.conversionProfileAsset }); if (this._validate()) { this._performAction(); } else { this._logger.info(`asset params is not valid, show confirmation`); this._browserService.confirm({ header: this._appLocalization.get('app.common.attention'), message: this._appLocalization.get('applications.content.entryDetails.flavours.link.requiredFlavorsMissing'), accept: () => { this._logger.info(`user confirmed proceed action`); this._performAction(); }, reject: () => { this._logger.info(`user didn't confirm abort action`); } }); } } else { this._logger.info(`form is not valid, abort action`); } } }
{ return true; }
conditional_block
flavor-link.component.ts
import { Component, Input, OnDestroy } from '@angular/core'; import { PopupWidgetComponent } from '@kaltura-ng/kaltura-ui'; import { Flavor } from '../flavor'; import { KalturaStorageProfile } from 'kaltura-ngx-client'; import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms'; import { KalturaLogger } from '@kaltura-ng/kaltura-logger'; import { KalturaClient, KalturaMultiRequest } from 'kaltura-ngx-client'; import { KalturaRemoteStorageResource } from 'kaltura-ngx-client'; import { FlavorAssetSetContentAction } from 'kaltura-ngx-client'; import { EntryFlavoursWidget } from '../entry-flavours-widget.service'; import { BrowserService } from 'app-shared/kmc-shell/providers'; import { Observable } from 'rxjs'; import { KalturaFlavorAsset } from 'kaltura-ngx-client'; import { FlavorAssetAddAction } from 'kaltura-ngx-client'; import { KalturaConversionProfileAssetParams } from 'kaltura-ngx-client'; import { KalturaFlavorReadyBehaviorType } from 'kaltura-ngx-client'; import { KalturaAssetParamsOrigin } from 'kaltura-ngx-client'; import { AppLocalization } from '@kaltura-ng/mc-shared'; import { cancelOnDestroy, tag } from '@kaltura-ng/kaltura-common'; @Component({ selector: 'kFlavorLink', templateUrl: './flavor-link.component.html', styleUrls: ['./flavor-link.component.scss'], providers: [KalturaLogger.createLogger('FlavorLinkComponent')] }) export class FlavorLinkComponent implements OnDestroy { @Input() flavor: Flavor; @Input() storageProfile: KalturaStorageProfile; @Input() conversionProfileAsset: KalturaConversionProfileAssetParams; @Input() parentPopupWidget: PopupWidgetComponent; public _form: FormGroup; public _filePathField: AbstractControl; constructor(private _appLocalization: AppLocalization, private _logger: KalturaLogger, private _widgetService: EntryFlavoursWidget, private _kalturaClient: KalturaClient, private _browserService: BrowserService, private _fb: FormBuilder) { this._buildForm(); } ngOnDestroy() { } private _buildForm(): void { this._form = this._fb.group({ filePath: ['', Validators.required]
this._filePathField = this._form.controls['filePath']; } private _updateFlavorAction(): Observable<void> { this._logger.info(`handle update flavor request`, { fileUrl: this._form.value.filePath, flavorAssetId: this.flavor.flavorAsset.id }); return this._kalturaClient .request(new FlavorAssetSetContentAction({ id: this.flavor.flavorAsset.id, contentResource: new KalturaRemoteStorageResource({ url: this._form.value.filePath, storageProfileId: this.storageProfile.id }) })) .map(() => { }); } private _uploadFlavorAction(): Observable<void> { this._logger.info(`handle upload flavor request, create asset and set its content`, { fileUrl: this._form.value.filePath, }); const entryId = this._widgetService.data.id; const flavorAsset = new KalturaFlavorAsset({ flavorParamsId: this.flavor.flavorParams.id }); const flavorAssetAddAction = new FlavorAssetAddAction({ entryId, flavorAsset }); const flavorAssetSetContentAction = new FlavorAssetSetContentAction({ id: '0', contentResource: new KalturaRemoteStorageResource({ storageProfileId: this.storageProfile.id, url: this._form.value.filePath }) }).setDependency(['id', 0, 'id']); return this._kalturaClient .multiRequest(new KalturaMultiRequest(flavorAssetAddAction, flavorAssetSetContentAction)) .map(responses => { if (responses.hasErrors()) { throw new Error(responses.reduce((acc, val) => `${acc}\n${val.error ? val.error.message : ''}`, '')); } return undefined; }); } private _validate(): boolean { const asset = this.conversionProfileAsset; if (!asset || asset.readyBehavior !== KalturaFlavorReadyBehaviorType.required || asset.origin !== KalturaAssetParamsOrigin.ingest) { return true; } return asset.assetParamsId === this.flavor.flavorParams.id; } private _performAction(): void { const linkAction = this.flavor.flavorAsset && this.flavor.flavorAsset.id ? this._updateFlavorAction() : this._uploadFlavorAction(); linkAction .pipe(tag('block-shell')) .pipe(cancelOnDestroy(this)) .subscribe( () => { this._logger.info(`handle successful link action, reload flavors data`); this.parentPopupWidget.close(); this._widgetService.refresh(); }, error => { this._logger.warn(`handle failed link action, show alert`, { errorMessage: error.message }); this._browserService.alert({ header: this._appLocalization.get('app.common.error'), message: error.message, accept: () => { this._logger.info(`user dismissed alert, reload flavors data`); this.parentPopupWidget.close(); this._widgetService.refresh(); } }); }); } public _link(): void { this._logger.info(`handle link action by user`); if (this._form.valid) { this._logger.info(`validate asset params`, { asset: this.conversionProfileAsset }); if (this._validate()) { this._performAction(); } else { this._logger.info(`asset params is not valid, show confirmation`); this._browserService.confirm({ header: this._appLocalization.get('app.common.attention'), message: this._appLocalization.get('applications.content.entryDetails.flavours.link.requiredFlavorsMissing'), accept: () => { this._logger.info(`user confirmed proceed action`); this._performAction(); }, reject: () => { this._logger.info(`user didn't confirm abort action`); } }); } } else { this._logger.info(`form is not valid, abort action`); } } }
});
random_line_split
flavor-link.component.ts
import { Component, Input, OnDestroy } from '@angular/core'; import { PopupWidgetComponent } from '@kaltura-ng/kaltura-ui'; import { Flavor } from '../flavor'; import { KalturaStorageProfile } from 'kaltura-ngx-client'; import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms'; import { KalturaLogger } from '@kaltura-ng/kaltura-logger'; import { KalturaClient, KalturaMultiRequest } from 'kaltura-ngx-client'; import { KalturaRemoteStorageResource } from 'kaltura-ngx-client'; import { FlavorAssetSetContentAction } from 'kaltura-ngx-client'; import { EntryFlavoursWidget } from '../entry-flavours-widget.service'; import { BrowserService } from 'app-shared/kmc-shell/providers'; import { Observable } from 'rxjs'; import { KalturaFlavorAsset } from 'kaltura-ngx-client'; import { FlavorAssetAddAction } from 'kaltura-ngx-client'; import { KalturaConversionProfileAssetParams } from 'kaltura-ngx-client'; import { KalturaFlavorReadyBehaviorType } from 'kaltura-ngx-client'; import { KalturaAssetParamsOrigin } from 'kaltura-ngx-client'; import { AppLocalization } from '@kaltura-ng/mc-shared'; import { cancelOnDestroy, tag } from '@kaltura-ng/kaltura-common'; @Component({ selector: 'kFlavorLink', templateUrl: './flavor-link.component.html', styleUrls: ['./flavor-link.component.scss'], providers: [KalturaLogger.createLogger('FlavorLinkComponent')] }) export class FlavorLinkComponent implements OnDestroy { @Input() flavor: Flavor; @Input() storageProfile: KalturaStorageProfile; @Input() conversionProfileAsset: KalturaConversionProfileAssetParams; @Input() parentPopupWidget: PopupWidgetComponent; public _form: FormGroup; public _filePathField: AbstractControl; constructor(private _appLocalization: AppLocalization, private _logger: KalturaLogger, private _widgetService: EntryFlavoursWidget, private _kalturaClient: KalturaClient, private _browserService: BrowserService, private _fb: FormBuilder) { this._buildForm(); } ngOnDestroy() { } private _buildForm(): void { this._form = this._fb.group({ filePath: ['', Validators.required] }); this._filePathField = this._form.controls['filePath']; } private _updateFlavorAction(): Observable<void>
private _uploadFlavorAction(): Observable<void> { this._logger.info(`handle upload flavor request, create asset and set its content`, { fileUrl: this._form.value.filePath, }); const entryId = this._widgetService.data.id; const flavorAsset = new KalturaFlavorAsset({ flavorParamsId: this.flavor.flavorParams.id }); const flavorAssetAddAction = new FlavorAssetAddAction({ entryId, flavorAsset }); const flavorAssetSetContentAction = new FlavorAssetSetContentAction({ id: '0', contentResource: new KalturaRemoteStorageResource({ storageProfileId: this.storageProfile.id, url: this._form.value.filePath }) }).setDependency(['id', 0, 'id']); return this._kalturaClient .multiRequest(new KalturaMultiRequest(flavorAssetAddAction, flavorAssetSetContentAction)) .map(responses => { if (responses.hasErrors()) { throw new Error(responses.reduce((acc, val) => `${acc}\n${val.error ? val.error.message : ''}`, '')); } return undefined; }); } private _validate(): boolean { const asset = this.conversionProfileAsset; if (!asset || asset.readyBehavior !== KalturaFlavorReadyBehaviorType.required || asset.origin !== KalturaAssetParamsOrigin.ingest) { return true; } return asset.assetParamsId === this.flavor.flavorParams.id; } private _performAction(): void { const linkAction = this.flavor.flavorAsset && this.flavor.flavorAsset.id ? this._updateFlavorAction() : this._uploadFlavorAction(); linkAction .pipe(tag('block-shell')) .pipe(cancelOnDestroy(this)) .subscribe( () => { this._logger.info(`handle successful link action, reload flavors data`); this.parentPopupWidget.close(); this._widgetService.refresh(); }, error => { this._logger.warn(`handle failed link action, show alert`, { errorMessage: error.message }); this._browserService.alert({ header: this._appLocalization.get('app.common.error'), message: error.message, accept: () => { this._logger.info(`user dismissed alert, reload flavors data`); this.parentPopupWidget.close(); this._widgetService.refresh(); } }); }); } public _link(): void { this._logger.info(`handle link action by user`); if (this._form.valid) { this._logger.info(`validate asset params`, { asset: this.conversionProfileAsset }); if (this._validate()) { this._performAction(); } else { this._logger.info(`asset params is not valid, show confirmation`); this._browserService.confirm({ header: this._appLocalization.get('app.common.attention'), message: this._appLocalization.get('applications.content.entryDetails.flavours.link.requiredFlavorsMissing'), accept: () => { this._logger.info(`user confirmed proceed action`); this._performAction(); }, reject: () => { this._logger.info(`user didn't confirm abort action`); } }); } } else { this._logger.info(`form is not valid, abort action`); } } }
{ this._logger.info(`handle update flavor request`, { fileUrl: this._form.value.filePath, flavorAssetId: this.flavor.flavorAsset.id }); return this._kalturaClient .request(new FlavorAssetSetContentAction({ id: this.flavor.flavorAsset.id, contentResource: new KalturaRemoteStorageResource({ url: this._form.value.filePath, storageProfileId: this.storageProfile.id }) })) .map(() => { }); }
identifier_body
flavor-link.component.ts
import { Component, Input, OnDestroy } from '@angular/core'; import { PopupWidgetComponent } from '@kaltura-ng/kaltura-ui'; import { Flavor } from '../flavor'; import { KalturaStorageProfile } from 'kaltura-ngx-client'; import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms'; import { KalturaLogger } from '@kaltura-ng/kaltura-logger'; import { KalturaClient, KalturaMultiRequest } from 'kaltura-ngx-client'; import { KalturaRemoteStorageResource } from 'kaltura-ngx-client'; import { FlavorAssetSetContentAction } from 'kaltura-ngx-client'; import { EntryFlavoursWidget } from '../entry-flavours-widget.service'; import { BrowserService } from 'app-shared/kmc-shell/providers'; import { Observable } from 'rxjs'; import { KalturaFlavorAsset } from 'kaltura-ngx-client'; import { FlavorAssetAddAction } from 'kaltura-ngx-client'; import { KalturaConversionProfileAssetParams } from 'kaltura-ngx-client'; import { KalturaFlavorReadyBehaviorType } from 'kaltura-ngx-client'; import { KalturaAssetParamsOrigin } from 'kaltura-ngx-client'; import { AppLocalization } from '@kaltura-ng/mc-shared'; import { cancelOnDestroy, tag } from '@kaltura-ng/kaltura-common'; @Component({ selector: 'kFlavorLink', templateUrl: './flavor-link.component.html', styleUrls: ['./flavor-link.component.scss'], providers: [KalturaLogger.createLogger('FlavorLinkComponent')] }) export class FlavorLinkComponent implements OnDestroy { @Input() flavor: Flavor; @Input() storageProfile: KalturaStorageProfile; @Input() conversionProfileAsset: KalturaConversionProfileAssetParams; @Input() parentPopupWidget: PopupWidgetComponent; public _form: FormGroup; public _filePathField: AbstractControl; constructor(private _appLocalization: AppLocalization, private _logger: KalturaLogger, private _widgetService: EntryFlavoursWidget, private _kalturaClient: KalturaClient, private _browserService: BrowserService, private _fb: FormBuilder) { this._buildForm(); } ngOnDestroy() { } private _buildForm(): void { this._form = this._fb.group({ filePath: ['', Validators.required] }); this._filePathField = this._form.controls['filePath']; } private _updateFlavorAction(): Observable<void> { this._logger.info(`handle update flavor request`, { fileUrl: this._form.value.filePath, flavorAssetId: this.flavor.flavorAsset.id }); return this._kalturaClient .request(new FlavorAssetSetContentAction({ id: this.flavor.flavorAsset.id, contentResource: new KalturaRemoteStorageResource({ url: this._form.value.filePath, storageProfileId: this.storageProfile.id }) })) .map(() => { }); } private _uploadFlavorAction(): Observable<void> { this._logger.info(`handle upload flavor request, create asset and set its content`, { fileUrl: this._form.value.filePath, }); const entryId = this._widgetService.data.id; const flavorAsset = new KalturaFlavorAsset({ flavorParamsId: this.flavor.flavorParams.id }); const flavorAssetAddAction = new FlavorAssetAddAction({ entryId, flavorAsset }); const flavorAssetSetContentAction = new FlavorAssetSetContentAction({ id: '0', contentResource: new KalturaRemoteStorageResource({ storageProfileId: this.storageProfile.id, url: this._form.value.filePath }) }).setDependency(['id', 0, 'id']); return this._kalturaClient .multiRequest(new KalturaMultiRequest(flavorAssetAddAction, flavorAssetSetContentAction)) .map(responses => { if (responses.hasErrors()) { throw new Error(responses.reduce((acc, val) => `${acc}\n${val.error ? val.error.message : ''}`, '')); } return undefined; }); } private _validate(): boolean { const asset = this.conversionProfileAsset; if (!asset || asset.readyBehavior !== KalturaFlavorReadyBehaviorType.required || asset.origin !== KalturaAssetParamsOrigin.ingest) { return true; } return asset.assetParamsId === this.flavor.flavorParams.id; } private
(): void { const linkAction = this.flavor.flavorAsset && this.flavor.flavorAsset.id ? this._updateFlavorAction() : this._uploadFlavorAction(); linkAction .pipe(tag('block-shell')) .pipe(cancelOnDestroy(this)) .subscribe( () => { this._logger.info(`handle successful link action, reload flavors data`); this.parentPopupWidget.close(); this._widgetService.refresh(); }, error => { this._logger.warn(`handle failed link action, show alert`, { errorMessage: error.message }); this._browserService.alert({ header: this._appLocalization.get('app.common.error'), message: error.message, accept: () => { this._logger.info(`user dismissed alert, reload flavors data`); this.parentPopupWidget.close(); this._widgetService.refresh(); } }); }); } public _link(): void { this._logger.info(`handle link action by user`); if (this._form.valid) { this._logger.info(`validate asset params`, { asset: this.conversionProfileAsset }); if (this._validate()) { this._performAction(); } else { this._logger.info(`asset params is not valid, show confirmation`); this._browserService.confirm({ header: this._appLocalization.get('app.common.attention'), message: this._appLocalization.get('applications.content.entryDetails.flavours.link.requiredFlavorsMissing'), accept: () => { this._logger.info(`user confirmed proceed action`); this._performAction(); }, reject: () => { this._logger.info(`user didn't confirm abort action`); } }); } } else { this._logger.info(`form is not valid, abort action`); } } }
_performAction
identifier_name
express-server.js
module.exports = function(grunt) { var express = require('express'), lockFile = require('lockfile'), Helpers = require('./helpers'), fs = require('fs'), path = require('path'), request = require('request'); /** Task for serving the static files. Note: The expressServer:debug task looks for files in multiple directories. */ grunt.registerTask('expressServer', function(target, proxyMethodToUse) { // Load namespace module before creating the server require('express-namespace'); var app = express(), done = this.async(), proxyMethod = proxyMethodToUse || grunt.config('express-server.options.APIMethod'); app.use(lock); app.use(express.compress()); if (proxyMethod === 'stub') { grunt.log.writeln('Using API Stub'); // Load API stub routes app.use(express.json()); app.use(express.urlencoded()); require('../api-stub/routes')(app); } else if (proxyMethod === 'proxy') { var proxyURL = grunt.config('express-server.options.proxyURL'), proxyPath = grunt.config('express-server.options.proxyPath') || '/api'; grunt.log.writeln('Proxying API requests matching ' + proxyPath + '/* to: ' + proxyURL); // Use API proxy app.all(proxyPath + '/*', passThrough(proxyURL)); } if (target === 'debug') { // For `expressServer:debug` // Add livereload middleware after lock middleware if enabled if (Helpers.isPackageAvailable("connect-livereload")) { var liveReloadPort = grunt.config('watch.options.livereload'); app.use(require("connect-livereload")({port: liveReloadPort})); } // YUIDoc serves static HTML, so just serve the index.html app.all('/docs', function(req, res) { res.redirect(302, '/docs/index.html'); }); app.use(static({ urlRoot: '/docs', directory: 'docs' })); // These three lines simulate what the `copy:assemble` task does app.use(static({ urlRoot: '/config', directory: 'config' })); app.use(static({ urlRoot: '/vendor', directory: 'vendor' })); app.use(static({ directory: 'public' })); app.use(static({ urlRoot: '/tests', directory: 'tests' })); // For test-helper.js and test-loader.js app.use(static({ directory: 'tmp/result' })); app.use(static({ file: 'tmp/result/index.html', ignoredFileExtensions: /\.\w{1,5}$/ })); // Gotta catch 'em all } else { // For `expressServer:dist` app.use(lock); app.use(static({ directory: 'dist' })); app.use(static({ file: 'dist/index.html', ignoredFileExtensions: /\.\w{1,5}$/ })); // Gotta catch 'em all } var port = parseInt(process.env.PORT || 8000, 10); if (isNaN(port) || port < 1 || port > 65535) { grunt.fail.fatal('The PORT environment variable of ' + process.env.PORT + ' is not valid.'); } app.listen(port); grunt.log.ok('Started development server on port %d.', port); if (!this.flags.keepalive) { done(); } }); // Middleware // ========== function lock(req, res, next) { // Works with tasks/locking.js (function retry() { if (lockFile.checkSync('tmp/connect.lock')) { setTimeout(retry, 30); } else { next(); } })(); } function static(options) { return function(req, res, next) { // Gotta catch 'em all (and serve index.html) var filePath = ""; if (options.directory) { var regex = new RegExp('^' + (options.urlRoot || '')); // URL must begin with urlRoot's value if (!req.path.match(regex)) { next(); return; } filePath = options.directory + req.path.replace(regex, ''); } else if (options.file) { filePath = options.file; } else { throw new Error('static() isn\'t properly configured!'); } fs.stat(filePath, function(err, stats) { if (err) { next(); return; } // Not a file, not a folder => can't handle it if (options.ignoredFileExtensions) { if (options.ignoredFileExtensions.test(req.path)) { res.send(404, {error: 'Resource not found'}); return; // Do not serve index.html } } // Is it a directory? If so, search for an index.html in it. if (stats.isDirectory()) { filePath = path.join(filePath, 'index.html'); } // Serve the file res.sendfile(filePath, function(err) { if (err) { next(); return; } grunt.verbose.ok('Served: ' + filePath); }); }); }; } function
(target) { return function(req, res) { req.pipe(request(target+req.url)).pipe(res); }; } };
passThrough
identifier_name
express-server.js
module.exports = function(grunt) { var express = require('express'), lockFile = require('lockfile'), Helpers = require('./helpers'), fs = require('fs'), path = require('path'), request = require('request'); /** Task for serving the static files. Note: The expressServer:debug task looks for files in multiple directories. */ grunt.registerTask('expressServer', function(target, proxyMethodToUse) { // Load namespace module before creating the server require('express-namespace'); var app = express(), done = this.async(), proxyMethod = proxyMethodToUse || grunt.config('express-server.options.APIMethod'); app.use(lock); app.use(express.compress()); if (proxyMethod === 'stub') { grunt.log.writeln('Using API Stub'); // Load API stub routes app.use(express.json()); app.use(express.urlencoded()); require('../api-stub/routes')(app); } else if (proxyMethod === 'proxy') { var proxyURL = grunt.config('express-server.options.proxyURL'), proxyPath = grunt.config('express-server.options.proxyPath') || '/api'; grunt.log.writeln('Proxying API requests matching ' + proxyPath + '/* to: ' + proxyURL); // Use API proxy app.all(proxyPath + '/*', passThrough(proxyURL)); } if (target === 'debug') { // For `expressServer:debug` // Add livereload middleware after lock middleware if enabled if (Helpers.isPackageAvailable("connect-livereload")) { var liveReloadPort = grunt.config('watch.options.livereload'); app.use(require("connect-livereload")({port: liveReloadPort})); } // YUIDoc serves static HTML, so just serve the index.html app.all('/docs', function(req, res) { res.redirect(302, '/docs/index.html'); }); app.use(static({ urlRoot: '/docs', directory: 'docs' })); // These three lines simulate what the `copy:assemble` task does app.use(static({ urlRoot: '/config', directory: 'config' })); app.use(static({ urlRoot: '/vendor', directory: 'vendor' })); app.use(static({ directory: 'public' })); app.use(static({ urlRoot: '/tests', directory: 'tests' })); // For test-helper.js and test-loader.js app.use(static({ directory: 'tmp/result' }));
// For `expressServer:dist` app.use(lock); app.use(static({ directory: 'dist' })); app.use(static({ file: 'dist/index.html', ignoredFileExtensions: /\.\w{1,5}$/ })); // Gotta catch 'em all } var port = parseInt(process.env.PORT || 8000, 10); if (isNaN(port) || port < 1 || port > 65535) { grunt.fail.fatal('The PORT environment variable of ' + process.env.PORT + ' is not valid.'); } app.listen(port); grunt.log.ok('Started development server on port %d.', port); if (!this.flags.keepalive) { done(); } }); // Middleware // ========== function lock(req, res, next) { // Works with tasks/locking.js (function retry() { if (lockFile.checkSync('tmp/connect.lock')) { setTimeout(retry, 30); } else { next(); } })(); } function static(options) { return function(req, res, next) { // Gotta catch 'em all (and serve index.html) var filePath = ""; if (options.directory) { var regex = new RegExp('^' + (options.urlRoot || '')); // URL must begin with urlRoot's value if (!req.path.match(regex)) { next(); return; } filePath = options.directory + req.path.replace(regex, ''); } else if (options.file) { filePath = options.file; } else { throw new Error('static() isn\'t properly configured!'); } fs.stat(filePath, function(err, stats) { if (err) { next(); return; } // Not a file, not a folder => can't handle it if (options.ignoredFileExtensions) { if (options.ignoredFileExtensions.test(req.path)) { res.send(404, {error: 'Resource not found'}); return; // Do not serve index.html } } // Is it a directory? If so, search for an index.html in it. if (stats.isDirectory()) { filePath = path.join(filePath, 'index.html'); } // Serve the file res.sendfile(filePath, function(err) { if (err) { next(); return; } grunt.verbose.ok('Served: ' + filePath); }); }); }; } function passThrough(target) { return function(req, res) { req.pipe(request(target+req.url)).pipe(res); }; } };
app.use(static({ file: 'tmp/result/index.html', ignoredFileExtensions: /\.\w{1,5}$/ })); // Gotta catch 'em all } else {
random_line_split
express-server.js
module.exports = function(grunt) { var express = require('express'), lockFile = require('lockfile'), Helpers = require('./helpers'), fs = require('fs'), path = require('path'), request = require('request'); /** Task for serving the static files. Note: The expressServer:debug task looks for files in multiple directories. */ grunt.registerTask('expressServer', function(target, proxyMethodToUse) { // Load namespace module before creating the server require('express-namespace'); var app = express(), done = this.async(), proxyMethod = proxyMethodToUse || grunt.config('express-server.options.APIMethod'); app.use(lock); app.use(express.compress()); if (proxyMethod === 'stub')
else if (proxyMethod === 'proxy') { var proxyURL = grunt.config('express-server.options.proxyURL'), proxyPath = grunt.config('express-server.options.proxyPath') || '/api'; grunt.log.writeln('Proxying API requests matching ' + proxyPath + '/* to: ' + proxyURL); // Use API proxy app.all(proxyPath + '/*', passThrough(proxyURL)); } if (target === 'debug') { // For `expressServer:debug` // Add livereload middleware after lock middleware if enabled if (Helpers.isPackageAvailable("connect-livereload")) { var liveReloadPort = grunt.config('watch.options.livereload'); app.use(require("connect-livereload")({port: liveReloadPort})); } // YUIDoc serves static HTML, so just serve the index.html app.all('/docs', function(req, res) { res.redirect(302, '/docs/index.html'); }); app.use(static({ urlRoot: '/docs', directory: 'docs' })); // These three lines simulate what the `copy:assemble` task does app.use(static({ urlRoot: '/config', directory: 'config' })); app.use(static({ urlRoot: '/vendor', directory: 'vendor' })); app.use(static({ directory: 'public' })); app.use(static({ urlRoot: '/tests', directory: 'tests' })); // For test-helper.js and test-loader.js app.use(static({ directory: 'tmp/result' })); app.use(static({ file: 'tmp/result/index.html', ignoredFileExtensions: /\.\w{1,5}$/ })); // Gotta catch 'em all } else { // For `expressServer:dist` app.use(lock); app.use(static({ directory: 'dist' })); app.use(static({ file: 'dist/index.html', ignoredFileExtensions: /\.\w{1,5}$/ })); // Gotta catch 'em all } var port = parseInt(process.env.PORT || 8000, 10); if (isNaN(port) || port < 1 || port > 65535) { grunt.fail.fatal('The PORT environment variable of ' + process.env.PORT + ' is not valid.'); } app.listen(port); grunt.log.ok('Started development server on port %d.', port); if (!this.flags.keepalive) { done(); } }); // Middleware // ========== function lock(req, res, next) { // Works with tasks/locking.js (function retry() { if (lockFile.checkSync('tmp/connect.lock')) { setTimeout(retry, 30); } else { next(); } })(); } function static(options) { return function(req, res, next) { // Gotta catch 'em all (and serve index.html) var filePath = ""; if (options.directory) { var regex = new RegExp('^' + (options.urlRoot || '')); // URL must begin with urlRoot's value if (!req.path.match(regex)) { next(); return; } filePath = options.directory + req.path.replace(regex, ''); } else if (options.file) { filePath = options.file; } else { throw new Error('static() isn\'t properly configured!'); } fs.stat(filePath, function(err, stats) { if (err) { next(); return; } // Not a file, not a folder => can't handle it if (options.ignoredFileExtensions) { if (options.ignoredFileExtensions.test(req.path)) { res.send(404, {error: 'Resource not found'}); return; // Do not serve index.html } } // Is it a directory? If so, search for an index.html in it. if (stats.isDirectory()) { filePath = path.join(filePath, 'index.html'); } // Serve the file res.sendfile(filePath, function(err) { if (err) { next(); return; } grunt.verbose.ok('Served: ' + filePath); }); }); }; } function passThrough(target) { return function(req, res) { req.pipe(request(target+req.url)).pipe(res); }; } };
{ grunt.log.writeln('Using API Stub'); // Load API stub routes app.use(express.json()); app.use(express.urlencoded()); require('../api-stub/routes')(app); }
conditional_block
express-server.js
module.exports = function(grunt) { var express = require('express'), lockFile = require('lockfile'), Helpers = require('./helpers'), fs = require('fs'), path = require('path'), request = require('request'); /** Task for serving the static files. Note: The expressServer:debug task looks for files in multiple directories. */ grunt.registerTask('expressServer', function(target, proxyMethodToUse) { // Load namespace module before creating the server require('express-namespace'); var app = express(), done = this.async(), proxyMethod = proxyMethodToUse || grunt.config('express-server.options.APIMethod'); app.use(lock); app.use(express.compress()); if (proxyMethod === 'stub') { grunt.log.writeln('Using API Stub'); // Load API stub routes app.use(express.json()); app.use(express.urlencoded()); require('../api-stub/routes')(app); } else if (proxyMethod === 'proxy') { var proxyURL = grunt.config('express-server.options.proxyURL'), proxyPath = grunt.config('express-server.options.proxyPath') || '/api'; grunt.log.writeln('Proxying API requests matching ' + proxyPath + '/* to: ' + proxyURL); // Use API proxy app.all(proxyPath + '/*', passThrough(proxyURL)); } if (target === 'debug') { // For `expressServer:debug` // Add livereload middleware after lock middleware if enabled if (Helpers.isPackageAvailable("connect-livereload")) { var liveReloadPort = grunt.config('watch.options.livereload'); app.use(require("connect-livereload")({port: liveReloadPort})); } // YUIDoc serves static HTML, so just serve the index.html app.all('/docs', function(req, res) { res.redirect(302, '/docs/index.html'); }); app.use(static({ urlRoot: '/docs', directory: 'docs' })); // These three lines simulate what the `copy:assemble` task does app.use(static({ urlRoot: '/config', directory: 'config' })); app.use(static({ urlRoot: '/vendor', directory: 'vendor' })); app.use(static({ directory: 'public' })); app.use(static({ urlRoot: '/tests', directory: 'tests' })); // For test-helper.js and test-loader.js app.use(static({ directory: 'tmp/result' })); app.use(static({ file: 'tmp/result/index.html', ignoredFileExtensions: /\.\w{1,5}$/ })); // Gotta catch 'em all } else { // For `expressServer:dist` app.use(lock); app.use(static({ directory: 'dist' })); app.use(static({ file: 'dist/index.html', ignoredFileExtensions: /\.\w{1,5}$/ })); // Gotta catch 'em all } var port = parseInt(process.env.PORT || 8000, 10); if (isNaN(port) || port < 1 || port > 65535) { grunt.fail.fatal('The PORT environment variable of ' + process.env.PORT + ' is not valid.'); } app.listen(port); grunt.log.ok('Started development server on port %d.', port); if (!this.flags.keepalive) { done(); } }); // Middleware // ========== function lock(req, res, next) { // Works with tasks/locking.js (function retry() { if (lockFile.checkSync('tmp/connect.lock')) { setTimeout(retry, 30); } else { next(); } })(); } function static(options)
function passThrough(target) { return function(req, res) { req.pipe(request(target+req.url)).pipe(res); }; } };
{ return function(req, res, next) { // Gotta catch 'em all (and serve index.html) var filePath = ""; if (options.directory) { var regex = new RegExp('^' + (options.urlRoot || '')); // URL must begin with urlRoot's value if (!req.path.match(regex)) { next(); return; } filePath = options.directory + req.path.replace(regex, ''); } else if (options.file) { filePath = options.file; } else { throw new Error('static() isn\'t properly configured!'); } fs.stat(filePath, function(err, stats) { if (err) { next(); return; } // Not a file, not a folder => can't handle it if (options.ignoredFileExtensions) { if (options.ignoredFileExtensions.test(req.path)) { res.send(404, {error: 'Resource not found'}); return; // Do not serve index.html } } // Is it a directory? If so, search for an index.html in it. if (stats.isDirectory()) { filePath = path.join(filePath, 'index.html'); } // Serve the file res.sendfile(filePath, function(err) { if (err) { next(); return; } grunt.verbose.ok('Served: ' + filePath); }); }); }; }
identifier_body