idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
248,000
async def check_permissions ( self , action : str , ** kwargs ) : for permission in await self . get_permissions ( action = action , ** kwargs ) : if not await ensure_async ( permission . has_permission ) ( scope = self . scope , consumer = self , action = action , ** kwargs ) : raise PermissionDenied ( )
Check if the action should be permitted . Raises an appropriate exception if the request is not permitted .
248,001
async def handle_exception ( self , exc : Exception , action : str , request_id ) : if isinstance ( exc , APIException ) : await self . reply ( action = action , errors = self . _format_errors ( exc . detail ) , status = exc . status_code , request_id = request_id ) elif exc == Http404 or isinstance ( exc , Http404 ) :...
Handle any exception that occurs by sending an appropriate message
248,002
async def receive_json ( self , content : typing . Dict , ** kwargs ) : request_id = content . pop ( 'request_id' ) action = content . pop ( 'action' ) await self . handle_action ( action , request_id = request_id , ** content )
Called with decoded JSON content .
248,003
def action ( atomic = None , ** kwargs ) : def decorator ( func ) : if atomic is None : _atomic = getattr ( settings , 'ATOMIC_REQUESTS' , False ) else : _atomic = atomic func . action = True func . kwargs = kwargs if asyncio . iscoroutinefunction ( func ) : if _atomic : raise ValueError ( 'Only synchronous actions can...
Mark a method as an action .
248,004
def datetime_parser ( s ) : try : ts = arrow . get ( s ) if ts . tzinfo == arrow . get ( ) . tzinfo : ts = ts . replace ( tzinfo = 'local' ) except : c = pdt . Calendar ( ) result , what = c . parse ( s ) ts = None if what in ( 1 , 2 , 3 ) : ts = datetime . datetime ( * result [ : 6 ] ) ts = arrow . get ( ts ) ts = ts ...
Parse timestamp s in local time . First the arrow parser is used if it fails the parsedatetime parser is used .
248,005
def seek ( self , offset : int = 0 , * args , ** kwargs ) : return self . fp . seek ( offset , * args , ** kwargs )
A shortcut to self . fp . seek .
248,006
def set_title ( self , title : str , url : str = None ) -> None : self . title = title self . url = url
Sets the title of the embed .
248,007
def set_timestamp ( self , time : Union [ str , datetime . datetime ] = None , now : bool = False ) -> None : if now : self . timestamp = str ( datetime . datetime . utcnow ( ) ) else : self . timestamp = str ( time )
Sets the timestamp of the embed .
248,008
def add_field ( self , name : str , value : str , inline : bool = True ) -> None : field = { 'name' : name , 'value' : value , 'inline' : inline } self . fields . append ( field )
Adds an embed field .
248,009
def set_author ( self , name : str , icon_url : str = None , url : str = None ) -> None : self . author = { 'name' : name , 'icon_url' : icon_url , 'url' : url }
Sets the author of the embed .
248,010
def set_footer ( self , text : str , icon_url : str = None ) -> None : self . footer = { 'text' : text , 'icon_url' : icon_url }
Sets the footer of the embed .
248,011
async def init ( app , loop ) : app . session = aiohttp . ClientSession ( loop = loop ) app . webhook = Webhook . Async ( webhook_url , session = app . session ) em = Embed ( color = 0x2ecc71 ) em . set_author ( '[INFO] Starting Worker' ) em . description = 'Host: {}' . format ( socket . gethostname ( ) ) await app . w...
Sends a message to the webhook channel when server starts .
248,012
async def server_stop ( app , loop ) : em = Embed ( color = 0xe67e22 ) em . set_footer ( 'Host: {}' . format ( socket . gethostname ( ) ) ) em . description = '[INFO] Server Stopped' await app . webhook . send ( embed = em ) await app . session . close ( )
Sends a message to the webhook channel when server stops .
248,013
def get_deprecated_msg ( self , wrapped , instance ) : if instance is None : if inspect . isclass ( wrapped ) : fmt = "Call to deprecated class {name}." else : fmt = "Call to deprecated function (or staticmethod) {name}." else : if inspect . isclass ( instance ) : fmt = "Call to deprecated class method {name}." else : ...
Get the deprecation warning message for the user .
248,014
def slack_user ( request , api_data ) : if request . user . is_anonymous : return request , api_data data = deepcopy ( api_data ) slacker , _ = SlackUser . objects . get_or_create ( slacker = request . user ) slacker . access_token = data . pop ( 'access_token' ) slacker . extras = data slacker . save ( ) messages . ad...
Pipeline for backward compatibility prior to 1 . 0 . 0 version . In case if you re willing maintain slack_user table .
248,015
def read ( varin , fname = 'MS2_L10.mat.txt' ) : d = np . loadtxt ( fname , comments = '*' ) if fname == 'MS2_L10.mat.txt' : var = [ 'lat' , 'lon' , 'depth' , 'temp' , 'density' , 'sigma' , 'oxygen' , 'voltage 2' , 'voltage 3' , 'fluorescence-CDOM' , 'fluorescence-ECO' , 'turbidity' , 'pressure' , 'salinity' , 'RINKO t...
Read in dataset for variable var
248,016
def show ( cmap , var , vmin = None , vmax = None ) : lat , lon , z , data = read ( var ) fig = plt . figure ( figsize = ( 16 , 12 ) ) ax = fig . add_subplot ( 3 , 1 , 1 ) map1 = ax . scatter ( lon , - z , c = data , cmap = 'gray' , s = 10 , linewidths = 0. , vmin = vmin , vmax = vmax ) plt . colorbar ( map1 , ax = ax ...
Show a colormap for a chosen input variable var side by side with black and white and jet colormaps .
248,017
def plot_data ( ) : var = [ 'temp' , 'oxygen' , 'salinity' , 'fluorescence-ECO' , 'density' , 'PAR' , 'turbidity' , 'fluorescence-CDOM' ] lims = np . array ( [ [ 26 , 33 ] , [ 0 , 10 ] , [ 0 , 36 ] , [ 0 , 6 ] , [ 1005 , 1025 ] , [ 0 , 0.6 ] , [ 0 , 2 ] , [ 0 , 9 ] ] ) for fname in fnames : fig , axes = plt . subplots ...
Plot sample data up with the fancy colormaps .
248,018
def plot_lightness ( saveplot = False ) : from colorspacious import cspace_converter dc = 1. x = np . linspace ( 0.0 , 1.0 , 256 ) locs = [ ] fig = plt . figure ( figsize = ( 16 , 5 ) ) ax = fig . add_subplot ( 111 ) fig . subplots_adjust ( left = 0.03 , right = 0.97 ) ax . set_xlim ( - 0.1 , len ( cm . cmap_d ) / 2. +...
Plot lightness of colormaps together .
248,019
def plot_gallery ( saveplot = False ) : from colorspacious import cspace_converter gradient = np . linspace ( 0 , 1 , 256 ) gradient = np . vstack ( ( gradient , gradient ) ) x = np . linspace ( 0.0 , 1.0 , 256 ) fig , axes = plt . subplots ( nrows = int ( len ( cm . cmap_d ) / 2 ) , ncols = 1 , figsize = ( 6 , 12 ) ) ...
Make plot of colormaps and labels like in the matplotlib gallery .
248,020
def wrap_viscm ( cmap , dpi = 100 , saveplot = False ) : from viscm import viscm viscm ( cmap ) fig = plt . gcf ( ) fig . set_size_inches ( 22 , 10 ) plt . show ( ) if saveplot : fig . savefig ( 'figures/eval_' + cmap . name + '.png' , bbox_inches = 'tight' , dpi = dpi ) fig . savefig ( 'figures/eval_' + cmap . name + ...
Evaluate goodness of colormap using perceptual deltas .
248,021
def quick_plot ( cmap , fname = None , fig = None , ax = None , N = 10 ) : x = np . linspace ( 0 , 10 , N ) X , _ = np . meshgrid ( x , x ) if ax is None : fig = plt . figure ( ) ax = fig . add_subplot ( 111 ) mappable = ax . pcolor ( X , cmap = cmap ) ax . set_title ( cmap . name , fontsize = 14 ) ax . set_xticks ( [ ...
Show quick test of a colormap .
248,022
def print_colormaps ( cmaps , N = 256 , returnrgb = True , savefiles = False ) : rgb = [ ] for cmap in cmaps : rgbtemp = cmap ( np . linspace ( 0 , 1 , N ) ) [ np . newaxis , : , : 3 ] [ 0 ] if savefiles : np . savetxt ( cmap . name + '-rgb.txt' , rgbtemp ) rgb . append ( rgbtemp ) if returnrgb : return rgb
Print colormaps in 256 RGB colors to text files .
248,023
def cmap ( rgbin , N = 256 ) : if not isinstance ( rgbin [ 0 ] , _string_types ) : if rgbin . max ( ) > 1 : rgbin = rgbin / 256. cmap = mpl . colors . LinearSegmentedColormap . from_list ( 'mycmap' , rgbin , N = N ) return cmap
Input an array of rgb values to generate a colormap .
248,024
def lighten ( cmapin , alpha ) : return cmap ( cmapin ( np . linspace ( 0 , 1 , cmapin . N ) , alpha ) )
Lighten a colormap by adding alpha < 1 .
248,025
def crop_by_percent ( cmap , per , which = 'both' , N = None ) : if which == 'both' : vmin = - 100 vmax = 100 pivot = 0 dmax = per elif which == 'min' : vmax = 10 pivot = 5 vmin = ( 0 + per / 100 ) * 2 * pivot dmax = None elif which == 'max' : vmin = 0 pivot = 5 vmax = ( 1 - per / 100 ) * 2 * pivot dmax = None newcmap ...
Crop end or ends of a colormap by per percent .
248,026
def _premium ( fn ) : @ _functools . wraps ( fn ) def _fn ( self , * args , ** kwargs ) : if self . _lite : raise RuntimeError ( 'Premium API not available in lite access.' ) return fn ( self , * args , ** kwargs ) return _fn
Premium decorator for APIs that require premium access level .
248,027
def make_retrieveParameters ( offset = 1 , count = 100 , name = 'RS' , sort = 'D' ) : return _OrderedDict ( [ ( 'firstRecord' , offset ) , ( 'count' , count ) , ( 'sortField' , _OrderedDict ( [ ( 'name' , name ) , ( 'sort' , sort ) ] ) ) ] )
Create retrieve parameters dictionary to be used with APIs .
248,028
def connect ( self ) : if not self . _SID : self . _SID = self . _auth . service . authenticate ( ) print ( 'Authenticated (SID: %s)' % self . _SID ) self . _search . set_options ( headers = { 'Cookie' : 'SID="%s"' % self . _SID } ) self . _auth . options . headers . update ( { 'Cookie' : 'SID="%s"' % self . _SID } ) r...
Authenticate to WOS and set the SID cookie .
248,029
def close ( self ) : if self . _SID : self . _auth . service . closeSession ( ) self . _SID = None
The close operation loads the session if it is valid and then closes it and releases the session seat . All the session data are deleted and become invalid after the request is processed . The session ID can no longer be used in subsequent requests .
248,030
def search ( self , query , count = 5 , offset = 1 , editions = None , symbolicTimeSpan = None , timeSpan = None , retrieveParameters = None ) : return self . _search . service . search ( queryParameters = _OrderedDict ( [ ( 'databaseId' , 'WOS' ) , ( 'userQuery' , query ) , ( 'editions' , editions ) , ( 'symbolicTimeS...
The search operation submits a search query to the specified database edition and retrieves data . This operation returns a query ID that can be used in subsequent operations to retrieve more records .
248,031
def citedReferences ( self , uid , count = 100 , offset = 1 , retrieveParameters = None ) : return self . _search . service . citedReferences ( databaseId = 'WOS' , uid = uid , queryLanguage = 'en' , retrieveParameters = ( retrieveParameters or self . make_retrieveParameters ( offset , count ) ) )
The citedReferences operation returns references cited by an article identified by a unique identifier . You may specify only one identifier per request .
248,032
def citedReferencesRetrieve ( self , queryId , count = 100 , offset = 1 , retrieveParameters = None ) : return self . _search . service . citedReferencesRetrieve ( queryId = queryId , retrieveParameters = ( retrieveParameters or self . make_retrieveParameters ( offset , count ) ) )
The citedReferencesRetrieve operation submits a query returned by a previous citedReferences operation .
248,033
def single ( wosclient , wos_query , xml_query = None , count = 5 , offset = 1 ) : result = wosclient . search ( wos_query , count , offset ) xml = _re . sub ( ' xmlns="[^"]+"' , '' , result . records , count = 1 ) . encode ( 'utf-8' ) if xml_query : xml = _ET . fromstring ( xml ) return [ el . text for el in xml . fin...
Perform a single Web of Science query and then XML query the results .
248,034
def query ( wosclient , wos_query , xml_query = None , count = 5 , offset = 1 , limit = 100 ) : results = [ single ( wosclient , wos_query , xml_query , min ( limit , count - x + 1 ) , x ) for x in range ( offset , count + 1 , limit ) ] if xml_query : return [ el for res in results for el in res ] else : pattern = _re ...
Query Web of Science and XML query results with multiple requests .
248,035
def doi_to_wos ( wosclient , doi ) : results = query ( wosclient , 'DO="%s"' % doi , './REC/UID' , count = 1 ) return results [ 0 ] . lstrip ( 'WOS:' ) if results else None
Convert DOI to WOS identifier .
248,036
def sql_fingerprint ( query , hide_columns = True ) : parsed_query = parse ( query ) [ 0 ] sql_recursively_simplify ( parsed_query , hide_columns = hide_columns ) return str ( parsed_query )
Simplify a query taking away exact values and fields selected .
248,037
def match_keyword ( token , keywords ) : if not token : return False if not token . is_keyword : return False return token . value . upper ( ) in keywords
Checks if the given token represents one of the given keywords
248,038
def _is_group ( token ) : is_group = token . is_group if isinstance ( is_group , bool ) : return is_group else : return is_group ( )
sqlparse 0 . 2 . 2 changed it from a callable to a bool property
248,039
def sorted_names ( names ) : names = list ( names ) have_default = False if 'default' in names : names . remove ( 'default' ) have_default = True sorted_names = sorted ( names ) if have_default : sorted_names = [ 'default' ] + sorted_names return sorted_names
Sort a list of names but keep the word default first if it s there .
248,040
def record_diff ( old , new ) : return '\n' . join ( difflib . ndiff ( [ '%s: %s' % ( k , v ) for op in old for k , v in op . items ( ) ] , [ '%s: %s' % ( k , v ) for op in new for k , v in op . items ( ) ] , ) )
Generate a human - readable diff of two performance records .
248,041
def dequeue ( self , block = True ) : return self . queue . get ( block , self . queue_get_timeout )
Dequeue a record and return item .
248,042
def start ( self ) : self . _thread = t = threading . Thread ( target = self . _monitor ) t . setDaemon ( True ) t . start ( )
Start the listener .
248,043
def handle ( self , record ) : record = self . prepare ( record ) for handler in self . handlers : handler ( record )
Handle an item .
248,044
def _monitor ( self ) : err_msg = ( "invalid internal state:" " _stop_nowait can not be set if _stop is not set" ) assert self . _stop . isSet ( ) or not self . _stop_nowait . isSet ( ) , err_msg q = self . queue has_task_done = hasattr ( q , 'task_done' ) while not self . _stop . isSet ( ) : try : record = self . dequ...
Monitor the queue for items and ask the handler to deal with them .
248,045
def stop ( self , nowait = False ) : self . _stop . set ( ) if nowait : self . _stop_nowait . set ( ) self . queue . put_nowait ( self . _sentinel_item ) if ( self . _thread . isAlive ( ) and self . _thread is not threading . currentThread ( ) ) : self . _thread . join ( ) self . _thread = None
Stop the listener .
248,046
def terminate ( self , nowait = False ) : logger . debug ( "Acquiring lock for service termination" ) with self . lock : logger . debug ( "Terminating service" ) if not self . listener : logger . warning ( "Service already stopped." ) return self . listener . stop ( nowait ) try : if not nowait : self . _post_log_batch...
Finalize and stop service
248,047
def process_log ( self , ** log_item ) : logger . debug ( "Processing log item: %s" , log_item ) self . log_batch . append ( log_item ) if len ( self . log_batch ) >= self . log_batch_size : self . _post_log_batch ( )
Special handler for log messages .
248,048
def process_item ( self , item ) : logger . debug ( "Processing item: %s (queue size: %s)" , item , self . queue . qsize ( ) ) method , kwargs = item if method not in self . supported_methods : raise Error ( "Not expected service method: {}" . format ( method ) ) try : if method == "log" : self . process_log ( ** kwarg...
Main item handler .
248,049
def log ( self , time , message , level = None , attachment = None ) : logger . debug ( "log queued" ) args = { "time" : time , "message" : message , "level" : level , "attachment" : attachment , } self . queue . put_nowait ( ( "log" , args ) )
Logs a message with attachment .
248,050
def log_batch ( self , log_data ) : url = uri_join ( self . base_url , "log" ) attachments = [ ] for log_item in log_data : log_item [ "item_id" ] = self . stack [ - 1 ] attachment = log_item . get ( "attachment" , None ) if "attachment" in log_item : del log_item [ "attachment" ] if attachment : if not isinstance ( at...
Logs batch of messages with attachment .
248,051
def git_versions_from_keywords ( keywords , tag_prefix , verbose ) : if not keywords : raise NotThisMethod ( "no keywords at all, weird" ) date = keywords . get ( "date" ) if date is not None : date = date . strip ( ) . replace ( " " , "T" , 1 ) . replace ( " " , "" , 1 ) refnames = keywords [ "refnames" ] . strip ( ) ...
Get version information from git keywords .
248,052
def render_pep440_branch_based ( pieces ) : replacements = ( [ ' ' , '.' ] , [ '(' , '' ] , [ ')' , '' ] , [ '\\' , '.' ] , [ '/' , '.' ] ) branch_name = pieces . get ( 'branch' ) or '' if branch_name : for old , new in replacements : branch_name = branch_name . replace ( old , new ) else : branch_name = 'unknown_branc...
Build up version string with post - release local version identifier .
248,053
def render ( pieces , style ) : if pieces [ "error" ] : return { "version" : "unknown" , "full-revisionid" : pieces . get ( "long" ) , "dirty" : None , "error" : pieces [ "error" ] , "date" : None } if not style or style == "default" : style = "pep440" if style == "pep440" : rendered = render_pep440 ( pieces ) elif sty...
Render the given version pieces into the requested style .
248,054
def do_setup ( ) : root = get_root ( ) try : cfg = get_config_from_root ( root ) except ( EnvironmentError , configparser . NoSectionError , configparser . NoOptionError ) as e : if isinstance ( e , ( EnvironmentError , configparser . NoSectionError ) ) : print ( "Adding sample versioneer config to setup.cfg" , file = ...
Do main VCS - independent setup function for installing Versioneer .
248,055
def scan_setup_py ( ) : found = set ( ) setters = False errors = 0 with open ( "setup.py" , "r" ) as f : for line in f . readlines ( ) : if "import versioneer" in line : found . add ( "import" ) if "versioneer.get_cmdclass(" in line : found . add ( "cmdclass" ) if "versioneer.get_version()" in line : found . add ( "get...
Validate the contents of setup . py against Versioneer s expectations .
248,056
def read ( fname ) : file_path = os . path . join ( SETUP_DIRNAME , fname ) with codecs . open ( file_path , encoding = 'utf-8' ) as rfh : return rfh . read ( )
Read a file from the directory where setup . py resides
248,057
def func ( self , w , * args ) : x0 = args [ 0 ] x1 = args [ 1 ] n0 = x0 . shape [ 0 ] n1 = x1 . shape [ 0 ] n = max ( n0 , n1 ) * 10 idx0 = np . random . choice ( range ( n0 ) , size = n ) idx1 = np . random . choice ( range ( n1 ) , size = n ) b0 = np . ones ( ( n0 , 1 ) ) b1 = np . ones ( ( n1 , 1 ) ) i1 = self . i ...
Return the costs of the neural network for predictions .
248,058
def fprime ( self , w , * args ) : x0 = args [ 0 ] x1 = args [ 1 ] n0 = x0 . shape [ 0 ] n1 = x1 . shape [ 0 ] n = max ( n0 , n1 ) * 10 idx0 = np . random . choice ( range ( n0 ) , size = n ) idx1 = np . random . choice ( range ( n1 ) , size = n ) b = np . ones ( ( n , 1 ) ) i1 = self . i + 1 h = self . h h1 = h + 1 w2...
Return the derivatives of the cost function for predictions .
248,059
def _transform_col ( self , x , col ) : return norm . ppf ( self . ecdfs [ col ] ( x ) * .998 + .001 )
Normalize one numerical column .
248,060
def _get_label_encoder_and_max ( self , x ) : label_count = x . fillna ( NAN_INT ) . value_counts ( ) n_uniq = label_count . shape [ 0 ] label_count = label_count [ label_count >= self . min_obs ] n_uniq_new = label_count . shape [ 0 ] offset = 0 if n_uniq == n_uniq_new else 1 label_encoder = pd . Series ( np . arange ...
Return a mapping from values and its maximum of a column to integer labels .
248,061
def _transform_col ( self , x , i ) : return x . fillna ( NAN_INT ) . map ( self . label_encoders [ i ] ) . fillna ( 0 )
Encode one categorical column into labels .
248,062
def _transform_col ( self , x , i ) : labels = self . label_encoder . _transform_col ( x , i ) label_max = self . label_encoder . label_maxes [ i ] index = np . array ( range ( len ( labels ) ) ) i = index [ labels > 0 ] j = labels [ labels > 0 ] - 1 if len ( i ) > 0 : return sparse . coo_matrix ( ( np . ones_like ( i ...
Encode one categorical column into sparse matrix with one - hot - encoding .
248,063
def transform ( self , X ) : for i , col in enumerate ( X . columns ) : X_col = self . _transform_col ( X [ col ] , i ) if X_col is not None : if i == 0 : X_new = X_col else : X_new = sparse . hstack ( ( X_new , X_col ) ) logger . debug ( '{} . format ( col , self . label_encoder . label_maxes [ i ] ) ) return X_new
Encode categorical columns into sparse matrix with one - hot - encoding .
248,064
def predict ( self , x ) : if self . _is_leaf ( ) : d1 = self . predict_initialize [ 'count_dict' ] d2 = count_dict ( self . Y ) for key , value in d1 . iteritems ( ) : if key in d2 : d2 [ key ] += value else : d2 [ key ] = value return argmax ( d2 ) else : if self . criterion ( x ) : return self . right . predict ( x ...
Make prediction recursively . Use both the samples inside the current node and the statistics inherited from parent .
248,065
def netflix ( es , ps , e0 , l = .0001 ) : m = len ( es ) n = len ( ps [ 0 ] ) X = np . stack ( ps ) . T pTy = .5 * ( n * e0 ** 2 + ( X ** 2 ) . sum ( axis = 0 ) - n * np . array ( es ) ** 2 ) w = np . linalg . pinv ( X . T . dot ( X ) + l * n * np . eye ( m ) ) . dot ( pTy ) return X . dot ( w ) , w
Combine predictions with the optimal weights to minimize RMSE .
248,066
def save_data ( X , y , path ) : catalog = { '.csv' : save_csv , '.sps' : save_libsvm , '.h5' : save_hdf5 } ext = os . path . splitext ( path ) [ 1 ] func = catalog [ ext ] if y is None : y = np . zeros ( ( X . shape [ 0 ] , ) ) func ( X , y , path )
Save data as a CSV LibSVM or HDF5 file based on the file extension .
248,067
def save_csv ( X , y , path ) : if sparse . issparse ( X ) : X = X . todense ( ) np . savetxt ( path , np . hstack ( ( y . reshape ( ( - 1 , 1 ) ) , X ) ) , delimiter = ',' )
Save data as a CSV file .
248,068
def save_libsvm ( X , y , path ) : dump_svmlight_file ( X , y , path , zero_based = False )
Save data as a LibSVM file .
248,069
def save_hdf5 ( X , y , path ) : with h5py . File ( path , 'w' ) as f : is_sparse = 1 if sparse . issparse ( X ) else 0 f [ 'issparse' ] = is_sparse f [ 'target' ] = y if is_sparse : if not sparse . isspmatrix_csr ( X ) : X = X . tocsr ( ) f [ 'shape' ] = np . array ( X . shape ) f [ 'data' ] = X . data f [ 'indices' ]...
Save data as a HDF5 file .
248,070
def load_data ( path , dense = False ) : catalog = { '.csv' : load_csv , '.sps' : load_svmlight_file , '.h5' : load_hdf5 } ext = os . path . splitext ( path ) [ 1 ] func = catalog [ ext ] X , y = func ( path ) if dense and sparse . issparse ( X ) : X = X . todense ( ) return X , y
Load data from a CSV LibSVM or HDF5 file based on the file extension .
248,071
def load_csv ( path ) : with open ( path ) as f : line = f . readline ( ) . strip ( ) X = np . loadtxt ( path , delimiter = ',' , skiprows = 0 if is_number ( line . split ( ',' ) [ 0 ] ) else 1 ) y = np . array ( X [ : , 0 ] ) . flatten ( ) X = X [ : , 1 : ] return X , y
Load data from a CSV file .
248,072
def load_hdf5 ( path ) : with h5py . File ( path , 'r' ) as f : is_sparse = f [ 'issparse' ] [ ... ] if is_sparse : shape = tuple ( f [ 'shape' ] [ ... ] ) data = f [ 'data' ] [ ... ] indices = f [ 'indices' ] [ ... ] indptr = f [ 'indptr' ] [ ... ] X = sparse . csr_matrix ( ( data , indices , indptr ) , shape = shape ...
Load data from a HDF5 file .
248,073
def read_sps ( path ) : for line in open ( path ) : xs = line . rstrip ( ) . split ( ' ' ) yield xs [ 1 : ] , int ( xs [ 0 ] )
Read a LibSVM file line - by - line .
248,074
def gini ( y , p ) : assert y . shape == p . shape n_samples = y . shape [ 0 ] arr = np . array ( [ y , p ] ) . transpose ( ) true_order = arr [ arr [ : , 0 ] . argsort ( ) ] [ : : - 1 , 0 ] pred_order = arr [ arr [ : , 1 ] . argsort ( ) ] [ : : - 1 , 0 ] l_true = np . cumsum ( true_order ) / np . sum ( true_order ) l_...
Normalized Gini Coefficient .
248,075
def logloss ( y , p ) : p [ p < EPS ] = EPS p [ p > 1 - EPS ] = 1 - EPS return log_loss ( y , p )
Bounded log loss error .
248,076
def convert ( input_file_name , ** kwargs ) : delimiter = kwargs [ "delimiter" ] or "," quotechar = kwargs [ "quotechar" ] or "|" if six . PY2 : delimiter = delimiter . encode ( "utf-8" ) quotechar = quotechar . encode ( "utf-8" ) with open ( input_file_name , "rb" ) as input_file : reader = csv . reader ( input_file ,...
Convert CSV file to HTML table
248,077
def save ( file_name , content ) : with open ( file_name , "w" , encoding = "utf-8" ) as output_file : output_file . write ( content ) return output_file . name
Save content to a file
248,078
def serve ( content ) : temp_folder = tempfile . gettempdir ( ) temp_file_name = tempfile . gettempprefix ( ) + str ( uuid . uuid4 ( ) ) + ".html" temp_file_path = os . path . join ( temp_folder , temp_file_name ) save ( temp_file_path , content ) webbrowser . open ( "file://{}" . format ( temp_file_path ) ) try : whil...
Write content to a temp file and serve it in browser
248,079
def render_template ( table_headers , table_items , ** options ) : caption = options . get ( "caption" ) or "Table" display_length = options . get ( "display_length" ) or - 1 height = options . get ( "height" ) or "70vh" default_length_menu = [ - 1 , 10 , 25 , 50 ] pagination = options . get ( "pagination" ) virtual_sc...
Render Jinja2 template
248,080
def freeze_js ( html ) : matches = js_src_pattern . finditer ( html ) if not matches : return html for match in reversed ( tuple ( matches ) ) : file_name = match . group ( 1 ) file_path = os . path . join ( js_files_path , file_name ) with open ( file_path , "r" , encoding = "utf-8" ) as f : file_content = f . read ( ...
Freeze all JS assets to the rendered html itself .
248,081
def cli ( * args , ** kwargs ) : content = convert . convert ( kwargs [ "input_file" ] , ** kwargs ) if kwargs [ "serve" ] : convert . serve ( content ) elif kwargs [ "output_file" ] : if ( not kwargs [ "overwrite" ] and not prompt_overwrite ( kwargs [ "output_file" ] ) ) : raise click . Abort ( ) convert . save ( kwar...
CSVtoTable commandline utility .
248,082
def activate_retry ( request , activation_key , template_name = 'userena/activate_retry_success.html' , extra_context = None ) : if not userena_settings . USERENA_ACTIVATION_RETRY : return redirect ( reverse ( 'userena_activate' , args = ( activation_key , ) ) ) try : if UserenaSignup . objects . check_expired_activati...
Reissue a new activation_key for the user with the expired activation_key .
248,083
def disabled_account ( request , username , template_name , extra_context = None ) : user = get_object_or_404 ( get_user_model ( ) , username__iexact = username ) if user . is_active : raise Http404 if not extra_context : extra_context = dict ( ) extra_context [ 'viewed_user' ] = user extra_context [ 'profile' ] = get_...
Checks if the account is disabled if so returns the disabled account template .
248,084
def profile_list ( request , page = 1 , template_name = 'userena/profile_list.html' , paginate_by = 50 , extra_context = None , ** kwargs ) : warnings . warn ( "views.profile_list is deprecated. Use ProfileListView instead" , DeprecationWarning , stacklevel = 2 ) try : page = int ( request . GET . get ( 'page' , None )...
Returns a list of all profiles that are public .
248,085
def get_or_create ( self , um_from_user , um_to_user , message ) : created = False try : contact = self . get ( Q ( um_from_user = um_from_user , um_to_user = um_to_user ) | Q ( um_from_user = um_to_user , um_to_user = um_from_user ) ) except self . model . DoesNotExist : created = True contact = self . create ( um_fro...
Get or create a Contact
248,086
def update_contact ( self , um_from_user , um_to_user , message ) : contact , created = self . get_or_create ( um_from_user , um_to_user , message ) if not created : contact . latest_message = message contact . save ( ) return contact
Get or update a contacts information
248,087
def get_contacts_for ( self , user ) : contacts = self . filter ( Q ( um_from_user = user ) | Q ( um_to_user = user ) ) return contacts
Returns the contacts for this user .
248,088
def send_message ( self , sender , um_to_user_list , body ) : msg = self . model ( sender = sender , body = body ) msg . save ( ) msg . save_recipients ( um_to_user_list ) msg . update_contacts ( um_to_user_list ) signals . email_sent . send ( sender = None , msg = msg ) return msg
Send a message from a user to a user .
248,089
def get_conversation_between ( self , um_from_user , um_to_user ) : messages = self . filter ( Q ( sender = um_from_user , recipients = um_to_user , sender_deleted_at__isnull = True ) | Q ( sender = um_to_user , recipients = um_from_user , messagerecipient__deleted_at__isnull = True ) ) return messages
Returns a conversation between two users
248,090
def count_unread_messages_for ( self , user ) : unread_total = self . filter ( user = user , read_at__isnull = True , deleted_at__isnull = True ) . count ( ) return unread_total
Returns the amount of unread messages for this user
248,091
def count_unread_messages_between ( self , um_to_user , um_from_user ) : unread_total = self . filter ( message__sender = um_from_user , user = um_to_user , read_at__isnull = True , deleted_at__isnull = True ) . count ( ) return unread_total
Returns the amount of unread messages between two users
248,092
def reissue_activation ( self , activation_key ) : try : userena = self . get ( activation_key = activation_key ) except self . model . DoesNotExist : return False try : salt , new_activation_key = generate_sha1 ( userena . user . username ) userena . activation_key = new_activation_key userena . save ( using = self . ...
Creates a new activation_key resetting activation timeframe when users let the previous key expire .
248,093
def check_expired_activation ( self , activation_key ) : if SHA1_RE . search ( activation_key ) : userena = self . get ( activation_key = activation_key ) return userena . activation_key_expired ( ) raise self . model . DoesNotExist
Check if activation_key is still valid .
248,094
def check_permissions ( self ) : changed_permissions = [ ] changed_users = [ ] warnings = [ ] for model , perms in ASSIGNED_PERMISSIONS . items ( ) : if model == 'profile' : model_obj = get_profile_model ( ) else : model_obj = get_user_model ( ) model_content_type = ContentType . objects . get_for_model ( model_obj ) f...
Checks that all permissions are set correctly for the users .
248,095
def get_unread_message_count_for ( parser , token ) : try : tag_name , arg = token . contents . split ( None , 1 ) except ValueError : raise template . TemplateSyntaxError ( "%s tag requires arguments" % token . contents . split ( ) [ 0 ] ) m = re . search ( r'(.*?) as (\w+)' , arg ) if not m : raise template . Templat...
Returns the unread message count for a user .
248,096
def get_unread_message_count_between ( parser , token ) : try : tag_name , arg = token . contents . split ( None , 1 ) except ValueError : raise template . TemplateSyntaxError ( "%s tag requires arguments" % token . contents . split ( ) [ 0 ] ) m = re . search ( r'(.*?) and (.*?) as (\w+)' , arg ) if not m : raise temp...
Returns the unread message count between two users .
248,097
def upload_to_mugshot ( instance , filename ) : extension = filename . split ( '.' ) [ - 1 ] . lower ( ) salt , hash = generate_sha1 ( instance . pk ) path = userena_settings . USERENA_MUGSHOT_PATH % { 'username' : instance . user . username , 'id' : instance . user . id , 'date' : instance . user . date_joined , 'date...
Uploads a mugshot for a user to the USERENA_MUGSHOT_PATH and saving it under unique hash for the image . This is for privacy reasons so others can t just browse through the mugshot directory .
248,098
def message_compose ( request , recipients = None , compose_form = ComposeForm , success_url = None , template_name = "umessages/message_form.html" , recipient_filter = None , extra_context = None ) : initial_data = dict ( ) if recipients : username_list = [ r . strip ( ) for r in recipients . split ( "+" ) ] recipient...
Compose a new message
248,099
def message_remove ( request , undo = False ) : message_pks = request . POST . getlist ( 'message_pks' ) redirect_to = request . GET . get ( REDIRECT_FIELD_NAME , request . POST . get ( REDIRECT_FIELD_NAME , False ) ) if message_pks : valid_message_pk_list = set ( ) for pk in message_pks : try : valid_pk = int ( pk ) e...
A POST to remove messages .