idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
240,700 | def _glslify ( r ) : if isinstance ( r , string_types ) : return r else : assert 2 <= len ( r ) <= 4 return 'vec{}({})' . format ( len ( r ) , ', ' . join ( map ( str , r ) ) ) | Transform a string or a n - tuple to a valid GLSL expression . |
240,701 | def get ( self , class_name ) : for transform in self . cpu_transforms + self . gpu_transforms : if transform . __class__ . __name__ == class_name : return transform | Get a transform in the chain from its name . |
240,702 | def remove ( self , name ) : cpu_transforms = self . _remove_transform ( self . cpu_transforms , name ) gpu_transforms = self . _remove_transform ( self . gpu_transforms , name ) return ( TransformChain ( ) . add_on_cpu ( cpu_transforms ) . add_on_gpu ( gpu_transforms ) ) | Remove a transform in the chain . |
240,703 | def apply ( self , arr ) : for t in self . cpu_transforms : arr = t . apply ( arr ) return arr | Apply all CPU transforms on an array . |
240,704 | def inverse ( self ) : transforms = self . cpu_transforms + self . gpu_transforms inv_transforms = [ transform . inverse ( ) for transform in transforms [ : : - 1 ] ] return TransformChain ( ) . add_on_cpu ( inv_transforms ) | Return the inverse chain of transforms . |
240,705 | def _create_emitter ( self , event ) : if not hasattr ( self , event ) : setattr ( self , event , lambda * args , ** kwargs : self . emit ( event , * args , ** kwargs ) ) | Create a method that emits an event of the same name . |
240,706 | def connect ( self , func = None , event = None , set_method = False ) : if func is None : return partial ( self . connect , set_method = set_method ) if event is None : event = self . _get_on_name ( func ) self . _callbacks [ event ] . append ( func ) if set_method : self . _create_emitter ( event ) return func | Register a callback function to a given event . |
240,707 | def unconnect ( self , * funcs ) : for func in funcs : for callbacks in self . _callbacks . values ( ) : if func in callbacks : callbacks . remove ( func ) | Unconnect specified callback functions . |
240,708 | def emit ( self , event , * args , ** kwargs ) : callbacks = self . _callbacks . get ( event , [ ] ) single = kwargs . pop ( 'single' , None ) if single and callbacks : return callbacks [ - 1 ] ( * args , ** kwargs ) res = [ ] for callback in callbacks : res . append ( callback ( * args , ** kwargs ) ) return res | Call all callback functions registered with an event . |
240,709 | def set_progress_message ( self , message , line_break = False ) : end = '\r' if not line_break else None @ self . connect def on_progress ( value , value_max , ** kwargs ) : kwargs [ 'end' ] = None if value == value_max else end _default_on_progress ( message , value , value_max , ** kwargs ) | Set a progress message . |
240,710 | def set_complete_message ( self , message ) : @ self . connect def on_complete ( ** kwargs ) : _default_on_complete ( message , ** kwargs ) | Set a complete message . |
240,711 | def get_plugin ( name ) : for plugin in IPluginRegistry . plugins : if name in plugin . __name__ : return plugin raise ValueError ( "The plugin %s cannot be found." % name ) | Get a plugin class from its name . |
240,712 | def discover_plugins ( dirs ) : for path in _iter_plugin_files ( dirs ) : filename = op . basename ( path ) subdir = op . dirname ( path ) modname , ext = op . splitext ( filename ) file , path , descr = imp . find_module ( modname , [ subdir ] ) if file : try : mod = imp . load_module ( modname , file , path , descr )... | Discover the plugin classes contained in Python files . |
240,713 | def add_view ( self , view , name = None , position = None , closable = False , floatable = True , floating = None ) : view . view_index = self . _get_view_index ( view ) view . name = name or view . __class__ . __name__ + str ( view . view_index ) widget = _try_get_vispy_canvas ( view ) widget = _try_get_matplotlib_ca... | Add a widget to the main window . |
240,714 | def list_views ( self , name = '' , is_visible = True ) : children = self . findChildren ( QWidget ) return [ child . view for child in children if isinstance ( child , QDockWidget ) and child . view . name . startswith ( name ) and ( child . isVisible ( ) if is_visible else True ) and child . width ( ) >= 10 and child... | List all views which name start with a given string . |
240,715 | def get_view ( self , name , is_visible = True ) : views = self . list_views ( name , is_visible = is_visible ) return views [ 0 ] if views else None | Return a view from its name . |
240,716 | def view_count ( self ) : views = self . list_views ( ) counts = defaultdict ( lambda : 0 ) for view in views : counts [ view . name ] += 1 return dict ( counts ) | Return the number of opened views . |
240,717 | def get_menu ( self , name ) : if name not in self . _menus : self . _menus [ name ] = self . menuBar ( ) . addMenu ( name ) return self . _menus [ name ] | Return or create a menu . |
240,718 | def restore_geometry_state ( self , gs ) : if not gs : return if gs . get ( 'geometry' , None ) : self . restoreGeometry ( ( gs [ 'geometry' ] ) ) if gs . get ( 'state' , None ) : self . restoreState ( ( gs [ 'state' ] ) ) | Restore the position of the main window and the docks . |
240,719 | def update_view_state ( self , view , state ) : if view . name not in self : self [ view . name ] = Bunch ( ) self [ view . name ] . update ( state ) | Update the state of a view . |
240,720 | def load ( self ) : if not op . exists ( self . path ) : logger . debug ( "The GUI state file `%s` doesn't exist." , self . path ) return assert op . exists ( self . path ) logger . debug ( "Load the GUI state from `%s`." , self . path ) self . update ( _bunchify ( _load_json ( self . path ) ) ) | Load the state from the JSON file in the config dir . |
240,721 | def save ( self ) : logger . debug ( "Save the GUI state to `%s`." , self . path ) _save_json ( self . path , { k : v for k , v in self . items ( ) if k not in ( 'config_dir' , 'name' ) } ) | Save the state to the JSON file in the config dir . |
240,722 | def cache ( self , f ) : if self . _memory is None : logger . debug ( "Joblib is not installed: skipping cacheing." ) return f assert f if 'self' in inspect . getargspec ( f ) . args : ignore = [ 'self' ] else : ignore = None disk_cached = self . _memory . cache ( f , ignore = ignore ) return disk_cached | Cache a function using the context s cache directory . |
240,723 | def memcache ( self , f ) : name = _fullname ( f ) cache = self . load_memcache ( name ) @ wraps ( f ) def memcached ( * args ) : h = args out = cache . get ( h , None ) if out is None : out = f ( * args ) cache [ h ] = out return out return memcached | Cache a function in memory using an internal dictionary . |
240,724 | def save ( self , name , data , location = 'local' , kind = 'json' ) : file_ext = '.json' if kind == 'json' else '.pkl' path = self . _get_path ( name , location , file_ext = file_ext ) _ensure_dir_exists ( op . dirname ( path ) ) logger . debug ( "Save data to `%s`." , path ) if kind == 'json' : _save_json ( path , da... | Save a dictionary in a JSON file within the cache directory . |
240,725 | def load ( self , name , location = 'local' ) : path = self . _get_path ( name , location , file_ext = '.json' ) if op . exists ( path ) : return _load_json ( path ) path = self . _get_path ( name , location , file_ext = '.pkl' ) if op . exists ( path ) : return _load_pickle ( path ) logger . debug ( "The file `%s` doe... | Load saved data from the cache directory . |
240,726 | def _ensure_dir_exists ( path ) : if not op . exists ( path ) : os . makedirs ( path ) assert op . exists ( path ) and op . isdir ( path ) | Ensure a directory exists . |
240,727 | def load_config ( path = None ) : if not path or not op . exists ( path ) : return Config ( ) path = op . realpath ( path ) dirpath , filename = op . split ( path ) file_ext = op . splitext ( path ) [ 1 ] logger . debug ( "Load config file `%s`." , path ) if file_ext == '.py' : config = PyFileConfigLoader ( filename , ... | Load a Python or JSON config file . |
240,728 | def save_config ( path , config ) : import json config [ 'version' ] = 1 with open ( path , 'w' ) as f : json . dump ( config , f ) | Save a config object to a JSON file . |
240,729 | def _edges_to_adjacency_list ( edges ) : adj = { } for i , j in edges : if i in adj : ni = adj [ i ] else : ni = adj [ i ] = set ( ) if j in adj : nj = adj [ j ] else : nj = adj [ j ] = set ( ) ni . add ( j ) nj . add ( i ) return adj | Convert a list of edges into an adjacency list . |
240,730 | def _probe_positions ( probe , group ) : positions = probe [ 'channel_groups' ] [ group ] [ 'geometry' ] channels = _probe_channels ( probe , group ) return np . array ( [ positions [ channel ] for channel in channels ] ) | Return the positions of a probe channel group . |
240,731 | def _probe_adjacency_list ( probe ) : cgs = probe [ 'channel_groups' ] . values ( ) graphs = [ cg [ 'graph' ] for cg in cgs ] edges = list ( itertools . chain ( * graphs ) ) adjacency_list = _edges_to_adjacency_list ( edges ) return adjacency_list | Return an adjacency list of a whole probe . |
240,732 | def load_probe ( name ) : if op . exists ( name ) : path = name else : curdir = op . realpath ( op . dirname ( __file__ ) ) path = op . join ( curdir , 'probes/{}.prb' . format ( name ) ) if not op . exists ( path ) : raise IOError ( "The probe `{}` cannot be found." . format ( name ) ) return MEA ( probe = _read_pytho... | Load one of the built - in probes . |
240,733 | def list_probes ( ) : curdir = op . realpath ( op . dirname ( __file__ ) ) return [ op . splitext ( fn ) [ 0 ] for fn in os . listdir ( op . join ( curdir , 'probes' ) ) if fn . endswith ( '.prb' ) ] | Return the list of built - in probes . |
240,734 | def linear_positions ( n_channels ) : return np . c_ [ np . zeros ( n_channels ) , np . linspace ( 0. , 1. , n_channels ) ] | Linear channel positions along the vertical axis . |
240,735 | def staggered_positions ( n_channels ) : i = np . arange ( n_channels - 1 ) x , y = ( - 1 ) ** i * ( 5 + i ) , 10 * ( i + 1 ) pos = np . flipud ( np . r_ [ np . zeros ( ( 1 , 2 ) ) , np . c_ [ x , y ] ] ) return pos | Generate channel positions for a staggered probe . |
240,736 | def change_channel_group ( self , group ) : assert self . _probe is not None self . _channels = _probe_channels ( self . _probe , group ) self . _positions = _probe_positions ( self . _probe , group ) | Change the current channel group . |
240,737 | def build ( self ) : if self . is_built ( ) : return with _wait_signal ( self . loadFinished , 20 ) : self . rebuild ( ) self . _built = True | Build the full HTML source . |
240,738 | def add_to_js ( self , name , var ) : frame = self . page ( ) . mainFrame ( ) frame . addToJavaScriptWindowObject ( name , var ) | Add an object to Javascript . |
240,739 | def eval_js ( self , expr ) : if not self . is_built ( ) : self . _pending_js_eval . append ( expr ) return logger . log ( 5 , "Evaluate Javascript: `%s`." , expr ) out = self . page ( ) . mainFrame ( ) . evaluateJavaScript ( expr ) return _to_py ( out ) | Evaluate a Javascript expression . |
240,740 | def add_column ( self , func , name = None , show = True ) : assert func name = name or func . __name__ if name == '<lambda>' : raise ValueError ( "Please provide a valid name for " + name ) d = { 'func' : func , 'show' : show , } self . _columns [ name ] = d data = _create_json_dict ( cols = self . column_names , ) se... | Add a column function which takes an id as argument and returns a value . |
240,741 | def column_names ( self ) : return [ name for ( name , d ) in self . _columns . items ( ) if d . get ( 'show' , True ) ] | List of column names . |
240,742 | def _get_row ( self , id ) : return { name : d [ 'func' ] ( id ) for ( name , d ) in self . _columns . items ( ) } | Create a row dictionary for a given object id . |
240,743 | def set_rows ( self , ids ) : assert all ( isinstance ( i , int ) for i in ids ) sort_col , sort_dir = self . current_sort default_sort_col , default_sort_dir = self . default_sort sort_col = sort_col or default_sort_col sort_dir = sort_dir or default_sort_dir or 'desc' logger . log ( 5 , "Set %d rows in the table." , ... | Set the rows of the table . |
240,744 | def sort_by ( self , name , sort_dir = 'asc' ) : logger . log ( 5 , "Sort by `%s` %s." , name , sort_dir ) self . eval_js ( 'table.sortBy("{}", "{}");' . format ( name , sort_dir ) ) | Sort by a given variable . |
240,745 | def select ( self , ids , do_emit = True , ** kwargs ) : self . eval_js ( 'table.select({}, false);' . format ( dumps ( ids ) ) ) if do_emit : self . emit ( 'select' , ids , ** kwargs ) | Select some rows in the table . |
240,746 | def set_interval ( self , interval = None , change_status = True , force_update = False ) : if interval is None : interval = self . _interval interval = self . _restrict_interval ( interval ) if not force_update and interval == self . _interval : return self . _interval = interval start , end = interval self . clear ( ... | Display the traces and spikes in a given interval . |
240,747 | def half_duration ( self ) : if self . _interval is not None : a , b = self . _interval return ( b - a ) * .5 else : return self . interval_duration * .5 | Half of the duration of the current interval . |
240,748 | def go_right ( self ) : start , end = self . _interval delay = ( end - start ) * .2 self . shift ( delay ) | Go to right . |
240,749 | def go_left ( self ) : start , end = self . _interval delay = ( end - start ) * .2 self . shift ( - delay ) | Go to left . |
240,750 | def widen ( self ) : t , h = self . time , self . half_duration h *= self . scaling_coeff_x self . set_interval ( ( t - h , t + h ) ) | Increase the interval size . |
240,751 | def narrow ( self ) : t , h = self . time , self . half_duration h /= self . scaling_coeff_x self . set_interval ( ( t - h , t + h ) ) | Decrease the interval size . |
240,752 | def auth_from_hass_config ( path = None , ** kwargs ) : if path is None : path = config . find_hass_config ( ) return Auth ( os . path . join ( path , ".storage/auth" ) , ** kwargs ) | Initialize auth from HASS config . |
240,753 | def user_name ( self , user_id ) : user = self . users . get ( user_id ) if user is None : return "Unknown user ({})" . format ( user_id ) return user [ "name" ] | Return name for user . |
240,754 | def default_hass_config_dir ( ) : data_dir = os . getenv ( "APPDATA" ) if os . name == "nt" else os . path . expanduser ( "~" ) return os . path . join ( data_dir , ".homeassistant" ) | Put together the default configuration directory based on the OS . |
240,755 | def find_hass_config ( ) : if "HASSIO_TOKEN" in os . environ : return "/config" config_dir = default_hass_config_dir ( ) if os . path . isdir ( config_dir ) : return config_dir raise ValueError ( "Unable to automatically find the location of Home Assistant " "config. Please pass it in." ) | Try to find HASS config . |
240,756 | def _secret_yaml ( loader , node ) : fname = os . path . join ( os . path . dirname ( loader . name ) , "secrets.yaml" ) try : with open ( fname , encoding = "utf-8" ) as secret_file : secrets = YAML ( typ = "safe" ) . load ( secret_file ) except FileNotFoundError : raise ValueError ( "Secrets file {} not found" . form... | Load secrets and embed it into the configuration YAML . |
240,757 | def _include_yaml ( loader , node ) : return load_yaml ( os . path . join ( os . path . dirname ( loader . name ) , node . value ) ) | Load another YAML file and embeds it using the !include tag . |
240,758 | def _stub_tag ( constructor , node ) : seen = getattr ( constructor , "_stub_seen" , None ) if seen is None : seen = constructor . _stub_seen = set ( ) if node . tag not in seen : print ( "YAML tag {} is not supported" . format ( node . tag ) ) seen . add ( node . tag ) return { } | Stub a constructor with a dictionary . |
240,759 | def load_yaml ( fname ) : yaml = YAML ( typ = "safe" ) yaml . allow_duplicate_keys = True HassSafeConstructor . name = fname yaml . Constructor = HassSafeConstructor with open ( fname , encoding = "utf-8" ) as conf_file : return yaml . load ( conf_file ) or { } | Load a YAML file . |
240,760 | def db_url_from_hass_config ( path ) : config = load_hass_config ( path ) default_path = os . path . join ( path , "home-assistant_v2.db" ) default_url = "sqlite:///{}" . format ( default_path ) recorder = config . get ( "recorder" ) if recorder : db_url = recorder . get ( "db_url" ) if db_url is not None : return db_u... | Find the recorder database url from a HASS config dir . |
240,761 | def localize ( dt ) : if dt . tzinfo is UTC : return ( dt + LOCAL_UTC_OFFSET ) . replace ( tzinfo = None ) return dt | Localize a datetime object to local time . |
240,762 | def sqlalch_datetime ( dt ) : if isinstance ( dt , str ) : return datetime . strptime ( dt , "%Y-%m-%d %H:%M:%S.%f" ) . replace ( tzinfo = UTC ) if dt . tzinfo is not None and dt . tzinfo . utcoffset ( dt ) is not None : return dt . astimezone ( UTC ) return dt . replace ( tzinfo = UTC ) | Convert a SQLAlchemy datetime string to a datetime object . |
240,763 | def db_from_hass_config ( path = None , ** kwargs ) : if path is None : path = config . find_hass_config ( ) url = config . db_url_from_hass_config ( path ) return HassDatabase ( url , ** kwargs ) | Initialize a database from HASS config . |
240,764 | def stripped_db_url ( url ) : parsed = urlparse ( url ) if parsed . password is None : return url return parsed . _replace ( netloc = "{}:***@{}" . format ( parsed . username , parsed . hostname ) ) . geturl ( ) | Return a version of the DB url with the password stripped out . |
240,765 | def perform_query ( self , query , ** params ) : try : return self . engine . execute ( query , params ) except : print ( "Error with query: {}" . format ( query ) ) raise | Perform a query where query is a string . |
240,766 | def fetch_entities ( self ) : query = text ( ) response = self . perform_query ( query ) entities = { } domains = set ( ) for [ entity ] in response : domain = entity . split ( "." ) [ 0 ] domains . add ( domain ) entities . setdefault ( domain , [ ] ) . append ( entity ) self . _domains = list ( domains ) self . _enti... | Fetch entities for which we have data . |
240,767 | def fetch_all_data ( self , limit = 50000 ) : query = text ( ) try : print ( "Querying the database, this could take a while" ) response = self . perform_query ( query , limit = limit ) master_df = pd . DataFrame ( response . fetchall ( ) ) print ( "master_df created successfully." ) self . _master_df = master_df . cop... | Fetch data for all entities . |
240,768 | def parse_all_data ( self ) : self . _master_df . columns = [ "domain" , "entity" , "state" , "last_changed" ] self . _master_df [ "numerical" ] = self . _master_df [ "state" ] . apply ( lambda x : functions . isfloat ( x ) ) self . _master_df . set_index ( [ "domain" , "entity" , "numerical" , "last_changed" ] , inpla... | Parses the master df . |
240,769 | def correlations ( self ) : corr_df = self . _sensors_num_df . corr ( ) corr_names = [ ] corrs = [ ] for i in range ( len ( corr_df . index ) ) : for j in range ( len ( corr_df . index ) ) : c_name = corr_df . index [ i ] r_name = corr_df . columns [ j ] corr_names . append ( "%s-%s" % ( c_name , r_name ) ) corrs . app... | Calculate the correlation coefficients . |
240,770 | def plot ( self , entities : List [ str ] ) : ax = self . _sensors_num_df [ entities ] . plot ( figsize = [ 12 , 6 ] ) ax . legend ( loc = "center left" , bbox_to_anchor = ( 1 , 0.5 ) ) ax . set_xlabel ( "Date" ) ax . set_ylabel ( "Reading" ) return | Basic plot of a numerical sensor data . |
240,771 | def plot ( self , entity ) : df = self . _binary_df [ [ entity ] ] resampled = df . resample ( "s" ) . ffill ( ) resampled . columns = [ "value" ] fig , ax = plt . subplots ( 1 , 1 , figsize = ( 16 , 2 ) ) ax . fill_between ( resampled . index , y1 = 0 , y2 = 1 , facecolor = "royalblue" , label = "off" ) ax . fill_betw... | Basic plot of a single binary sensor data . |
240,772 | def is_sf_database ( db , model = None ) : from django . db import connections if db is None : return getattr ( model , '_salesforce_object' , False ) engine = connections [ db ] . settings_dict [ 'ENGINE' ] return engine == 'salesforce.backend' or connections [ db ] . vendor == 'salesforce' | The alias is a Salesforce database . |
240,773 | def allow_migrate ( self , db , app_label , model_name = None , ** hints ) : if model_name : model = apps . get_model ( app_label , model_name ) else : model = hints . get ( 'model' ) if hasattr ( model , '_salesforce_object' ) : if not ( is_sf_database ( db ) or db == self . sf_alias ) : return False else : if is_sf_d... | Don t attempt to sync SF models to non SF databases and vice versa . |
240,774 | def update ( self , ** kwargs ) : assert not self . called self . kw . update ( kwargs ) return self | Customize the lazy field |
240,775 | def create ( self ) : assert not self . called return self . klass ( * self . args , ** self . kw ) | Create a normal field from the lazy field |
240,776 | def get_queryset ( self ) : if router . is_sf_database ( self . db ) : q = models_sql_query . SalesforceQuery ( self . model , where = compiler . SalesforceWhereNode ) return query . SalesforceQuerySet ( self . model , query = q , using = self . db ) return super ( SalesforceManager , self ) . get_queryset ( ) | Returns a QuerySet which access remote SF objects . |
240,777 | def get_attname_column ( self ) : attname = self . get_attname ( ) if self . db_column is not None : column = self . db_column else : if not self . name . islower ( ) : column = self . name else : column = self . name . title ( ) . replace ( '_' , '' ) if self . sf_custom : column = self . sf_namespace + column + '__c'... | Get the database column name automatically in most cases . |
240,778 | def extract_values ( query ) : if isinstance ( query , subqueries . UpdateQuery ) : row = query . values return extract_values_inner ( row , query ) if isinstance ( query , subqueries . InsertQuery ) : ret = [ ] for row in query . objs : ret . append ( extract_values_inner ( row , query ) ) return ret raise NotSupporte... | Extract values from insert or update query . Supports bulk_create |
240,779 | def execute ( self , q , args = ( ) ) : self . rowcount = None response = None if self . query is None : self . execute_select ( q , args ) else : response = self . execute_django ( q , args ) if isinstance ( response , list ) : return if response and response . text : data = response . json ( parse_float = decimal . D... | Send a query to the Salesforce API . |
240,780 | def execute_django ( self , soql , args = ( ) ) : response = None sqltype = soql . split ( None , 1 ) [ 0 ] . upper ( ) if isinstance ( self . query , subqueries . InsertQuery ) : response = self . execute_insert ( self . query ) elif isinstance ( self . query , subqueries . UpdateQuery ) : response = self . execute_up... | Fixed execute for queries coming from Django query compilers |
240,781 | def get_pks_from_query ( self , query ) : where = query . where sql = None if where . connector == 'AND' and not where . negated and len ( where . children ) == 1 : child = where . children [ 0 ] if ( child . lookup_name in ( 'exact' , 'in' ) and child . lhs . target . column == 'Id' and not child . bilateral_transform... | Prepare primary keys for update and delete queries |
240,782 | def versions_request ( self ) : ret = self . handle_api_exceptions ( 'GET' , '' , api_ver = '' ) return [ str_dict ( x ) for x in ret . json ( ) ] | List Available REST API Versions |
240,783 | def fix_international ( text ) : "Fix excaped international characters back to utf-8" class SmartInternational ( str ) : def __new__ ( cls , text ) : return str . __new__ ( cls , text ) def endswith ( self , string ) : return super ( SmartInternational , self ) . endswith ( str ( string ) ) if PY3 : return text out = [... | Fix excaped international characters back to utf - 8 |
240,784 | def get_meta ( self , table_name , constraints = None , column_to_field_name = None , is_view = False , is_partition = None ) : meta = [ " class Meta(models.Model.Meta):" , " db_table = '%s'" % table_name ] if self . connection . vendor == 'salesforce' : for line in self . connection . introspection . get_add... | Return a sequence comprising the lines of code necessary to construct the inner Meta class for the model corresponding to the given database table name . |
240,785 | def relative_path ( path ) : return os . path . join ( os . path . dirname ( __file__ ) , path ) | Return the given path relative to this file . |
240,786 | def get_tagged_version ( ) : with open ( relative_path ( 'salesforce/__init__.py' ) , 'r' ) as fd : version = re . search ( r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]' , fd . read ( ) , re . MULTILINE ) . group ( 1 ) return version | Determine the current version of this package . |
240,787 | def dynamic_start ( self , access_token , instance_url = None , ** kw ) : self . dynamic = { 'access_token' : str ( access_token ) , 'instance_url' : str ( instance_url ) } self . dynamic . update ( kw ) | Set the access token dynamically according to the current user . |
240,788 | def mark_quoted_strings ( sql ) : pm_pattern = re . compile ( r"'[^\\']*(?:\\[\\'][^\\']*)*'" ) bs_pattern = re . compile ( r"\\([\\'])" ) out_pattern = re . compile ( r"^(?:[-!()*+,.:<=>\w\s|%s])*$" ) missing_apostrophe = "invalid character in SOQL or a missing apostrophe" start = 0 out = [ ] params = [ ] for match in... | Mark all quoted strings in the SOQL by |
240,789 | def subst_quoted_strings ( sql , params ) : parts = sql . split ( '@' ) params_dont_match = "number of parameters doesn' match the transformed query" assert len ( parts ) == len ( params ) + 1 , params_dont_match out = [ ] for i , param in enumerate ( params ) : out . append ( parts [ i ] ) out . append ( "'%s'" % para... | Reverse operation to mark_quoted_strings - substitutes |
240,790 | def find_closing_parenthesis ( sql , startpos ) : pattern = re . compile ( r'[()]' ) level = 0 opening = [ ] for match in pattern . finditer ( sql , startpos ) : par = match . group ( ) if par == '(' : if level == 0 : opening = match . start ( ) level += 1 if par == ')' : assert level > 0 , "missing '(' before ')'" lev... | Find the pair of opening and closing parentheses . |
240,791 | def split_subquery ( sql ) : sql , params = mark_quoted_strings ( sql ) sql = simplify_expression ( sql ) _ = params start = 0 out = [ ] subqueries = [ ] pattern = re . compile ( r'\(SELECT\b' , re . I ) match = pattern . search ( sql , start ) while match : out . append ( sql [ start : match . start ( ) + 1 ] + '&' ) ... | Split on subqueries and replace them by & . |
240,792 | def simplify_expression ( txt ) : minimal = re . sub ( r'\s' , ' ' , re . sub ( r'\s(?=\W)' , '' , re . sub ( r'(?<=\W)\s' , '' , txt . strip ( ) ) ) ) return re . sub ( r'\)(?=\w)' , ') ' , re . sub ( r'(,|\b(?:{}))\(' . format ( '|' . join ( RESERVED_WORDS ) ) , '\\1 (' , minimal ) ) | Remove all unecessary whitespace and some very usual space |
240,793 | def _make_flat ( self , row_dict , path , subroots ) : out = { } for k , v in row_dict . items ( ) : klc = k . lower ( ) if ( not ( isinstance ( v , dict ) and 'attributes' in v ) or ( 'done' in v and 'records' in v and 'totalSize' in v ) ) : if klc not in subroots : out [ klc ] = v else : strpath = '.' . join ( path +... | Replace the nested dict objects by a flat dict with keys object . object . name . |
240,794 | def parse_rest_response ( self , records , rowcount , row_type = list ) : if self . is_plain_count : assert list ( records ) == [ ] yield rowcount else : while True : for row_deep in records : assert self . is_aggregation == ( row_deep [ 'attributes' ] [ 'type' ] == 'AggregateResult' ) row_flat = self . _make_flat ( ro... | Parse the REST API response to DB API cursor flat response |
240,795 | def make_dynamic_fields ( pattern_module , dynamic_field_patterns , attrs ) : import re attr_meta = attrs [ 'Meta' ] db_table = getattr ( attr_meta , 'db_table' , None ) if not db_table : raise RuntimeError ( 'The "db_table" must be set in Meta if "dynamic_field_patterns" is used.' ) is_custom_model = getattr ( attr_me... | Add some Salesforce fields from a pattern_module models . py |
240,796 | def prepare_exception ( obj , messages = None , response = None , verbs = None ) : verbs = set ( verbs or [ ] ) known_options = [ 'method+url' ] if messages is None : messages = [ ] if isinstance ( messages , ( text_type , str ) ) : messages = [ messages ] assert isinstance ( messages , list ) assert not verbs . differ... | Prepare excetion params or only an exception message |
240,797 | def warn_sf ( messages , response , verbs = None , klass = SalesforceWarning ) : warnings . warn ( klass ( messages , response , verbs ) , stacklevel = 2 ) | Issue a warning SalesforceWarning with message combined from message and data from SFDC response |
240,798 | def get_from_clause ( self ) : self . query_topology ( ) root_table = self . soql_trans [ self . root_alias ] return [ root_table ] , [ ] | Return the FROM clause converted the SOQL dialect . |
240,799 | def quote_name_unless_alias ( self , name ) : r = self . connection . ops . quote_name ( name ) self . quote_cache [ name ] = r return r | A wrapper around connection . ops . quote_name that doesn t quote aliases for table names . Mostly used during the ORDER BY clause . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.