idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
240,800 | def get_soap_client ( db_alias , client_class = None ) : if not beatbox : raise InterfaceError ( "To use SOAP API, you'll need to install the Beatbox package." ) if client_class is None : client_class = beatbox . PythonClient soap_client = client_class ( ) connection = connections [ db_alias ] cursor = connection . cur... | Create the SOAP client for the current user logged in the db_alias |
240,801 | def signalize_extensions ( ) : warnings . warn ( "DB-API extension cursor.rownumber used" , SalesforceWarning ) warnings . warn ( "DB-API extension connection.<exception> used" , SalesforceWarning ) warnings . warn ( "DB-API extension cursor.connection used" , SalesforceWarning ) warnings . warn ( "DB-API extension cur... | DB API 2 . 0 extension are reported by warnings at run - time . |
240,802 | def arg_to_soql ( arg ) : conversion = sql_conversions . get ( type ( arg ) ) if conversion : return conversion ( arg ) for type_ in subclass_conversions : if isinstance ( arg , type_ ) : return sql_conversions [ type_ ] ( arg ) return sql_conversions [ str ] ( arg ) | Perform necessary SOQL quoting on the arg . |
240,803 | def arg_to_json ( arg ) : conversion = json_conversions . get ( type ( arg ) ) if conversion : return conversion ( arg ) for type_ in subclass_conversions : if isinstance ( arg , type_ ) : return json_conversions [ type_ ] ( arg ) return json_conversions [ str ] ( arg ) | Perform necessary JSON conversion on the arg . |
240,804 | def merge_dict ( dict_1 , * other , ** kw ) : tmp = dict_1 . copy ( ) for x in other : tmp . update ( x ) tmp . update ( kw ) return tmp | Merge two or more dict including kw into result dict . |
240,805 | def make_session ( self ) : with connect_lock : if self . _sf_session is None : sf_session = requests . Session ( ) sf_session . auth = SalesforcePasswordAuth ( db_alias = self . alias , settings_dict = self . settings_dict ) sf_instance_url = sf_session . auth . instance_url sf_requests_adapter = HTTPAdapter ( max_ret... | Authenticate and get the name of assigned SFDC data server |
240,806 | def rest_api_url ( self , * url_parts , ** kwargs ) : url_parts = list ( url_parts ) if url_parts and re . match ( r'^(?:https|mock)://' , url_parts [ 0 ] ) : return '/' . join ( url_parts ) relative = kwargs . pop ( 'relative' , False ) api_ver = kwargs . pop ( 'api_ver' , None ) api_ver = api_ver if api_ver is not No... | Join the URL of REST_API |
240,807 | def raise_errors ( self , response ) : verb = self . debug_verbs method = response . request . method data = None is_json = 'json' in response . headers . get ( 'Content-Type' , '' ) and response . text if is_json : data = json . loads ( response . text ) if not ( isinstance ( data , list ) and data and 'errorCode' in ... | The innermost part - report errors by exceptions |
240,808 | def composite_request ( self , data ) : post_data = { 'compositeRequest' : data , 'allOrNone' : True } resp = self . handle_api_exceptions ( 'POST' , 'composite' , json = post_data ) comp_resp = resp . json ( ) [ 'compositeResponse' ] is_ok = all ( x [ 'httpStatusCode' ] < 400 for x in comp_resp ) if is_ok : return res... | Call a composite request with subrequests error handling |
240,809 | def align_after ( self , offset ) : f = self . reader if offset <= 0 : f . seek ( 0 ) self . _block_count = 0 self . _read_header ( ) return sm = self . sync_marker sml = len ( sm ) pos = offset while pos < self . file_length - sml : f . seek ( pos ) data = f . read ( self . FORWARD_WINDOW_SIZE ) sync_offset = data . f... | Search for a sync point after offset and align just after that . |
240,810 | def get_progress ( self ) : pos = self . reader . reader . tell ( ) return min ( ( pos - self . region_start ) / float ( self . region_end - self . region_start ) , 1.0 ) | Give a rough estimate of the progress done . |
240,811 | def is_exe ( fpath ) : return os . path . isfile ( fpath ) and os . access ( fpath , os . X_OK ) | Path references an executable file . |
240,812 | def is_readable ( fpath ) : return os . path . isfile ( fpath ) and os . access ( fpath , os . R_OK ) | Path references a readable file . |
240,813 | def is_local ( self , hadoop_conf = None , hadoop_home = None ) : conf = self . hadoop_params ( hadoop_conf , hadoop_home ) keys = ( 'mapreduce.framework.name' , 'mapreduce.jobtracker.address' , 'mapred.job.tracker' ) for k in keys : if conf . get ( k , 'local' ) . lower ( ) != 'local' : return False return True | \ Is Hadoop configured to run in local mode? |
240,814 | def abspath ( hdfs_path , user = None , local = False ) : if local : return 'file:%s' % os . path . abspath ( hdfs_path ) if isfull ( hdfs_path ) : return hdfs_path hostname , port , path = split ( hdfs_path , user = user ) if hostname : fs = hdfs_fs . hdfs ( hostname , port ) apath = join ( "hdfs://%s:%s" % ( fs . hos... | Return an absolute path for hdfs_path . |
240,815 | def dirname ( hdfs_path ) : scheme , netloc , path = parse ( hdfs_path ) return unparse ( scheme , netloc , os . path . dirname ( path ) ) | Return the directory component of hdfs_path . |
240,816 | def expanduser ( path ) : if hdfs_fs . default_is_local ( ) : return os . path . expanduser ( path ) m = re . match ( r'^~([^/]*)' , path ) if m is None : return path user = m . groups ( ) [ 0 ] or common . DEFAULT_USER return '/user/%s%s' % ( user , path [ m . end ( 1 ) : ] ) | Replace initial ~ or ~user with the user s home directory . |
240,817 | def normpath ( path ) : scheme , netloc , path_ = parse ( path ) return unparse ( scheme , netloc , os . path . normpath ( path_ ) ) | Normalize path collapsing redundant separators and up - level refs . |
240,818 | def realpath ( path ) : scheme , netloc , path_ = parse ( path ) if scheme == 'file' or hdfs_fs . default_is_local ( ) : return unparse ( scheme , netloc , os . path . realpath ( path_ ) ) return path | Return path with symlinks resolved . |
240,819 | def default_is_local ( hadoop_conf = None , hadoop_home = None ) : params = pydoop . hadoop_params ( hadoop_conf , hadoop_home ) for k in 'fs.defaultFS' , 'fs.default.name' : if not params . get ( k , 'file:' ) . startswith ( 'file:' ) : return False return True | \ Is Hadoop configured to use the local file system? |
240,820 | def open_file ( self , path , mode = "r" , buff_size = 0 , replication = 0 , blocksize = 0 , encoding = None , errors = None ) : _complain_ifclosed ( self . closed ) if not path : raise ValueError ( "Empty path" ) m , is_text = common . parse_mode ( mode ) if not self . host : fret = local_file ( self , path , m ) if i... | Open an HDFS file . |
240,821 | def capacity ( self ) : _complain_ifclosed ( self . closed ) if not self . __status . host : raise RuntimeError ( 'Capacity is not defined for a local fs' ) return self . fs . get_capacity ( ) | Return the raw capacity of the filesystem . |
240,822 | def copy ( self , from_path , to_hdfs , to_path ) : _complain_ifclosed ( self . closed ) if isinstance ( to_hdfs , self . __class__ ) : to_hdfs = to_hdfs . fs return self . fs . copy ( from_path , to_hdfs , to_path ) | Copy file from one filesystem to another . |
240,823 | def delete ( self , path , recursive = True ) : _complain_ifclosed ( self . closed ) return self . fs . delete ( path , recursive ) | Delete path . |
240,824 | def exists ( self , path ) : _complain_ifclosed ( self . closed ) return self . fs . exists ( path ) | Check if a given path exists on the filesystem . |
240,825 | def get_path_info ( self , path ) : _complain_ifclosed ( self . closed ) return self . fs . get_path_info ( path ) | Get information about path as a dict of properties . |
240,826 | def list_directory ( self , path ) : r _complain_ifclosed ( self . closed ) return self . fs . list_directory ( path ) | r Get list of files and directories for path \ . |
240,827 | def rename ( self , from_path , to_path ) : _complain_ifclosed ( self . closed ) return self . fs . rename ( from_path , to_path ) | Rename file . |
240,828 | def set_replication ( self , path , replication ) : r _complain_ifclosed ( self . closed ) return self . fs . set_replication ( path , replication ) | r Set the replication of path to replication \ . |
240,829 | def set_working_directory ( self , path ) : r _complain_ifclosed ( self . closed ) return self . fs . set_working_directory ( path ) | r Set the working directory to path \ . All relative paths will be resolved relative to it . |
240,830 | def working_directory ( self ) : _complain_ifclosed ( self . closed ) wd = self . fs . get_working_directory ( ) return wd | Get the current working directory . |
240,831 | def __compute_mode_from_string ( self , path , mode_string ) : Char_to_perm_byte = { 'r' : 4 , 'w' : 2 , 'x' : 1 } Fields = ( ( 'u' , 6 ) , ( 'g' , 3 ) , ( 'o' , 0 ) ) m = re . match ( r"\s*([ugoa]*)([-+=])([rwx]*)\s*" , mode_string ) if not m : raise ValueError ( "Invalid mode string %s" % mode_string ) who = m . grou... | Scan a unix - style mode string and apply it to path . |
240,832 | def utime ( self , path , mtime , atime ) : _complain_ifclosed ( self . closed ) return self . fs . utime ( path , int ( mtime ) , int ( atime ) ) | Change file last access and modification times . |
240,833 | def rm_rf ( path , dry_run = False ) : log . info ( "removing %s" % path ) if dry_run : return try : if os . path . isdir ( path ) and not os . path . islink ( path ) : shutil . rmtree ( path ) else : os . remove ( path ) except OSError : pass | Remove a file or directory tree . |
240,834 | def __finalize_hdfs ( self , ext ) : java_home = jvm . get_java_home ( ) jvm_lib_path , _ = jvm . get_jvm_lib_path_and_name ( java_home ) ext . include_dirs = jvm . get_include_dirs ( ) + ext . include_dirs ext . libraries = jvm . get_libraries ( ) ext . library_dirs = [ os . path . join ( java_home , "Libraries" ) , j... | \ Adds a few bits that depend on the specific environment . |
240,835 | def run_tool_cmd ( tool , cmd , args = None , properties = None , hadoop_conf_dir = None , logger = None , keep_streams = True ) : if logger is None : logger = utils . NullLogger ( ) _args = [ tool ] if hadoop_conf_dir : _args . extend ( [ "--config" , hadoop_conf_dir ] ) _args . append ( cmd ) if properties : _args . ... | Run a Hadoop command . |
240,836 | def get_task_trackers ( properties = None , hadoop_conf_dir = None , offline = False ) : if offline : if not hadoop_conf_dir : hadoop_conf_dir = pydoop . hadoop_conf ( ) slaves = os . path . join ( hadoop_conf_dir , "slaves" ) try : with open ( slaves ) as f : task_trackers = [ ( l . strip ( ) , 0 ) for l in f ] except... | Get the list of task trackers in the Hadoop cluster . |
240,837 | def get_num_nodes ( properties = None , hadoop_conf_dir = None , offline = False ) : return len ( get_task_trackers ( properties , hadoop_conf_dir , offline ) ) | Get the number of task trackers in the Hadoop cluster . |
240,838 | def dfs ( args = None , properties = None , hadoop_conf_dir = None ) : return run_class ( "org.apache.hadoop.fs.FsShell" , args , properties , hadoop_conf_dir = hadoop_conf_dir , keep_streams = True ) | Run the Hadoop file system shell . |
240,839 | def run_pipes ( executable , input_path , output_path , more_args = None , properties = None , force_pydoop_submitter = False , hadoop_conf_dir = None , logger = None , keep_streams = False ) : if logger is None : logger = utils . NullLogger ( ) if not hdfs . path . exists ( executable ) : raise IOError ( "executable %... | Run a pipes command . |
240,840 | def collect_output ( mr_out_dir , out_file = None ) : if out_file is None : output = [ ] for fn in iter_mr_out_files ( mr_out_dir ) : with hdfs . open ( fn , "rt" ) as f : output . append ( f . read ( ) ) return "" . join ( output ) else : block_size = 16777216 with open ( out_file , 'a' ) as o : for fn in iter_mr_out_... | Return all mapreduce output in mr_out_dir . |
240,841 | def set_output ( self , output ) : self . output = output self . logger . info ( "assigning output to %s" , self . output ) | Set the output path for the job . Optional if the runner has been instantiated with a prefix . |
240,842 | def set_exe ( self , pipes_code ) : if not self . output : raise RuntimeError ( "no output directory, can't create launcher" ) parent = hdfs . path . dirname ( hdfs . path . abspath ( self . output . rstrip ( "/" ) ) ) self . exe = hdfs . path . join ( parent , utils . make_random_str ( ) ) hdfs . dump ( pipes_code , s... | Dump launcher code to the distributed file system . |
240,843 | def dump ( data , hdfs_path , ** kwargs ) : kwargs [ "mode" ] = "w" if isinstance ( data , bintype ) else "wt" with open ( hdfs_path , ** kwargs ) as fo : i = 0 bufsize = common . BUFSIZE while i < len ( data ) : fo . write ( data [ i : i + bufsize ] ) i += bufsize fo . fs . close ( ) | \ Write data to hdfs_path . |
240,844 | def load ( hdfs_path , ** kwargs ) : m , _ = common . parse_mode ( kwargs . get ( "mode" , "r" ) ) if m != "r" : raise ValueError ( "opening mode must be readonly" ) with open ( hdfs_path , ** kwargs ) as fi : data = fi . read ( ) fi . fs . close ( ) return data | \ Read the content of hdfs_path and return it . |
240,845 | def cp ( src_hdfs_path , dest_hdfs_path , ** kwargs ) : src , dest = { } , { } try : for d , p in ( ( src , src_hdfs_path ) , ( dest , dest_hdfs_path ) ) : d [ "host" ] , d [ "port" ] , d [ "path" ] = path . split ( p ) d [ "fs" ] = hdfs ( d [ "host" ] , d [ "port" ] ) try : src [ "info" ] = src [ "fs" ] . get_path_inf... | \ Copy the contents of src_hdfs_path to dest_hdfs_path . |
240,846 | def put ( src_path , dest_hdfs_path , ** kwargs ) : cp ( path . abspath ( src_path , local = True ) , dest_hdfs_path , ** kwargs ) | \ Copy the contents of src_path to dest_hdfs_path . |
240,847 | def get ( src_hdfs_path , dest_path , ** kwargs ) : cp ( src_hdfs_path , path . abspath ( dest_path , local = True ) , ** kwargs ) | \ Copy the contents of src_hdfs_path to dest_path . |
240,848 | def mkdir ( hdfs_path , user = None ) : host , port , path_ = path . split ( hdfs_path , user ) fs = hdfs ( host , port , user ) retval = fs . create_directory ( path_ ) fs . close ( ) return retval | Create a directory and its parents as needed . |
240,849 | def lsl ( hdfs_path , user = None , recursive = False ) : host , port , path_ = path . split ( hdfs_path , user ) fs = hdfs ( host , port , user ) if not recursive : dir_list = fs . list_directory ( path_ ) else : treewalk = fs . walk ( path_ ) top = next ( treewalk ) if top [ 'kind' ] == 'directory' : dir_list = list ... | Return a list of dictionaries of file properties . |
240,850 | def ls ( hdfs_path , user = None , recursive = False ) : dir_list = lsl ( hdfs_path , user , recursive ) return [ d [ "name" ] for d in dir_list ] | Return a list of hdfs paths . |
240,851 | def move ( src , dest , user = None ) : src_host , src_port , src_path = path . split ( src , user ) dest_host , dest_port , dest_path = path . split ( dest , user ) src_fs = hdfs ( src_host , src_port , user ) dest_fs = hdfs ( dest_host , dest_port , user ) try : retval = src_fs . move ( src_path , dest_fs , dest_path... | Move or rename src to dest . |
240,852 | def renames ( from_path , to_path , user = None ) : to_dir = path . dirname ( to_path ) if to_dir : mkdir ( to_dir , user = user ) rename ( from_path , to_path , user = user ) | Rename from_path to to_path creating parents as needed . |
240,853 | def readline ( self ) : _complain_ifclosed ( self . closed ) line = self . f . readline ( ) if self . __encoding : return line . decode ( self . __encoding , self . __errors ) else : return line | Read and return a line of text . |
240,854 | def pread ( self , position , length ) : r _complain_ifclosed ( self . closed ) if position > self . size : raise IOError ( "position cannot be past EOF" ) if length < 0 : length = self . size - position data = self . f . raw . pread ( position , length ) if self . __encoding : return data . decode ( self . __encoding ... | r Read length bytes of data from the file starting from position \ . |
240,855 | def read ( self , length = - 1 ) : _complain_ifclosed ( self . closed ) if length < 0 : length = self . size chunks = [ ] while 1 : if length <= 0 : break c = self . f . read ( min ( self . buff_size , length ) ) if c == b"" : break chunks . append ( c ) length -= len ( c ) data = b"" . join ( chunks ) if self . __enco... | Read length bytes from the file . If length is negative or omitted read all data until EOF . |
240,856 | def seek ( self , position , whence = os . SEEK_SET ) : _complain_ifclosed ( self . closed ) return self . f . seek ( position , whence ) | Seek to position in file . |
240,857 | def write ( self , data ) : _complain_ifclosed ( self . closed ) if self . __encoding : self . f . write ( data . encode ( self . __encoding , self . __errors ) ) return len ( data ) else : return self . f . write ( data ) | Write data to the file . |
240,858 | def set_args ( self , args , unknown_args = None ) : if unknown_args is None : unknown_args = [ ] self . logger . setLevel ( getattr ( logging , args . log_level ) ) parent = hdfs . path . dirname ( hdfs . path . abspath ( args . output . rstrip ( "/" ) ) ) self . remote_wd = hdfs . path . join ( parent , utils . make_... | Configure job based on the arguments provided . |
240,859 | def __warn_user_if_wd_maybe_unreadable ( self , abs_remote_path ) : host , port , path = hdfs . path . split ( abs_remote_path ) if host == '' and port == 0 : host_port = "file:///" else : host_port = "hdfs://%s:%s/" % ( host , port ) path_pieces = path . strip ( '/' ) . split ( os . path . sep ) fs = hdfs . hdfs ( hos... | Check directories above the remote module and issue a warning if they are not traversable by all users . |
240,860 | def __setup_remote_paths ( self ) : self . logger . debug ( "remote_wd: %s" , self . remote_wd ) self . logger . debug ( "remote_exe: %s" , self . remote_exe ) self . logger . debug ( "remotes: %s" , self . files_to_upload ) if self . args . module : self . logger . debug ( 'Generated pipes_code:\n\n %s' , self . _gene... | Actually create the working directory and copy the module into it . |
240,861 | def docker_client ( ) : cert_path = os . environ . get ( 'DOCKER_CERT_PATH' , '' ) if cert_path == '' : cert_path = os . path . join ( os . environ . get ( 'HOME' , '' ) , '.docker' ) base_url = os . environ . get ( 'DOCKER_HOST' ) tls_config = None if os . environ . get ( 'DOCKER_TLS_VERIFY' , '' ) != '' : parts = bas... | Returns a docker - py client configured using environment variables according to the same logic as the official Docker client . |
240,862 | def get_java_home ( ) : error = RuntimeError ( "java home not found, try setting JAVA_HOME" ) try : return os . environ [ "JAVA_HOME" ] except KeyError : wd = tempfile . mkdtemp ( prefix = 'pydoop_' ) jclass = "Temp" jsrc = os . path . join ( wd , "%s.java" % jclass ) with open ( jsrc , "w" ) as f : f . write ( JPROG .... | \ Try getting JAVA_HOME from system properties . |
240,863 | def run_task ( factory , ** kwargs ) : context = TaskContext ( factory , ** kwargs ) pstats_dir = kwargs . get ( "pstats_dir" , os . getenv ( PSTATS_DIR ) ) if pstats_dir : import cProfile import tempfile import pydoop . hdfs as hdfs hdfs . mkdir ( pstats_dir ) fd , pstats_fn = tempfile . mkstemp ( suffix = ".pstats" )... | \ Run a MapReduce task . |
240,864 | def progress ( self ) : now = time ( ) if now - self . last_progress_t > 1 : self . last_progress_t = now if self . status : self . uplink . status ( self . status ) self . status = None self . __spill_counters ( ) self . uplink . progress ( self . progress_value ) self . uplink . flush ( ) | \ Report progress to the Java side . |
240,865 | def merge_pages ( self , replacements ) : warnings . warn ( "merge_pages has been deprecated in favour of merge_templates" , category = DeprecationWarning , stacklevel = 2 ) self . merge_templates ( replacements , "page_break" ) | Deprecated method . |
240,866 | def importpath ( path , error_text = None ) : result = None attrs = [ ] parts = path . split ( '.' ) exception = None while parts : try : result = __import__ ( '.' . join ( parts ) , { } , { } , [ '' ] ) except ImportError as e : if exception is None : exception = e attrs = parts [ - 1 : ] + attrs parts = parts [ : - 1... | Import value by specified path . Value can represent module class object attribute or method . If error_text is not None and import will raise ImproperlyConfigured with user friendly text . |
240,867 | def get_booking ( request ) : booking = None if request . user . is_authenticated ( ) : try : booking = Booking . objects . get ( user = request . user , booking_status__slug = 'inprogress' ) except Booking . DoesNotExist : pass else : session = Session . objects . get ( session_key = request . session . session_key ) ... | Returns the booking that is in progress for the current user or None |
240,868 | def persist_booking ( booking , user ) : if booking is not None : existing_bookings = Booking . objects . filter ( user = user , booking_status__slug = 'inprogress' ) . exclude ( pk = booking . pk ) existing_bookings . delete ( ) booking . session = None booking . user = user booking . save ( ) | Ties an in - progress booking from a session to a user when the user logs in . |
240,869 | def compare_config ( self , target , init = True , indent_level = 0 ) : if init : fwd = self . full_path_fwd bwd = self . full_path_bwd else : fwd = self . rel_path_fwd bwd = self . rel_path_bwd indent = 4 * indent_level * ' ' if indent_level == 0 and self . vdom is not None : if self . vdom == 'global' : pre = 'conf g... | This method will return all the necessary commands to get from the config we are in to the target config . |
240,870 | def to_text ( self , relative = False , indent_level = 0 , clean_empty_block = False ) : if relative : fwd = self . rel_path_fwd bwd = self . rel_path_bwd else : fwd = self . full_path_fwd bwd = self . full_path_bwd indent = 4 * indent_level * ' ' pre = '%s%s' % ( indent , fwd ) post = '%s%s' % ( indent , bwd ) text = ... | This method returns the object model in text format . You should be able to copy&paste this text into any device running a supported version of FortiOS . |
240,871 | def open ( self ) : logger . debug ( 'Connecting to device %s, vdom %s' % ( self . hostname , self . vdom ) ) self . ssh = paramiko . SSHClient ( ) self . ssh . set_missing_host_key_policy ( paramiko . AutoAddPolicy ( ) ) cfg = { 'hostname' : self . hostname , 'timeout' : self . timeout , 'username' : self . username ,... | Opens the ssh session with the device . |
240,872 | def _read_wrapper ( data ) : if isinstance ( data , int ) : data = chr ( data ) return py23_compat . text_type ( data ) | Ensure unicode always returned on read . |
240,873 | def _parse_batch_lastlog ( last_log ) : regexp = re . compile ( '(-?[0-9]\d*):\W+(.*)' ) wrong_commands = list ( ) for line in last_log : result = regexp . match ( line ) if result is not None : status_code = result . group ( 1 ) command = result . group ( 2 ) if int ( status_code ) < 0 : wrong_commands . append ( ( st... | This static method will help reading the result of the commit command by command . |
240,874 | def _reload_config ( self , reload_original_config ) : if reload_original_config : self . original_config = self . running_config self . original_config . set_name ( 'original' ) paths = self . running_config . get_paths ( ) self . running_config = FortiConfig ( 'running' , vdom = self . vdom ) for path in paths : self... | This command will update the running config from the live device . |
240,875 | def generate_states ( self , initial_condition = None , with_noise = True , stateseq = None ) : from pybasicbayes . util . stats import sample_discrete T , K , n = self . T , self . num_states , self . D_latent A = self . trans_matrix dss = - 1 * np . ones ( T , dtype = np . int32 ) if stateseq is None else stateseq . ... | Jointly sample the discrete and continuous states |
240,876 | def heldout_log_likelihood ( self , test_mask = None ) : if test_mask is None : if self . mask is None : return 0 else : test_mask = ~ self . mask xs = np . hstack ( ( self . gaussian_states , self . inputs ) ) if self . single_emission : return self . emission_distns [ 0 ] . log_likelihood ( ( xs , self . data ) , mas... | Compute the log likelihood of the masked data given the latent discrete and continuous states . |
240,877 | def empirical_rate ( data , sigma = 3.0 ) : from scipy . ndimage . filters import gaussian_filter1d return 0.001 + gaussian_filter1d ( data . astype ( np . float ) , sigma , axis = 0 ) | Smooth count data to get an empirical rate |
240,878 | def get_empirical_ar_params ( train_datas , params ) : assert isinstance ( train_datas , list ) and len ( train_datas ) > 0 datadimension = train_datas [ 0 ] . shape [ 1 ] assert params [ "nu_0" ] > datadimension + 1 obs_params = dict ( nu_0 = params [ "nu_0" ] , S_0 = params [ 'S_0' ] , M_0 = params [ 'M_0' ] , K_0 = ... | Estimate the parameters of an AR observation model by fitting a single AR model to the entire dataset . |
240,879 | def capture ( target_url , user_agent = "savepagenow (https://github.com/pastpages/savepagenow)" , accept_cache = False ) : domain = "https://web.archive.org" save_url = urljoin ( domain , "/save/" ) request_url = save_url + target_url headers = { 'User-Agent' : user_agent , } response = requests . get ( request_url , ... | Archives the provided URL using archive . org s Wayback Machine . |
240,880 | def capture_or_cache ( target_url , user_agent = "savepagenow (https://github.com/pastpages/savepagenow)" ) : try : return capture ( target_url , user_agent = user_agent , accept_cache = False ) , True except CachedPage : return capture ( target_url , user_agent = user_agent , accept_cache = True ) , False | Archives the provided URL using archive . org s Wayback Machine unless the page has been recently captured . |
240,881 | def get_unique_id ( element ) : this_id = make_id ( element ) dup = True while dup : if this_id not in ids : dup = False ids . append ( this_id ) else : this_id = make_id ( element ) return ids [ - 1 ] | Returns a unique id for a given element |
240,882 | def get_xml_type ( val ) : if type ( val ) . __name__ in ( 'str' , 'unicode' ) : return 'str' if type ( val ) . __name__ in ( 'int' , 'long' ) : return 'int' if type ( val ) . __name__ == 'float' : return 'float' if type ( val ) . __name__ == 'bool' : return 'bool' if isinstance ( val , numbers . Number ) : return 'num... | Returns the data type for the xml type attribute |
240,883 | def make_attrstring ( attr ) : attrstring = ' ' . join ( [ '%s="%s"' % ( k , v ) for k , v in attr . items ( ) ] ) return '%s%s' % ( ' ' if attrstring != '' else '' , attrstring ) | Returns an attribute string in the form key = val |
240,884 | def key_is_valid_xml ( key ) : LOG . info ( 'Inside key_is_valid_xml(). Testing "%s"' % ( unicode_me ( key ) ) ) test_xml = '<?xml version="1.0" encoding="UTF-8" ?><%s>foo</%s>' % ( key , key ) try : parseString ( test_xml ) return True except Exception : return False | Checks that a key is a valid XML name |
240,885 | def make_valid_xml_name ( key , attr ) : LOG . info ( 'Inside make_valid_xml_name(). Testing key "%s" with attr "%s"' % ( unicode_me ( key ) , unicode_me ( attr ) ) ) key = escape_xml ( key ) attr = escape_xml ( attr ) if key_is_valid_xml ( key ) : return key , attr if key . isdigit ( ) : return 'n%s' % ( key ) , attr ... | Tests an XML name and fixes it if invalid |
240,886 | def convert ( obj , ids , attr_type , item_func , cdata , parent = 'root' ) : LOG . info ( 'Inside convert(). obj type is: "%s", obj="%s"' % ( type ( obj ) . __name__ , unicode_me ( obj ) ) ) item_name = item_func ( parent ) if isinstance ( obj , numbers . Number ) or type ( obj ) in ( str , unicode ) : return convert_... | Routes the elements of an object to the right function to convert them based on their data type |
240,887 | def convert_dict ( obj , ids , parent , attr_type , item_func , cdata ) : LOG . info ( 'Inside convert_dict(): obj type is: "%s", obj="%s"' % ( type ( obj ) . __name__ , unicode_me ( obj ) ) ) output = [ ] addline = output . append item_name = item_func ( parent ) for key , val in obj . items ( ) : LOG . info ( 'Loopin... | Converts a dict into an XML string . |
240,888 | def convert_list ( items , ids , parent , attr_type , item_func , cdata ) : LOG . info ( 'Inside convert_list()' ) output = [ ] addline = output . append item_name = item_func ( parent ) if ids : this_id = get_unique_id ( parent ) for i , item in enumerate ( items ) : LOG . info ( 'Looping inside convert_list(): item="... | Converts a list into an XML string . |
240,889 | def convert_kv ( key , val , attr_type , attr = { } , cdata = False ) : LOG . info ( 'Inside convert_kv(): key="%s", val="%s", type(val) is: "%s"' % ( unicode_me ( key ) , unicode_me ( val ) , type ( val ) . __name__ ) ) key , attr = make_valid_xml_name ( key , attr ) if attr_type : attr [ 'type' ] = get_xml_type ( val... | Converts a number or string into an XML element |
240,890 | def convert_bool ( key , val , attr_type , attr = { } , cdata = False ) : LOG . info ( 'Inside convert_bool(): key="%s", val="%s", type(val) is: "%s"' % ( unicode_me ( key ) , unicode_me ( val ) , type ( val ) . __name__ ) ) key , attr = make_valid_xml_name ( key , attr ) if attr_type : attr [ 'type' ] = get_xml_type (... | Converts a boolean into an XML element |
240,891 | def convert_none ( key , val , attr_type , attr = { } , cdata = False ) : LOG . info ( 'Inside convert_none(): key="%s"' % ( unicode_me ( key ) ) ) key , attr = make_valid_xml_name ( key , attr ) if attr_type : attr [ 'type' ] = get_xml_type ( val ) attrstring = make_attrstring ( attr ) return '<%s%s></%s>' % ( key , a... | Converts a null value into an XML element |
240,892 | def getCallSourceLines ( callFrame , icNames , icMethod ) : code = callFrame . f_code try : if code . co_name == '<module>' : parentBlockStartLine = 1 lines = inspect . findsource ( code ) [ 0 ] parentBlockSource = '' . join ( lines ) else : parentBlockStartLine = code . co_firstlineno parentBlockSource = inspect . get... | Raises NoSourceAvailableError . |
240,893 | def init_websocket ( self , event_handler , websocket_cls = Websocket ) : self . websocket = websocket_cls ( self . options , self . client . token ) loop = asyncio . get_event_loop ( ) loop . run_until_complete ( self . websocket . connect ( event_handler ) ) return loop | Will initialize the websocket connection to the mattermost server . |
240,894 | def login ( self ) : if self . options [ 'token' ] : self . client . token = self . options [ 'token' ] result = self . users . get_user ( 'me' ) else : response = self . users . login_user ( { 'login_id' : self . options [ 'login_id' ] , 'password' : self . options [ 'password' ] , 'token' : self . options [ 'mfa_toke... | Logs the user in . |
240,895 | def connect ( self , event_handler ) : context = ssl . create_default_context ( purpose = ssl . Purpose . CLIENT_AUTH ) if not self . options [ 'verify' ] : context . verify_mode = ssl . CERT_NONE scheme = 'wss://' if self . options [ 'scheme' ] != 'https' : scheme = 'ws://' context = None url = '{scheme:s}{url:s}:{por... | Connect to the websocket and authenticate it . When the authentication has finished start the loop listening for messages sending a ping to the server to keep the connection alive . |
240,896 | def _authenticate_websocket ( self , websocket , event_handler ) : log . debug ( 'Authenticating websocket' ) json_data = json . dumps ( { "seq" : 1 , "action" : "authentication_challenge" , "data" : { "token" : self . _token } } ) . encode ( 'utf8' ) yield from websocket . send ( json_data ) while True : message = yie... | Sends a authentication challenge over a websocket . This is not needed when we just send the cookie we got on login when connecting to the websocket . |
240,897 | def run_cell ( self , cell ) : logging . info ( 'Running cell:\n%s\n' , cell . input ) self . kc . execute ( cell . input ) reply = self . kc . get_shell_msg ( ) status = reply [ 'content' ] [ 'status' ] traceback_text = '' if status == 'error' : traceback_text = 'Cell raised uncaught exception: \n' + '\n' . join ( rep... | Run a notebook cell and update the output of that cell in - place . |
240,898 | def iter_code_cells ( self ) : for ws in self . nb . worksheets : for cell in ws . cells : if cell . cell_type == 'code' : yield cell | Iterate over the notebook cells containing code . |
240,899 | def run_notebook ( self , skip_exceptions = False , progress_callback = None ) : for i , cell in enumerate ( self . iter_code_cells ( ) ) : try : self . run_cell ( cell ) except NotebookError : if not skip_exceptions : raise if progress_callback : progress_callback ( i ) | Run all the notebook cells in order and update the outputs in - place . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.