idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
240,300 | def heatmap ( self , df , imagefile ) : import seaborn as sns import matplotlib . ticker as tkr import matplotlib . pyplot as plt from matplotlib . colors import LinearSegmentedColormap sns . set ( ) with sns . axes_style ( 'whitegrid' ) : fig , ax = plt . subplots ( figsize = ( 5 , 11 ) ) cmax = max ( df [ self . args... | Create the heat map . |
240,301 | def mainloop ( self ) : proxy = config . engine . open ( ) views = [ x for x in sorted ( proxy . view . list ( ) ) if x . startswith ( self . PREFIX ) ] current_view = real_current_view = proxy . ui . current_view ( ) if current_view not in views : if views : current_view = views [ 0 ] else : raise error . UserError ( ... | Manage category views . |
240,302 | def _custom_fields ( ) : import os from pyrocore . torrent import engine , matching from pyrocore . util import fmt def has_room ( obj ) : "Check disk space." pathname = obj . path if pathname and not os . path . exists ( pathname ) : pathname = os . path . dirname ( pathname ) if pathname and os . path . exists ( path... | Yield custom field definitions . |
240,303 | def engine_data ( engine ) : views = ( "default" , "main" , "started" , "stopped" , "complete" , "incomplete" , "seeding" , "leeching" , "active" , "messages" ) methods = [ "throttle.global_up.rate" , "throttle.global_up.max_rate" , "throttle.global_down.rate" , "throttle.global_down.max_rate" , ] proxy = engine . open... | Get important performance data and metadata from rTorrent . |
240,304 | def _write_pidfile ( pidfile ) : pid = str ( os . getpid ( ) ) handle = open ( pidfile , 'w' ) try : handle . write ( "%s\n" % pid ) finally : handle . close ( ) | Write file with current process ID . |
240,305 | def guard ( pidfile , guardfile = None ) : if guardfile and not os . path . exists ( guardfile ) : raise EnvironmentError ( "Guard file '%s' not found, won't start!" % guardfile ) if os . path . exists ( pidfile ) : running , pid = check_process ( pidfile ) if running : raise EnvironmentError ( "Daemon process #%d stil... | Raise an EnvironmentError when the guardfile doesn t exist or the process with the ID found in pidfile is still active . |
240,306 | def daemonize ( pidfile = None , logfile = None , sync = True ) : log = logging . getLogger ( "daemonize" ) ppid = os . getpid ( ) try : pid = os . fork ( ) if pid > 0 : log . debug ( "Parent exiting (PID %d, CHILD %d)" % ( ppid , pid ) ) sys . exit ( 0 ) except OSError as exc : log . critical ( "fork #1 failed (PID %d... | Fork the process into the background . |
240,307 | def flatten ( nested , containers = ( list , tuple ) ) : flat = list ( nested ) i = 0 while i < len ( flat ) : while isinstance ( flat [ i ] , containers ) : if not flat [ i ] : flat . pop ( i ) i -= 1 break else : flat [ i : i + 1 ] = ( flat [ i ] ) i += 1 return flat | Flatten a nested list in - place and return it . |
240,308 | def gendocs ( ) : "create some doc pages automatically" helppage = path ( "docs/references-cli-usage.rst" ) content = [ ".. automatically generated using 'paver gendocs'." , "" , ".. contents::" , " :local:" , "" , ".. note::" , "" , " The help output presented here applies to version ``%s`` of the tools." % sh (... | create some doc pages automatically |
240,309 | def watchdog_pid ( ) : result = sh ( 'netstat -tulpn 2>/dev/null | grep 127.0.0.1:{:d}' . format ( SPHINX_AUTOBUILD_PORT ) , capture = True , ignore_error = True ) pid = result . strip ( ) pid = pid . split ( ) [ - 1 ] if pid else None pid = pid . split ( '/' , 1 ) [ 0 ] if pid and pid != '-' else None return pid | Get watchdog PID via netstat . |
240,310 | def autodocs ( ) : "create Sphinx docs locally, and start a watchdog" build_dir = path ( 'docs/_build' ) index_html = build_dir / 'html/index.html' if build_dir . exists ( ) : build_dir . rmtree ( ) with pushd ( "docs" ) : print "\n*** Generating API doc ***\n" sh ( "sphinx-apidoc -o apidoc -f -T -M ../src/pyrocore" ) ... | create Sphinx docs locally and start a watchdog |
240,311 | def stopdocs ( ) : "stop Sphinx watchdog" for i in range ( 4 ) : pid = watchdog_pid ( ) if pid : if not i : sh ( 'ps {}' . format ( pid ) ) sh ( 'kill {}' . format ( pid ) ) time . sleep ( .5 ) else : break | stop Sphinx watchdog |
240,312 | def coverage ( ) : "generate coverage report and show in browser" coverage_index = path ( "build/coverage/index.html" ) coverage_index . remove ( ) sh ( "paver test" ) coverage_index . exists ( ) and webbrowser . open ( coverage_index ) | generate coverage report and show in browser |
240,313 | def lookup_announce_alias ( name ) : for alias , urls in announce . items ( ) : if alias . lower ( ) == name . lower ( ) : return alias , urls raise KeyError ( "Unknown alias %s" % ( name , ) ) | Get canonical alias name and announce URL list for the given alias . |
240,314 | def map_announce2alias ( url ) : import urlparse for alias , urls in announce . items ( ) : if any ( i == url for i in urls ) : return alias parts = urlparse . urlparse ( url ) server = urlparse . urlunparse ( ( parts . scheme , parts . netloc , "/" , None , None , None ) ) for alias , urls in announce . items ( ) : if... | Get tracker alias for announce URL and if none is defined the 2nd level domain . |
240,315 | def validate ( key , val ) : if val and val . startswith ( "~/" ) : return os . path . expanduser ( val ) if key == "output_header_frequency" : return int ( val , 10 ) if key . endswith ( "_ecma48" ) : return eval ( "'%s'" % val . replace ( "'" , r"\'" ) ) return val | Validate a configuration value . |
240,316 | def _update_config ( self , namespace ) : for key , val in namespace . items ( ) : setattr ( config , key , val ) | Inject the items from the given dict into the configuration . |
240,317 | def _interpolation_escape ( self , namespace ) : for key , val in namespace . items ( ) : if '%' in val : namespace [ key ] = self . INTERPOLATION_ESCAPE . sub ( lambda match : '%' + match . group ( 0 ) , val ) | Re - escape interpolation strings . |
240,318 | def _validate_namespace ( self , namespace ) : self . _update_config ( namespace ) for key , val in namespace [ "announce" ] . items ( ) : if isinstance ( val , basestring ) : namespace [ "announce" ] [ key ] = val . split ( ) self . _interpolation_escape ( namespace [ "formats" ] ) for factory in ( "engine" , ) : if i... | Validate the given namespace . This method is idempotent! |
240,319 | def _set_from_ini ( self , namespace , ini_file ) : global_vars = dict ( ( key , val ) for key , val in namespace . items ( ) if isinstance ( val , basestring ) ) for section in ini_file . sections ( ) : if section == "GLOBAL" : raw_vars = global_vars else : raw_vars = namespace . setdefault ( section . lower ( ) , { }... | Copy values from loaded INI file to namespace . |
240,320 | def _set_defaults ( self , namespace , optional_cfg_files ) : namespace [ "config_dir" ] = self . config_dir for idx , cfg_file in enumerate ( [ self . CONFIG_INI ] + optional_cfg_files ) : if any ( i in cfg_file for i in set ( '/' + os . sep ) ) : continue try : defaults = pymagic . resource_string ( "pyrocore" , "dat... | Set default values in the given dict . |
240,321 | def _load_ini ( self , namespace , config_file ) : self . LOG . debug ( "Loading %r..." % ( config_file , ) ) ini_file = ConfigParser . SafeConfigParser ( ) ini_file . optionxform = str if ini_file . read ( config_file ) : self . _set_from_ini ( namespace , ini_file ) else : self . LOG . warning ( "Configuration file %... | Load INI style configuration . |
240,322 | def _load_py ( self , namespace , config_file ) : if config_file and os . path . isfile ( config_file ) : self . LOG . debug ( "Loading %r..." % ( config_file , ) ) exec ( compile ( open ( config_file ) . read ( ) , config_file , 'exec' ) , vars ( config ) , namespace ) else : self . LOG . warning ( "Configuration file... | Load scripted configuration . |
240,323 | def load ( self , optional_cfg_files = None ) : optional_cfg_files = optional_cfg_files or [ ] if self . _loaded : raise RuntimeError ( "INTERNAL ERROR: Attempt to load configuration twice!" ) try : namespace = { } self . _set_defaults ( namespace , optional_cfg_files ) self . _load_ini ( namespace , os . path . join (... | Actually load the configuation from either the default location or the given directory . |
240,324 | def create ( self , remove_all_rc_files = False ) : if os . path . exists ( self . config_dir ) : self . LOG . debug ( "Configuration directory %r already exists!" % ( self . config_dir , ) ) else : os . mkdir ( self . config_dir ) if remove_all_rc_files : for subdir in ( '.' , 'rtorrent.d' ) : config_files = list ( gl... | Create default configuration files at either the default location or the given directory . |
240,325 | def make_magnet_meta ( self , magnet_uri ) : import cgi import hashlib if magnet_uri . startswith ( "magnet:" ) : magnet_uri = magnet_uri [ 7 : ] meta = { "magnet-uri" : "magnet:" + magnet_uri } magnet_params = cgi . parse_qs ( magnet_uri . lstrip ( '?' ) ) meta_name = magnet_params . get ( "xt" , [ hashlib . sha1 ( ma... | Create a magnet - uri torrent . |
240,326 | def get_class_logger ( obj ) : return logging . getLogger ( obj . __class__ . __module__ + '.' + obj . __class__ . __name__ ) | Get a logger specific for the given object s class . |
240,327 | def default ( self , o ) : if isinstance ( o , set ) : return list ( sorted ( o ) ) elif hasattr ( o , 'as_dict' ) : return o . as_dict ( ) else : return super ( JSONEncoder , self ) . default ( o ) | Support more object types . |
240,328 | def fmt_sz ( intval ) : try : return fmt . human_size ( intval ) except ( ValueError , TypeError ) : return "N/A" . rjust ( len ( fmt . human_size ( 0 ) ) ) | Format a byte sized value . |
240,329 | def fmt_iso ( timestamp ) : try : return fmt . iso_datetime ( timestamp ) except ( ValueError , TypeError ) : return "N/A" . rjust ( len ( fmt . iso_datetime ( 0 ) ) ) | Format a UNIX timestamp to an ISO datetime string . |
240,330 | def fmt_duration ( duration ) : try : return fmt . human_duration ( float ( duration ) , 0 , 2 , True ) except ( ValueError , TypeError ) : return "N/A" . rjust ( len ( fmt . human_duration ( 0 , 0 , 2 , True ) ) ) | Format a duration value in seconds to a readable form . |
240,331 | def fmt_subst ( regex , subst ) : return lambda text : re . sub ( regex , subst , text ) if text else text | Replace regex with string . |
240,332 | def preparse ( output_format ) : try : return templating . preparse ( output_format , lambda path : os . path . join ( config . config_dir , "templates" , path ) ) except ImportError as exc : if "tempita" in str ( exc ) : raise error . UserError ( "To be able to use Tempita templates, install the 'tempita' package (%s)... | Do any special processing of a template and return the result . |
240,333 | def validate_field_list ( fields , allow_fmt_specs = False , name_filter = None ) : formats = [ i [ 4 : ] for i in globals ( ) if i . startswith ( "fmt_" ) ] try : fields = [ i . strip ( ) for i in fields . replace ( ',' , ' ' ) . split ( ) ] except AttributeError : pass if name_filter : fields = [ name_filter ( name )... | Make sure the fields in the given list exist . |
240,334 | def validate_sort_fields ( sort_fields ) : descending = set ( ) def sort_order_filter ( name ) : "Helper to remove flag and memoize sort order" if name . startswith ( '-' ) : name = name [ 1 : ] descending . add ( name ) return name sort_fields = validate_field_list ( sort_fields , name_filter = sort_order_filter ) log... | Make sure the fields in the given list exist and return sorting key . |
240,335 | def formatter_help ( cls ) : result = [ ( "raw" , "Switch off the default field formatter." ) ] for name , method in globals ( ) . items ( ) : if name . startswith ( "fmt_" ) : result . append ( ( name [ 4 : ] , method . __doc__ . strip ( ) ) ) return result | Return a list of format specifiers and their documentation . |
240,336 | def timeparse ( sval , granularity = 'seconds' ) : match = COMPILED_SIGN . match ( sval ) sign = - 1 if match . groupdict ( ) [ 'sign' ] == '-' else 1 sval = match . groupdict ( ) [ 'unsigned' ] for timefmt in COMPILED_TIMEFORMATS : match = timefmt . match ( sval ) if match and match . group ( 0 ) . strip ( ) : mdict =... | Parse a time expression returning it as a number of seconds . If possible the return value will be an int ; if this is not possible the return will be a float . Returns None if a time expression cannot be parsed from the given string . |
240,337 | def get_client ( project_id = None , credentials = None , service_url = None , service_account = None , private_key = None , private_key_file = None , json_key = None , json_key_file = None , readonly = True , swallow_results = True , num_retries = 0 ) : if not credentials : assert ( service_account and ( private_key o... | Return a singleton instance of BigQueryClient . Either AssertionCredentials or a service account and private key combination need to be provided in order to authenticate requests to BigQuery . |
240,338 | def get_projects ( bq_service ) : projects_request = bq_service . projects ( ) . list ( ) . execute ( ) projects = [ ] for project in projects_request . get ( 'projects' , [ ] ) : project_data = { 'id' : project [ 'id' ] , 'name' : project [ 'friendlyName' ] } projects . append ( project_data ) return projects | Given the BigQuery service return data about all projects . |
240,339 | def _get_bq_service ( credentials = None , service_url = None ) : assert credentials , 'Must provide ServiceAccountCredentials' http = credentials . authorize ( Http ( ) ) service = build ( 'bigquery' , 'v2' , http = http , discoveryServiceUrl = service_url , cache_discovery = False ) return service | Construct an authorized BigQuery service object . |
240,340 | def _submit_query_job ( self , query_data ) : logger . debug ( 'Submitting query job: %s' % query_data ) job_collection = self . bigquery . jobs ( ) try : query_reply = job_collection . query ( projectId = self . project_id , body = query_data ) . execute ( num_retries = self . num_retries ) except HttpError as e : if ... | Submit a query job to BigQuery . |
240,341 | def _insert_job ( self , body_object ) : logger . debug ( 'Submitting job: %s' % body_object ) job_collection = self . bigquery . jobs ( ) return job_collection . insert ( projectId = self . project_id , body = body_object ) . execute ( num_retries = self . num_retries ) | Submit a job to BigQuery |
240,342 | def query ( self , query , max_results = None , timeout = 0 , dry_run = False , use_legacy_sql = None , external_udf_uris = None ) : logger . debug ( 'Executing query: %s' % query ) query_data = { 'query' : query , 'timeoutMs' : timeout * 1000 , 'dryRun' : dry_run , 'maxResults' : max_results } if use_legacy_sql is not... | Submit a query to BigQuery . |
240,343 | def get_query_schema ( self , job_id ) : query_reply = self . get_query_results ( job_id , offset = 0 , limit = 0 ) if not query_reply [ 'jobComplete' ] : logger . warning ( 'BigQuery job %s not complete' % job_id ) raise UnfinishedQueryException ( ) return query_reply [ 'schema' ] [ 'fields' ] | Retrieve the schema of a query by job id . |
240,344 | def get_table_schema ( self , dataset , table , project_id = None ) : project_id = self . _get_project_id ( project_id ) try : result = self . bigquery . tables ( ) . get ( projectId = project_id , tableId = table , datasetId = dataset ) . execute ( num_retries = self . num_retries ) except HttpError as e : if int ( e ... | Return the table schema . |
240,345 | def check_job ( self , job_id ) : query_reply = self . get_query_results ( job_id , offset = 0 , limit = 0 ) return ( query_reply . get ( 'jobComplete' , False ) , int ( query_reply . get ( 'totalRows' , 0 ) ) ) | Return the state and number of results of a query by job id . |
240,346 | def get_query_rows ( self , job_id , offset = None , limit = None , timeout = 0 ) : query_reply = self . get_query_results ( job_id , offset = offset , limit = limit , timeout = timeout ) if not query_reply [ 'jobComplete' ] : logger . warning ( 'BigQuery job %s not complete' % job_id ) raise UnfinishedQueryException (... | Retrieve a list of rows from a query table by job id . This method will append results from multiple pages together . If you want to manually page through results you can use get_query_results method directly . |
240,347 | def check_dataset ( self , dataset_id , project_id = None ) : dataset = self . get_dataset ( dataset_id , project_id ) return bool ( dataset ) | Check to see if a dataset exists . |
240,348 | def get_dataset ( self , dataset_id , project_id = None ) : project_id = self . _get_project_id ( project_id ) try : dataset = self . bigquery . datasets ( ) . get ( projectId = project_id , datasetId = dataset_id ) . execute ( num_retries = self . num_retries ) except HttpError : dataset = { } return dataset | Retrieve a dataset if it exists otherwise return an empty dict . |
240,349 | def get_table ( self , dataset , table , project_id = None ) : project_id = self . _get_project_id ( project_id ) try : table = self . bigquery . tables ( ) . get ( projectId = project_id , datasetId = dataset , tableId = table ) . execute ( num_retries = self . num_retries ) except HttpError : table = { } return table | Retrieve a table if it exists otherwise return an empty dict . |
240,350 | def create_table ( self , dataset , table , schema , expiration_time = None , time_partitioning = False , project_id = None ) : project_id = self . _get_project_id ( project_id ) body = { 'schema' : { 'fields' : schema } , 'tableReference' : { 'tableId' : table , 'projectId' : project_id , 'datasetId' : dataset } } if ... | Create a new table in the dataset . |
240,351 | def patch_table ( self , dataset , table , schema , project_id = None ) : project_id = self . _get_project_id ( project_id ) body = { 'schema' : { 'fields' : schema } , 'tableReference' : { 'tableId' : table , 'projectId' : project_id , 'datasetId' : dataset } } try : result = self . bigquery . tables ( ) . patch ( pro... | Patch an existing table in the dataset . |
240,352 | def create_view ( self , dataset , view , query , use_legacy_sql = None , project_id = None ) : project_id = self . _get_project_id ( project_id ) body = { 'tableReference' : { 'tableId' : view , 'projectId' : project_id , 'datasetId' : dataset } , 'view' : { 'query' : query } } if use_legacy_sql is not None : body [ '... | Create a new view in the dataset . |
240,353 | def delete_table ( self , dataset , table , project_id = None ) : project_id = self . _get_project_id ( project_id ) try : response = self . bigquery . tables ( ) . delete ( projectId = project_id , datasetId = dataset , tableId = table ) . execute ( num_retries = self . num_retries ) if self . swallow_results : return... | Delete a table from the dataset . |
240,354 | def get_tables ( self , dataset_id , app_id , start_time , end_time , project_id = None ) : if isinstance ( start_time , datetime ) : start_time = calendar . timegm ( start_time . utctimetuple ( ) ) if isinstance ( end_time , datetime ) : end_time = calendar . timegm ( end_time . utctimetuple ( ) ) every_table = self .... | Retrieve a list of tables that are related to the given app id and are inside the range of start and end times . |
240,355 | def wait_for_job ( self , job , interval = 5 , timeout = 60 ) : complete = False job_id = str ( job if isinstance ( job , ( six . binary_type , six . text_type , int ) ) else job [ 'jobReference' ] [ 'jobId' ] ) job_resource = None start_time = time ( ) elapsed_time = 0 while not ( complete or elapsed_time > timeout ) ... | Waits until the job indicated by job_resource is done or has failed |
240,356 | def push_rows ( self , dataset , table , rows , insert_id_key = None , skip_invalid_rows = None , ignore_unknown_values = None , template_suffix = None , project_id = None ) : project_id = self . _get_project_id ( project_id ) table_data = self . bigquery . tabledata ( ) rows_data = [ ] for row in rows : each_row = { }... | Upload rows to BigQuery table . |
240,357 | def get_all_tables ( self , dataset_id , project_id = None ) : tables_data = self . _get_all_tables_for_dataset ( dataset_id , project_id ) tables = [ ] for table in tables_data . get ( 'tables' , [ ] ) : table_name = table . get ( 'tableReference' , { } ) . get ( 'tableId' ) if table_name : tables . append ( table_nam... | Retrieve a list of tables for the dataset . |
240,358 | def _get_all_tables_for_dataset ( self , dataset_id , project_id = None ) : project_id = self . _get_project_id ( project_id ) result = self . bigquery . tables ( ) . list ( projectId = project_id , datasetId = dataset_id ) . execute ( num_retries = self . num_retries ) page_token = result . get ( 'nextPageToken' ) whi... | Retrieve a list of all tables for the dataset . |
240,359 | def _parse_table_list_response ( self , list_response ) : tables = defaultdict ( dict ) for table in list_response . get ( 'tables' , [ ] ) : table_ref = table . get ( 'tableReference' ) if not table_ref : continue table_id = table_ref . get ( 'tableId' , '' ) year_month , app_id = self . _parse_table_name ( table_id )... | Parse the response received from calling list on tables . |
240,360 | def _parse_table_name ( self , table_id ) : attributes = table_id . split ( '_' ) year_month = "-" . join ( attributes [ : 2 ] ) app_id = "-" . join ( attributes [ 2 : ] ) if year_month . count ( "-" ) == 1 and all ( [ num . isdigit ( ) for num in year_month . split ( '-' ) ] ) : return year_month , app_id attributes =... | Parse a table name in the form of appid_YYYY_MM or YYYY_MM_appid and return a tuple consisting of YYYY - MM and the app id . |
240,361 | def _filter_tables_by_time ( self , tables , start_time , end_time ) : return [ table_name for ( table_name , unix_seconds ) in tables . items ( ) if self . _in_range ( start_time , end_time , unix_seconds ) ] | Filter a table dictionary and return table names based on the range of start and end times in unix seconds . |
240,362 | def _in_range ( self , start_time , end_time , time ) : ONE_MONTH = 2764800 return start_time <= time <= end_time or time <= start_time <= time + ONE_MONTH or time <= end_time <= time + ONE_MONTH | Indicate if the given time falls inside of the given range . |
240,363 | def _transform_row ( self , row , schema ) : log = { } for index , col_dict in enumerate ( schema ) : col_name = col_dict [ 'name' ] row_value = row [ 'f' ] [ index ] [ 'v' ] if row_value is None : log [ col_name ] = None continue if col_dict [ 'type' ] == 'RECORD' : row_value = self . _recurse_on_row ( col_dict , row_... | Apply the given schema to the given BigQuery data row . |
240,364 | def _recurse_on_row ( self , col_dict , nested_value ) : row_value = None if col_dict [ 'mode' ] == 'REPEATED' and isinstance ( nested_value , list ) : row_value = [ self . _transform_row ( record [ 'v' ] , col_dict [ 'fields' ] ) for record in nested_value ] else : row_value = self . _transform_row ( nested_value , co... | Apply the schema specified by the given dict to the nested value by recursing on it . |
240,365 | def _generate_hex_for_uris ( self , uris ) : return sha256 ( ( ":" . join ( uris ) + str ( time ( ) ) ) . encode ( ) ) . hexdigest ( ) | Given uris generate and return hex version of it |
240,366 | def create_dataset ( self , dataset_id , friendly_name = None , description = None , access = None , location = None , project_id = None ) : project_id = self . _get_project_id ( project_id ) try : datasets = self . bigquery . datasets ( ) dataset_data = self . dataset_resource ( dataset_id , project_id = project_id , ... | Create a new BigQuery dataset . |
240,367 | def delete_dataset ( self , dataset_id , delete_contents = False , project_id = None ) : project_id = self . _get_project_id ( project_id ) try : datasets = self . bigquery . datasets ( ) request = datasets . delete ( projectId = project_id , datasetId = dataset_id , deleteContents = delete_contents ) response = reques... | Delete a BigQuery dataset . |
240,368 | def update_dataset ( self , dataset_id , friendly_name = None , description = None , access = None , project_id = None ) : project_id = self . _get_project_id ( project_id ) try : datasets = self . bigquery . datasets ( ) body = self . dataset_resource ( dataset_id , friendly_name = friendly_name , description = descri... | Updates information in an existing dataset . The update method replaces the entire dataset resource whereas the patch method only replaces fields that are provided in the submitted dataset resource . |
240,369 | def schema_from_record ( record , timestamp_parser = default_timestamp_parser ) : return [ describe_field ( k , v , timestamp_parser = timestamp_parser ) for k , v in list ( record . items ( ) ) ] | Generate a BigQuery schema given an example of a record that is to be inserted into BigQuery . |
240,370 | def describe_field ( k , v , timestamp_parser = default_timestamp_parser ) : def bq_schema_field ( name , bq_type , mode ) : return { "name" : name , "type" : bq_type , "mode" : mode } if isinstance ( v , list ) : if len ( v ) == 0 : raise Exception ( "Can't describe schema because of empty list {0}:[]" . format ( k ) ... | Given a key representing a column name and value representing the value stored in the column return a representation of the BigQuery schema element describing that field . Raise errors if invalid value types are provided . |
240,371 | def render_query ( dataset , tables , select = None , conditions = None , groupings = None , having = None , order_by = None , limit = None ) : if None in ( dataset , tables ) : return None query = "%s %s %s %s %s %s %s" % ( _render_select ( select ) , _render_sources ( dataset , tables ) , _render_conditions ( conditi... | Render a query that will run over the given tables using the specified parameters . |
240,372 | def _render_select ( selections ) : if not selections : return 'SELECT *' rendered_selections = [ ] for name , options in selections . items ( ) : if not isinstance ( options , list ) : options = [ options ] original_name = name for options_dict in options : name = original_name alias = options_dict . get ( 'alias' ) a... | Render the selection part of a query . |
240,373 | def _format_select ( formatter , name ) : for caster in formatter . split ( '-' ) : if caster == 'SEC_TO_MICRO' : name = "%s*1000000" % name elif ':' in caster : caster , args = caster . split ( ':' ) name = "%s(%s,%s)" % ( caster , name , args ) else : name = "%s(%s)" % ( caster , name ) return name | Modify the query selector by applying any formatters to it . |
240,374 | def _render_sources ( dataset , tables ) : if isinstance ( tables , dict ) : if tables . get ( 'date_range' , False ) : try : dataset_table = '.' . join ( [ dataset , tables [ 'table' ] ] ) return "FROM (TABLE_DATE_RANGE([{}], TIMESTAMP('{}')," " TIMESTAMP('{}'))) " . format ( dataset_table , tables [ 'from_date' ] , t... | Render the source part of a query . |
240,375 | def _render_conditions ( conditions ) : if not conditions : return "" rendered_conditions = [ ] for condition in conditions : field = condition . get ( 'field' ) field_type = condition . get ( 'type' ) comparators = condition . get ( 'comparators' ) if None in ( field , field_type , comparators ) or not comparators : l... | Render the conditions part of a query . |
240,376 | def _render_condition ( field , field_type , comparators ) : field_type = field_type . upper ( ) negated_conditions , normal_conditions = [ ] , [ ] for comparator in comparators : condition = comparator . get ( "condition" ) . upper ( ) negated = "NOT " if comparator . get ( "negate" ) else "" value = comparator . get ... | Render a single query condition . |
240,377 | def _render_condition_value ( value , field_type ) : if field_type == "BOOLEAN" : value = 1 if value else 0 elif field_type in ( "STRING" , "INTEGER" , "FLOAT" ) : value = "'%s'" % ( value ) elif field_type in ( "TIMESTAMP" ) : value = "'%s'" % ( str ( value ) ) return "%s(%s)" % ( field_type , value ) | Render a query condition value . |
240,378 | def _render_having ( having_conditions ) : if not having_conditions : return "" rendered_conditions = [ ] for condition in having_conditions : field = condition . get ( 'field' ) field_type = condition . get ( 'type' ) comparators = condition . get ( 'comparators' ) if None in ( field , field_type , comparators ) or no... | Render the having part of a query . |
240,379 | def init_app ( self , app ) : self . client_id = app . config . get ( "MQTT_CLIENT_ID" , "" ) if isinstance ( self . client_id , unicode ) : self . client . _client_id = self . client_id . encode ( 'utf-8' ) else : self . client . _client_id = self . client_id self . client . _transport = app . config . get ( "MQTT_TRA... | Init the Flask - MQTT addon . |
240,380 | def subscribe ( self , topic , qos = 0 ) : result , mid = self . client . subscribe ( topic = topic , qos = qos ) if result == MQTT_ERR_SUCCESS : self . topics [ topic ] = TopicQos ( topic = topic , qos = qos ) logger . debug ( 'Subscribed to topic: {0}, qos: {1}' . format ( topic , qos ) ) else : logger . error ( 'Err... | Subscribe to a certain topic . |
240,381 | def unsubscribe ( self , topic ) : if topic in self . topics : result , mid = self . client . unsubscribe ( topic ) if result == MQTT_ERR_SUCCESS : self . topics . pop ( topic ) logger . debug ( 'Unsubscribed from topic: {0}' . format ( topic ) ) else : logger . debug ( 'Error {0} unsubscribing from topic: {1}' . forma... | Unsubscribe from a single topic . |
240,382 | def unsubscribe_all ( self ) : topics = list ( self . topics . keys ( ) ) for topic in topics : self . unsubscribe ( topic ) | Unsubscribe from all topics . |
240,383 | def publish ( self , topic , payload = None , qos = 0 , retain = False ) : if not self . connected : self . client . reconnect ( ) result , mid = self . client . publish ( topic , payload , qos , retain ) if result == MQTT_ERR_SUCCESS : logger . debug ( 'Published topic {0}: {1}' . format ( topic , payload ) ) else : l... | Send a message to the broker . |
240,384 | def on_subscribe ( self ) : def decorator ( handler ) : self . client . on_subscribe = handler return handler return decorator | Decorate a callback function to handle subscritions . |
240,385 | def on_unsubscribe ( self ) : def decorator ( handler ) : self . client . on_unsubscribe = handler return handler return decorator | Decorate a callback funtion to handle unsubscribtions . |
240,386 | def on_log ( self ) : def decorator ( handler ) : self . client . on_log = handler return handler return decorator | Decorate a callback function to handle MQTT logging . |
240,387 | def list ( ) : s3 = boto3 . resource ( 's3' ) return [ b . name for b in s3 . buckets . all ( ) ] | Lists buckets by name . |
240,388 | def delete ( self , key = None ) : if key is None : for key in self . all ( ) : key . delete ( ) return self . _boto_bucket . delete ( ) k = self . key ( key ) return k . delete ( ) | Deletes the given key or the whole bucket . |
240,389 | def rename ( self , new_name ) : self . bucket . set ( new_name , self . get ( ) , self . meta ) self . delete ( ) self . name = new_name | Renames the key to a given new name . |
240,390 | def is_public ( self ) : for grant in self . _boto_object . Acl ( ) . grants : if 'AllUsers' in grant [ 'Grantee' ] . get ( 'URI' , '' ) : if grant [ 'Permission' ] == 'READ' : return True return False | Returns True if the public - read ACL is set for the Key . |
240,391 | def url ( self ) : if self . is_public : return '{0}/{1}/{2}' . format ( self . bucket . _boto_s3 . meta . client . meta . endpoint_url , self . bucket . name , self . name ) else : raise ValueError ( '{0!r} does not have the public-read ACL set. ' 'Use the make_public() method to allow for ' 'public URL sharing.' . fo... | Returns the public URL for the given key . |
240,392 | def temp_url ( self , duration = 120 ) : return self . bucket . _boto_s3 . meta . client . generate_presigned_url ( 'get_object' , Params = { 'Bucket' : self . bucket . name , 'Key' : self . name } , ExpiresIn = duration ) | Returns a temporary URL for the given key . |
240,393 | def eprint ( * args , ** kwargs ) : end = kwargs . get ( "end" , "\n" ) sep = kwargs . get ( "sep" , " " ) ( filename , lineno ) = inspect . stack ( ) [ 1 ] [ 1 : 3 ] print ( "{}:{}: " . format ( filename , lineno ) , end = "" ) print ( * args , end = end , file = sys . stderr , sep = sep ) | Print an error message to standard error prefixing it with file name and line number from which method was called . |
240,394 | def formatException ( type , value , tb ) : packages = tuple ( join ( abspath ( p ) , "" ) for p in sys . path [ 1 : ] ) lines = [ ] for line in format_exception ( type , value , tb ) : matches = re . search ( r"^ File \"([^\"]+)\", line \d+, in .+" , line ) if matches and matches . group ( 1 ) . startswith ( packages... | Format traceback darkening entries from global site - packages directories and user - specific site - packages directory . |
240,395 | def get_char ( prompt = None ) : while True : s = get_string ( prompt ) if s is None : return None if len ( s ) == 1 : return s [ 0 ] if prompt is None : print ( "Retry: " , end = "" ) | Read a line of text from standard input and return the equivalent char ; if text is not a single char user is prompted to retry . If line can t be read return None . |
240,396 | def get_float ( prompt = None ) : while True : s = get_string ( prompt ) if s is None : return None if len ( s ) > 0 and re . search ( r"^[+-]?\d*(?:\.\d*)?$" , s ) : try : return float ( s ) except ValueError : pass if prompt is None : print ( "Retry: " , end = "" ) | Read a line of text from standard input and return the equivalent float as precisely as possible ; if text does not represent a double user is prompted to retry . If line can t be read return None . |
240,397 | def get_int ( prompt = None ) : while True : s = get_string ( prompt ) if s is None : return None if re . search ( r"^[+-]?\d+$" , s ) : try : i = int ( s , 10 ) if type ( i ) is int : return i except ValueError : pass if prompt is None : print ( "Retry: " , end = "" ) | Read a line of text from standard input and return the equivalent int ; if text does not represent an int user is prompted to retry . If line can t be read return None . |
240,398 | def _connect ( dbapi_connection , connection_record ) : if type ( dbapi_connection ) is sqlite3 . Connection : cursor = dbapi_connection . cursor ( ) cursor . execute ( "PRAGMA foreign_keys=ON" ) cursor . close ( ) | Enables foreign key support . |
240,399 | def _parse ( self , e ) : matches = re . search ( r"^\(_mysql_exceptions\.OperationalError\) \(\d+, \"(.+)\"\)$" , str ( e ) ) if matches : return matches . group ( 1 ) matches = re . search ( r"^\(psycopg2\.OperationalError\) (.+)$" , str ( e ) ) if matches : return matches . group ( 1 ) matches = re . search ( r"^\(s... | Parses an exception returns its message . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.