idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
39,200 | def export_to_xlsx ( table , filename_or_fobj = None , sheet_name = "Sheet1" , * args , ** kwargs ) : workbook = Workbook ( ) sheet = workbook . active sheet . title = sheet_name prepared_table = prepare_to_export ( table , * args , ** kwargs ) field_names = next ( prepared_table ) for col_index , field_name in enumerate ( field_names ) : cell = sheet . cell ( row = 1 , column = col_index + 1 ) cell . value = field_name _convert_row = _python_to_cell ( list ( map ( table . fields . get , field_names ) ) ) for row_index , row in enumerate ( prepared_table , start = 1 ) : for col_index , ( value , number_format ) in enumerate ( _convert_row ( row ) ) : cell = sheet . cell ( row = row_index + 1 , column = col_index + 1 ) cell . value = value if number_format is not None : cell . number_format = number_format return_result = False if filename_or_fobj is None : filename_or_fobj = BytesIO ( ) return_result = True source = Source . from_file ( filename_or_fobj , mode = "wb" , plugin_name = "xlsx" ) workbook . save ( source . fobj ) source . fobj . flush ( ) if return_result : source . fobj . seek ( 0 ) result = source . fobj . read ( ) else : result = source . fobj if source . should_close : source . fobj . close ( ) return result | Export the rows . Table to XLSX file and return the saved file . |
39,201 | def download_organizations ( ) : "Download organizations JSON and extract its properties" response = requests . get ( URL ) data = response . json ( ) organizations = [ organization [ "properties" ] for organization in data [ "features" ] ] return rows . import_from_dicts ( organizations ) | Download organizations JSON and extract its properties |
39,202 | def import_from_html ( filename_or_fobj , encoding = "utf-8" , index = 0 , ignore_colspan = True , preserve_html = False , properties = False , table_tag = "table" , row_tag = "tr" , column_tag = "td|th" , * args , ** kwargs ) : source = Source . from_file ( filename_or_fobj , plugin_name = "html" , mode = "rb" , encoding = encoding ) html = source . fobj . read ( ) . decode ( source . encoding ) html_tree = document_fromstring ( html ) tables = html_tree . xpath ( "//{}" . format ( table_tag ) ) table = tables [ index ] strip_tags ( table , "thead" ) strip_tags ( table , "tbody" ) row_elements = table . xpath ( row_tag ) table_rows = [ _get_row ( row , column_tag = column_tag , preserve_html = preserve_html , properties = properties , ) for row in row_elements ] if properties : table_rows [ 0 ] [ - 1 ] = "properties" if preserve_html and kwargs . get ( "fields" , None ) is None : table_rows [ 0 ] = list ( map ( _extract_node_text , row_elements [ 0 ] ) ) if ignore_colspan : max_columns = max ( map ( len , table_rows ) ) table_rows = [ row for row in table_rows if len ( row ) == max_columns ] meta = { "imported_from" : "html" , "source" : source } return create_table ( table_rows , meta = meta , * args , ** kwargs ) | Return rows . Table from HTML file . |
39,203 | def export_to_html ( table , filename_or_fobj = None , encoding = "utf-8" , caption = False , * args , ** kwargs ) : serialized_table = serialize ( table , * args , ** kwargs ) fields = next ( serialized_table ) result = [ "<table>\n\n" ] if caption and table . name : result . extend ( [ " <caption>" , table . name , "</caption>\n\n" ] ) result . extend ( [ " <thead>\n" , " <tr>\n" ] ) header = [ " <th> {} </th>\n" . format ( field ) for field in fields ] result . extend ( header ) result . extend ( [ " </tr>\n" , " </thead>\n" , "\n" , " <tbody>\n" , "\n" ] ) for index , row in enumerate ( serialized_table , start = 1 ) : css_class = "odd" if index % 2 == 1 else "even" result . append ( ' <tr class="{}">\n' . format ( css_class ) ) for value in row : result . extend ( [ " <td> " , escape ( value ) , " </td>\n" ] ) result . append ( " </tr>\n\n" ) result . append ( " </tbody>\n\n</table>\n" ) html = "" . join ( result ) . encode ( encoding ) return export_data ( filename_or_fobj , html , mode = "wb" ) | Export and return rows . Table data to HTML file . |
39,204 | def _extract_node_text ( node ) : texts = map ( six . text_type . strip , map ( six . text_type , map ( unescape , node . xpath ( ".//text()" ) ) ) ) return " " . join ( text for text in texts if text ) | Extract text from a given lxml node . |
39,205 | def count_tables ( filename_or_fobj , encoding = "utf-8" , table_tag = "table" ) : source = Source . from_file ( filename_or_fobj , plugin_name = "html" , mode = "rb" , encoding = encoding ) html = source . fobj . read ( ) . decode ( source . encoding ) html_tree = document_fromstring ( html ) tables = html_tree . xpath ( "//{}" . format ( table_tag ) ) result = len ( tables ) if source . should_close : source . fobj . close ( ) return result | Read a file passed by arg and return your table HTML tag count . |
39,206 | def tag_to_dict ( html ) : element = document_fromstring ( html ) . xpath ( "//html/body/child::*" ) [ 0 ] attributes = dict ( element . attrib ) attributes [ "text" ] = element . text_content ( ) return attributes | Extract tag s attributes into a dict . |
39,207 | def create_table ( data , meta = None , fields = None , skip_header = True , import_fields = None , samples = None , force_types = None , max_rows = None , * args , ** kwargs ) : table_rows = iter ( data ) force_types = force_types or { } if import_fields is not None : import_fields = make_header ( import_fields ) if fields is None : header = make_header ( next ( table_rows ) ) if samples is not None : sample_rows = list ( islice ( table_rows , 0 , samples ) ) table_rows = chain ( sample_rows , table_rows ) else : if max_rows is not None and max_rows > 0 : sample_rows = table_rows = list ( islice ( table_rows , max_rows ) ) else : sample_rows = table_rows = list ( table_rows ) detected_fields = detect_types ( header , sample_rows , skip_indexes = [ index for index , field in enumerate ( header ) if field in force_types or field not in ( import_fields or header ) ] , * args , ** kwargs ) new_fields = [ field_name for field_name in detected_fields . keys ( ) if field_name not in header ] fields = OrderedDict ( [ ( field_name , detected_fields . get ( field_name , TextField ) ) for field_name in header + new_fields ] ) fields . update ( force_types ) header = list ( fields . keys ( ) ) if import_fields is None : import_fields = header else : if not isinstance ( fields , OrderedDict ) : raise ValueError ( "`fields` must be an `OrderedDict`" ) if skip_header : next ( table_rows ) header = make_header ( list ( fields . keys ( ) ) ) if import_fields is None : import_fields = header fields = OrderedDict ( [ ( field_name , fields [ key ] ) for field_name , key in zip ( header , fields ) ] ) diff = set ( import_fields ) - set ( header ) if diff : field_names = ", " . join ( '"{}"' . format ( field ) for field in diff ) raise ValueError ( "Invalid field names: {}" . format ( field_names ) ) fields = OrderedDict ( [ ( field_name , fields [ field_name ] ) for field_name in import_fields ] ) get_row = get_items ( * map ( header . index , import_fields ) ) table = Table ( fields = fields , meta = meta ) if max_rows is not None and max_rows > 0 : table_rows = islice ( table_rows , max_rows ) table . extend ( dict ( zip ( import_fields , get_row ( row ) ) ) for row in table_rows ) source = table . meta . get ( "source" , None ) if source is not None : if source . should_close : source . fobj . close ( ) if source . should_delete and Path ( source . uri ) . exists ( ) : unlink ( source . uri ) return table | Create a rows . Table object based on data rows and some configurations |
39,208 | def export_data ( filename_or_fobj , data , mode = "w" ) : if filename_or_fobj is None : return data _ , fobj = get_filename_and_fobj ( filename_or_fobj , mode = mode ) source = Source . from_file ( filename_or_fobj , mode = mode , plugin_name = None ) source . fobj . write ( data ) source . fobj . flush ( ) return source . fobj | Return the object ready to be exported or only data if filename_or_fobj is not passed . |
39,209 | def read_sample ( fobj , sample ) : cursor = fobj . tell ( ) data = fobj . read ( sample ) fobj . seek ( cursor ) return data | Read sample bytes from fobj and return the cursor to where it was . |
39,210 | def export_to_csv ( table , filename_or_fobj = None , encoding = "utf-8" , dialect = unicodecsv . excel , batch_size = 100 , callback = None , * args , ** kwargs ) : return_data , should_close = False , None if filename_or_fobj is None : filename_or_fobj = BytesIO ( ) return_data = should_close = True source = Source . from_file ( filename_or_fobj , plugin_name = "csv" , mode = "wb" , encoding = encoding , should_close = should_close , ) writer = unicodecsv . writer ( source . fobj , encoding = encoding , dialect = dialect ) if callback is None : for batch in ipartition ( serialize ( table , * args , ** kwargs ) , batch_size ) : writer . writerows ( batch ) else : serialized = serialize ( table , * args , ** kwargs ) writer . writerow ( next ( serialized ) ) total = 0 for batch in ipartition ( serialized , batch_size ) : writer . writerows ( batch ) total += len ( batch ) callback ( total ) if return_data : source . fobj . seek ( 0 ) result = source . fobj . read ( ) else : source . fobj . flush ( ) result = source . fobj if source . should_close : source . fobj . close ( ) return result | Export a rows . Table to a CSV file . |
39,211 | def join ( keys , tables ) : fields = OrderedDict ( ) for table in tables : fields . update ( table . fields ) fields_keys = set ( fields . keys ( ) ) for key in keys : if key not in fields_keys : raise ValueError ( 'Invalid key: "{}"' . format ( key ) ) none_fields = lambda : OrderedDict ( { field : None for field in fields . keys ( ) } ) data = OrderedDict ( ) for table in tables : for row in table : row_key = tuple ( [ getattr ( row , key ) for key in keys ] ) if row_key not in data : data [ row_key ] = none_fields ( ) data [ row_key ] . update ( row . _asdict ( ) ) merged = Table ( fields = fields ) merged . extend ( data . values ( ) ) return merged | Merge a list of Table objects using keys to group rows |
39,212 | def transform ( fields , function , * tables ) : "Return a new table based on other tables and a transformation function" new_table = Table ( fields = fields ) for table in tables : for row in filter ( bool , map ( lambda row : function ( row , table ) , table ) ) : new_table . append ( row ) return new_table | Return a new table based on other tables and a transformation function |
39,213 | def make_pvc ( name , storage_class , access_modes , storage , labels = None , annotations = None , ) : pvc = V1PersistentVolumeClaim ( ) pvc . kind = "PersistentVolumeClaim" pvc . api_version = "v1" pvc . metadata = V1ObjectMeta ( ) pvc . metadata . name = name pvc . metadata . annotations = ( annotations or { } ) . copy ( ) pvc . metadata . labels = ( labels or { } ) . copy ( ) pvc . spec = V1PersistentVolumeClaimSpec ( ) pvc . spec . access_modes = access_modes pvc . spec . resources = V1ResourceRequirements ( ) pvc . spec . resources . requests = { "storage" : storage } if storage_class : pvc . metadata . annotations . update ( { "volume.beta.kubernetes.io/storage-class" : storage_class } ) pvc . spec . storage_class_name = storage_class return pvc | Make a k8s pvc specification for running a user notebook . |
39,214 | def make_ingress ( name , routespec , target , data ) : from kubernetes . client . models import ( V1beta1Ingress , V1beta1IngressSpec , V1beta1IngressRule , V1beta1HTTPIngressRuleValue , V1beta1HTTPIngressPath , V1beta1IngressBackend , ) meta = V1ObjectMeta ( name = name , annotations = { 'hub.jupyter.org/proxy-data' : json . dumps ( data ) , 'hub.jupyter.org/proxy-routespec' : routespec , 'hub.jupyter.org/proxy-target' : target } , labels = { 'heritage' : 'jupyterhub' , 'component' : 'singleuser-server' , 'hub.jupyter.org/proxy-route' : 'true' } ) if routespec . startswith ( '/' ) : host = None path = routespec else : host , path = routespec . split ( '/' , 1 ) target_parts = urlparse ( target ) target_ip = target_parts . hostname target_port = target_parts . port target_is_ip = re . match ( '^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$' , target_ip ) is not None if target_is_ip : endpoint = V1Endpoints ( kind = 'Endpoints' , metadata = meta , subsets = [ V1EndpointSubset ( addresses = [ V1EndpointAddress ( ip = target_ip ) ] , ports = [ V1EndpointPort ( port = target_port ) ] ) ] ) else : endpoint = None if target_is_ip : service = V1Service ( kind = 'Service' , metadata = meta , spec = V1ServiceSpec ( type = 'ClusterIP' , external_name = '' , ports = [ V1ServicePort ( port = target_port , target_port = target_port ) ] ) ) else : service = V1Service ( kind = 'Service' , metadata = meta , spec = V1ServiceSpec ( type = 'ExternalName' , external_name = target_ip , cluster_ip = '' , ports = [ V1ServicePort ( port = target_port , target_port = target_port ) ] , ) , ) ingress = V1beta1Ingress ( kind = 'Ingress' , metadata = meta , spec = V1beta1IngressSpec ( rules = [ V1beta1IngressRule ( host = host , http = V1beta1HTTPIngressRuleValue ( paths = [ V1beta1HTTPIngressPath ( path = path , backend = V1beta1IngressBackend ( service_name = name , service_port = target_port ) ) ] ) ) ] ) ) return endpoint , service , ingress | Returns an ingress service endpoint object that ll work for this service |
39,215 | def shared_client ( ClientType , * args , ** kwargs ) : kwarg_key = tuple ( ( key , kwargs [ key ] ) for key in sorted ( kwargs ) ) cache_key = ( ClientType , args , kwarg_key ) client = None if cache_key in _client_cache : client = _client_cache [ cache_key ] ( ) if client is None : Client = getattr ( kubernetes . client , ClientType ) client = Client ( * args , ** kwargs ) _client_cache [ cache_key ] = weakref . ref ( client ) return client | Return a single shared kubernetes client instance |
39,216 | def generate_hashed_slug ( slug , limit = 63 , hash_length = 6 ) : if len ( slug ) < ( limit - hash_length ) : return slug slug_hash = hashlib . sha256 ( slug . encode ( 'utf-8' ) ) . hexdigest ( ) return '{prefix}-{hash}' . format ( prefix = slug [ : limit - hash_length - 1 ] , hash = slug_hash [ : hash_length ] , ) . lower ( ) | Generate a unique name that s within a certain length limit |
39,217 | def get_k8s_model ( model_type , model_dict ) : model_dict = copy . deepcopy ( model_dict ) if isinstance ( model_dict , model_type ) : return model_dict elif isinstance ( model_dict , dict ) : model_dict = _map_dict_keys_to_model_attributes ( model_type , model_dict ) return model_type ( ** model_dict ) else : raise AttributeError ( "Expected object of type 'dict' (or '{}') but got '{}'." . format ( model_type . __name__ , type ( model_dict ) . __name__ ) ) | Returns an instance of type specified model_type from an model instance or represantative dictionary . |
39,218 | def _get_k8s_model_dict ( model_type , model ) : model = copy . deepcopy ( model ) if isinstance ( model , model_type ) : return model . to_dict ( ) elif isinstance ( model , dict ) : return _map_dict_keys_to_model_attributes ( model_type , model ) else : raise AttributeError ( "Expected object of type '{}' (or 'dict') but got '{}'." . format ( model_type . __name__ , type ( model ) . __name__ ) ) | Returns a dictionary representation of a provided model type |
39,219 | def _list_and_update ( self ) : initial_resources = getattr ( self . api , self . list_method_name ) ( self . namespace , label_selector = self . label_selector , field_selector = self . field_selector , _request_timeout = self . request_timeout , ) self . resources = { p . metadata . name : p for p in initial_resources . items } return initial_resources . metadata . resource_version | Update current list of resources by doing a full fetch . |
39,220 | def _watch_and_update ( self ) : selectors = [ ] log_name = "" if self . label_selector : selectors . append ( "label selector=%r" % self . label_selector ) if self . field_selector : selectors . append ( "field selector=%r" % self . field_selector ) log_selector = ', ' . join ( selectors ) cur_delay = 0.1 self . log . info ( "watching for %s with %s in namespace %s" , self . kind , log_selector , self . namespace , ) while True : self . log . debug ( "Connecting %s watcher" , self . kind ) start = time . monotonic ( ) w = watch . Watch ( ) try : resource_version = self . _list_and_update ( ) if not self . first_load_future . done ( ) : self . first_load_future . set_result ( None ) watch_args = { 'namespace' : self . namespace , 'label_selector' : self . label_selector , 'field_selector' : self . field_selector , 'resource_version' : resource_version , } if self . request_timeout : watch_args [ '_request_timeout' ] = self . request_timeout if self . timeout_seconds : watch_args [ 'timeout_seconds' ] = self . timeout_seconds for ev in w . stream ( getattr ( self . api , self . list_method_name ) , ** watch_args ) : cur_delay = 0.1 resource = ev [ 'object' ] if ev [ 'type' ] == 'DELETED' : self . resources . pop ( resource . metadata . name , None ) else : self . resources [ resource . metadata . name ] = resource if self . _stop_event . is_set ( ) : self . log . info ( "%s watcher stopped" , self . kind ) break watch_duration = time . monotonic ( ) - start if watch_duration >= self . restart_seconds : self . log . debug ( "Restarting %s watcher after %i seconds" , self . kind , watch_duration , ) break except ReadTimeoutError : self . log . warning ( "Read timeout watching %s, reconnecting" , self . kind ) continue except Exception : cur_delay = cur_delay * 2 if cur_delay > 30 : self . log . exception ( "Watching resources never recovered, giving up" ) if self . on_failure : self . on_failure ( ) return self . log . exception ( "Error when watching resources, retrying in %ss" , cur_delay ) time . sleep ( cur_delay ) continue else : self . log . debug ( "%s watcher timeout" , self . kind ) finally : w . stop ( ) if self . _stop_event . is_set ( ) : self . log . info ( "%s watcher stopped" , self . kind ) break self . log . warning ( "%s watcher finished" , self . kind ) | Keeps the current list of resources up - to - date |
39,221 | def start ( self ) : if hasattr ( self , 'watch_thread' ) : raise ValueError ( 'Thread watching for resources is already running' ) self . _list_and_update ( ) self . watch_thread = threading . Thread ( target = self . _watch_and_update ) self . watch_thread . daemon = True self . watch_thread . start ( ) | Start the reflection process! |
39,222 | def get_pod_manifest ( self ) : if callable ( self . uid ) : uid = yield gen . maybe_future ( self . uid ( self ) ) else : uid = self . uid if callable ( self . gid ) : gid = yield gen . maybe_future ( self . gid ( self ) ) else : gid = self . gid if callable ( self . fs_gid ) : fs_gid = yield gen . maybe_future ( self . fs_gid ( self ) ) else : fs_gid = self . fs_gid if callable ( self . supplemental_gids ) : supplemental_gids = yield gen . maybe_future ( self . supplemental_gids ( self ) ) else : supplemental_gids = self . supplemental_gids if self . cmd : real_cmd = self . cmd + self . get_args ( ) else : real_cmd = None labels = self . _build_pod_labels ( self . _expand_all ( self . extra_labels ) ) annotations = self . _build_common_annotations ( self . _expand_all ( self . extra_annotations ) ) return make_pod ( name = self . pod_name , cmd = real_cmd , port = self . port , image = self . image , image_pull_policy = self . image_pull_policy , image_pull_secret = self . image_pull_secrets , node_selector = self . node_selector , run_as_uid = uid , run_as_gid = gid , fs_gid = fs_gid , supplemental_gids = supplemental_gids , run_privileged = self . privileged , env = self . get_env ( ) , volumes = self . _expand_all ( self . volumes ) , volume_mounts = self . _expand_all ( self . volume_mounts ) , working_dir = self . working_dir , labels = labels , annotations = annotations , cpu_limit = self . cpu_limit , cpu_guarantee = self . cpu_guarantee , mem_limit = self . mem_limit , mem_guarantee = self . mem_guarantee , extra_resource_limits = self . extra_resource_limits , extra_resource_guarantees = self . extra_resource_guarantees , lifecycle_hooks = self . lifecycle_hooks , init_containers = self . _expand_all ( self . init_containers ) , service_account = self . service_account , extra_container_config = self . extra_container_config , extra_pod_config = self . extra_pod_config , extra_containers = self . _expand_all ( self . extra_containers ) , scheduler_name = self . scheduler_name , tolerations = self . tolerations , node_affinity_preferred = self . node_affinity_preferred , node_affinity_required = self . node_affinity_required , pod_affinity_preferred = self . pod_affinity_preferred , pod_affinity_required = self . pod_affinity_required , pod_anti_affinity_preferred = self . pod_anti_affinity_preferred , pod_anti_affinity_required = self . pod_anti_affinity_required , priority_class_name = self . priority_class_name , logger = self . log , ) | Make a pod manifest that will spawn current user s notebook pod . |
39,223 | def get_pvc_manifest ( self ) : labels = self . _build_common_labels ( self . _expand_all ( self . storage_extra_labels ) ) labels . update ( { 'component' : 'singleuser-storage' } ) annotations = self . _build_common_annotations ( { } ) return make_pvc ( name = self . pvc_name , storage_class = self . storage_class , access_modes = self . storage_access_modes , storage = self . storage_capacity , labels = labels , annotations = annotations ) | Make a pvc manifest that will spawn current user s pvc . |
39,224 | def is_pod_running ( self , pod ) : is_running = ( pod is not None and pod . status . phase == 'Running' and pod . status . pod_ip is not None and pod . metadata . deletion_timestamp is None and all ( [ cs . ready for cs in pod . status . container_statuses ] ) ) return is_running | Check if the given pod is running |
39,225 | def get_env ( self ) : env = super ( KubeSpawner , self ) . get_env ( ) env [ 'JUPYTER_IMAGE_SPEC' ] = self . image env [ 'JUPYTER_IMAGE' ] = self . image return env | Return the environment dict to use for the Spawner . |
39,226 | def poll ( self ) : if not self . pod_reflector . first_load_future . done ( ) : yield self . pod_reflector . first_load_future data = self . pod_reflector . pods . get ( self . pod_name , None ) if data is not None : if data . status . phase == 'Pending' : return None ctr_stat = data . status . container_statuses if ctr_stat is None : return 1 for c in ctr_stat : if c . name == 'notebook' : if c . state . terminated : if self . delete_stopped_pods : yield self . stop ( now = True ) return c . state . terminated . exit_code break return None return 1 | Check if the pod is still running . |
39,227 | def events ( self ) : if not self . event_reflector : return [ ] events = [ ] for event in self . event_reflector . events : if event . involved_object . name != self . pod_name : continue if self . _last_event and event . metadata . uid == self . _last_event : events = [ ] else : events . append ( event ) return events | Filter event - reflector to just our events |
39,228 | def _start_reflector ( self , key , ReflectorClass , replace = False , ** kwargs ) : main_loop = IOLoop . current ( ) def on_reflector_failure ( ) : self . log . critical ( "%s reflector failed, halting Hub." , key . title ( ) , ) sys . exit ( 1 ) previous_reflector = self . __class__ . reflectors . get ( key ) if replace or not previous_reflector : self . __class__ . reflectors [ key ] = ReflectorClass ( parent = self , namespace = self . namespace , on_failure = on_reflector_failure , ** kwargs , ) if replace and previous_reflector : previous_reflector . stop ( ) return self . __class__ . reflectors [ key ] | Start a shared reflector on the KubeSpawner class |
39,229 | def _start_watching_events ( self , replace = False ) : return self . _start_reflector ( "events" , EventReflector , fields = { "involvedObject.kind" : "Pod" } , replace = replace , ) | Start the events reflector |
39,230 | def _options_form_default ( self ) : if not self . profile_list : return '' if callable ( self . profile_list ) : return self . _render_options_form_dynamically else : return self . _render_options_form ( self . profile_list ) | Build the form template according to the profile_list setting . |
39,231 | def options_from_form ( self , formdata ) : if not self . profile_list or self . _profile_list is None : return formdata try : selected_profile = int ( formdata . get ( 'profile' , [ 0 ] ) [ 0 ] ) options = self . _profile_list [ selected_profile ] except ( TypeError , IndexError , ValueError ) : raise web . HTTPError ( 400 , "No such profile: %i" , formdata . get ( 'profile' , None ) ) return { 'profile' : options [ 'display_name' ] } | get the option selected by the user on the form |
39,232 | def _load_profile ( self , profile_name ) : default_profile = self . _profile_list [ 0 ] for profile in self . _profile_list : if profile . get ( 'default' , False ) : default_profile = profile if profile [ 'display_name' ] == profile_name : break else : if profile_name : raise ValueError ( "No such profile: %s. Options include: %s" % ( profile_name , ', ' . join ( p [ 'display_name' ] for p in self . _profile_list ) ) ) else : profile = default_profile self . log . debug ( "Applying KubeSpawner override for profile '%s'" , profile [ 'display_name' ] ) kubespawner_override = profile . get ( 'kubespawner_override' , { } ) for k , v in kubespawner_override . items ( ) : if callable ( v ) : v = v ( self ) self . log . debug ( ".. overriding KubeSpawner value %s=%s (callable result)" , k , v ) else : self . log . debug ( ".. overriding KubeSpawner value %s=%s" , k , v ) setattr ( self , k , v ) | Load a profile by name |
39,233 | def load_user_options ( self ) : if self . _profile_list is None : if callable ( self . profile_list ) : self . _profile_list = yield gen . maybe_future ( self . profile_list ( self ) ) else : self . _profile_list = self . profile_list if self . _profile_list : yield self . _load_profile ( self . user_options . get ( 'profile' , None ) ) | Load user options from self . user_options dict |
39,234 | def list_motors ( name_pattern = Motor . SYSTEM_DEVICE_NAME_CONVENTION , ** kwargs ) : class_path = abspath ( Device . DEVICE_ROOT_PATH + '/' + Motor . SYSTEM_CLASS_NAME ) return ( Motor ( name_pattern = name , name_exact = True ) for name in list_device_names ( class_path , name_pattern , ** kwargs ) ) | This is a generator function that enumerates all tacho motors that match the provided arguments . |
39,235 | def to_native_units ( self , motor ) : assert abs ( self . rotations_per_second ) <= motor . max_rps , "invalid rotations-per-second: {} max RPS is {}, {} was requested" . format ( motor , motor . max_rps , self . rotations_per_second ) return self . rotations_per_second / motor . max_rps * motor . max_speed | Return the native speed measurement required to achieve desired rotations - per - second |
39,236 | def to_native_units ( self , motor ) : assert abs ( self . rotations_per_minute ) <= motor . max_rpm , "invalid rotations-per-minute: {} max RPM is {}, {} was requested" . format ( motor , motor . max_rpm , self . rotations_per_minute ) return self . rotations_per_minute / motor . max_rpm * motor . max_speed | Return the native speed measurement required to achieve desired rotations - per - minute |
39,237 | def to_native_units ( self , motor ) : assert abs ( self . degrees_per_second ) <= motor . max_dps , "invalid degrees-per-second: {} max DPS is {}, {} was requested" . format ( motor , motor . max_dps , self . degrees_per_second ) return self . degrees_per_second / motor . max_dps * motor . max_speed | Return the native speed measurement required to achieve desired degrees - per - second |
39,238 | def to_native_units ( self , motor ) : assert abs ( self . degrees_per_minute ) <= motor . max_dpm , "invalid degrees-per-minute: {} max DPM is {}, {} was requested" . format ( motor , motor . max_dpm , self . degrees_per_minute ) return self . degrees_per_minute / motor . max_dpm * motor . max_speed | Return the native speed measurement required to achieve desired degrees - per - minute |
39,239 | def address ( self ) : self . _address , value = self . get_attr_string ( self . _address , 'address' ) return value | Returns the name of the port that this motor is connected to . |
39,240 | def commands ( self ) : ( self . _commands , value ) = self . get_cached_attr_set ( self . _commands , 'commands' ) return value | Returns a list of commands that are supported by the motor controller . Possible values are run - forever run - to - abs - pos run - to - rel - pos run - timed run - direct stop and reset . Not all commands may be supported . |
39,241 | def driver_name ( self ) : ( self . _driver_name , value ) = self . get_cached_attr_string ( self . _driver_name , 'driver_name' ) return value | Returns the name of the driver that provides this tacho motor device . |
39,242 | def duty_cycle ( self ) : self . _duty_cycle , value = self . get_attr_int ( self . _duty_cycle , 'duty_cycle' ) return value | Returns the current duty cycle of the motor . Units are percent . Values are - 100 to 100 . |
39,243 | def duty_cycle_sp ( self ) : self . _duty_cycle_sp , value = self . get_attr_int ( self . _duty_cycle_sp , 'duty_cycle_sp' ) return value | Writing sets the duty cycle setpoint . Reading returns the current value . Units are in percent . Valid values are - 100 to 100 . A negative value causes the motor to rotate in reverse . |
39,244 | def polarity ( self ) : self . _polarity , value = self . get_attr_string ( self . _polarity , 'polarity' ) return value | Sets the polarity of the motor . With normal polarity a positive duty cycle will cause the motor to rotate clockwise . With inversed polarity a positive duty cycle will cause the motor to rotate counter - clockwise . Valid values are normal and inversed . |
39,245 | def position ( self ) : self . _position , value = self . get_attr_int ( self . _position , 'position' ) return value | Returns the current position of the motor in pulses of the rotary encoder . When the motor rotates clockwise the position will increase . Likewise rotating counter - clockwise causes the position to decrease . Writing will set the position to that value . |
39,246 | def position_p ( self ) : self . _position_p , value = self . get_attr_int ( self . _position_p , 'hold_pid/Kp' ) return value | The proportional constant for the position PID . |
39,247 | def position_i ( self ) : self . _position_i , value = self . get_attr_int ( self . _position_i , 'hold_pid/Ki' ) return value | The integral constant for the position PID . |
39,248 | def position_d ( self ) : self . _position_d , value = self . get_attr_int ( self . _position_d , 'hold_pid/Kd' ) return value | The derivative constant for the position PID . |
39,249 | def max_speed ( self ) : ( self . _max_speed , value ) = self . get_cached_attr_int ( self . _max_speed , 'max_speed' ) return value | Returns the maximum value that is accepted by the speed_sp attribute . This may be slightly different than the maximum speed that a particular motor can reach - it s the maximum theoretical speed . |
39,250 | def ramp_up_sp ( self ) : self . _ramp_up_sp , value = self . get_attr_int ( self . _ramp_up_sp , 'ramp_up_sp' ) return value | Writing sets the ramp up setpoint . Reading returns the current value . Units are in milliseconds and must be positive . When set to a non - zero value the motor speed will increase from 0 to 100% of max_speed over the span of this setpoint . The actual ramp time is the ratio of the difference between the speed_sp and the current speed and max_speed multiplied by ramp_up_sp . |
39,251 | def ramp_down_sp ( self ) : self . _ramp_down_sp , value = self . get_attr_int ( self . _ramp_down_sp , 'ramp_down_sp' ) return value | Writing sets the ramp down setpoint . Reading returns the current value . Units are in milliseconds and must be positive . When set to a non - zero value the motor speed will decrease from 0 to 100% of max_speed over the span of this setpoint . The actual ramp time is the ratio of the difference between the speed_sp and the current speed and max_speed multiplied by ramp_down_sp . |
39,252 | def speed_p ( self ) : self . _speed_p , value = self . get_attr_int ( self . _speed_p , 'speed_pid/Kp' ) return value | The proportional constant for the speed regulation PID . |
39,253 | def speed_i ( self ) : self . _speed_i , value = self . get_attr_int ( self . _speed_i , 'speed_pid/Ki' ) return value | The integral constant for the speed regulation PID . |
39,254 | def speed_d ( self ) : self . _speed_d , value = self . get_attr_int ( self . _speed_d , 'speed_pid/Kd' ) return value | The derivative constant for the speed regulation PID . |
39,255 | def state ( self ) : self . _state , value = self . get_attr_set ( self . _state , 'state' ) return value | Reading returns a list of state flags . Possible flags are running ramping holding overloaded and stalled . |
39,256 | def stop_action ( self ) : self . _stop_action , value = self . get_attr_string ( self . _stop_action , 'stop_action' ) return value | Reading returns the current stop action . Writing sets the stop action . The value determines the motors behavior when command is set to stop . Also it determines the motors behavior when a run command completes . See stop_actions for a list of possible values . |
39,257 | def stop_actions ( self ) : ( self . _stop_actions , value ) = self . get_cached_attr_set ( self . _stop_actions , 'stop_actions' ) return value | Returns a list of stop actions supported by the motor controller . Possible values are coast brake and hold . coast means that power will be removed from the motor and it will freely coast to a stop . brake means that power will be removed from the motor and a passive electrical load will be placed on the motor . This is usually done by shorting the motor terminals together . This load will absorb the energy from the rotation of the motors and cause the motor to stop more quickly than coasting . hold does not remove power from the motor . Instead it actively tries to hold the motor at the current position . If an external force tries to turn the motor the motor will push back to maintain its position . |
39,258 | def time_sp ( self ) : self . _time_sp , value = self . get_attr_int ( self . _time_sp , 'time_sp' ) return value | Writing specifies the amount of time the motor will run when using the run - timed command . Reading returns the current value . Units are in milliseconds . |
39,259 | def run_forever ( self , ** kwargs ) : for key in kwargs : setattr ( self , key , kwargs [ key ] ) self . command = self . COMMAND_RUN_FOREVER | Run the motor until another command is sent . |
39,260 | def run_to_abs_pos ( self , ** kwargs ) : for key in kwargs : setattr ( self , key , kwargs [ key ] ) self . command = self . COMMAND_RUN_TO_ABS_POS | Run to an absolute position specified by position_sp and then stop using the action specified in stop_action . |
39,261 | def run_to_rel_pos ( self , ** kwargs ) : for key in kwargs : setattr ( self , key , kwargs [ key ] ) self . command = self . COMMAND_RUN_TO_REL_POS | Run to a position relative to the current position value . The new position will be current position + position_sp . When the new position is reached the motor will stop using the action specified by stop_action . |
39,262 | def run_timed ( self , ** kwargs ) : for key in kwargs : setattr ( self , key , kwargs [ key ] ) self . command = self . COMMAND_RUN_TIMED | Run the motor for the amount of time specified in time_sp and then stop the motor using the action specified by stop_action . |
39,263 | def stop ( self , ** kwargs ) : for key in kwargs : setattr ( self , key , kwargs [ key ] ) self . command = self . COMMAND_STOP | Stop any of the run commands before they are complete using the action specified by stop_action . |
39,264 | def reset ( self , ** kwargs ) : for key in kwargs : setattr ( self , key , kwargs [ key ] ) self . command = self . COMMAND_RESET | Reset all of the motor parameter attributes to their default value . This will also have the effect of stopping the motor . |
39,265 | def on_for_rotations ( self , speed , rotations , brake = True , block = True ) : speed_sp = self . _speed_native_units ( speed ) self . _set_rel_position_degrees_and_speed_sp ( rotations * 360 , speed_sp ) self . _set_brake ( brake ) self . run_to_rel_pos ( ) if block : self . wait_until ( 'running' , timeout = WAIT_RUNNING_TIMEOUT ) self . wait_until_not_moving ( ) | Rotate the motor at speed for rotations |
39,266 | def on_for_degrees ( self , speed , degrees , brake = True , block = True ) : speed_sp = self . _speed_native_units ( speed ) self . _set_rel_position_degrees_and_speed_sp ( degrees , speed_sp ) self . _set_brake ( brake ) self . run_to_rel_pos ( ) if block : self . wait_until ( 'running' , timeout = WAIT_RUNNING_TIMEOUT ) self . wait_until_not_moving ( ) | Rotate the motor at speed for degrees |
39,267 | def on_to_position ( self , speed , position , brake = True , block = True ) : speed = self . _speed_native_units ( speed ) self . speed_sp = int ( round ( speed ) ) self . position_sp = position self . _set_brake ( brake ) self . run_to_abs_pos ( ) if block : self . wait_until ( 'running' , timeout = WAIT_RUNNING_TIMEOUT ) self . wait_until_not_moving ( ) | Rotate the motor at speed to position |
39,268 | def on_for_seconds ( self , speed , seconds , brake = True , block = True ) : if seconds < 0 : raise ValueError ( "seconds is negative ({})" . format ( seconds ) ) speed = self . _speed_native_units ( speed ) self . speed_sp = int ( round ( speed ) ) self . time_sp = int ( seconds * 1000 ) self . _set_brake ( brake ) self . run_timed ( ) if block : self . wait_until ( 'running' , timeout = WAIT_RUNNING_TIMEOUT ) self . wait_until_not_moving ( ) | Rotate the motor at speed for seconds |
39,269 | def on ( self , speed , brake = True , block = False ) : speed = self . _speed_native_units ( speed ) self . speed_sp = int ( round ( speed ) ) self . _set_brake ( brake ) self . run_forever ( ) if block : self . wait_until ( 'running' , timeout = WAIT_RUNNING_TIMEOUT ) self . wait_until_not_moving ( ) | Rotate the motor at speed for forever |
39,270 | def commands ( self ) : self . _commands , value = self . get_attr_set ( self . _commands , 'commands' ) return value | Returns a list of commands supported by the motor controller . |
39,271 | def stop_actions ( self ) : self . _stop_actions , value = self . get_attr_set ( self . _stop_actions , 'stop_actions' ) return value | Gets a list of stop actions . Valid values are coast and brake . |
39,272 | def mid_pulse_sp ( self ) : self . _mid_pulse_sp , value = self . get_attr_int ( self . _mid_pulse_sp , 'mid_pulse_sp' ) return value | Used to set the pulse size in milliseconds for the signal that tells the servo to drive to the mid position_sp . Default value is 1500 . Valid values are 1300 to 1700 . For example on a 180 degree servo this would be 90 degrees . On continuous rotation servo this is the neutral position_sp where the motor does not turn . You must write to the position_sp attribute for changes to this attribute to take effect . |
39,273 | def run ( self , ** kwargs ) : for key in kwargs : setattr ( self , key , kwargs [ key ] ) self . command = self . COMMAND_RUN | Drive servo to the position set in the position_sp attribute . |
39,274 | def float ( self , ** kwargs ) : for key in kwargs : setattr ( self , key , kwargs [ key ] ) self . command = self . COMMAND_FLOAT | Remove power from the motor . |
39,275 | def off ( self , motors = None , brake = True ) : motors = motors if motors is not None else self . motors . values ( ) for motor in motors : motor . _set_brake ( brake ) for motor in motors : motor . stop ( ) | Stop motors immediately . Configure motors to brake if brake is set . |
39,276 | def on_for_degrees ( self , left_speed , right_speed , degrees , brake = True , block = True ) : ( left_speed_native_units , right_speed_native_units ) = self . _unpack_speeds_to_native_units ( left_speed , right_speed ) if degrees == 0 or ( left_speed_native_units == 0 and right_speed_native_units == 0 ) : left_degrees = degrees right_degrees = degrees elif abs ( left_speed_native_units ) > abs ( right_speed_native_units ) : left_degrees = degrees right_degrees = abs ( right_speed_native_units / left_speed_native_units ) * degrees else : left_degrees = abs ( left_speed_native_units / right_speed_native_units ) * degrees right_degrees = degrees self . left_motor . _set_rel_position_degrees_and_speed_sp ( left_degrees , left_speed_native_units ) self . left_motor . _set_brake ( brake ) self . right_motor . _set_rel_position_degrees_and_speed_sp ( right_degrees , right_speed_native_units ) self . right_motor . _set_brake ( brake ) log . debug ( "{}: on_for_degrees {}" . format ( self , degrees ) ) self . left_motor . run_to_rel_pos ( ) self . right_motor . run_to_rel_pos ( ) if block : self . _block ( ) | Rotate the motors at left_speed & right_speed for degrees . Speeds can be percentages or any SpeedValue implementation . |
39,277 | def on_for_rotations ( self , left_speed , right_speed , rotations , brake = True , block = True ) : MoveTank . on_for_degrees ( self , left_speed , right_speed , rotations * 360 , brake , block ) | Rotate the motors at left_speed & right_speed for rotations . Speeds can be percentages or any SpeedValue implementation . |
39,278 | def on_for_seconds ( self , left_speed , right_speed , seconds , brake = True , block = True ) : if seconds < 0 : raise ValueError ( "seconds is negative ({})" . format ( seconds ) ) ( left_speed_native_units , right_speed_native_units ) = self . _unpack_speeds_to_native_units ( left_speed , right_speed ) self . left_motor . speed_sp = int ( round ( left_speed_native_units ) ) self . left_motor . time_sp = int ( seconds * 1000 ) self . left_motor . _set_brake ( brake ) self . right_motor . speed_sp = int ( round ( right_speed_native_units ) ) self . right_motor . time_sp = int ( seconds * 1000 ) self . right_motor . _set_brake ( brake ) log . debug ( "%s: on_for_seconds %ss at left-speed %s, right-speed %s" % ( self , seconds , left_speed , right_speed ) ) self . left_motor . run_timed ( ) self . right_motor . run_timed ( ) if block : self . _block ( ) | Rotate the motors at left_speed & right_speed for seconds . Speeds can be percentages or any SpeedValue implementation . |
39,279 | def on ( self , left_speed , right_speed ) : ( left_speed_native_units , right_speed_native_units ) = self . _unpack_speeds_to_native_units ( left_speed , right_speed ) self . left_motor . speed_sp = int ( round ( left_speed_native_units ) ) self . right_motor . speed_sp = int ( round ( right_speed_native_units ) ) self . left_motor . run_forever ( ) self . right_motor . run_forever ( ) | Start rotating the motors according to left_speed and right_speed forever . Speeds can be percentages or any SpeedValue implementation . |
39,280 | def on_for_seconds ( self , steering , speed , seconds , brake = True , block = True ) : ( left_speed , right_speed ) = self . get_speed_steering ( steering , speed ) MoveTank . on_for_seconds ( self , SpeedNativeUnits ( left_speed ) , SpeedNativeUnits ( right_speed ) , seconds , brake , block ) | Rotate the motors according to the provided steering for seconds . |
39,281 | def on ( self , steering , speed ) : ( left_speed , right_speed ) = self . get_speed_steering ( steering , speed ) MoveTank . on ( self , SpeedNativeUnits ( left_speed ) , SpeedNativeUnits ( right_speed ) ) | Start rotating the motors according to the provided steering and speed forever . |
39,282 | def _on_arc ( self , speed , radius_mm , distance_mm , brake , block , arc_right ) : if radius_mm < self . min_circle_radius_mm : raise ValueError ( "{}: radius_mm {} is less than min_circle_radius_mm {}" . format ( self , radius_mm , self . min_circle_radius_mm ) ) circle_outer_mm = 2 * math . pi * ( radius_mm + ( self . wheel_distance_mm / 2 ) ) circle_middle_mm = 2 * math . pi * radius_mm circle_inner_mm = 2 * math . pi * ( radius_mm - ( self . wheel_distance_mm / 2 ) ) if arc_right : left_speed = speed right_speed = float ( circle_inner_mm / circle_outer_mm ) * left_speed else : right_speed = speed left_speed = float ( circle_inner_mm / circle_outer_mm ) * right_speed log . debug ( "%s: arc %s, radius %s, distance %s, left-speed %s, right-speed %s, circle_outer_mm %s, circle_middle_mm %s, circle_inner_mm %s" % ( self , "right" if arc_right else "left" , radius_mm , distance_mm , left_speed , right_speed , circle_outer_mm , circle_middle_mm , circle_inner_mm ) ) circle_middle_percentage = float ( distance_mm / circle_middle_mm ) circle_outer_final_mm = circle_middle_percentage * circle_outer_mm outer_wheel_rotations = float ( circle_outer_final_mm / self . wheel . circumference_mm ) outer_wheel_degrees = outer_wheel_rotations * 360 log . debug ( "%s: arc %s, circle_middle_percentage %s, circle_outer_final_mm %s, outer_wheel_rotations %s, outer_wheel_degrees %s" % ( self , "right" if arc_right else "left" , circle_middle_percentage , circle_outer_final_mm , outer_wheel_rotations , outer_wheel_degrees ) ) MoveTank . on_for_degrees ( self , left_speed , right_speed , outer_wheel_degrees , brake , block ) | Drive in a circle with radius for distance |
39,283 | def on_arc_right ( self , speed , radius_mm , distance_mm , brake = True , block = True ) : self . _on_arc ( speed , radius_mm , distance_mm , brake , block , True ) | Drive clockwise in a circle with radius_mm for distance_mm |
39,284 | def on_arc_left ( self , speed , radius_mm , distance_mm , brake = True , block = True ) : self . _on_arc ( speed , radius_mm , distance_mm , brake , block , False ) | Drive counter - clockwise in a circle with radius_mm for distance_mm |
39,285 | def _turn ( self , speed , degrees , brake = True , block = True ) : distance_mm = ( abs ( degrees ) / 360 ) * self . circumference_mm rotations = distance_mm / self . wheel . circumference_mm log . debug ( "%s: turn() degrees %s, distance_mm %s, rotations %s, degrees %s" % ( self , degrees , distance_mm , rotations , degrees ) ) if degrees > 0 : MoveTank . on_for_rotations ( self , speed , speed * - 1 , rotations , brake , block ) else : rotations = distance_mm / self . wheel . circumference_mm MoveTank . on_for_rotations ( self , speed * - 1 , speed , rotations , brake , block ) | Rotate in place degrees . Both wheels must turn at the same speed for us to rotate in place . |
39,286 | def turn_right ( self , speed , degrees , brake = True , block = True ) : self . _turn ( speed , abs ( degrees ) , brake , block ) | Rotate clockwise degrees in place |
39,287 | def turn_to_angle ( self , speed , angle_target_degrees , brake = True , block = True ) : assert self . odometry_thread_id , "odometry_start() must be called to track robot coordinates" if angle_target_degrees < 0 : angle_target_degrees += 360 angle_current_degrees = math . degrees ( self . theta ) if angle_current_degrees < 0 : angle_current_degrees += 360 if angle_current_degrees > angle_target_degrees : turn_right = True angle_delta = angle_current_degrees - angle_target_degrees else : turn_right = False angle_delta = angle_target_degrees - angle_current_degrees if angle_delta > 180 : angle_delta = 360 - angle_delta turn_right = not turn_right log . debug ( "%s: turn_to_angle %s, current angle %s, delta %s, turn_right %s" % ( self , angle_target_degrees , angle_current_degrees , angle_delta , turn_right ) ) self . odometry_coordinates_log ( ) if turn_right : self . turn_right ( speed , angle_delta , brake , block ) else : self . turn_left ( speed , angle_delta , brake , block ) self . odometry_coordinates_log ( ) | Rotate in place to angle_target_degrees at speed |
39,288 | def datetime_delta_to_ms ( delta ) : delta_ms = delta . days * 24 * 60 * 60 * 1000 delta_ms += delta . seconds * 1000 delta_ms += delta . microseconds / 1000 delta_ms = int ( delta_ms ) return delta_ms | Given a datetime . timedelta object return the delta in milliseconds |
39,289 | def duration_expired ( start_time , duration_seconds ) : if duration_seconds is not None : delta_seconds = datetime_delta_to_seconds ( dt . datetime . now ( ) - start_time ) if delta_seconds >= duration_seconds : return True return False | Return True if duration_seconds have expired since start_time |
39,290 | def max_brightness ( self ) : self . _max_brightness , value = self . get_cached_attr_int ( self . _max_brightness , 'max_brightness' ) return value | Returns the maximum allowable brightness value . |
39,291 | def brightness ( self ) : self . _brightness , value = self . get_attr_int ( self . _brightness , 'brightness' ) return value | Sets the brightness level . Possible values are from 0 to max_brightness . |
39,292 | def triggers ( self ) : self . _triggers , value = self . get_attr_set ( self . _triggers , 'trigger' ) return value | Returns a list of available triggers . |
39,293 | def trigger ( self ) : self . _trigger , value = self . get_attr_from_set ( self . _trigger , 'trigger' ) return value | Sets the LED trigger . A trigger is a kernel based source of LED events . Triggers can either be simple or complex . A simple trigger isn t configurable and is designed to slot into existing subsystems with minimal additional code . Examples are the ide - disk and nand - disk triggers . |
39,294 | def delay_on ( self ) : for retry in ( True , False ) : try : self . _delay_on , value = self . get_attr_int ( self . _delay_on , 'delay_on' ) return value except OSError : if retry : self . _delay_on = None else : raise | The timer trigger will periodically change the LED brightness between 0 and the current brightness setting . The on time can be specified via delay_on attribute in milliseconds . |
39,295 | def delay_off ( self ) : for retry in ( True , False ) : try : self . _delay_off , value = self . get_attr_int ( self . _delay_off , 'delay_off' ) return value except OSError : if retry : self . _delay_off = None else : raise | The timer trigger will periodically change the LED brightness between 0 and the current brightness setting . The off time can be specified via delay_off attribute in milliseconds . |
39,296 | def set_color ( self , group , color , pct = 1 ) : if not self . leds : return color_tuple = color if isinstance ( color , str ) : assert color in self . led_colors , "%s is an invalid LED color, valid choices are %s" % ( color , ', ' . join ( self . led_colors . keys ( ) ) ) color_tuple = self . led_colors [ color ] assert group in self . led_groups , "%s is an invalid LED group, valid choices are %s" % ( group , ', ' . join ( self . led_groups . keys ( ) ) ) for led , value in zip ( self . led_groups [ group ] , color_tuple ) : led . brightness_pct = value * pct | Sets brightness of LEDs in the given group to the values specified in color tuple . When percentage is specified brightness of each LED is reduced proportionally . |
39,297 | def set ( self , group , ** kwargs ) : if not self . leds : return assert group in self . led_groups , "%s is an invalid LED group, valid choices are %s" % ( group , ', ' . join ( self . led_groups . keys ( ) ) ) for led in self . led_groups [ group ] : for k in kwargs : setattr ( led , k , kwargs [ k ] ) | Set attributes for each LED in group . |
39,298 | def all_off ( self ) : if not self . leds : return for led in self . leds . values ( ) : led . brightness = 0 | Turn all LEDs off |
39,299 | def reset ( self ) : if not self . leds : return self . animate_stop ( ) for group in self . led_groups : self . set_color ( group , LED_DEFAULT_COLOR ) | Put all LEDs back to their default color |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.