idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
238,200
def _add_to_submit_args ( s ) : new_args = os . environ . get ( "PYSPARK_SUBMIT_ARGS" , "" ) + ( " %s" % s ) os . environ [ "PYSPARK_SUBMIT_ARGS" ] = new_args return new_args
Adds string s to the PYSPARK_SUBMIT_ARGS env var
238,201
def add_packages ( packages ) : if isinstance ( packages , str ) : packages = [ packages ] _add_to_submit_args ( "--packages " + "," . join ( packages ) + " pyspark-shell" )
Add external packages to the pyspark interpreter .
238,202
def add_jars ( jars ) : if isinstance ( jars , str ) : jars = [ jars ] _add_to_submit_args ( "--jars " + "," . join ( jars ) + " pyspark-shell" )
Add external jars to the pyspark interpreter .
238,203
def parse ( cls , expression ) : parsed = { "name" : None , "arguments" : [ ] , "options" : [ ] } if not expression . strip ( ) : raise ValueError ( "Console command signature is empty." ) expression = expression . replace ( os . linesep , "" ) matches = re . match ( r"[^\s]+" , expression ) if not matches : raise Valu...
Parse the given console command definition into a dict .
238,204
def _parameters ( cls , tokens ) : arguments = [ ] options = [ ] for token in tokens : if not token . startswith ( "--" ) : arguments . append ( cls . _parse_argument ( token ) ) else : options . append ( cls . _parse_option ( token ) ) return { "arguments" : arguments , "options" : options }
Extract all of the parameters from the tokens .
238,205
def _parse_argument ( cls , token ) : description = "" validator = None if " : " in token : token , description = tuple ( token . split ( " : " , 2 ) ) token = token . strip ( ) description = description . strip ( ) matches = re . match ( r"(.*)\((.*?)\)" , token ) if matches : token = matches . group ( 1 ) . strip ( )...
Parse an argument expression .
238,206
def _parse_option ( cls , token ) : description = "" validator = None if " : " in token : token , description = tuple ( token . split ( " : " , 2 ) ) token = token . strip ( ) description = description . strip ( ) matches = re . match ( r"(.*)\((.*?)\)" , token ) if matches : token = matches . group ( 1 ) . strip ( ) v...
Parse an option expression .
238,207
def add ( self , command ) : self . add_command ( command . config ) command . set_application ( self ) return self
Adds a command object .
238,208
def _configure_using_fluent_definition ( self ) : definition = Parser . parse ( self . signature ) self . _config . set_name ( definition [ "name" ] ) for name , flags , description , default in definition [ "arguments" ] : self . _config . add_argument ( name , flags , description , default ) for long_name , short_nam...
Configure the console command using a fluent definition .
238,209
def argument ( self , key = None ) : if key is None : return self . _args . arguments ( ) return self . _args . argument ( key )
Get the value of a command argument .
238,210
def option ( self , key = None ) : if key is None : return self . _args . options ( ) return self . _args . option ( key )
Get the value of a command option .
238,211
def confirm ( self , question , default = False , true_answer_regex = "(?i)^y" ) : return self . _io . confirm ( question , default , true_answer_regex )
Confirm a question with the user .
238,212
def ask ( self , question , default = None ) : if isinstance ( question , Question ) : return self . _io . ask_question ( question ) return self . _io . ask ( question , default )
Prompt the user for input .
238,213
def choice ( self , question , choices , default = None , attempts = None , multiple = False ) : question = ChoiceQuestion ( question , choices , default ) question . set_max_attempts ( attempts ) question . set_multi_select ( multiple ) return self . _io . ask_question ( question )
Give the user a single choice from an list of answers .
238,214
def create_question ( self , question , type = None , ** kwargs ) : if not type : return Question ( question , ** kwargs ) if type == "choice" : return ChoiceQuestion ( question , ** kwargs ) if type == "confirmation" : return ConfirmationQuestion ( question , ** kwargs )
Returns a Question of specified type .
238,215
def table ( self , header = None , rows = None , style = None ) : if style is not None : style = self . TABLE_STYLES [ style ] table = Table ( style ) if header : table . set_header_row ( header ) if rows : table . set_rows ( rows ) return table
Return a Table instance .
238,216
def render_table ( self , headers , rows , style = None ) : table = self . table ( headers , rows , style ) table . render ( self . _io )
Format input to textual table .
238,217
def line ( self , text , style = None , verbosity = None ) : if style : styled = "<%s>%s</>" % ( style , text ) else : styled = text self . _io . write_line ( styled , verbosity )
Write a string as information output .
238,218
def line_error ( self , text , style = None , verbosity = None ) : if style : styled = "<%s>%s</>" % ( style , text ) else : styled = text self . _io . error_line ( styled , verbosity )
Write a string as information output to stderr .
238,219
def progress_indicator ( self , fmt = None , interval = 100 , values = None ) : return ProgressIndicator ( self . io , fmt , interval , values )
Creates a new progress indicator .
238,220
def spin ( self , start_message , end_message , fmt = None , interval = 100 , values = None ) : spinner = ProgressIndicator ( self . io , fmt , interval , values ) return spinner . auto ( start_message , end_message )
Automatically spin a progress indicator .
238,221
def add_style ( self , name , fg = None , bg = None , options = None ) : style = Style ( name ) if fg is not None : style . fg ( fg ) if bg is not None : style . bg ( bg ) if options is not None : if "bold" in options : style . bold ( ) if "underline" in options : style . underlined ( ) self . _io . output . formatter ...
Adds a new style
238,222
def overwrite ( self , text , size = None ) : self . _io . overwrite ( text , size = size )
Overwrites the current line .
238,223
def get_github_hostname_user_repo_from_url ( url ) : parsed = parse . urlparse ( url ) if parsed . netloc == '' : host , sep , path = parsed . path . partition ( ":" ) if "@" in host : username , sep , host = host . partition ( "@" ) else : path = parsed . path [ 1 : ] . rstrip ( '/' ) host = parsed . netloc user , rep...
Return hostname user and repository to fork from .
238,224
def git_get_title_and_message ( begin , end ) : titles = git_get_log_titles ( begin , end ) title = "Pull request for " + end if len ( titles ) == 1 : title = titles [ 0 ] pr_template = find_pull_request_template ( ) if pr_template : message = get_pr_template_message ( pr_template ) else : if len ( titles ) == 1 : mess...
Get title and message summary for patches between 2 commits .
238,225
def validate_commit_index ( func ) : @ functools . wraps ( func ) def wrapped ( self , * args , ** kwargs ) : for not_applied in range ( self . log . last_applied + 1 , self . log . commit_index + 1 ) : self . state_machine . apply ( self . log [ not_applied ] [ 'command' ] ) self . log . last_applied += 1 try : self ....
Apply to State Machine everything up to commit index
238,226
async def execute_command ( self , command ) : self . apply_future = asyncio . Future ( loop = self . loop ) entry = self . log . write ( self . storage . term , command ) asyncio . ensure_future ( self . append_entries ( ) , loop = self . loop ) await self . apply_future
Write to log & send AppendEntries RPC
238,227
def start ( self ) : self . storage . update ( { 'term' : self . storage . term + 1 , 'voted_for' : self . id } ) self . vote_count = 1 self . request_vote ( ) self . election_timer . start ( )
Increment current term vote for herself & send vote requests
238,228
def on_receive_request_vote_response ( self , data ) : if data . get ( 'vote_granted' ) : self . vote_count += 1 if self . state . is_majority ( self . vote_count ) : self . state . to_leader ( )
Receives response for vote request . If the vote was granted then check if we got majority and may become Leader
238,229
def init_storage ( self ) : if not self . storage . exists ( 'term' ) : self . storage . update ( { 'term' : 0 , } ) self . storage . update ( { 'voted_for' : None } )
Set current term to zero upon initialization & voted_for to None
238,230
async def wait_for_election_success ( cls ) : if cls . leader is None : cls . leader_future = asyncio . Future ( loop = cls . loop ) await cls . leader_future
Await this function if your cluster must have a leader
238,231
async def wait_until_leader ( cls , node_id ) : if node_id is None : raise ValueError ( 'Node id can not be None!' ) if cls . get_leader ( ) != node_id : cls . wait_until_leader_id = node_id cls . wait_until_leader_future = asyncio . Future ( loop = cls . loop ) await cls . wait_until_leader_future cls . wait_until_lea...
Await this function if you want to do nothing until node_id becomes a leader
238,232
def declare ( full_table_name , definition , context ) : table_name = full_table_name . strip ( '`' ) . split ( '.' ) [ 1 ] if len ( table_name ) > MAX_TABLE_NAME_LENGTH : raise DataJointError ( 'Table name `{name}` exceeds the max length of {max_length}' . format ( name = table_name , max_length = MAX_TABLE_NAME_LENGT...
Parse declaration and create new SQL table accordingly .
238,233
def create_virtual_module ( module_name , schema_name , create_schema = False , create_tables = False , connection = None ) : module = types . ModuleType ( module_name ) _schema = Schema ( schema_name , create_schema = create_schema , create_tables = create_tables , connection = connection ) _schema . spawn_missing_cla...
Creates a python module with the given name from the name of a schema on the server and automatically adds classes to it corresponding to the tables in the schema .
238,234
def drop ( self , force = False ) : if not self . exists : logger . info ( "Schema named `{database}` does not exist. Doing nothing." . format ( database = self . database ) ) elif ( not config [ 'safemode' ] or force or user_choice ( "Proceed to delete entire schema `%s`?" % self . database , default = 'no' ) == 'yes'...
Drop the associated schema if it exists
238,235
def process_relation_class ( self , relation_class , context , assert_declared = False ) : relation_class . database = self . database relation_class . _connection = self . connection relation_class . _heading = Heading ( ) instance = relation_class ( ) is_declared = instance . is_declared if not is_declared : if not s...
assign schema properties to the relation class and declare the table
238,236
def declare ( self , context = None ) : try : sql , uses_external = declare ( self . full_table_name , self . definition , context ) if uses_external : sql = sql . format ( external_table = self . external_table . full_table_name ) self . connection . query ( sql ) except pymysql . OperationalError as error : if error ...
Use self . definition to declare the table in the schema .
238,237
def delete_quick ( self , get_count = False ) : query = 'DELETE FROM ' + self . full_table_name + self . where_clause self . connection . query ( query ) count = self . connection . query ( "SELECT ROW_COUNT()" ) . fetchone ( ) [ 0 ] if get_count else None self . _log ( query [ : 255 ] ) return count
Deletes the table without cascading and without user prompt . If this table has populated dependent tables this will fail .
238,238
def _update ( self , attrname , value = None ) : if len ( self ) != 1 : raise DataJointError ( 'Update is only allowed on one tuple at a time' ) if attrname not in self . heading : raise DataJointError ( 'Invalid attribute name' ) if attrname in self . heading . primary_key : raise DataJointError ( 'Cannot update a key...
Updates a field in an existing tuple . This is not a datajoyous operation and should not be used routinely . Relational database maintain referential integrity on the level of a tuple . Therefore the UPDATE operator can violate referential integrity . The datajoyous way to update information is to delete the entire tup...
238,239
def where_clause ( self ) : cond = self . _make_condition ( self . restriction ) return '' if cond is True else ' WHERE %s' % cond
convert self . restriction to the SQL WHERE clause
238,240
def preview ( self , limit = None , width = None ) : heading = self . heading rel = self . proj ( * heading . non_blobs ) if limit is None : limit = config [ 'display.limit' ] if width is None : width = config [ 'display.width' ] tuples = rel . fetch ( limit = limit + 1 , format = "array" ) has_more = len ( tuples ) > ...
returns a preview of the contents of the query .
238,241
def make_argument_subquery ( arg ) : return Subquery . create ( arg ) if isinstance ( arg , ( GroupBy , Projection ) ) or arg . restriction else arg
Decide when a Join argument needs to be wrapped in a subquery
238,242
def _need_subquery ( arg , attributes , named_attributes ) : if arg . heading . expressions or arg . distinct : return True restricting_attributes = arg . attributes_in_restriction ( ) return ( not restricting_attributes . issubset ( attributes ) or any ( v . strip ( ) in restricting_attributes for v in named_attribute...
Decide whether the projection argument needs to be wrapped in a subquery
238,243
def create ( cls , arg ) : obj = cls ( ) obj . _connection = arg . connection obj . _heading = arg . heading . make_subquery_heading ( ) obj . _arg = arg return obj
construct a subquery from arg
238,244
def user_choice ( prompt , choices = ( "yes" , "no" ) , default = None ) : assert default is None or default in choices choice_list = ', ' . join ( ( choice . title ( ) if choice == default else choice for choice in choices ) ) response = None while response not in choices : response = input ( prompt + ' [' + choice_li...
Prompts the user for confirmation . The default value if any is capitalized .
238,245
def to_dicts ( recarray ) : for rec in recarray : yield dict ( zip ( recarray . dtype . names , rec . tolist ( ) ) )
convert record array to a dictionaries
238,246
def keys ( self , ** kwargs ) : warnings . warn ( 'Use of `rel.fetch.keys()` notation is deprecated. ' 'Please use `rel.fetch("KEY")` or `rel.fetch(dj.key)` for equivalent result' , stacklevel = 2 ) yield from self . _expression . proj ( ) . fetch ( as_dict = True , ** kwargs )
DEPRECATED Iterator that returns primary keys as a sequence of dicts .
238,247
def key_hash ( key ) : hashed = hashlib . md5 ( ) for k , v in sorted ( key . items ( ) ) : hashed . update ( str ( v ) . encode ( ) ) return hashed . hexdigest ( )
32 - byte hash used for lookup of primary keys of jobs
238,248
def conn ( host = None , user = None , password = None , init_fun = None , reset = False ) : if not hasattr ( conn , 'connection' ) or reset : host = host if host is not None else config [ 'database.host' ] user = user if user is not None else config [ 'database.user' ] password = password if password is not None else ...
Returns a persistent connection object to be shared by multiple modules . If the connection is not yet established or reset = True a new connection is set up . If connection information is not provided it is taken from config which takes the information from dj_local_conf . json . If the password is not specified in th...
238,249
def connect ( self ) : with warnings . catch_warnings ( ) : warnings . filterwarnings ( 'ignore' , '.*deprecated.*' ) self . _conn = client . connect ( init_command = self . init_fun , sql_mode = "NO_ZERO_DATE,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO," "STRICT_ALL_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION" , ...
Connects to the database server .
238,250
def start_transaction ( self ) : if self . in_transaction : raise DataJointError ( "Nested connections are not supported." ) self . query ( 'START TRANSACTION WITH CONSISTENT SNAPSHOT' ) self . _in_transaction = True logger . info ( "Transaction started" )
Starts a transaction error .
238,251
def save_global ( self , verbose = False ) : self . save ( os . path . expanduser ( os . path . join ( '~' , GLOBALCONFIG ) ) , verbose )
saves the settings in the global config file
238,252
def todict ( self ) : return OrderedDict ( ( name , self [ i ] ) for i , name in enumerate ( self . _fields ) )
Convert namedtuple to dict .
238,253
def as_dtype ( self ) : return np . dtype ( dict ( names = self . names , formats = [ v . dtype for v in self . attributes . values ( ) ] ) )
represent the heading as a numpy dtype
238,254
def as_sql ( self ) : return ',' . join ( '`%s`' % name if self . attributes [ name ] . sql_expression is None else '%s as `%s`' % ( self . attributes [ name ] . sql_expression , name ) for name in self . names )
represent heading as SQL field list
238,255
def join ( self , other ) : return Heading ( [ self . attributes [ name ] . todict ( ) for name in self . primary_key ] + [ other . attributes [ name ] . todict ( ) for name in other . primary_key if name not in self . primary_key ] + [ self . attributes [ name ] . todict ( ) for name in self . dependent_attributes if ...
Join two headings into a new one . It assumes that self and other are headings that share no common dependent attributes .
238,256
def make_subquery_heading ( self ) : return Heading ( dict ( v . todict ( ) , sql_expression = None ) for v in self . attributes . values ( ) )
Create a new heading with removed attribute sql_expressions . Used by subqueries which resolve the sql_expressions .
238,257
def squeeze ( self , array ) : if not self . _squeeze : return array array = array . copy ( ) array = array . squeeze ( ) if array . ndim == 0 : array = array [ ( ) ] return array
Simplify the given array as much as possible - squeeze out all singleton dimensions and also convert a zero dimensional array into array scalar
238,258
def read_string ( self , advance = True ) : target = self . _blob . find ( b'\0' , self . pos ) assert target >= self . _pos data = self . _blob [ self . _pos : target ] if advance : self . _pos = target + 1 return data . decode ( 'ascii' )
Read a string terminated by null byte \ 0 . The returned string object is ASCII decoded and will not include the terminating null byte .
238,259
def read_value ( self , dtype = 'uint64' , count = 1 , advance = True ) : data = np . frombuffer ( self . _blob , dtype = dtype , count = count , offset = self . pos ) if advance : self . _pos += data . dtype . itemsize * data . size if count == 1 : data = data [ 0 ] return data
Read one or more scalars of the indicated dtype . Count specifies the number of scalars to be read in .
238,260
def put ( self , store , obj ) : spec = self . _get_store_spec ( store ) blob = pack ( obj ) blob_hash = long_hash ( blob ) + store [ len ( 'external-' ) : ] if spec [ 'protocol' ] == 'file' : folder = os . path . join ( spec [ 'location' ] , self . database ) full_path = os . path . join ( folder , blob_hash ) if not ...
put an object in external store
238,261
def get ( self , blob_hash ) : if blob_hash is None : return None store = blob_hash [ STORE_HASH_LENGTH : ] store = 'external' + ( '-' if store else '' ) + store cache_folder = config . get ( 'cache' , None ) blob = None if cache_folder : try : with open ( os . path . join ( cache_folder , blob_hash ) , 'rb' ) as f : b...
get an object from external store . Does not need to check whether it s in the table .
238,262
def delete_garbage ( self ) : self . connection . query ( "DELETE FROM `{db}`.`{tab}` WHERE " . format ( tab = self . table_name , db = self . database ) + " AND " . join ( 'hash NOT IN (SELECT {column_name} FROM {referencing_table})' . format ( ** ref ) for ref in self . references ) or "TRUE" ) print ( 'Deleted %d it...
Delete items that are no longer referenced . This operation is safe to perform at any time .
238,263
def clean_store ( self , store , display_progress = True ) : spec = self . _get_store_spec ( store ) progress = tqdm if display_progress else lambda x : x if spec [ 'protocol' ] == 'file' : folder = os . path . join ( spec [ 'location' ] , self . database ) delete_list = set ( os . listdir ( folder ) ) . difference ( s...
Clean unused data in an external storage repository from unused blobs . This must be performed after delete_garbage during low - usage periods to reduce risks of data loss .
238,264
def is_connection_error ( e ) : return ( isinstance ( e , err . InterfaceError ) and e . args [ 0 ] == "(0, '')" ) or ( isinstance ( e , err . OperationalError ) and e . args [ 0 ] in operation_error_codes . values ( ) )
Checks if error e pertains to a connection issue
238,265
def decompress ( data ) : d = Decompressor ( ) data = d . decompress ( data ) d . finish ( ) return data
Decompress a complete Brotli - compressed string .
238,266
def compress ( data , mode = DEFAULT_MODE , quality = lib . BROTLI_DEFAULT_QUALITY , lgwin = lib . BROTLI_DEFAULT_WINDOW , lgblock = 0 , dictionary = b'' ) : compressor = Compressor ( mode = mode , quality = quality , lgwin = lgwin , lgblock = lgblock , dictionary = dictionary ) compressed_data = compressor . _compress...
Compress a string using Brotli .
238,267
def _compress ( self , data , operation ) : original_output_size = int ( math . ceil ( len ( data ) + ( len ( data ) >> 2 ) + 10240 ) ) available_out = ffi . new ( "size_t *" ) available_out [ 0 ] = original_output_size output_buffer = ffi . new ( "uint8_t []" , available_out [ 0 ] ) ptr_to_output_buffer = ffi . new ( ...
This private method compresses some data in a given mode . This is used because almost all of the code uses the exact same setup . It wouldn t have to but it doesn t hurt at all .
238,268
def flush ( self ) : chunks = [ ] chunks . append ( self . _compress ( b'' , lib . BROTLI_OPERATION_FLUSH ) ) while lib . BrotliEncoderHasMoreOutput ( self . _encoder ) == lib . BROTLI_TRUE : chunks . append ( self . _compress ( b'' , lib . BROTLI_OPERATION_FLUSH ) ) return b'' . join ( chunks )
Flush the compressor . This will emit the remaining output data but will not destroy the compressor . It can be used for example to ensure that given chunks of content will decompress immediately .
238,269
def finish ( self ) : chunks = [ ] while lib . BrotliEncoderIsFinished ( self . _encoder ) == lib . BROTLI_FALSE : chunks . append ( self . _compress ( b'' , lib . BROTLI_OPERATION_FINISH ) ) return b'' . join ( chunks )
Finish the compressor . This will emit the remaining output data and transition the compressor to a completed state . The compressor cannot be used again after this point and must be replaced .
238,270
def decompress ( self , data ) : chunks = [ ] available_in = ffi . new ( "size_t *" , len ( data ) ) in_buffer = ffi . new ( "uint8_t[]" , data ) next_in = ffi . new ( "uint8_t **" , in_buffer ) while True : buffer_size = 5 * len ( data ) available_out = ffi . new ( "size_t *" , buffer_size ) out_buffer = ffi . new ( "...
Decompress part of a complete Brotli - compressed string .
238,271
def finish ( self ) : assert ( lib . BrotliDecoderHasMoreOutput ( self . _decoder ) == lib . BROTLI_FALSE ) if lib . BrotliDecoderIsFinished ( self . _decoder ) == lib . BROTLI_FALSE : raise Error ( "Decompression error: incomplete compressed stream." ) return b''
Finish the decompressor . As the decompressor decompresses eagerly this will never actually emit any data . However it will potentially throw errors if a truncated or damaged data stream has been used .
238,272
def hsv_to_rgb ( hsv ) : h , s , v = hsv if s == 0 : return ( v , v , v ) h /= 60.0 i = math . floor ( h ) f = h - i p = v * ( 1.0 - s ) q = v * ( 1.0 - s * f ) t = v * ( 1.0 - s * ( 1.0 - f ) ) if i == 0 : return ( v , t , p ) elif i == 1 : return ( q , v , p ) elif i == 2 : return ( p , v , t ) elif i == 3 : return (...
Converts a tuple of hue saturation value to a tuple of red green blue . Hue should be an angle from 0 . 0 to 359 . 0 . Saturation and value should be a value from 0 . 0 to 1 . 0 where saturation controls the intensity of the hue and value controls the brightness .
238,273
def set_cursor ( self , col , row ) : if row > self . _lines : row = self . _lines - 1 self . write8 ( LCD_SETDDRAMADDR | ( col + LCD_ROW_OFFSETS [ row ] ) )
Move the cursor to an explicit column and row position .
238,274
def enable_display ( self , enable ) : if enable : self . displaycontrol |= LCD_DISPLAYON else : self . displaycontrol &= ~ LCD_DISPLAYON self . write8 ( LCD_DISPLAYCONTROL | self . displaycontrol )
Enable or disable the display . Set enable to True to enable .
238,275
def show_cursor ( self , show ) : if show : self . displaycontrol |= LCD_CURSORON else : self . displaycontrol &= ~ LCD_CURSORON self . write8 ( LCD_DISPLAYCONTROL | self . displaycontrol )
Show or hide the cursor . Cursor is shown if show is True .
238,276
def blink ( self , blink ) : if blink : self . displaycontrol |= LCD_BLINKON else : self . displaycontrol &= ~ LCD_BLINKON self . write8 ( LCD_DISPLAYCONTROL | self . displaycontrol )
Turn on or off cursor blinking . Set blink to True to enable blinking .
238,277
def set_left_to_right ( self ) : self . displaymode |= LCD_ENTRYLEFT self . write8 ( LCD_ENTRYMODESET | self . displaymode )
Set text direction left to right .
238,278
def set_right_to_left ( self ) : self . displaymode &= ~ LCD_ENTRYLEFT self . write8 ( LCD_ENTRYMODESET | self . displaymode )
Set text direction right to left .
238,279
def autoscroll ( self , autoscroll ) : if autoscroll : self . displaymode |= LCD_ENTRYSHIFTINCREMENT else : self . displaymode &= ~ LCD_ENTRYSHIFTINCREMENT self . write8 ( LCD_ENTRYMODESET | self . displaymode )
Autoscroll will right justify text from the cursor if set True otherwise it will left justify the text .
238,280
def message ( self , text ) : line = 0 for char in text : if char == '\n' : line += 1 col = 0 if self . displaymode & LCD_ENTRYLEFT > 0 else self . _cols - 1 self . set_cursor ( col , line ) else : self . write8 ( ord ( char ) , True )
Write text to display . Note that text can include newlines .
238,281
def findExp ( self , data ) : temp = [ ] for r in self . reg_exp : try : temp += re . findall ( r , data ) except : print self . name print r print "CABOOOOM!" verifiedExp = [ ] for t in temp : if self . isValidExp ( t ) : if t not in verifiedExp : verifiedExp . append ( t ) return self . getResults ( verifiedExp )
Method to look for the current regular expression in the provided string .
238,282
def exportUsufy ( data , ext , fileH ) : if ext == "csv" : usufyToCsvExport ( data , fileH + "." + ext ) elif ext == "gml" : usufyToGmlExport ( data , fileH + "." + ext ) elif ext == "json" : usufyToJsonExport ( data , fileH + "." + ext ) elif ext == "ods" : usufyToOdsExport ( data , fileH + "." + ext ) elif ext == "pn...
Method that exports the different structures onto different formats .
238,283
def _generateTabularData ( res , oldTabularData = { } , isTerminal = False , canUnicode = True ) : def _grabbingNewHeader ( h ) : if h [ 0 ] == "@" : h = h . replace ( "@" , "_" ) elif "i3visio." in h : h = h . replace ( "i3visio." , "i3visio_" ) return h allowedInTerminal = [ "i3visio_alias" , "i3visio_uri" , "i3visio...
Method that recovers the values and columns from the current structure
238,284
def usufyToJsonExport ( d , fPath ) : oldData = [ ] try : with open ( fPath ) as iF : oldText = iF . read ( ) if oldText != "" : oldData = json . loads ( oldText ) except : pass jsonText = json . dumps ( oldData + d , indent = 2 , sort_keys = True ) with open ( fPath , "w" ) as oF : oF . write ( jsonText )
Workaround to export to a json file .
238,285
def usufyToTextExport ( d , fPath = None ) : if d == [ ] : return "+------------------+\n| No data found... |\n+------------------+" import pyexcel as pe import pyexcel . ext . text as text if fPath == None : isTerminal = True else : isTerminal = False try : oldData = get_data ( fPath ) except : oldData = { "OSRFramewo...
Workaround to export to a . txt file or to show the information .
238,286
def usufyToCsvExport ( d , fPath ) : from pyexcel_io import get_data try : oldData = { "OSRFramework" : get_data ( fPath ) } except : oldData = { "OSRFramework" : [ ] } tabularData = _generateTabularData ( d , oldData ) from pyexcel_io import save_data save_data ( fPath , tabularData [ "OSRFramework" ] )
Workaround to export to a CSV file .
238,287
def usufyToOdsExport ( d , fPath ) : from pyexcel_ods import get_data try : oldData = { "OSRFramework" : get_data ( fPath ) } except : oldData = { "OSRFramework" : [ ] } tabularData = _generateTabularData ( d , oldData ) from pyexcel_ods import save_data save_data ( fPath , tabularData )
Workaround to export to a . ods file .
238,288
def usufyToXlsExport ( d , fPath ) : from pyexcel_xls import get_data try : oldData = { "OSRFramework" : get_data ( fPath ) } except : oldData = { "OSRFramework" : [ ] } tabularData = _generateTabularData ( d , oldData ) from pyexcel_xls import save_data save_data ( fPath , tabularData )
Workaround to export to a . xls file .
238,289
def usufyToXlsxExport ( d , fPath ) : from pyexcel_xlsx import get_data try : oldData = { "OSRFramework" : get_data ( fPath ) } except : oldData = { "OSRFramework" : [ ] } tabularData = _generateTabularData ( d , oldData ) from pyexcel_xlsx import save_data save_data ( fPath , tabularData )
Workaround to export to a . xlsx file .
238,290
def _generateGraphData ( data , oldData = nx . Graph ( ) ) : def _addNewNode ( ent , g ) : try : label = unicode ( ent [ "value" ] ) except UnicodeEncodeError as e : label = str ( ent [ "value" ] ) g . add_node ( label ) g . node [ label ] [ "type" ] = ent [ "type" ] return label def _processAttributes ( elems , g ) : ...
Processing the data from i3visio structures to generate nodes and edges
238,291
def usufyToGmlExport ( d , fPath ) : try : oldData = nx . read_gml ( fPath ) except UnicodeDecodeError as e : print ( "UnicodeDecodeError:\t" + str ( e ) ) print ( "Something went wrong when reading the .gml file relating to the decoding of UNICODE." ) import time as time fPath += "_" + str ( time . time ( ) ) print ( ...
Workaround to export data to a . gml file .
238,292
def usufyToPngExport ( d , fPath ) : newGraph = _generateGraphData ( d ) import matplotlib . pyplot as plt nx . draw ( newGraph ) plt . savefig ( fPath )
Workaround to export to a png file .
238,293
def fileToMD5 ( filename , block_size = 256 * 128 , binary = False ) : md5 = hashlib . md5 ( ) with open ( filename , 'rb' ) as f : for chunk in iter ( lambda : f . read ( block_size ) , b'' ) : md5 . update ( chunk ) if not binary : return md5 . hexdigest ( ) return md5 . digest ( )
A function that calculates the MD5 hash of a file .
238,294
def getCurrentStrDatetime ( ) : i = datetime . datetime . now ( ) strTime = "%s-%s-%s_%sh%sm" % ( i . year , i . month , i . day , i . hour , i . minute ) return strTime
Generating the current Datetime with a given format
238,295
def getFilesFromAFolder ( path ) : from os import listdir from os . path import isfile , join onlyFiles = [ ] for f in listdir ( path ) : if isfile ( join ( path , f ) ) : onlyFiles . append ( f ) return onlyFiles
Getting all the files in a folder .
238,296
def urisToBrowser ( uris = [ ] , autoraise = True ) : savout1 = os . dup ( 1 ) savout2 = os . dup ( 2 ) os . close ( 1 ) os . close ( 2 ) os . open ( os . devnull , os . O_RDWR ) try : for uri in uris : if ".onion" in uri : wb . open ( uri . replace ( ".onion" , ".onion.city" ) , new = 2 , autoraise = autoraise ) else ...
Method that launches the URI in the default browser of the system
238,297
def openResultsInBrowser ( res ) : print ( emphasis ( "\n\tOpening URIs in the default web browser..." ) ) urisToBrowser ( [ "https://github.com/i3visio/osrframework" ] , autoraise = False ) time . sleep ( 2 ) uris = [ ] for r in res : for att in r [ "attributes" ] : if att [ "type" ] == "i3visio.uri" : uris . append (...
Method that collects the URI from a list of entities and opens them
238,298
def colorize ( text , messageType = None ) : formattedText = str ( text ) if "ERROR" in messageType : formattedText = colorama . Fore . RED + formattedText elif "WARNING" in messageType : formattedText = colorama . Fore . YELLOW + formattedText elif "SUCCESS" in messageType : formattedText = colorama . Fore . GREEN + f...
Function that colorizes a message .
238,299
def showLicense ( ) : print ( "Trying to recover the contents of the license...\n" ) try : text = urllib . urlopen ( LICENSE_URL ) . read ( ) print ( "License retrieved from " + emphasis ( LICENSE_URL ) + "." ) raw_input ( "\n\tPress " + emphasis ( "<ENTER>" ) + " to print it.\n" ) print ( text ) except : print ( warni...
Method that prints the license if requested .