query
stringlengths
5
1.23k
positive
stringlengths
53
15.2k
id_
int64
0
252k
task_name
stringlengths
87
242
negative
listlengths
20
553
Set - up for the rectangularly - gridded superposition of analytical solutions method for solving flexure
def SAS ( self ) : if self . x is None : self . x = np . arange ( self . dx / 2. , self . dx * self . qs . shape [ 0 ] , self . dx ) if self . filename : # Define the (scalar) elastic thickness self . Te = self . configGet ( "float" , "input" , "ElasticThickness" ) # Define a stress-based qs = q0 self . qs = self . q0 . copy ( ) # Remove self.q0 to avoid issues with multiply-defined inputs # q0 is the parsable input to either a qs grid or contains (x,(y),q) del self . q0 if self . dimension == 2 : if self . y is None : self . y = np . arange ( self . dy / 2. , self . dy * self . qs . shape [ 0 ] , self . dy ) # Define a stress-based qs = q0 # But only if the latter has not already been defined # (e.g., by the getters and setters) try : self . qs except : self . qs = self . q0 . copy ( ) # Remove self.q0 to avoid issues with multiply-defined inputs # q0 is the parsable input to either a qs grid or contains (x,(y),q) del self . q0 from scipy . special import kei
1,600
https://github.com/awickert/gFlex/blob/3ac32249375b0f8d342a142585d86ea4d905a5a0/gflex/base.py#L1017-L1045
[ "def", "permutation_entropy", "(", "x", ",", "n", ",", "tau", ")", ":", "PeSeq", "=", "[", "]", "Em", "=", "embed_seq", "(", "x", ",", "tau", ",", "n", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "Em", ")", ")", ":", "r", "=", "[", "]", "z", "=", "[", "]", "for", "j", "in", "range", "(", "0", ",", "len", "(", "Em", "[", "i", "]", ")", ")", ":", "z", ".", "append", "(", "Em", "[", "i", "]", "[", "j", "]", ")", "for", "j", "in", "range", "(", "0", ",", "len", "(", "Em", "[", "i", "]", ")", ")", ":", "z", ".", "sort", "(", ")", "r", ".", "append", "(", "z", ".", "index", "(", "Em", "[", "i", "]", "[", "j", "]", ")", ")", "z", "[", "z", ".", "index", "(", "Em", "[", "i", "]", "[", "j", "]", ")", "]", "=", "-", "1", "PeSeq", ".", "append", "(", "r", ")", "RankMat", "=", "[", "]", "while", "len", "(", "PeSeq", ")", ">", "0", ":", "RankMat", ".", "append", "(", "PeSeq", ".", "count", "(", "PeSeq", "[", "0", "]", ")", ")", "x", "=", "PeSeq", "[", "0", "]", "for", "j", "in", "range", "(", "0", ",", "PeSeq", ".", "count", "(", "PeSeq", "[", "0", "]", ")", ")", ":", "PeSeq", ".", "pop", "(", "PeSeq", ".", "index", "(", "x", ")", ")", "RankMat", "=", "numpy", ".", "array", "(", "RankMat", ")", "RankMat", "=", "numpy", ".", "true_divide", "(", "RankMat", ",", "RankMat", ".", "sum", "(", ")", ")", "EntropyMat", "=", "numpy", ".", "multiply", "(", "numpy", ".", "log2", "(", "RankMat", ")", ",", "RankMat", ")", "PE", "=", "-", "1", "*", "EntropyMat", ".", "sum", "(", ")", "return", "PE" ]
Set - up for the ungridded superposition of analytical solutions method for solving flexure
def SAS_NG ( self ) : if self . filename : # Define the (scalar) elastic thickness self . Te = self . configGet ( "float" , "input" , "ElasticThickness" ) # See if it wants to be run in lat/lon # Could put under in 2D if-statement, but could imagine an eventual desire # to change this and have 1D lat/lon profiles as well. # So while the options will be under "numerical2D", this place here will # remain held for an eventual future. self . latlon = self . configGet ( "string" , "numerical2D" , "latlon" , optional = True ) self . PlanetaryRadius = self . configGet ( "float" , "numerical2D" , "PlanetaryRadius" , optional = True ) if self . dimension == 2 : from scipy . special import kei # Parse out input q0 into variables of imoprtance for solution if self . dimension == 1 : try : # If these have already been set, e.g., by getters/setters, great! self . x self . q except : # Using [x, y, w] configuration file if self . q0 . shape [ 1 ] == 2 : self . x = self . q0 [ : , 0 ] self . q = self . q0 [ : , 1 ] else : sys . exit ( "For 1D (ungridded) SAS_NG configuration file, need [x,w] array. Your dimensions are: " + str ( self . q0 . shape ) ) else : try : # If these have already been set, e.g., by getters/setters, great! self . x self . u self . q except : # Using [x, y, w] configuration file if self . q0 . shape [ 1 ] == 3 : self . x = self . q0 [ : , 0 ] self . y = self . q0 [ : , 1 ] self . q = self . q0 [ : , 2 ] else : sys . exit ( "For 2D (ungridded) SAS_NG configuration file, need [x,y,w] array. Your dimensions are: " + str ( self . q0 . shape ) ) # x, y are in absolute coordinates. Create a local grid reference to # these. This local grid, which starts at (0,0), is defined just so that # we have a way of running the model without defined real-world # coordinates self . x = self . x if self . dimension == 2 : self . y = self . y # Remove self.q0 to avoid issues with multiply-defined inputs # q0 is the parsable input to either a qs grid or contains (x,(y),q) del self . q0 # Check if a seperate output set of x,y points has been defined # otherwise, set those values to None # First, try to load the arrays try : self . xw except : try : self . xw = self . configGet ( 'string' , "input" , "xw" , optional = True ) if self . xw == '' : self . xw = None except : self . xw = None # If strings, load arrays if type ( self . xw ) == str : self . xw = self . loadFile ( self . xw ) if self . dimension == 2 : try : # already set by setter? self . yw except : try : self . yw = self . configGet ( 'string' , "input" , "yw" , optional = True ) if self . yw == '' : self . yw = None except : self . yw = None # At this point, can check if we have both None or both defined if ( self . xw is not None and self . yw is None ) or ( self . xw is None and self . yw is not None ) : sys . exit ( "SAS_NG output at specified points requires both xw and yw to be defined" ) # All right, now just finish defining if type ( self . yw ) == str : self . yw = self . loadFile ( self . yw ) elif self . yw is None : self . yw = self . y . copy ( ) if self . xw is None : self . xw = self . x . copy ( )
1,601
https://github.com/awickert/gFlex/blob/3ac32249375b0f8d342a142585d86ea4d905a5a0/gflex/base.py#L1047-L1138
[ "def", "write_to_datastore", "(", "self", ")", ":", "client", "=", "self", ".", "_datastore_client", "with", "client", ".", "no_transact_batch", "(", ")", "as", "client_batch", ":", "for", "batch_id", ",", "batch_data", "in", "iteritems", "(", "self", ".", "_data", ")", ":", "batch_key", "=", "client", ".", "key", "(", "self", ".", "_entity_kind_batches", ",", "batch_id", ")", "batch_entity", "=", "client", ".", "entity", "(", "batch_key", ")", "for", "k", ",", "v", "in", "iteritems", "(", "batch_data", ")", ":", "if", "k", "!=", "'images'", ":", "batch_entity", "[", "k", "]", "=", "v", "client_batch", ".", "put", "(", "batch_entity", ")", "self", ".", "_write_single_batch_images_internal", "(", "batch_id", ",", "client_batch", ")" ]
Computes the method resolution order using extended C3 linearization .
def _c3_mro ( cls , abcs = None ) : for i , base in enumerate ( reversed ( cls . __bases__ ) ) : if hasattr ( base , '__abstractmethods__' ) : boundary = len ( cls . __bases__ ) - i break # Bases up to the last explicit ABC are considered first. else : boundary = 0 abcs = list ( abcs ) if abcs else [ ] explicit_bases = list ( cls . __bases__ [ : boundary ] ) abstract_bases = [ ] other_bases = list ( cls . __bases__ [ boundary : ] ) for base in abcs : if issubclass ( cls , base ) and not any ( issubclass ( b , base ) for b in cls . __bases__ ) : # If *cls* is the class that introduces behaviour described by # an ABC *base*, insert said ABC to its MRO. abstract_bases . append ( base ) for base in abstract_bases : abcs . remove ( base ) explicit_c3_mros = [ _c3_mro ( base , abcs = abcs ) for base in explicit_bases ] abstract_c3_mros = [ _c3_mro ( base , abcs = abcs ) for base in abstract_bases ] other_c3_mros = [ _c3_mro ( base , abcs = abcs ) for base in other_bases ] return _c3_merge ( [ [ cls ] ] + explicit_c3_mros + abstract_c3_mros + other_c3_mros + [ explicit_bases ] + [ abstract_bases ] + [ other_bases ] )
1,602
https://github.com/bionikspoon/pureyaml/blob/784830b907ca14525c4cecdb6ae35306f6f8a877/pureyaml/_compat/singledispatch.py#L49-L88
[ "def", "set_clipboard", "(", "self", ",", "data", ",", "datatype", "=", "\"text\"", ")", ":", "error_log", "=", "[", "]", "if", "datatype", "==", "\"text\"", ":", "clip_data", "=", "wx", ".", "TextDataObject", "(", "text", "=", "data", ")", "elif", "datatype", "==", "\"bitmap\"", ":", "clip_data", "=", "wx", ".", "BitmapDataObject", "(", "bitmap", "=", "data", ")", "else", ":", "msg", "=", "_", "(", "\"Datatype {type} unknown\"", ")", ".", "format", "(", "type", "=", "datatype", ")", "raise", "ValueError", "(", "msg", ")", "if", "self", ".", "clipboard", ".", "Open", "(", ")", ":", "self", ".", "clipboard", ".", "SetData", "(", "clip_data", ")", "self", ".", "clipboard", ".", "Close", "(", ")", "else", ":", "wx", ".", "MessageBox", "(", "_", "(", "\"Can't open the clipboard\"", ")", ",", "_", "(", "\"Error\"", ")", ")", "return", "error_log" ]
Single - dispatch generic function decorator .
def singledispatch ( function ) : # noqa registry = { } dispatch_cache = WeakKeyDictionary ( ) def ns ( ) : pass ns . cache_token = None # noinspection PyIncorrectDocstring def dispatch ( cls ) : """generic_func.dispatch(cls) -> <function implementation> Runs the dispatch algorithm to return the best available implementation for the given *cls* registered on *generic_func*. """ if ns . cache_token is not None : current_token = get_cache_token ( ) if ns . cache_token != current_token : dispatch_cache . clear ( ) ns . cache_token = current_token try : impl = dispatch_cache [ cls ] except KeyError : try : impl = registry [ cls ] except KeyError : impl = _find_impl ( cls , registry ) dispatch_cache [ cls ] = impl return impl # noinspection PyIncorrectDocstring def register ( cls , func = None ) : """generic_func.register(cls, func) -> func Registers a new implementation for the given *cls* on a *generic_func*. """ if func is None : return lambda f : register ( cls , f ) registry [ cls ] = func if ns . cache_token is None and hasattr ( cls , '__abstractmethods__' ) : ns . cache_token = get_cache_token ( ) dispatch_cache . clear ( ) return func def wrapper ( * args , * * kw ) : return dispatch ( args [ 0 ] . __class__ ) ( * args , * * kw ) registry [ object ] = function wrapper . register = register wrapper . dispatch = dispatch wrapper . registry = MappingProxyType ( registry ) wrapper . _clear_cache = dispatch_cache . clear update_wrapper ( wrapper , function ) return wrapper
1,603
https://github.com/bionikspoon/pureyaml/blob/784830b907ca14525c4cecdb6ae35306f6f8a877/pureyaml/_compat/singledispatch.py#L170-L235
[ "def", "_init_libcrypto", "(", ")", ":", "libcrypto", "=", "_load_libcrypto", "(", ")", "try", ":", "libcrypto", ".", "OPENSSL_init_crypto", "(", ")", "except", "AttributeError", ":", "# Support for OpenSSL < 1.1 (OPENSSL_API_COMPAT < 0x10100000L)", "libcrypto", ".", "OPENSSL_no_config", "(", ")", "libcrypto", ".", "OPENSSL_add_all_algorithms_noconf", "(", ")", "libcrypto", ".", "RSA_new", ".", "argtypes", "=", "(", ")", "libcrypto", ".", "RSA_new", ".", "restype", "=", "c_void_p", "libcrypto", ".", "RSA_free", ".", "argtypes", "=", "(", "c_void_p", ",", ")", "libcrypto", ".", "RSA_size", ".", "argtype", "=", "(", "c_void_p", ")", "libcrypto", ".", "BIO_new_mem_buf", ".", "argtypes", "=", "(", "c_char_p", ",", "c_int", ")", "libcrypto", ".", "BIO_new_mem_buf", ".", "restype", "=", "c_void_p", "libcrypto", ".", "BIO_free", ".", "argtypes", "=", "(", "c_void_p", ",", ")", "libcrypto", ".", "PEM_read_bio_RSAPrivateKey", ".", "argtypes", "=", "(", "c_void_p", ",", "c_void_p", ",", "c_void_p", ",", "c_void_p", ")", "libcrypto", ".", "PEM_read_bio_RSAPrivateKey", ".", "restype", "=", "c_void_p", "libcrypto", ".", "PEM_read_bio_RSA_PUBKEY", ".", "argtypes", "=", "(", "c_void_p", ",", "c_void_p", ",", "c_void_p", ",", "c_void_p", ")", "libcrypto", ".", "PEM_read_bio_RSA_PUBKEY", ".", "restype", "=", "c_void_p", "libcrypto", ".", "RSA_private_encrypt", ".", "argtypes", "=", "(", "c_int", ",", "c_char_p", ",", "c_char_p", ",", "c_void_p", ",", "c_int", ")", "libcrypto", ".", "RSA_public_decrypt", ".", "argtypes", "=", "(", "c_int", ",", "c_char_p", ",", "c_char_p", ",", "c_void_p", ",", "c_int", ")", "return", "libcrypto" ]
Parses any supplied command - line args and provides help text .
def _parse_args ( self , args ) : parser = ArgumentParser ( description = "Runs pylint recursively on a directory" ) parser . add_argument ( "-v" , "--verbose" , dest = "verbose" , action = "store_true" , default = False , help = "Verbose mode (report which files were found for testing)." , ) parser . add_argument ( "--rcfile" , dest = "rcfile" , action = "store" , default = ".pylintrc" , help = "A relative or absolute path to your pylint rcfile. Defaults to\ `.pylintrc` at the current working directory" , ) parser . add_argument ( "-V" , "--version" , action = "version" , version = "%(prog)s ({0}) for Python {1}" . format ( __version__ , PYTHON_VERSION ) , ) options , _ = parser . parse_known_args ( args ) self . verbose = options . verbose if options . rcfile : if not os . path . isfile ( options . rcfile ) : options . rcfile = os . getcwd ( ) + "/" + options . rcfile self . rcfile = options . rcfile return options
1,604
https://github.com/MasterOdin/pylint_runner/blob/b8ec3324e568e172d38fc0b6fa6f5551b229de07/pylint_runner/main.py#L39-L78
[ "def", "get_inconsistent_fieldnames", "(", ")", ":", "field_name_list", "=", "[", "]", "for", "fieldset_title", ",", "fields_list", "in", "settings", ".", "CONFIG_FIELDSETS", ".", "items", "(", ")", ":", "for", "field_name", "in", "fields_list", ":", "field_name_list", ".", "append", "(", "field_name", ")", "if", "not", "field_name_list", ":", "return", "{", "}", "return", "set", "(", "set", "(", "settings", ".", "CONFIG", ".", "keys", "(", ")", ")", "-", "set", "(", "field_name_list", ")", ")" ]
Parse the ignores setting from the pylintrc file if available .
def _parse_ignores ( self ) : error_message = ( colorama . Fore . RED + "{} does not appear to be a valid pylintrc file" . format ( self . rcfile ) + colorama . Fore . RESET ) if not os . path . isfile ( self . rcfile ) : if not self . _is_using_default_rcfile ( ) : print ( error_message ) sys . exit ( 1 ) else : return config = configparser . ConfigParser ( ) try : config . read ( self . rcfile ) except configparser . MissingSectionHeaderError : print ( error_message ) sys . exit ( 1 ) if config . has_section ( "MASTER" ) and config . get ( "MASTER" , "ignore" ) : self . ignore_folders += config . get ( "MASTER" , "ignore" ) . split ( "," )
1,605
https://github.com/MasterOdin/pylint_runner/blob/b8ec3324e568e172d38fc0b6fa6f5551b229de07/pylint_runner/main.py#L80-L104
[ "def", "join_event_view", "(", "request", ",", "id", ")", ":", "event", "=", "get_object_or_404", "(", "Event", ",", "id", "=", "id", ")", "if", "request", ".", "method", "==", "\"POST\"", ":", "if", "not", "event", ".", "show_attending", ":", "return", "redirect", "(", "\"events\"", ")", "if", "\"attending\"", "in", "request", ".", "POST", ":", "attending", "=", "request", ".", "POST", ".", "get", "(", "\"attending\"", ")", "attending", "=", "(", "attending", "==", "\"true\"", ")", "if", "attending", ":", "event", ".", "attending", ".", "add", "(", "request", ".", "user", ")", "else", ":", "event", ".", "attending", ".", "remove", "(", "request", ".", "user", ")", "return", "redirect", "(", "\"events\"", ")", "context", "=", "{", "\"event\"", ":", "event", ",", "\"is_events_admin\"", ":", "request", ".", "user", ".", "has_admin_permission", "(", "'events'", ")", "}", "return", "render", "(", "request", ",", "\"events/join_event.html\"", ",", "context", ")" ]
Runs pylint on all python files in the current directory
def run ( self , output = None , error = None ) : pylint_output = output if output is not None else sys . stdout pylint_error = error if error is not None else sys . stderr savedout , savederr = sys . __stdout__ , sys . __stderr__ sys . stdout = pylint_output sys . stderr = pylint_error pylint_files = self . get_files_from_dir ( os . curdir ) self . _print_line ( "Using pylint " + colorama . Fore . RED + pylint . __version__ + colorama . Fore . RESET + " for python " + colorama . Fore . RED + PYTHON_VERSION + colorama . Fore . RESET ) self . _print_line ( "pylint running on the following files:" ) for pylint_file in pylint_files : # we need to recast this as a string, else pylint enters an endless recursion split_file = str ( pylint_file ) . split ( "/" ) split_file [ - 1 ] = colorama . Fore . CYAN + split_file [ - 1 ] + colorama . Fore . RESET pylint_file = "/" . join ( split_file ) self . _print_line ( "- " + pylint_file ) self . _print_line ( "----" ) if not self . _is_using_default_rcfile ( ) : self . args += [ "--rcfile={}" . format ( self . rcfile ) ] exit_kwarg = { "do_exit" : False } run = pylint . lint . Run ( self . args + pylint_files , * * exit_kwarg ) sys . stdout = savedout sys . stderr = savederr sys . exit ( run . linter . msg_status )
1,606
https://github.com/MasterOdin/pylint_runner/blob/b8ec3324e568e172d38fc0b6fa6f5551b229de07/pylint_runner/main.py#L145-L184
[ "def", "collect_rms", "(", "self", ",", "rms", ")", ":", "if", "self", ".", "_data", ":", "self", ".", "_data", "[", "'min'", "]", "=", "min", "(", "rms", ",", "self", ".", "_data", "[", "'min'", "]", ")", "self", ".", "_data", "[", "'max'", "]", "=", "max", "(", "rms", ",", "self", ".", "_data", "[", "'max'", "]", ")", "self", ".", "_data", "[", "'avg'", "]", "=", "float", "(", "rms", "+", "self", ".", "_data", "[", "'avg'", "]", ")", "/", "2", "else", ":", "self", ".", "_data", "[", "'min'", "]", "=", "rms", "self", ".", "_data", "[", "'max'", "]", "=", "rms", "self", ".", "_data", "[", "'avg'", "]", "=", "rms" ]
Decorator type check production rule output
def strict ( * types ) : def decorate ( func ) : @ wraps ( func ) def wrapper ( self , p ) : func ( self , p ) if not isinstance ( p [ 0 ] , types ) : raise YAMLStrictTypeError ( p [ 0 ] , types , func ) wrapper . co_firstlineno = func . __code__ . co_firstlineno return wrapper return decorate
1,607
https://github.com/bionikspoon/pureyaml/blob/784830b907ca14525c4cecdb6ae35306f6f8a877/pureyaml/grammar/utils.py#L11-L24
[ "def", "wrap", "(", "vtkdataset", ")", ":", "wrappers", "=", "{", "'vtkUnstructuredGrid'", ":", "vtki", ".", "UnstructuredGrid", ",", "'vtkRectilinearGrid'", ":", "vtki", ".", "RectilinearGrid", ",", "'vtkStructuredGrid'", ":", "vtki", ".", "StructuredGrid", ",", "'vtkPolyData'", ":", "vtki", ".", "PolyData", ",", "'vtkImageData'", ":", "vtki", ".", "UniformGrid", ",", "'vtkStructuredPoints'", ":", "vtki", ".", "UniformGrid", ",", "'vtkMultiBlockDataSet'", ":", "vtki", ".", "MultiBlock", ",", "}", "key", "=", "vtkdataset", ".", "GetClassName", "(", ")", "try", ":", "wrapped", "=", "wrappers", "[", "key", "]", "(", "vtkdataset", ")", "except", ":", "logging", ".", "warning", "(", "'VTK data type ({}) is not currently supported by vtki.'", ".", "format", "(", "key", ")", ")", "return", "vtkdataset", "# if not supported just passes the VTK data object", "return", "wrapped" ]
Get cursor position based on previous newline
def find_column ( t ) : pos = t . lexer . lexpos data = t . lexer . lexdata last_cr = data . rfind ( '\n' , 0 , pos ) if last_cr < 0 : last_cr = - 1 column = pos - last_cr return column
1,608
https://github.com/bionikspoon/pureyaml/blob/784830b907ca14525c4cecdb6ae35306f6f8a877/pureyaml/grammar/utils.py#L27-L35
[ "def", "set_USRdict", "(", "self", ",", "USRdict", "=", "{", "}", ")", ":", "self", ".", "_check_inputs", "(", "USRdict", "=", "USRdict", ")", "self", ".", "_USRdict", "=", "USRdict" ]
Context that prevents the computer from going to sleep .
def no_sleep ( ) : mode = power . ES . continuous | power . ES . system_required handle_nonzero_success ( power . SetThreadExecutionState ( mode ) ) try : yield finally : handle_nonzero_success ( power . SetThreadExecutionState ( power . ES . continuous ) )
1,609
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/power.py#L68-L77
[ "def", "bootstrap_unihan", "(", "metadata", ",", "options", "=", "{", "}", ")", ":", "options", "=", "merge_dict", "(", "UNIHAN_ETL_DEFAULT_OPTIONS", ".", "copy", "(", ")", ",", "options", ")", "p", "=", "unihan", ".", "Packager", "(", "options", ")", "p", ".", "download", "(", ")", "data", "=", "p", ".", "export", "(", ")", "table", "=", "create_unihan_table", "(", "UNIHAN_FIELDS", ",", "metadata", ")", "metadata", ".", "create_all", "(", ")", "metadata", ".", "bind", ".", "execute", "(", "table", ".", "insert", "(", ")", ",", "data", ")" ]
Install update and set up selfoss .
def selfoss ( reset_password = False ) : hostname = re . sub ( r'^[^@]+@' , '' , env . host ) # without username if any sitename = query_input ( question = '\nEnter site-name of Your trac web service' , default = flo ( 'selfoss.{hostname}' ) ) username = env . user site_dir = flo ( '/home/{username}/sites/{sitename}' ) checkout_latest_release_of_selfoss ( ) create_directory_structure ( site_dir ) restored = install_selfoss ( sitename , site_dir , username ) nginx_site_config ( username , sitename , hostname ) enable_php5_socket_file ( ) if not restored or reset_password : setup_selfoss_user ( username , sitename , site_dir ) print_msg ( '\n## reload nginx and restart php\n' ) run ( 'sudo service nginx reload' ) run ( 'sudo service php5-fpm restart' )
1,610
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabfile/setup/service/selfoss.py#L19-L54
[ "def", "insert", "(", "self", ",", "storagemodel", ")", "->", "StorageTableModel", ":", "modeldefinition", "=", "self", ".", "getmodeldefinition", "(", "storagemodel", ",", "True", ")", "try", ":", "modeldefinition", "[", "'tableservice'", "]", ".", "insert_or_replace_entity", "(", "modeldefinition", "[", "'tablename'", "]", ",", "storagemodel", ".", "entity", "(", ")", ")", "storagemodel", ".", "_exists", "=", "True", "except", "AzureMissingResourceHttpError", "as", "e", ":", "storagemodel", ".", "_exists", "=", "False", "log", ".", "debug", "(", "'can not insert or replace table entity: Table {}, PartitionKey {}, RowKey {} because {!s}'", ".", "format", "(", "modeldefinition", "[", "'tablename'", "]", ",", "storagemodel", ".", "getPartitionKey", "(", ")", ",", "storagemodel", ".", "getRowKey", "(", ")", ",", "e", ")", ")", "except", "Exception", "as", "e", ":", "storagemodel", ".", "_exists", "=", "False", "msg", "=", "'can not insert or replace table entity: Table {}, PartitionKey {}, RowKey {} because {!s}'", ".", "format", "(", "modeldefinition", "[", "'tablename'", "]", ",", "storagemodel", ".", "PartitionKey", ",", "storagemodel", ".", "RowKey", ",", "e", ")", "raise", "AzureStorageWrapException", "(", "msg", "=", "msg", ")", "finally", ":", "return", "storagemodel" ]
get file path
def get_cache_path ( filename ) : cwd = os . path . dirname ( os . path . realpath ( __file__ ) ) return os . path . join ( cwd , filename )
1,611
https://github.com/NearHuscarl/py-currency/blob/4e30426399872fd6bfaa4c752a91d67c2d7bf52c/currency/cache.py#L8-L11
[ "def", "console", "(", "self", ",", "console", ")", ":", "if", "console", "==", "self", ".", "_console", ":", "return", "if", "self", ".", "_console_type", "==", "\"vnc\"", "and", "console", "is", "not", "None", "and", "console", "<", "5900", ":", "raise", "NodeError", "(", "\"VNC console require a port superior or equal to 5900 currently it's {}\"", ".", "format", "(", "console", ")", ")", "if", "self", ".", "_console", ":", "self", ".", "_manager", ".", "port_manager", ".", "release_tcp_port", "(", "self", ".", "_console", ",", "self", ".", "_project", ")", "self", ".", "_console", "=", "None", "if", "console", "is", "not", "None", ":", "if", "self", ".", "console_type", "==", "\"vnc\"", ":", "self", ".", "_console", "=", "self", ".", "_manager", ".", "port_manager", ".", "reserve_tcp_port", "(", "console", ",", "self", ".", "_project", ",", "port_range_start", "=", "5900", ",", "port_range_end", "=", "6000", ")", "else", ":", "self", ".", "_console", "=", "self", ".", "_manager", ".", "port_manager", ".", "reserve_tcp_port", "(", "console", ",", "self", ".", "_project", ")", "log", ".", "info", "(", "\"{module}: '{name}' [{id}]: console port set to {port}\"", ".", "format", "(", "module", "=", "self", ".", "manager", ".", "module_name", ",", "name", "=", "self", ".", "name", ",", "id", "=", "self", ".", "id", ",", "port", "=", "console", ")", ")" ]
Get the current process token
def get_process_token ( ) : token = wintypes . HANDLE ( ) res = process . OpenProcessToken ( process . GetCurrentProcess ( ) , process . TOKEN_ALL_ACCESS , token ) if not res > 0 : raise RuntimeError ( "Couldn't get process token" ) return token
1,612
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/privilege.py#L11-L20
[ "def", "matrix", "(", "self", ",", "title", "=", "None", ")", ":", "if", "title", "is", "None", ":", "return", "javabridge", ".", "call", "(", "self", ".", "jobject", ",", "\"toMatrixString\"", ",", "\"()Ljava/lang/String;\"", ")", "else", ":", "return", "javabridge", ".", "call", "(", "self", ".", "jobject", ",", "\"toMatrixString\"", ",", "\"(Ljava/lang/String;)Ljava/lang/String;\"", ",", "title", ")" ]
Get the LUID for the SeCreateSymbolicLinkPrivilege
def get_symlink_luid ( ) : symlink_luid = privilege . LUID ( ) res = privilege . LookupPrivilegeValue ( None , "SeCreateSymbolicLinkPrivilege" , symlink_luid ) if not res > 0 : raise RuntimeError ( "Couldn't lookup privilege value" ) return symlink_luid
1,613
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/privilege.py#L23-L32
[ "def", "update_cors_configuration", "(", "self", ",", "enable_cors", "=", "True", ",", "allow_credentials", "=", "True", ",", "origins", "=", "None", ",", "overwrite_origins", "=", "False", ")", ":", "if", "origins", "is", "None", ":", "origins", "=", "[", "]", "cors_config", "=", "{", "'enable_cors'", ":", "enable_cors", ",", "'allow_credentials'", ":", "allow_credentials", ",", "'origins'", ":", "origins", "}", "if", "overwrite_origins", ":", "return", "self", ".", "_write_cors_configuration", "(", "cors_config", ")", "old_config", "=", "self", ".", "cors_configuration", "(", ")", "# update config values", "updated_config", "=", "old_config", ".", "copy", "(", ")", "updated_config", "[", "'enable_cors'", "]", "=", "cors_config", ".", "get", "(", "'enable_cors'", ")", "updated_config", "[", "'allow_credentials'", "]", "=", "cors_config", ".", "get", "(", "'allow_credentials'", ")", "if", "cors_config", ".", "get", "(", "'origins'", ")", "==", "[", "\"*\"", "]", ":", "updated_config", "[", "'origins'", "]", "=", "[", "\"*\"", "]", "elif", "old_config", ".", "get", "(", "'origins'", ")", "!=", "cors_config", ".", "get", "(", "'origins'", ")", ":", "new_origins", "=", "list", "(", "set", "(", "old_config", ".", "get", "(", "'origins'", ")", ")", ".", "union", "(", "set", "(", "cors_config", ".", "get", "(", "'origins'", ")", ")", ")", ")", "updated_config", "[", "'origins'", "]", "=", "new_origins", "return", "self", ".", "_write_cors_configuration", "(", "updated_config", ")" ]
Get all privileges associated with the current process .
def get_privilege_information ( ) : # first call with zero length to determine what size buffer we need return_length = wintypes . DWORD ( ) params = [ get_process_token ( ) , privilege . TOKEN_INFORMATION_CLASS . TokenPrivileges , None , 0 , return_length , ] res = privilege . GetTokenInformation ( * params ) # assume we now have the necessary length in return_length buffer = ctypes . create_string_buffer ( return_length . value ) params [ 2 ] = buffer params [ 3 ] = return_length . value res = privilege . GetTokenInformation ( * params ) assert res > 0 , "Error in second GetTokenInformation (%d)" % res privileges = ctypes . cast ( buffer , ctypes . POINTER ( privilege . TOKEN_PRIVILEGES ) ) . contents return privileges
1,614
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/privilege.py#L35-L63
[ "def", "delete_index", "(", "self", ")", ":", "es", "=", "self", ".", "_init_connection", "(", ")", "if", "es", ".", "indices", ".", "exists", "(", "index", "=", "self", ".", "index", ")", ":", "es", ".", "indices", ".", "delete", "(", "index", "=", "self", ".", "index", ")" ]
Try to assign the symlink privilege to the current process token . Return True if the assignment is successful .
def enable_symlink_privilege ( ) : # create a space in memory for a TOKEN_PRIVILEGES structure # with one element size = ctypes . sizeof ( privilege . TOKEN_PRIVILEGES ) size += ctypes . sizeof ( privilege . LUID_AND_ATTRIBUTES ) buffer = ctypes . create_string_buffer ( size ) tp = ctypes . cast ( buffer , ctypes . POINTER ( privilege . TOKEN_PRIVILEGES ) ) . contents tp . count = 1 tp . get_array ( ) [ 0 ] . enable ( ) tp . get_array ( ) [ 0 ] . LUID = get_symlink_luid ( ) token = get_process_token ( ) res = privilege . AdjustTokenPrivileges ( token , False , tp , 0 , None , None ) if res == 0 : raise RuntimeError ( "Error in AdjustTokenPrivileges" ) ERROR_NOT_ALL_ASSIGNED = 1300 return ctypes . windll . kernel32 . GetLastError ( ) != ERROR_NOT_ALL_ASSIGNED
1,615
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/privilege.py#L75-L95
[ "def", "from_data", "(", "cls", ",", "blob", ")", ":", "version", ",", "data", "=", "decompress_datablob", "(", "DATA_BLOB_MAGIC_RETRY", ",", "blob", ")", "if", "version", "==", "1", ":", "for", "clazz", "in", "cls", ".", "_all_subclasses", "(", ")", ":", "if", "clazz", ".", "__name__", "==", "data", "[", "\"_class_name\"", "]", ":", "return", "clazz", ".", "_from_data_v1", "(", "data", ")", "raise", "Exception", "(", "\"Invalid data blob data or version\"", ")" ]
Grant the create symlink privilege to who .
def grant_symlink_privilege ( who , machine = '' ) : flags = security . POLICY_CREATE_ACCOUNT | security . POLICY_LOOKUP_NAMES policy = OpenPolicy ( machine , flags ) return policy
1,616
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/privilege.py#L123-L131
[ "def", "_read_footer", "(", "file_obj", ")", ":", "footer_size", "=", "_get_footer_size", "(", "file_obj", ")", "if", "logger", ".", "isEnabledFor", "(", "logging", ".", "DEBUG", ")", ":", "logger", ".", "debug", "(", "\"Footer size in bytes: %s\"", ",", "footer_size", ")", "file_obj", ".", "seek", "(", "-", "(", "8", "+", "footer_size", ")", ",", "2", ")", "# seek to beginning of footer", "tin", "=", "TFileTransport", "(", "file_obj", ")", "pin", "=", "TCompactProtocolFactory", "(", ")", ".", "get_protocol", "(", "tin", ")", "fmd", "=", "parquet_thrift", ".", "FileMetaData", "(", ")", "fmd", ".", "read", "(", "pin", ")", "return", "fmd" ]
Recursively iterate through package_module and add every fabric task to the addon_module keeping the task hierarchy .
def add_tasks_r ( addon_module , package_module , package_name ) : module_dict = package_module . __dict__ for attr_name , attr_val in module_dict . items ( ) : if isinstance ( attr_val , fabric . tasks . WrappedCallableTask ) : addon_module . __dict__ [ attr_name ] = attr_val elif attr_name != package_name and isinstance ( attr_val , types . ModuleType ) and attr_val . __name__ . startswith ( 'fabsetup_' ) and attr_name . split ( '.' ) [ - 1 ] != package_name : submodule_name = flo ( '{addon_module.__name__}.{attr_name}' ) submodule = get_or_create_module_r ( submodule_name ) package_module = attr_val add_tasks_r ( submodule , package_module , package_name ) addon_module . __dict__ [ attr_name ] = submodule
1,617
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/addons.py#L50-L77
[ "def", "local_session", "(", "factory", ")", ":", "factory_region", "=", "getattr", "(", "factory", ",", "'region'", ",", "'global'", ")", "s", "=", "getattr", "(", "CONN_CACHE", ",", "factory_region", ",", "{", "}", ")", ".", "get", "(", "'session'", ")", "t", "=", "getattr", "(", "CONN_CACHE", ",", "factory_region", ",", "{", "}", ")", ".", "get", "(", "'time'", ")", "n", "=", "time", ".", "time", "(", ")", "if", "s", "is", "not", "None", "and", "t", "+", "(", "60", "*", "45", ")", ">", "n", ":", "return", "s", "s", "=", "factory", "(", ")", "setattr", "(", "CONN_CACHE", ",", "factory_region", ",", "{", "'session'", ":", "s", ",", "'time'", ":", "n", "}", ")", "return", "s" ]
Load an fabsetup addon given by package_name and hook it in the base task namespace username .
def load_addon ( username , package_name , _globals ) : addon_module = get_or_create_module_r ( username ) package_module = __import__ ( package_name ) add_tasks_r ( addon_module , package_module , package_name ) _globals . update ( { username : addon_module } ) del package_module del addon_module
1,618
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/addons.py#L80-L96
[ "def", "generate", "(", "self", ",", "*", "*", "options", ")", ":", "if", "options", ".", "get", "(", "'unsafe'", ",", "False", ")", ":", "return", "unsafe_url", "(", "*", "*", "options", ")", "else", ":", "return", "self", ".", "generate_new", "(", "options", ")" ]
Load all known fabsetup addons which are installed as pypi pip - packages .
def load_pip_addons ( _globals ) : for package_name in known_pip_addons : _ , username = package_username ( package_name ) try : load_addon ( username , package_name . replace ( '-' , '_' ) , _globals ) except ImportError : pass
1,619
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/addons.py#L99-L112
[ "def", "_DeleteClientStats", "(", "self", ",", "limit", ",", "retention_time", ",", "cursor", "=", "None", ")", ":", "cursor", ".", "execute", "(", "\"DELETE FROM client_stats WHERE timestamp < FROM_UNIXTIME(%s) LIMIT %s\"", ",", "[", "mysql_utils", ".", "RDFDatetimeToTimestamp", "(", "retention_time", ")", ",", "limit", "]", ")", "return", "cursor", ".", "rowcount" ]
r Find the DLL for a given library .
def find_lib ( lib ) : if isinstance ( lib , str ) : lib = getattr ( ctypes . windll , lib ) size = 1024 result = ctypes . create_unicode_buffer ( size ) library . GetModuleFileName ( lib . _handle , result , size ) return result . value
1,620
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/lib.py#L6-L21
[ "def", "get_experiment_time", "(", "port", ")", ":", "response", "=", "rest_get", "(", "experiment_url", "(", "port", ")", ",", "REST_TIME_OUT", ")", "if", "response", "and", "check_response", "(", "response", ")", ":", "content", "=", "convert_time_stamp_to_date", "(", "json", ".", "loads", "(", "response", ".", "text", ")", ")", "return", "content", ".", "get", "(", "'startTime'", ")", ",", "content", ".", "get", "(", "'endTime'", ")", "return", "None", ",", "None" ]
Get science metadata for a resource in XML + RDF format
def getScienceMetadataRDF ( self , pid ) : url = "{url_base}/scimeta/{pid}/" . format ( url_base = self . url_base , pid = pid ) r = self . _request ( 'GET' , url ) if r . status_code != 200 : if r . status_code == 403 : raise HydroShareNotAuthorized ( ( 'GET' , url ) ) elif r . status_code == 404 : raise HydroShareNotFound ( ( pid , ) ) else : raise HydroShareHTTPException ( ( url , 'GET' , r . status_code ) ) return str ( r . content )
1,621
https://github.com/hydroshare/hs_restclient/blob/9cd106238b512e01ecd3e33425fe48c13b7f63d5/hs_restclient/__init__.py#L245-L358
[ "def", "vb_destroy_machine", "(", "name", "=", "None", ",", "timeout", "=", "10000", ")", ":", "vbox", "=", "vb_get_box", "(", ")", "log", ".", "info", "(", "'Destroying machine %s'", ",", "name", ")", "machine", "=", "vbox", ".", "findMachine", "(", "name", ")", "files", "=", "machine", ".", "unregister", "(", "2", ")", "progress", "=", "machine", ".", "deleteConfig", "(", "files", ")", "progress", ".", "waitForCompletion", "(", "timeout", ")", "log", ".", "info", "(", "'Finished destroying machine %s'", ",", "name", ")" ]
Get a resource in BagIt format
def getResource ( self , pid , destination = None , unzip = False , wait_for_bag_creation = True ) : stream = self . _getBagStream ( pid , wait_for_bag_creation ) if destination : self . _storeBagOnFilesystem ( stream , pid , destination , unzip ) return None else : return stream
1,622
https://github.com/hydroshare/hs_restclient/blob/9cd106238b512e01ecd3e33425fe48c13b7f63d5/hs_restclient/__init__.py#L567-L594
[ "def", "get_active_token", "(", "self", ")", ":", "expire_time", "=", "self", ".", "store_handler", ".", "has_value", "(", "\"expires\"", ")", "access_token", "=", "self", ".", "store_handler", ".", "has_value", "(", "\"access_token\"", ")", "if", "expire_time", "and", "access_token", ":", "expire_time", "=", "self", ".", "store_handler", ".", "get_value", "(", "\"expires\"", ")", "if", "not", "datetime", ".", "now", "(", ")", "<", "datetime", ".", "fromtimestamp", "(", "float", "(", "expire_time", ")", ")", ":", "self", ".", "store_handler", ".", "delete_value", "(", "\"access_token\"", ")", "self", ".", "store_handler", ".", "delete_value", "(", "\"expires\"", ")", "logger", ".", "info", "(", "'Access token expired, going to get new token'", ")", "self", ".", "auth", "(", ")", "else", ":", "logger", ".", "info", "(", "'Access token noy expired yet'", ")", "else", ":", "self", ".", "auth", "(", ")", "return", "self", ".", "store_handler", ".", "get_value", "(", "\"access_token\"", ")" ]
Get the list of resource types supported by the HydroShare server
def getResourceTypes ( self ) : url = "{url_base}/resource/types" . format ( url_base = self . url_base ) r = self . _request ( 'GET' , url ) if r . status_code != 200 : raise HydroShareHTTPException ( ( url , 'GET' , r . status_code ) ) resource_types = r . json ( ) return set ( [ t [ 'resource_type' ] for t in resource_types ] )
1,623
https://github.com/hydroshare/hs_restclient/blob/9cd106238b512e01ecd3e33425fe48c13b7f63d5/hs_restclient/__init__.py#L668-L682
[ "def", "_log_error_and_abort", "(", "ret", ",", "obj", ")", ":", "ret", "[", "'result'", "]", "=", "False", "ret", "[", "'abort'", "]", "=", "True", "if", "'error'", "in", "obj", ":", "ret", "[", "'comment'", "]", "=", "'{0}'", ".", "format", "(", "obj", ".", "get", "(", "'error'", ")", ")", "return", "ret" ]
Create a new resource .
def createResource ( self , resource_type , title , resource_file = None , resource_filename = None , abstract = None , keywords = None , edit_users = None , view_users = None , edit_groups = None , view_groups = None , metadata = None , extra_metadata = None , progress_callback = None ) : url = "{url_base}/resource/" . format ( url_base = self . url_base ) close_fd = False if resource_type not in self . resource_types : raise HydroShareArgumentException ( "Resource type {0} is not among known resources: {1}" . format ( resource_type , ", " . join ( [ r for r in self . resource_types ] ) ) ) # Prepare request params = { 'resource_type' : resource_type , 'title' : title } if abstract : params [ 'abstract' ] = abstract if keywords : # Put keywords in a format that django-rest's serializer will understand for ( i , kw ) in enumerate ( keywords ) : key = "keywords[{index}]" . format ( index = i ) params [ key ] = kw if edit_users : params [ 'edit_users' ] = edit_users if view_users : params [ 'view_users' ] = view_users if edit_groups : params [ 'edit_groups' ] = edit_groups if view_groups : params [ 'view_groups' ] = view_groups if metadata : params [ 'metadata' ] = metadata if extra_metadata : params [ 'extra_metadata' ] = extra_metadata if resource_file : close_fd = self . _prepareFileForUpload ( params , resource_file , resource_filename ) encoder = MultipartEncoder ( params ) if progress_callback is None : progress_callback = default_progress_callback monitor = MultipartEncoderMonitor ( encoder , progress_callback ) r = self . _request ( 'POST' , url , data = monitor , headers = { 'Content-Type' : monitor . content_type } ) if close_fd : fd = params [ 'file' ] [ 1 ] fd . close ( ) if r . status_code != 201 : if r . status_code == 403 : raise HydroShareNotAuthorized ( ( 'POST' , url ) ) else : raise HydroShareHTTPException ( ( url , 'POST' , r . status_code , params ) ) response = r . json ( ) new_resource_id = response [ 'resource_id' ] return new_resource_id
1,624
https://github.com/hydroshare/hs_restclient/blob/9cd106238b512e01ecd3e33425fe48c13b7f63d5/hs_restclient/__init__.py#L684-L773
[ "def", "_purge_index", "(", "self", ",", "database_name", ",", "collection_name", "=", "None", ",", "index_name", "=", "None", ")", ":", "with", "self", ".", "__index_cache_lock", ":", "if", "not", "database_name", "in", "self", ".", "__index_cache", ":", "return", "if", "collection_name", "is", "None", ":", "del", "self", ".", "__index_cache", "[", "database_name", "]", "return", "if", "not", "collection_name", "in", "self", ".", "__index_cache", "[", "database_name", "]", ":", "return", "if", "index_name", "is", "None", ":", "del", "self", ".", "__index_cache", "[", "database_name", "]", "[", "collection_name", "]", "return", "if", "index_name", "in", "self", ".", "__index_cache", "[", "database_name", "]", "[", "collection_name", "]", ":", "del", "self", ".", "__index_cache", "[", "database_name", "]", "[", "collection_name", "]", "[", "index_name", "]" ]
Set access rules for a resource . Current only allows for setting the public or private setting .
def setAccessRules ( self , pid , public = False ) : url = "{url_base}/resource/accessRules/{pid}/" . format ( url_base = self . url_base , pid = pid ) params = { 'public' : public } r = self . _request ( 'PUT' , url , data = params ) if r . status_code != 200 : if r . status_code == 403 : raise HydroShareNotAuthorized ( ( 'PUT' , url ) ) elif r . status_code == 404 : raise HydroShareNotFound ( ( pid , ) ) else : raise HydroShareHTTPException ( ( url , 'PUT' , r . status_code , params ) ) resource = r . json ( ) assert ( resource [ 'resource_id' ] == pid ) return resource [ 'resource_id' ]
1,625
https://github.com/hydroshare/hs_restclient/blob/9cd106238b512e01ecd3e33425fe48c13b7f63d5/hs_restclient/__init__.py#L797-L819
[ "def", "create_chunked_body_end", "(", "trailers", "=", "None", ")", ":", "chunk", "=", "[", "]", "chunk", ".", "append", "(", "'0\\r\\n'", ")", "if", "trailers", ":", "for", "name", ",", "value", "in", "trailers", ":", "chunk", ".", "append", "(", "name", ")", "chunk", ".", "append", "(", "': '", ")", "chunk", ".", "append", "(", "value", ")", "chunk", ".", "append", "(", "'\\r\\n'", ")", "chunk", ".", "append", "(", "'\\r\\n'", ")", "return", "s2b", "(", "''", ".", "join", "(", "chunk", ")", ")" ]
Add a new file to an existing resource
def addResourceFile ( self , pid , resource_file , resource_filename = None , progress_callback = None ) : url = "{url_base}/resource/{pid}/files/" . format ( url_base = self . url_base , pid = pid ) params = { } close_fd = self . _prepareFileForUpload ( params , resource_file , resource_filename ) encoder = MultipartEncoder ( params ) if progress_callback is None : progress_callback = default_progress_callback monitor = MultipartEncoderMonitor ( encoder , progress_callback ) r = self . _request ( 'POST' , url , data = monitor , headers = { 'Content-Type' : monitor . content_type } ) if close_fd : fd = params [ 'file' ] [ 1 ] fd . close ( ) if r . status_code != 201 : if r . status_code == 403 : raise HydroShareNotAuthorized ( ( 'POST' , url ) ) elif r . status_code == 404 : raise HydroShareNotFound ( ( pid , ) ) else : raise HydroShareHTTPException ( ( url , 'POST' , r . status_code ) ) response = r . json ( ) # assert(response['resource_id'] == pid) return response
1,626
https://github.com/hydroshare/hs_restclient/blob/9cd106238b512e01ecd3e33425fe48c13b7f63d5/hs_restclient/__init__.py#L821-L870
[ "def", "get_battery_info", "(", "self", ")", "->", "dict", ":", "output", ",", "_", "=", "self", ".", "_execute", "(", "'-s'", ",", "self", ".", "device_sn", ",", "'shell'", ",", "'dumpsys'", ",", "'battery'", ")", "battery_status", "=", "re", ".", "split", "(", "'\\n |: '", ",", "output", "[", "33", ":", "]", ".", "strip", "(", ")", ")", "return", "dict", "(", "zip", "(", "battery_status", "[", ":", ":", "2", "]", ",", "battery_status", "[", "1", ":", ":", "2", "]", ")", ")" ]
Get a file within a resource .
def getResourceFile ( self , pid , filename , destination = None ) : url = "{url_base}/resource/{pid}/files/{filename}" . format ( url_base = self . url_base , pid = pid , filename = filename ) if destination : if not os . path . isdir ( destination ) : raise HydroShareArgumentException ( "{0} is not a directory." . format ( destination ) ) if not os . access ( destination , os . W_OK ) : raise HydroShareArgumentException ( "You do not have write permissions to directory '{0}'." . format ( destination ) ) r = self . _request ( 'GET' , url , stream = True ) if r . status_code != 200 : if r . status_code == 403 : raise HydroShareNotAuthorized ( ( 'GET' , url ) ) elif r . status_code == 404 : raise HydroShareNotFound ( ( pid , filename ) ) else : raise HydroShareHTTPException ( ( url , 'GET' , r . status_code ) ) if destination is None : return r . iter_content ( STREAM_CHUNK_SIZE ) else : filepath = os . path . join ( destination , filename ) with open ( filepath , 'wb' ) as fd : for chunk in r . iter_content ( STREAM_CHUNK_SIZE ) : fd . write ( chunk ) return filepath
1,627
https://github.com/hydroshare/hs_restclient/blob/9cd106238b512e01ecd3e33425fe48c13b7f63d5/hs_restclient/__init__.py#L872-L913
[ "def", "remove_device", "(", "self", ",", "device", ",", "id_override", "=", "None", ",", "type_override", "=", "None", ")", ":", "object_id", "=", "id_override", "or", "device", ".", "object_id", "(", ")", "object_type", "=", "type_override", "or", "device", ".", "object_type", "(", ")", "url_string", "=", "\"{}/{}s/{}\"", ".", "format", "(", "self", ".", "BASE_URL", ",", "object_type", ",", "object_id", ")", "try", ":", "arequest", "=", "requests", ".", "delete", "(", "url_string", ",", "headers", "=", "API_HEADERS", ")", "if", "arequest", ".", "status_code", "==", "204", ":", "return", "True", "_LOGGER", ".", "error", "(", "\"Failed to remove device. Status code: %s\"", ",", "arequest", ".", "status_code", ")", "return", "False", "except", "requests", ".", "exceptions", ".", "RequestException", ":", "_LOGGER", ".", "error", "(", "\"Failed to remove device.\"", ")", "return", "False" ]
Delete a resource file
def deleteResourceFile ( self , pid , filename ) : url = "{url_base}/resource/{pid}/files/{filename}" . format ( url_base = self . url_base , pid = pid , filename = filename ) r = self . _request ( 'DELETE' , url ) if r . status_code != 200 : if r . status_code == 403 : raise HydroShareNotAuthorized ( ( 'DELETE' , url ) ) elif r . status_code == 404 : raise HydroShareNotFound ( ( pid , filename ) ) else : raise HydroShareHTTPException ( ( url , 'DELETE' , r . status_code ) ) response = r . json ( ) assert ( response [ 'resource_id' ] == pid ) return response [ 'resource_id' ]
1,628
https://github.com/hydroshare/hs_restclient/blob/9cd106238b512e01ecd3e33425fe48c13b7f63d5/hs_restclient/__init__.py#L915-L944
[ "def", "parse_url", "(", "url", ")", ":", "parsed", "=", "url", "if", "not", "url", ".", "startswith", "(", "\"http://\"", ")", "and", "not", "url", ".", "startswith", "(", "\"https://\"", ")", ":", "# if url is like www.yahoo.com", "parsed", "=", "\"http://\"", "+", "parsed", "elif", "url", ".", "startswith", "(", "\"https://\"", ")", ":", "parsed", "=", "parsed", "[", "8", ":", "]", "parsed", "=", "\"http://\"", "+", "parsed", "index_hash", "=", "parsed", ".", "rfind", "(", "\"#\"", ")", "# remove trailing #", "index_slash", "=", "parsed", ".", "rfind", "(", "\"/\"", ")", "if", "index_hash", ">", "index_slash", ":", "parsed", "=", "parsed", "[", "0", ":", "index_hash", "]", "return", "parsed" ]
Get a listing of files within a resource .
def getResourceFileList ( self , pid ) : url = "{url_base}/resource/{pid}/files/" . format ( url_base = self . url_base , pid = pid ) return resultsListGenerator ( self , url )
1,629
https://github.com/hydroshare/hs_restclient/blob/9cd106238b512e01ecd3e33425fe48c13b7f63d5/hs_restclient/__init__.py#L946-L994
[ "def", "swo_set_emu_buffer_size", "(", "self", ",", "buf_size", ")", ":", "buf", "=", "ctypes", ".", "c_uint32", "(", "buf_size", ")", "res", "=", "self", ".", "_dll", ".", "JLINKARM_SWO_Control", "(", "enums", ".", "JLinkSWOCommands", ".", "SET_BUFFERSIZE_EMU", ",", "ctypes", ".", "byref", "(", "buf", ")", ")", "if", "res", "<", "0", ":", "raise", "errors", ".", "JLinkException", "(", "res", ")", "return", "None" ]
Get the decrypted value of an SSM parameter
def get_ssm_parameter ( parameter_name ) : try : response = boto3 . client ( 'ssm' ) . get_parameters ( Names = [ parameter_name ] , WithDecryption = True ) return response . get ( 'Parameters' , None ) [ 0 ] . get ( 'Value' , '' ) except Exception : pass return ''
1,630
https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/utility/get_ssm_parameter.py#L6-L26
[ "def", "share", "(", "self", ",", "group_id", ",", "group_access", ",", "expires_at", "=", "None", ",", "*", "*", "kwargs", ")", ":", "path", "=", "'/projects/%s/share'", "%", "self", ".", "get_id", "(", ")", "data", "=", "{", "'group_id'", ":", "group_id", ",", "'group_access'", ":", "group_access", ",", "'expires_at'", ":", "expires_at", "}", "self", ".", "manager", ".", "gitlab", ".", "http_post", "(", "path", ",", "post_data", "=", "data", ",", "*", "*", "kwargs", ")" ]
Install and set up powerline for vim bash tmux and i3 .
def powerline ( ) : bindings_dir , scripts_dir = install_upgrade_powerline ( ) set_up_powerline_fonts ( ) set_up_powerline_daemon ( scripts_dir ) powerline_for_vim ( bindings_dir ) powerline_for_bash_or_powerline_shell ( bindings_dir ) powerline_for_tmux ( bindings_dir ) powerline_for_i3 ( bindings_dir ) print ( '\nYou may have to reboot for make changes take effect' )
1,631
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabfile/setup/powerline.py#L16-L36
[ "def", "query_unbound_ong", "(", "self", ",", "base58_address", ":", "str", ")", "->", "int", ":", "contract_address", "=", "self", ".", "get_asset_address", "(", "'ont'", ")", "unbound_ong", "=", "self", ".", "__sdk", ".", "rpc", ".", "get_allowance", "(", "\"ong\"", ",", "Address", "(", "contract_address", ")", ".", "b58encode", "(", ")", ",", "base58_address", ")", "return", "int", "(", "unbound_ong", ")" ]
Returns the contents of the tag if the provided path consitutes the base of the current pages path .
def ifancestor ( parser , token ) : # Grab the contents between contents = parser . parse ( ( 'endifancestor' , ) ) parser . delete_first_token ( ) # If there is only one argument (2 including tag name) # parse it as a variable bits = token . split_contents ( ) if len ( bits ) == 2 : arg = parser . compile_filter ( bits [ 1 ] ) else : arg = None # Also pass all arguments to the original url tag url_node = url ( parser , token ) return AncestorNode ( url_node , arg = arg , contents = contents )
1,632
https://github.com/marcuswhybrow/django-lineage/blob/2bd18b54f721dd39bacf5fe5e7f07e7e99b75b5e/lineage/templatetags/lineage.py#L14-L54
[ "def", "register_keepalive", "(", "self", ",", "cmd", ",", "callback", ")", ":", "regid", "=", "random", ".", "random", "(", ")", "if", "self", ".", "_customkeepalives", "is", "None", ":", "self", ".", "_customkeepalives", "=", "{", "regid", ":", "(", "cmd", ",", "callback", ")", "}", "else", ":", "while", "regid", "in", "self", ".", "_customkeepalives", ":", "regid", "=", "random", ".", "random", "(", ")", "self", ".", "_customkeepalives", "[", "regid", "]", "=", "(", "cmd", ",", "callback", ")", "return", "regid" ]
Print ping exit statistics
def exit_statistics ( hostname , start_time , count_sent , count_received , min_time , avg_time , max_time , deviation ) : end_time = datetime . datetime . now ( ) duration = end_time - start_time duration_sec = float ( duration . seconds * 1000 ) duration_ms = float ( duration . microseconds / 1000 ) duration = duration_sec + duration_ms package_loss = 100 - ( ( float ( count_received ) / float ( count_sent ) ) * 100 ) print ( f'\b\b--- {hostname} ping statistics ---' ) try : print ( f'{count_sent} packages transmitted, {count_received} received, {package_loss}% package loss, time {duration}ms' ) except ZeroDivisionError : print ( f'{count_sent} packets transmitted, {count_received} received, 100% packet loss, time {duration}ms' ) print ( 'rtt min/avg/max/dev = %.2f/%.2f/%.2f/%.2f ms' % ( min_time . seconds * 1000 + float ( min_time . microseconds ) / 1000 , float ( avg_time ) / 1000 , max_time . seconds * 1000 + float ( max_time . microseconds ) / 1000 , float ( deviation ) ) )
1,633
https://github.com/yahoo/serviceping/blob/1f9df5ee5b3cba466426b1164262278472ba4977/serviceping/cli.py#L23-L45
[ "def", "initialize_schema", "(", "connection", ")", ":", "cursor", "=", "connection", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "\"PRAGMA application_id={}\"", ".", "format", "(", "_TENSORBOARD_APPLICATION_ID", ")", ")", "cursor", ".", "execute", "(", "\"PRAGMA user_version={}\"", ".", "format", "(", "_TENSORBOARD_USER_VERSION", ")", ")", "with", "connection", ":", "for", "statement", "in", "_SCHEMA_STATEMENTS", ":", "lines", "=", "statement", ".", "strip", "(", "'\\n'", ")", ".", "split", "(", "'\\n'", ")", "message", "=", "lines", "[", "0", "]", "+", "(", "'...'", "if", "len", "(", "lines", ")", ">", "1", "else", "''", ")", "logger", ".", "debug", "(", "'Running DB init statement: %s'", ",", "message", ")", "cursor", ".", "execute", "(", "statement", ")" ]
static method that calls os . walk but filters out anything that doesn t match the filter
def _filtered_walk ( path , file_filter ) : for root , dirs , files in os . walk ( path ) : log . debug ( 'looking in %s' , root ) log . debug ( 'files is %s' , files ) file_filter . set_root ( root ) files = filter ( file_filter , files ) log . debug ( 'filtered files is %s' , files ) yield ( root , dirs , files )
1,634
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/filesystem/change.py#L171-L182
[ "def", "aux", "(", "self", ",", "aux", ")", ":", "if", "aux", "==", "self", ".", "_aux", ":", "return", "if", "self", ".", "_aux", ":", "self", ".", "_manager", ".", "port_manager", ".", "release_tcp_port", "(", "self", ".", "_aux", ",", "self", ".", "_project", ")", "self", ".", "_aux", "=", "None", "if", "aux", "is", "not", "None", ":", "self", ".", "_aux", "=", "self", ".", "_manager", ".", "port_manager", ".", "reserve_tcp_port", "(", "aux", ",", "self", ".", "_project", ")", "log", ".", "info", "(", "\"{module}: '{name}' [{id}]: aux port set to {port}\"", ".", "format", "(", "module", "=", "self", ".", "manager", ".", "module_name", ",", "name", "=", "self", ".", "name", ",", "id", "=", "self", ".", "id", ",", "port", "=", "aux", ")", ")" ]
Set the appropriate Cache - Control and Expires headers for the given number of hours .
def cache_control_expires ( num_hours ) : num_seconds = int ( num_hours * 60 * 60 ) def decorator ( func ) : @ wraps ( func ) def inner ( request , * args , * * kwargs ) : response = func ( request , * args , * * kwargs ) patch_response_headers ( response , num_seconds ) return response return inner return decorator
1,635
https://github.com/pmac/django-redirect-urls/blob/21495194b0b2a2bdd1013e13ec0d54d34dd7f750/redirect_urls/decorators.py#L10-L26
[ "async", "def", "on_raw_422", "(", "self", ",", "message", ")", ":", "await", "self", ".", "_registration_completed", "(", "message", ")", "self", ".", "motd", "=", "None", "await", "self", ".", "on_connect", "(", ")" ]
The main event of the utility . Create or update a Cloud Formation stack . Injecting properties where needed
def upsert ( self ) : required_parameters = [ ] self . _stackParameters = [ ] try : self . _initialize_upsert ( ) except Exception : return False try : available_parameters = self . _parameters . keys ( ) for parameter_name in self . _template . get ( 'Parameters' , { } ) : required_parameters . append ( str ( parameter_name ) ) logging . info ( ' required parameters: ' + str ( required_parameters ) ) logging . info ( 'available parameters: ' + str ( available_parameters ) ) parameters = [ ] for required_parameter in required_parameters : parameter = { } parameter [ 'ParameterKey' ] = str ( required_parameter ) required_parameter = str ( required_parameter ) if required_parameter in self . _parameters : parameter [ 'ParameterValue' ] = self . _parameters [ required_parameter ] else : parameter [ 'ParameterValue' ] = self . _parameters [ required_parameter . lower ( ) ] parameters . append ( parameter ) if not self . _analyze_stuff ( ) : sys . exit ( 1 ) if self . _config . get ( 'dryrun' , False ) : logging . info ( 'Generating change set' ) set_id = self . _generate_change_set ( parameters ) if set_id : self . _describe_change_set ( set_id ) logging . info ( 'This was a dryrun' ) sys . exit ( 0 ) self . _tags . append ( { "Key" : "CODE_VERSION_SD" , "Value" : self . _config . get ( 'codeVersion' ) } ) self . _tags . append ( { "Key" : "ANSWER" , "Value" : str ( 42 ) } ) if self . _updateStack : stack = self . _cloudFormation . update_stack ( StackName = self . _config . get ( 'environment' , { } ) . get ( 'stack_name' , None ) , TemplateURL = self . _templateUrl , Parameters = parameters , Capabilities = [ 'CAPABILITY_IAM' , 'CAPABILITY_NAMED_IAM' ] , Tags = self . _tags , ClientRequestToken = str ( uuid . uuid4 ( ) ) ) logging . info ( 'existing stack ID: {}' . format ( stack . get ( 'StackId' , 'unknown' ) ) ) else : stack = self . _cloudFormation . create_stack ( StackName = self . _config . get ( 'environment' , { } ) . get ( 'stack_name' , None ) , TemplateURL = self . _templateUrl , Parameters = parameters , Capabilities = [ 'CAPABILITY_IAM' , 'CAPABILITY_NAMED_IAM' ] , Tags = self . _tags , ClientRequestToken = str ( uuid . uuid4 ( ) ) ) logging . info ( 'new stack ID: {}' . format ( stack . get ( 'StackId' , 'unknown' ) ) ) except Exception as x : if self . _verbose : logging . error ( x , exc_info = True ) else : logging . error ( x , exc_info = False ) return False return True
1,636
https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/CloudStackUtility.py#L89-L179
[ "def", "end_offsets", "(", "self", ",", "partitions", ")", ":", "offsets", "=", "self", ".", "_fetcher", ".", "end_offsets", "(", "partitions", ",", "self", ".", "config", "[", "'request_timeout_ms'", "]", ")", "return", "offsets" ]
List the existing stacks in the indicated region
def list ( self ) : self . _initialize_list ( ) interested = True response = self . _cloudFormation . list_stacks ( ) print ( 'Stack(s):' ) while interested : if 'StackSummaries' in response : for stack in response [ 'StackSummaries' ] : stack_status = stack [ 'StackStatus' ] if stack_status != 'DELETE_COMPLETE' : print ( ' [{}] - {}' . format ( stack [ 'StackStatus' ] , stack [ 'StackName' ] ) ) next_token = response . get ( 'NextToken' , None ) if next_token : response = self . _cloudFormation . list_stacks ( NextToken = next_token ) else : interested = False return True
1,637
https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/CloudStackUtility.py#L321-L353
[ "def", "config", "(", "self", ")", ":", "return", "{", "key", ":", "self", ".", "__dict__", "[", "key", "]", "for", "key", "in", "dir", "(", "self", ")", "if", "key", ".", "isupper", "(", ")", "}" ]
Smash the given stack
def smash ( self ) : self . _initialize_smash ( ) try : stack_name = self . _config . get ( 'environment' , { } ) . get ( 'stack_name' , None ) response = self . _cloudFormation . describe_stacks ( StackName = stack_name ) logging . debug ( 'smash pre-flight returned: {}' . format ( json . dumps ( response , indent = 4 , default = json_util . default ) ) ) except ClientError as wtf : logging . warning ( 'your stack is in another castle [0].' ) return False except Exception as wtf : logging . error ( 'failed to find intial status of smash candidate: {}' . format ( wtf ) ) return False response = self . _cloudFormation . delete_stack ( StackName = stack_name ) logging . info ( 'delete started for stack: {}' . format ( stack_name ) ) logging . debug ( 'delete_stack returned: {}' . format ( json . dumps ( response , indent = 4 ) ) ) return self . poll_stack ( )
1,638
https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/CloudStackUtility.py#L355-L388
[ "def", "make_anchor_id", "(", "self", ")", ":", "result", "=", "re", ".", "sub", "(", "'[^a-zA-Z0-9_]'", ",", "'_'", ",", "self", ".", "user", "+", "'_'", "+", "self", ".", "timestamp", ")", "return", "result" ]
The utililty requires boto3 clients to Cloud Formation and S3 . Here is where we make them .
def _init_boto3_clients ( self ) : try : profile = self . _config . get ( 'environment' , { } ) . get ( 'profile' ) region = self . _config . get ( 'environment' , { } ) . get ( 'region' ) if profile : self . _b3Sess = boto3 . session . Session ( profile_name = profile ) else : self . _b3Sess = boto3 . session . Session ( ) self . _s3 = self . _b3Sess . client ( 's3' ) self . _cloudFormation = self . _b3Sess . client ( 'cloudformation' , region_name = region ) self . _ssm = self . _b3Sess . client ( 'ssm' , region_name = region ) return True except Exception as wtf : logging . error ( 'Exception caught in intialize_session(): {}' . format ( wtf ) ) traceback . print_exc ( file = sys . stdout ) return False
1,639
https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/CloudStackUtility.py#L390-L417
[ "def", "watchdog_handler", "(", "self", ")", ":", "_LOGGING", ".", "debug", "(", "'%s Watchdog expired. Resetting connection.'", ",", "self", ".", "name", ")", "self", ".", "watchdog", ".", "stop", "(", ")", "self", ".", "reset_thrd", ".", "set", "(", ")" ]
Get parameters from Simple Systems Manager
def _get_ssm_parameter ( self , p ) : try : response = self . _ssm . get_parameter ( Name = p , WithDecryption = True ) return response . get ( 'Parameter' , { } ) . get ( 'Value' , None ) except Exception as ruh_roh : logging . error ( ruh_roh , exc_info = False ) return None
1,640
https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/CloudStackUtility.py#L434-L451
[ "def", "_validate_columns", "(", "self", ")", ":", "geom_cols", "=", "{", "'the_geom'", ",", "'the_geom_webmercator'", ",", "}", "col_overlap", "=", "set", "(", "self", ".", "style_cols", ")", "&", "geom_cols", "if", "col_overlap", ":", "raise", "ValueError", "(", "'Style columns cannot be geometry '", "'columns. `{col}` was chosen.'", ".", "format", "(", "col", "=", "','", ".", "join", "(", "col_overlap", ")", ")", ")" ]
Fill in the _parameters dict from the properties file .
def _fill_parameters ( self ) : self . _parameters = self . _config . get ( 'parameters' , { } ) self . _fill_defaults ( ) for k in self . _parameters . keys ( ) : try : if self . _parameters [ k ] . startswith ( self . SSM ) and self . _parameters [ k ] . endswith ( ']' ) : parts = self . _parameters [ k ] . split ( ':' ) tmp = parts [ 1 ] . replace ( ']' , '' ) val = self . _get_ssm_parameter ( tmp ) if val : self . _parameters [ k ] = val else : logging . error ( 'SSM parameter {} not found' . format ( tmp ) ) return False elif self . _parameters [ k ] == self . ASK : val = None a1 = '__x___' a2 = '__y___' prompt1 = "Enter value for '{}': " . format ( k ) prompt2 = "Confirm value for '{}': " . format ( k ) while a1 != a2 : a1 = getpass . getpass ( prompt = prompt1 ) a2 = getpass . getpass ( prompt = prompt2 ) if a1 == a2 : val = a1 else : print ( 'values do not match, try again' ) self . _parameters [ k ] = val except : pass return True
1,641
https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/CloudStackUtility.py#L453-L498
[ "def", "to_weld_vec", "(", "weld_type", ",", "ndim", ")", ":", "for", "i", "in", "range", "(", "ndim", ")", ":", "weld_type", "=", "WeldVec", "(", "weld_type", ")", "return", "weld_type" ]
Fill in the _tags dict from the tags file .
def _read_tags ( self ) : tags = self . _config . get ( 'tags' , { } ) logging . info ( 'Tags:' ) for tag_name in tags . keys ( ) : tag = { } tag [ 'Key' ] = tag_name tag [ 'Value' ] = tags [ tag_name ] self . _tags . append ( tag ) logging . info ( '{} = {}' . format ( tag_name , tags [ tag_name ] ) ) logging . debug ( json . dumps ( self . _tags , indent = 2 , sort_keys = True ) ) return True
1,642
https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/CloudStackUtility.py#L500-L528
[ "async", "def", "open_session", "(", "self", ",", "request", ":", "BaseRequestWebsocket", ")", "->", "Session", ":", "return", "await", "ensure_coroutine", "(", "self", ".", "session_interface", ".", "open_session", ")", "(", "self", ",", "request", ")" ]
Determine if we are creating a new stack or updating and existing one . The update member is set as you would expect at the end of this query .
def _set_update ( self ) : try : self . _updateStack = False stack_name = self . _config . get ( 'environment' , { } ) . get ( 'stack_name' , None ) response = self . _cloudFormation . describe_stacks ( StackName = stack_name ) stack = response [ 'Stacks' ] [ 0 ] if stack [ 'StackStatus' ] == 'ROLLBACK_COMPLETE' : logging . info ( 'stack is in ROLLBACK_COMPLETE status and should be deleted' ) del_stack_resp = self . _cloudFormation . delete_stack ( StackName = stack_name ) logging . info ( 'delete started for stack: {}' . format ( stack_name ) ) logging . debug ( 'delete_stack returned: {}' . format ( json . dumps ( del_stack_resp , indent = 4 ) ) ) stack_delete = self . poll_stack ( ) if not stack_delete : return False if stack [ 'StackStatus' ] in [ 'CREATE_COMPLETE' , 'UPDATE_COMPLETE' , 'UPDATE_ROLLBACK_COMPLETE' ] : self . _updateStack = True except : self . _updateStack = False logging . info ( 'update_stack: ' + str ( self . _updateStack ) ) return True
1,643
https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/CloudStackUtility.py#L530-L561
[ "def", "compute_busiest_date", "(", "feed", ":", "\"Feed\"", ",", "dates", ":", "List", "[", "str", "]", ")", "->", "str", ":", "f", "=", "feed", ".", "compute_trip_activity", "(", "dates", ")", "s", "=", "[", "(", "f", "[", "c", "]", ".", "sum", "(", ")", ",", "c", ")", "for", "c", "in", "f", ".", "columns", "if", "c", "!=", "\"trip_id\"", "]", "return", "max", "(", "s", ")", "[", "1", "]" ]
We are putting stuff into S3 were supplied the bucket . Here we craft the key of the elements we are putting up there in the internet clouds .
def _craft_s3_keys ( self ) : now = time . gmtime ( ) stub = "templates/{stack_name}/{version}" . format ( stack_name = self . _config . get ( 'environment' , { } ) . get ( 'stack_name' , None ) , version = self . _config . get ( 'codeVersion' ) ) stub = stub + "/" + str ( now . tm_year ) stub = stub + "/" + str ( '%02d' % now . tm_mon ) stub = stub + "/" + str ( '%02d' % now . tm_mday ) stub = stub + "/" + str ( '%02d' % now . tm_hour ) stub = stub + ":" + str ( '%02d' % now . tm_min ) stub = stub + ":" + str ( '%02d' % now . tm_sec ) if self . _yaml : template_key = stub + "/stack.yaml" else : template_key = stub + "/stack.json" property_key = stub + "/stack.properties" return template_key , property_key
1,644
https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/CloudStackUtility.py#L605-L636
[ "def", "read_file", "(", "self", ",", "registry", ")", ":", "with", "open", "(", "registry", ",", "\"r\"", ")", "as", "file_txt", ":", "read_file", "=", "file_txt", ".", "read", "(", ")", "file_txt", ".", "close", "(", ")", "return", "read_file" ]
Spin in a loop while the Cloud Formation process either fails or succeeds
def poll_stack ( self ) : logging . info ( 'polling stack status, POLL_INTERVAL={}' . format ( POLL_INTERVAL ) ) time . sleep ( POLL_INTERVAL ) completed_states = [ 'CREATE_COMPLETE' , 'UPDATE_COMPLETE' , 'DELETE_COMPLETE' ] stack_name = self . _config . get ( 'environment' , { } ) . get ( 'stack_name' , None ) while True : try : response = self . _cloudFormation . describe_stacks ( StackName = stack_name ) stack = response [ 'Stacks' ] [ 0 ] current_status = stack [ 'StackStatus' ] logging . info ( 'current status of {}: {}' . format ( stack_name , current_status ) ) if current_status . endswith ( 'COMPLETE' ) or current_status . endswith ( 'FAILED' ) : if current_status in completed_states : return True else : return False time . sleep ( POLL_INTERVAL ) except ClientError as wtf : if str ( wtf ) . find ( 'does not exist' ) == - 1 : logging . error ( 'Exception caught in wait_for_stack(): {}' . format ( wtf ) ) traceback . print_exc ( file = sys . stdout ) return False else : logging . info ( '{} is gone' . format ( stack_name ) ) return True except Exception as wtf : logging . error ( 'Exception caught in wait_for_stack(): {}' . format ( wtf ) ) traceback . print_exc ( file = sys . stdout ) return False
1,645
https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/CloudStackUtility.py#L638-L680
[ "def", "add_mimedb_data", "(", "mimedb", ")", ":", "mimedb", ".", "encodings_map", "[", "'.bz2'", "]", "=", "'bzip2'", "mimedb", ".", "encodings_map", "[", "'.lzma'", "]", "=", "'lzma'", "mimedb", ".", "encodings_map", "[", "'.xz'", "]", "=", "'xz'", "mimedb", ".", "encodings_map", "[", "'.lz'", "]", "=", "'lzip'", "mimedb", ".", "suffix_map", "[", "'.tbz2'", "]", "=", "'.tar.bz2'", "add_mimetype", "(", "mimedb", ",", "'application/x-lzop'", ",", "'.lzo'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-adf'", ",", "'.adf'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-arj'", ",", "'.arj'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-lzma'", ",", "'.lzma'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-xz'", ",", "'.xz'", ")", "add_mimetype", "(", "mimedb", ",", "'application/java-archive'", ",", "'.jar'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-rar'", ",", "'.rar'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-rar'", ",", "'.cbr'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-7z-compressed'", ",", "'.7z'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-7z-compressed'", ",", "'.cb7'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-cab'", ",", "'.cab'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-rpm'", ",", "'.rpm'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-debian-package'", ",", "'.deb'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-ace'", ",", "'.ace'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-ace'", ",", "'.cba'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-archive'", ",", "'.a'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-alzip'", ",", "'.alz'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-arc'", ",", "'.arc'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-lrzip'", ",", "'.lrz'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-lha'", ",", "'.lha'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-lzh'", ",", "'.lzh'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-rzip'", ",", "'.rz'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-zoo'", ",", "'.zoo'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-dms'", ",", "'.dms'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-zip-compressed'", ",", "'.crx'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-shar'", ",", "'.shar'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-tar'", ",", "'.cbt'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-vhd'", ",", "'.vhd'", ")", "add_mimetype", "(", "mimedb", ",", "'audio/x-ape'", ",", "'.ape'", ")", "add_mimetype", "(", "mimedb", ",", "'audio/x-shn'", ",", "'.shn'", ")", "add_mimetype", "(", "mimedb", ",", "'audio/flac'", ",", "'.flac'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-chm'", ",", "'.chm'", ")", "add_mimetype", "(", "mimedb", ",", "'application/x-iso9660-image'", ",", "'.iso'", ")", "add_mimetype", "(", "mimedb", ",", "'application/zip'", ",", "'.cbz'", ")", "add_mimetype", "(", "mimedb", ",", "'application/zip'", ",", "'.epub'", ")", "add_mimetype", "(", "mimedb", ",", "'application/zip'", ",", "'.apk'", ")", "add_mimetype", "(", "mimedb", ",", "'application/zpaq'", ",", "'.zpaq'", ")" ]
Run setup tasks to set up a nicely configured desktop pc .
def setup_desktop ( ) : run ( 'sudo apt-get update' ) install_packages ( packages_desktop ) execute ( custom . latex ) execute ( setup . ripping_of_cds ) execute ( setup . regex_repl ) execute ( setup . i3 ) execute ( setup . solarized ) execute ( setup . vim ) execute ( setup . tmux ) execute ( setup . pyenv ) # circumvent circular import, cf. http://stackoverflow.com/a/18486863 from fabfile import dfh , check_reboot dfh ( ) check_reboot ( )
1,646
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabfile-data/presetting-fabsetup-custom/fabfile_/__init__.py#L52-L73
[ "def", "update_api_key_description", "(", "apiKey", ",", "description", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", "response", "=", "_api_key_patch_replace", "(", "conn", ",", "apiKey", ",", "'/description'", ",", "description", ")", "return", "{", "'updated'", ":", "True", ",", "'apiKey'", ":", "_convert_datetime_str", "(", "response", ")", "}", "except", "ClientError", "as", "e", ":", "return", "{", "'updated'", ":", "False", ",", "'error'", ":", "__utils__", "[", "'boto3.get_error'", "]", "(", "e", ")", "}" ]
Run setup tasks to set up a nicely configured webserver .
def setup_webserver ( ) : run ( 'sudo apt-get update' ) install_packages ( packages_webserver ) execute ( custom . latex ) execute ( setup . solarized ) execute ( setup . vim ) execute ( setup . tmux ) checkup_git_repo_legacy ( url = 'git@github.com:letsencrypt/letsencrypt.git' ) execute ( setup . service . fdroid ) execute ( setup . service . owncloud ) # circumvent circular import, cf. http://stackoverflow.com/a/18486863 from fabfile import dfh , check_reboot dfh ( ) check_reboot ( )
1,647
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabfile-data/presetting-fabsetup-custom/fabfile_/__init__.py#L77-L101
[ "def", "update_api_key_description", "(", "apiKey", ",", "description", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", "response", "=", "_api_key_patch_replace", "(", "conn", ",", "apiKey", ",", "'/description'", ",", "description", ")", "return", "{", "'updated'", ":", "True", ",", "'apiKey'", ":", "_convert_datetime_str", "(", "response", ")", "}", "except", "ClientError", "as", "e", ":", "return", "{", "'updated'", ":", "False", ",", "'error'", ":", "__utils__", "[", "'boto3.get_error'", "]", "(", "e", ")", "}" ]
Open a server on Unix Domain Socket
def start_recv ( sockfile = None ) : if sockfile is not None : SOCKFILE = sockfile else : # default sockfile SOCKFILE = "/tmp/snort_alert" if os . path . exists ( SOCKFILE ) : os . unlink ( SOCKFILE ) unsock = socket . socket ( socket . AF_UNIX , socket . SOCK_DGRAM ) unsock . bind ( SOCKFILE ) logging . warning ( 'Unix socket start listening...' ) while True : data = unsock . recv ( BUFSIZE ) parsed_msg = alert . AlertPkt . parser ( data ) if parsed_msg : yield parsed_msg
1,648
https://github.com/John-Lin/snortunsock/blob/f0eb540d76c02b59e3899a16acafada79754dc3e/snortunsock/snort_listener.py#L11-L29
[ "def", "delete_attachments", "(", "self", ",", "volumeID", ",", "attachmentsID", ")", ":", "log", ".", "debug", "(", "\"deleting attachments from volume '{}': {}\"", ".", "format", "(", "volumeID", ",", "attachmentsID", ")", ")", "rawVolume", "=", "self", ".", "_req_raw_volume", "(", "volumeID", ")", "insID", "=", "[", "a", "[", "'id'", "]", "for", "a", "in", "rawVolume", "[", "'_source'", "]", "[", "'_attachments'", "]", "]", "# check that all requested file are present", "for", "id", "in", "attachmentsID", ":", "if", "id", "not", "in", "insID", ":", "raise", "NotFoundException", "(", "\"could not found attachment '{}' of the volume '{}'\"", ".", "format", "(", "id", ",", "volumeID", ")", ")", "for", "index", ",", "id", "in", "enumerate", "(", "attachmentsID", ")", ":", "rawVolume", "[", "'_source'", "]", "[", "'_attachments'", "]", ".", "pop", "(", "insID", ".", "index", "(", "id", ")", ")", "self", ".", "_db", ".", "modify_book", "(", "volumeID", ",", "rawVolume", "[", "'_source'", "]", ",", "version", "=", "rawVolume", "[", "'_version'", "]", ")" ]
Dump object to a file like object or string .
def dump ( obj , fp = None , indent = None , sort_keys = False , * * kw ) : if fp : iterable = YAMLEncoder ( indent = indent , sort_keys = sort_keys , * * kw ) . iterencode ( obj ) for chunk in iterable : fp . write ( chunk ) else : return dumps ( obj , indent = indent , sort_keys = sort_keys , * * kw )
1,649
https://github.com/bionikspoon/pureyaml/blob/784830b907ca14525c4cecdb6ae35306f6f8a877/pureyaml/__init__.py#L28-L44
[ "def", "_container_registration", "(", "self", ",", "alias", ")", ":", "containers", "=", "Container", ".", "find_by_name", "(", "self", ".", "_client_session", ",", "alias", ")", "def", "validate_name", "(", "name", ")", ":", "valid", "=", "True", "if", "name", "in", "containers", ":", "valid", "=", "False", "return", "valid", "count", "=", "1", "container_name", "=", "\"{0}-0{1}\"", ".", "format", "(", "alias", ",", "count", ")", "while", "not", "validate_name", "(", "container_name", ")", ":", "count", "+=", "1", "container_index", "=", "count", "if", "count", ">", "10", "else", "\"0{0}\"", ".", "format", "(", "count", ")", "container_name", "=", "\"{0}-{1}\"", ".", "format", "(", "alias", ",", "container_index", ")", "return", "container_name" ]
Dump string .
def dumps ( obj , indent = None , default = None , sort_keys = False , * * kw ) : return YAMLEncoder ( indent = indent , default = default , sort_keys = sort_keys , * * kw ) . encode ( obj )
1,650
https://github.com/bionikspoon/pureyaml/blob/784830b907ca14525c4cecdb6ae35306f6f8a877/pureyaml/__init__.py#L47-L49
[ "def", "_add_dependency", "(", "self", ",", "dependency", ",", "var_name", "=", "None", ")", ":", "if", "var_name", "is", "None", ":", "var_name", "=", "next", "(", "self", ".", "temp_var_names", ")", "# Don't add duplicate dependencies", "if", "(", "dependency", ",", "var_name", ")", "not", "in", "self", ".", "dependencies", ":", "self", ".", "dependencies", ".", "append", "(", "(", "dependency", ",", "var_name", ")", ")", "return", "var_name" ]
Load yaml file
def load ( s , * * kwargs ) : try : return loads ( s , * * kwargs ) except TypeError : return loads ( s . read ( ) , * * kwargs )
1,651
https://github.com/bionikspoon/pureyaml/blob/784830b907ca14525c4cecdb6ae35306f6f8a877/pureyaml/__init__.py#L52-L57
[ "def", "cmd_oreoled", "(", "self", ",", "args", ")", ":", "if", "len", "(", "args", ")", "<", "4", ":", "print", "(", "\"Usage: oreoled LEDNUM RED GREEN BLUE <RATE>\"", ")", "return", "lednum", "=", "int", "(", "args", "[", "0", "]", ")", "pattern", "=", "[", "0", "]", "*", "24", "pattern", "[", "0", "]", "=", "ord", "(", "'R'", ")", "pattern", "[", "1", "]", "=", "ord", "(", "'G'", ")", "pattern", "[", "2", "]", "=", "ord", "(", "'B'", ")", "pattern", "[", "3", "]", "=", "ord", "(", "'0'", ")", "pattern", "[", "4", "]", "=", "0", "pattern", "[", "5", "]", "=", "int", "(", "args", "[", "1", "]", ")", "pattern", "[", "6", "]", "=", "int", "(", "args", "[", "2", "]", ")", "pattern", "[", "7", "]", "=", "int", "(", "args", "[", "3", "]", ")", "self", ".", "master", ".", "mav", ".", "led_control_send", "(", "self", ".", "settings", ".", "target_system", ",", "self", ".", "settings", ".", "target_component", ",", "lednum", ",", "255", ",", "8", ",", "pattern", ")" ]
The address in big - endian
def address ( self ) : _ = struct . pack ( 'L' , self . address_num ) return struct . unpack ( '!L' , _ ) [ 0 ]
1,652
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/api/inet.py#L81-L84
[ "def", "make_random_models_table", "(", "n_sources", ",", "param_ranges", ",", "random_state", "=", "None", ")", ":", "prng", "=", "check_random_state", "(", "random_state", ")", "sources", "=", "Table", "(", ")", "for", "param_name", ",", "(", "lower", ",", "upper", ")", "in", "param_ranges", ".", "items", "(", ")", ":", "# Generate a column for every item in param_ranges, even if it", "# is not in the model (e.g. flux). However, such columns will", "# be ignored when rendering the image.", "sources", "[", "param_name", "]", "=", "prng", ".", "uniform", "(", "lower", ",", "upper", ",", "n_sources", ")", "return", "sources" ]
some validation checks before doing anything
def validate_currency ( * currencies ) : validated_currency = [ ] if not currencies : raise CurrencyException ( 'My function need something to run, duh' ) for currency in currencies : currency = currency . upper ( ) if not isinstance ( currency , str ) : raise TypeError ( 'Currency code should be a string: ' + repr ( currency ) ) if currency not in _currencies : raise CurrencyException ( 'Currency code not found: ' + repr ( currency ) ) validated_currency . append ( currency ) return validated_currency [ 0 ] if len ( validated_currency ) == 1 else validated_currency
1,653
https://github.com/NearHuscarl/py-currency/blob/4e30426399872fd6bfaa4c752a91d67c2d7bf52c/currency/currency.py#L35-L47
[ "def", "read_frames", "(", "cls", ",", "reader", ")", ":", "rval", "=", "deque", "(", ")", "while", "True", ":", "frame_start_pos", "=", "reader", ".", "tell", "(", ")", "try", ":", "frame", "=", "Frame", ".", "_read_frame", "(", "reader", ")", "except", "Reader", ".", "BufferUnderflow", ":", "# No more data in the stream", "frame", "=", "None", "except", "Reader", ".", "ReaderError", "as", "e", ":", "# Some other format error", "raise", "Frame", ".", "FormatError", ",", "str", "(", "e", ")", ",", "sys", ".", "exc_info", "(", ")", "[", "-", "1", "]", "except", "struct", ".", "error", "as", "e", ":", "raise", "Frame", ".", "FormatError", ",", "str", "(", "e", ")", ",", "sys", ".", "exc_info", "(", ")", "[", "-", "1", "]", "if", "frame", "is", "None", ":", "reader", ".", "seek", "(", "frame_start_pos", ")", "break", "rval", ".", "append", "(", "frame", ")", "return", "rval" ]
validation checks for price argument
def validate_price ( price ) : if isinstance ( price , str ) : try : price = int ( price ) except ValueError : # fallback if convert to int failed price = float ( price ) if not isinstance ( price , ( int , float ) ) : raise TypeError ( 'Price should be a number: ' + repr ( price ) ) return price
1,654
https://github.com/NearHuscarl/py-currency/blob/4e30426399872fd6bfaa4c752a91d67c2d7bf52c/currency/currency.py#L49-L58
[ "def", "cli", "(", "conf", ")", ":", "try", ":", "config", "=", "init_config", "(", "conf", ")", "debug", "=", "config", ".", "getboolean", "(", "'DEFAULT'", ",", "'debug'", ")", "conn", "=", "get_conn", "(", "config", ".", "get", "(", "'DEFAULT'", ",", "'statusdb'", ")", ")", "cur", "=", "conn", ".", "cursor", "(", ")", "sqlstr", "=", "'''create table client_status\n (session_id text PRIMARY KEY, username text, userip text, \n realip text, realport int,ctime int,\n inbytes int, outbytes int, \n acct_interval int, session_timeout int, uptime int)\n '''", "try", ":", "cur", ".", "execute", "(", "'drop table client_status'", ")", "except", ":", "pass", "cur", ".", "execute", "(", "sqlstr", ")", "print", "'flush client status database'", "conn", ".", "commit", "(", ")", "conn", ".", "close", "(", ")", "except", ":", "traceback", ".", "print_exc", "(", ")" ]
return name of currency
def name ( currency , * , plural = False ) : currency = validate_currency ( currency ) if plural : return _currencies [ currency ] [ 'name_plural' ] return _currencies [ currency ] [ 'name' ]
1,655
https://github.com/NearHuscarl/py-currency/blob/4e30426399872fd6bfaa4c752a91d67c2d7bf52c/currency/currency.py#L70-L75
[ "def", "_get_env_var", "(", "env_var_name", ")", ":", "if", "env_var_name", "in", "os", ".", "environ", ":", "return", "os", ".", "environ", "[", "env_var_name", "]", "fname", "=", "os", ".", "path", ".", "join", "(", "get_home", "(", ")", ",", "'.tangorc'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "fname", ")", ":", "if", "os", ".", "name", "==", "'posix'", ":", "fname", "=", "\"/etc/tangorc\"", "if", "not", "os", ".", "path", ".", "exists", "(", "fname", ")", ":", "return", "None", "for", "line", "in", "open", "(", "fname", ")", ":", "strippedline", "=", "line", ".", "split", "(", "'#'", ",", "1", ")", "[", "0", "]", ".", "strip", "(", ")", "if", "not", "strippedline", ":", "# empty line", "continue", "tup", "=", "strippedline", ".", "split", "(", "'='", ",", "1", ")", "if", "len", "(", "tup", ")", "!=", "2", ":", "# illegal line!", "continue", "key", ",", "val", "=", "map", "(", "str", ".", "strip", ",", "tup", ")", "if", "key", "==", "env_var_name", ":", "return", "val" ]
return symbol of currency
def symbol ( currency , * , native = True ) : currency = validate_currency ( currency ) if native : return _currencies [ currency ] [ 'symbol_native' ] return _currencies [ currency ] [ 'symbol' ]
1,656
https://github.com/NearHuscarl/py-currency/blob/4e30426399872fd6bfaa4c752a91d67c2d7bf52c/currency/currency.py#L77-L82
[ "def", "_get_env_var", "(", "env_var_name", ")", ":", "if", "env_var_name", "in", "os", ".", "environ", ":", "return", "os", ".", "environ", "[", "env_var_name", "]", "fname", "=", "os", ".", "path", ".", "join", "(", "get_home", "(", ")", ",", "'.tangorc'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "fname", ")", ":", "if", "os", ".", "name", "==", "'posix'", ":", "fname", "=", "\"/etc/tangorc\"", "if", "not", "os", ".", "path", ".", "exists", "(", "fname", ")", ":", "return", "None", "for", "line", "in", "open", "(", "fname", ")", ":", "strippedline", "=", "line", ".", "split", "(", "'#'", ",", "1", ")", "[", "0", "]", ".", "strip", "(", ")", "if", "not", "strippedline", ":", "# empty line", "continue", "tup", "=", "strippedline", ".", "split", "(", "'='", ",", "1", ")", "if", "len", "(", "tup", ")", "!=", "2", ":", "# illegal line!", "continue", "key", ",", "val", "=", "map", "(", "str", ".", "strip", ",", "tup", ")", "if", "key", "==", "env_var_name", ":", "return", "val" ]
rounding currency value based on its max decimal digits
def rounding ( price , currency ) : currency = validate_currency ( currency ) price = validate_price ( price ) if decimals ( currency ) == 0 : return round ( int ( price ) , decimals ( currency ) ) return round ( price , decimals ( currency ) )
1,657
https://github.com/NearHuscarl/py-currency/blob/4e30426399872fd6bfaa4c752a91d67c2d7bf52c/currency/currency.py#L94-L100
[ "def", "convertToRateMatrix", "(", "self", ",", "Q", ")", ":", "rowSums", "=", "Q", ".", "sum", "(", "axis", "=", "1", ")", ".", "getA1", "(", ")", "idxRange", "=", "np", ".", "arange", "(", "Q", ".", "shape", "[", "0", "]", ")", "Qdiag", "=", "coo_matrix", "(", "(", "rowSums", ",", "(", "idxRange", ",", "idxRange", ")", ")", ",", "shape", "=", "Q", ".", "shape", ")", ".", "tocsr", "(", ")", "return", "Q", "-", "Qdiag" ]
check if last update is over 30 mins ago . if so return True to update else False
def check_update ( from_currency , to_currency ) : if from_currency not in ccache : # if currency never get converted before ccache [ from_currency ] = { } if ccache [ from_currency ] . get ( to_currency ) is None : ccache [ from_currency ] [ to_currency ] = { 'last_update' : 0 } last_update = float ( ccache [ from_currency ] [ to_currency ] [ 'last_update' ] ) if time . time ( ) - last_update >= 30 * 60 : # if last update is more than 30 min ago return True return False
1,658
https://github.com/NearHuscarl/py-currency/blob/4e30426399872fd6bfaa4c752a91d67c2d7bf52c/currency/currency.py#L133-L142
[ "def", "createReaderUser", "(", "self", ",", "accessibleBundles", "=", "None", ")", ":", "url", "=", "self", ".", "__serviceAccount", ".", "get_url", "(", ")", "+", "'/'", "+", "self", ".", "__serviceAccount", ".", "get_instance_id", "(", ")", "+", "'/v2/users/new'", "headers", "=", "{", "'content-type'", ":", "'application/json'", "}", "data", "=", "{", "}", "data", "[", "'type'", "]", "=", "'READER'", "if", "accessibleBundles", "is", "not", "None", ":", "data", "[", "'bundles'", "]", "=", "accessibleBundles", "json_data", "=", "json", ".", "dumps", "(", "data", ")", "response", "=", "self", ".", "__perform_rest_call", "(", "requestURL", "=", "url", ",", "restType", "=", "'POST'", ",", "body", "=", "json_data", ",", "headers", "=", "headers", ")", "return", "response" ]
update from_currency to_currency pair in cache if last update for that pair is over 30 minutes ago by request API info
def update_cache ( from_currency , to_currency ) : if check_update ( from_currency , to_currency ) is True : ccache [ from_currency ] [ to_currency ] [ 'value' ] = convert_using_api ( from_currency , to_currency ) ccache [ from_currency ] [ to_currency ] [ 'last_update' ] = time . time ( ) cache . write ( ccache )
1,659
https://github.com/NearHuscarl/py-currency/blob/4e30426399872fd6bfaa4c752a91d67c2d7bf52c/currency/currency.py#L144-L150
[ "def", "BeginOfEventAction", "(", "self", ",", "event", ")", ":", "self", ".", "log", ".", "info", "(", "\"Simulating event %s\"", ",", "event", ".", "GetEventID", "(", ")", ")", "self", ".", "sd", ".", "setEventNumber", "(", "event", ".", "GetEventID", "(", ")", ")" ]
convert from from_currency to to_currency by requesting API
def convert_using_api ( from_currency , to_currency ) : convert_str = from_currency + '_' + to_currency options = { 'compact' : 'ultra' , 'q' : convert_str } api_url = 'https://free.currencyconverterapi.com/api/v5/convert' result = requests . get ( api_url , params = options ) . json ( ) return result [ convert_str ]
1,660
https://github.com/NearHuscarl/py-currency/blob/4e30426399872fd6bfaa4c752a91d67c2d7bf52c/currency/currency.py#L152-L158
[ "def", "get_traindata", "(", "self", ")", "->", "np", ".", "ndarray", ":", "traindata", "=", "None", "for", "key", ",", "value", "in", "self", ".", "data", ".", "items", "(", ")", ":", "if", "key", "not", "in", "[", "'__header__'", ",", "'__version__'", ",", "'__globals__'", "]", ":", "if", "traindata", "is", "None", ":", "traindata", "=", "value", "[", "np", ".", "where", "(", "value", "[", ":", ",", "4", "]", "!=", "0", ")", "]", "else", ":", "traindata", "=", "np", ".", "concatenate", "(", "(", "traindata", ",", "value", "[", "np", ".", "where", "(", "value", "[", ":", ",", "4", "]", "!=", "0", ")", "]", ")", ")", "return", "traindata" ]
convert from from_currency to to_currency using cached info
def convert ( from_currency , to_currency , from_currency_price = 1 ) : get_cache ( ) from_currency , to_currency = validate_currency ( from_currency , to_currency ) update_cache ( from_currency , to_currency ) return ccache [ from_currency ] [ to_currency ] [ 'value' ] * from_currency_price
1,661
https://github.com/NearHuscarl/py-currency/blob/4e30426399872fd6bfaa4c752a91d67c2d7bf52c/currency/currency.py#L160-L165
[ "def", "hurst", "(", "X", ")", ":", "X", "=", "numpy", ".", "array", "(", "X", ")", "N", "=", "X", ".", "size", "T", "=", "numpy", ".", "arange", "(", "1", ",", "N", "+", "1", ")", "Y", "=", "numpy", ".", "cumsum", "(", "X", ")", "Ave_T", "=", "Y", "/", "T", "S_T", "=", "numpy", ".", "zeros", "(", "N", ")", "R_T", "=", "numpy", ".", "zeros", "(", "N", ")", "for", "i", "in", "range", "(", "N", ")", ":", "S_T", "[", "i", "]", "=", "numpy", ".", "std", "(", "X", "[", ":", "i", "+", "1", "]", ")", "X_T", "=", "Y", "-", "T", "*", "Ave_T", "[", "i", "]", "R_T", "[", "i", "]", "=", "numpy", ".", "ptp", "(", "X_T", "[", ":", "i", "+", "1", "]", ")", "R_S", "=", "R_T", "/", "S_T", "R_S", "=", "numpy", ".", "log", "(", "R_S", ")", "[", "1", ":", "]", "n", "=", "numpy", ".", "log", "(", "T", ")", "[", "1", ":", "]", "A", "=", "numpy", ".", "column_stack", "(", "(", "n", ",", "numpy", ".", "ones", "(", "n", ".", "size", ")", ")", ")", "[", "m", ",", "c", "]", "=", "numpy", ".", "linalg", ".", "lstsq", "(", "A", ",", "R_S", ")", "[", "0", "]", "H", "=", "m", "return", "H" ]
wait for the signal ; return after the signal has occurred or the timeout in seconds elapses .
def wait_for_signal ( self , timeout = None ) : timeout_ms = int ( timeout * 1000 ) if timeout else win32event . INFINITE win32event . WaitForSingleObject ( self . signal_event , timeout_ms )
1,662
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/timers.py#L36-L42
[ "def", "generate_http_manifest", "(", "self", ")", ":", "base_path", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "translate_path", "(", "self", ".", "path", ")", ")", "self", ".", "dataset", "=", "dtoolcore", ".", "DataSet", ".", "from_uri", "(", "base_path", ")", "admin_metadata_fpath", "=", "os", ".", "path", ".", "join", "(", "base_path", ",", "\".dtool\"", ",", "\"dtool\"", ")", "with", "open", "(", "admin_metadata_fpath", ")", "as", "fh", ":", "admin_metadata", "=", "json", ".", "load", "(", "fh", ")", "http_manifest", "=", "{", "\"admin_metadata\"", ":", "admin_metadata", ",", "\"manifest_url\"", ":", "self", ".", "generate_url", "(", "\".dtool/manifest.json\"", ")", ",", "\"readme_url\"", ":", "self", ".", "generate_url", "(", "\"README.yml\"", ")", ",", "\"overlays\"", ":", "self", ".", "generate_overlay_urls", "(", ")", ",", "\"item_urls\"", ":", "self", ".", "generate_item_urls", "(", ")", "}", "return", "bytes", "(", "json", ".", "dumps", "(", "http_manifest", ")", ",", "\"utf-8\"", ")" ]
Get IP geolocation .
def ip_geoloc ( ip , hit_api = True ) : from . . logs . models import IPInfoCheck try : obj = IPInfoCheck . objects . get ( ip_address = ip ) . ip_info except IPInfoCheck . DoesNotExist : if hit_api : try : obj = IPInfoCheck . check_ip ( ip ) except RateExceededError : return None else : return None return obj . latitude , obj . longitude
1,663
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/geolocation.py#L8-L30
[ "def", "_init_libcrypto", "(", ")", ":", "libcrypto", "=", "_load_libcrypto", "(", ")", "try", ":", "libcrypto", ".", "OPENSSL_init_crypto", "(", ")", "except", "AttributeError", ":", "# Support for OpenSSL < 1.1 (OPENSSL_API_COMPAT < 0x10100000L)", "libcrypto", ".", "OPENSSL_no_config", "(", ")", "libcrypto", ".", "OPENSSL_add_all_algorithms_noconf", "(", ")", "libcrypto", ".", "RSA_new", ".", "argtypes", "=", "(", ")", "libcrypto", ".", "RSA_new", ".", "restype", "=", "c_void_p", "libcrypto", ".", "RSA_free", ".", "argtypes", "=", "(", "c_void_p", ",", ")", "libcrypto", ".", "RSA_size", ".", "argtype", "=", "(", "c_void_p", ")", "libcrypto", ".", "BIO_new_mem_buf", ".", "argtypes", "=", "(", "c_char_p", ",", "c_int", ")", "libcrypto", ".", "BIO_new_mem_buf", ".", "restype", "=", "c_void_p", "libcrypto", ".", "BIO_free", ".", "argtypes", "=", "(", "c_void_p", ",", ")", "libcrypto", ".", "PEM_read_bio_RSAPrivateKey", ".", "argtypes", "=", "(", "c_void_p", ",", "c_void_p", ",", "c_void_p", ",", "c_void_p", ")", "libcrypto", ".", "PEM_read_bio_RSAPrivateKey", ".", "restype", "=", "c_void_p", "libcrypto", ".", "PEM_read_bio_RSA_PUBKEY", ".", "argtypes", "=", "(", "c_void_p", ",", "c_void_p", ",", "c_void_p", ",", "c_void_p", ")", "libcrypto", ".", "PEM_read_bio_RSA_PUBKEY", ".", "restype", "=", "c_void_p", "libcrypto", ".", "RSA_private_encrypt", ".", "argtypes", "=", "(", "c_int", ",", "c_char_p", ",", "c_char_p", ",", "c_void_p", ",", "c_int", ")", "libcrypto", ".", "RSA_public_decrypt", ".", "argtypes", "=", "(", "c_int", ",", "c_char_p", ",", "c_char_p", ",", "c_void_p", ",", "c_int", ")", "return", "libcrypto" ]
Get a link to google maps pointing on this IP s geolocation .
def google_maps_geoloc_link ( data ) : if isinstance ( data , str ) : lat_lon = ip_geoloc ( data ) if lat_lon is None : return '' lat , lon = lat_lon else : lat , lon = data loc = '%s,%s' % ( lat , lon ) return 'https://www.google.com/maps/place/@%s,17z/' 'data=!3m1!4b1!4m5!3m4!1s0x0:0x0!8m2!3d%s!4d%s' % ( loc , lat , lon )
1,664
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/geolocation.py#L33-L53
[ "def", "rename_sectors", "(", "self", ",", "sectors", ")", ":", "if", "type", "(", "sectors", ")", "is", "list", ":", "sectors", "=", "{", "old", ":", "new", "for", "old", ",", "new", "in", "zip", "(", "self", ".", "get_sectors", "(", ")", ",", "sectors", ")", "}", "for", "df", "in", "self", ".", "get_DataFrame", "(", "data", "=", "True", ")", ":", "df", ".", "rename", "(", "index", "=", "sectors", ",", "columns", "=", "sectors", ",", "inplace", "=", "True", ")", "try", ":", "for", "ext", "in", "self", ".", "get_extensions", "(", "data", "=", "True", ")", ":", "for", "df", "in", "ext", ".", "get_DataFrame", "(", "data", "=", "True", ")", ":", "df", ".", "rename", "(", "index", "=", "sectors", ",", "columns", "=", "sectors", ",", "inplace", "=", "True", ")", "except", ":", "pass", "self", ".", "meta", ".", "_add_modify", "(", "\"Changed sector names\"", ")", "return", "self" ]
Get a link to open street map pointing on this IP s geolocation .
def open_street_map_geoloc_link ( data ) : if isinstance ( data , str ) : lat_lon = ip_geoloc ( data ) if lat_lon is None : return '' lat , lon = lat_lon else : lat , lon = data return 'https://www.openstreetmap.org/search' '?query=%s%%2C%s#map=7/%s/%s' % ( lat , lon , lat , lon )
1,665
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/geolocation.py#L56-L74
[ "def", "setGroups", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "requests", "=", "0", "groups", "=", "[", "]", "try", ":", "for", "gk", "in", "self", "[", "'groupKeys'", "]", ":", "try", ":", "g", "=", "self", ".", "mambugroupclass", "(", "entid", "=", "gk", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "AttributeError", "as", "ae", ":", "from", ".", "mambugroup", "import", "MambuGroup", "self", ".", "mambugroupclass", "=", "MambuGroup", "g", "=", "self", ".", "mambugroupclass", "(", "entid", "=", "gk", ",", "*", "args", ",", "*", "*", "kwargs", ")", "requests", "+=", "1", "groups", ".", "append", "(", "g", ")", "except", "KeyError", ":", "pass", "self", "[", "'groups'", "]", "=", "groups", "return", "requests" ]
Chart for status codes .
def status_codes_chart ( ) : stats = status_codes_stats ( ) chart_options = { 'chart' : { 'type' : 'pie' } , 'title' : { 'text' : '' } , 'subtitle' : { 'text' : '' } , 'tooltip' : { 'formatter' : "return this.y + '/' + this.total + ' (' + " "Highcharts.numberFormat(this.percentage, 1) + '%)';" } , 'legend' : { 'enabled' : True , } , 'plotOptions' : { 'pie' : { 'allowPointSelect' : True , 'cursor' : 'pointer' , 'dataLabels' : { 'enabled' : True , 'format' : '<b>{point.name}</b>: {point.y}/{point.total} ' '({point.percentage:.1f}%)' } , 'showInLegend' : True } } , 'series' : [ { 'name' : _ ( 'Status Codes' ) , 'colorByPoint' : True , 'data' : sorted ( [ { 'name' : '%s %s' % ( k , STATUS_CODES [ int ( k ) ] [ 'name' ] ) , 'y' : v } for k , v in stats . items ( ) ] , key = lambda x : x [ 'y' ] , reverse = True ) } ] } return chart_options
1,666
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/charts.py#L19-L63
[ "def", "libvlc_video_set_crop_geometry", "(", "p_mi", ",", "psz_geometry", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_video_set_crop_geometry'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_video_set_crop_geometry'", ",", "(", "(", "1", ",", ")", ",", "(", "1", ",", ")", ",", ")", ",", "None", ",", "None", ",", "MediaPlayer", ",", "ctypes", ".", "c_char_p", ")", "return", "f", "(", "p_mi", ",", "psz_geometry", ")" ]
Chart for most visited pages legend .
def most_visited_pages_legend_chart ( ) : return { 'chart' : { 'type' : 'bar' , 'height' : 200 , } , 'title' : { 'text' : _ ( 'Legend' ) } , 'xAxis' : { 'categories' : [ _ ( 'Project URL' ) , _ ( 'Old project URL' ) , _ ( 'Asset URL' ) , _ ( 'Old asset URL' ) , _ ( 'Common asset URL' ) , _ ( 'False-negative project URL' ) , _ ( 'Suspicious URL (potential attack)' ) ] , 'title' : { 'text' : None } } , 'yAxis' : { 'title' : { 'text' : None , 'align' : 'high' } , 'labels' : { 'overflow' : 'justify' } } , 'tooltip' : { 'enabled' : False } , 'legend' : { 'enabled' : False } , 'credits' : { 'enabled' : False } , 'series' : [ { 'name' : _ ( 'Legend' ) , 'data' : [ { 'color' : URL_TYPE_COLOR [ PROJECT ] , 'y' : 1 } , { 'color' : URL_TYPE_COLOR [ OLD_PROJECT ] , 'y' : 1 } , { 'color' : URL_TYPE_COLOR [ ASSET ] , 'y' : 1 } , { 'color' : URL_TYPE_COLOR [ OLD_ASSET ] , 'y' : 1 } , { 'color' : URL_TYPE_COLOR [ COMMON_ASSET ] , 'y' : 1 } , { 'color' : URL_TYPE_COLOR [ FALSE_NEGATIVE ] , 'y' : 1 } , { 'color' : URL_TYPE_COLOR [ SUSPICIOUS ] , 'y' : 1 } , ] } ] }
1,667
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/charts.py#L100-L154
[ "def", "receive", "(", "self", ",", "path", ",", "diff", ",", "showProgress", "=", "True", ")", ":", "directory", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "cmd", "=", "[", "\"btrfs\"", ",", "\"receive\"", ",", "\"-e\"", ",", "directory", "]", "if", "Store", ".", "skipDryRun", "(", "logger", ",", "self", ".", "dryrun", ")", "(", "\"Command: %s\"", ",", "cmd", ")", ":", "return", "None", "if", "not", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", "os", ".", "makedirs", "(", "directory", ")", "process", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdin", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "stdout", "=", "DEVNULL", ",", ")", "_makeNice", "(", "process", ")", "return", "_Writer", "(", "process", ",", "process", ".", "stdin", ",", "path", ",", "diff", ",", "showProgress", ")" ]
Adds all settings that are part of mod to the global settings object .
def add_settings ( mod , allow_extras = True , settings = django_settings ) : extras = { } for setting in dir ( mod ) : if setting == setting . upper ( ) : setting_value = getattr ( mod , setting ) if setting in TUPLE_SETTINGS and type ( setting_value ) == str : setting_value = ( setting_value , ) # In case the user forgot the comma. # Any setting that starts with EXTRA_ and matches a setting that is a list or tuple # will automatically append the values to the current setting. # It might make sense to make this less magical if setting . startswith ( 'EXTRA_' ) : base_setting = setting . split ( 'EXTRA_' , 1 ) [ - 1 ] if isinstance ( getattr ( settings , base_setting ) , ( list , tuple ) ) : extras [ base_setting ] = setting_value continue setattr ( settings , setting , setting_value ) for key , value in extras . items ( ) : curval = getattr ( settings , key ) setattr ( settings , key , curval + type ( curval ) ( value ) )
1,668
https://github.com/dcramer/logan/blob/8b18456802d631a822e2823bf9a4e9810a15a20e/logan/settings.py#L73-L101
[ "def", "get_descriptor_output", "(", "descriptor", ",", "key", ",", "handler", "=", "None", ")", ":", "line", "=", "'stub'", "lines", "=", "''", "while", "line", "!=", "''", ":", "try", ":", "line", "=", "descriptor", ".", "readline", "(", ")", "lines", "+=", "line", "except", "UnicodeDecodeError", ":", "error_msg", "=", "\"Error while decoding output of process {}\"", ".", "format", "(", "key", ")", "if", "handler", ":", "handler", ".", "logger", ".", "error", "(", "\"{} with command {}\"", ".", "format", "(", "error_msg", ",", "handler", ".", "queue", "[", "key", "]", "[", "'command'", "]", ")", ")", "lines", "+=", "error_msg", "+", "'\\n'", "return", "lines", ".", "replace", "(", "'\\n'", ",", "'\\n '", ")" ]
Get urls method .
def get_urls ( self ) : urls = super ( DashboardSite , self ) . get_urls ( ) custom_urls = [ url ( r'^$' , self . admin_view ( HomeView . as_view ( ) ) , name = 'index' ) , url ( r'^logs/' , include ( logs_urlpatterns ( self . admin_view ) ) ) , ] custom_urls += get_realtime_urls ( self . admin_view ) del urls [ 0 ] return custom_urls + urls
1,669
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/sites.py#L23-L41
[ "def", "enhanced_vd_factory", "(", "sys_ident", ",", "vol_ident", ",", "set_size", ",", "seqnum", ",", "log_block_size", ",", "vol_set_ident", ",", "pub_ident_str", ",", "preparer_ident_str", ",", "app_ident_str", ",", "copyright_file", ",", "abstract_file", ",", "bibli_file", ",", "vol_expire_date", ",", "app_use", ",", "xa", ")", ":", "# type: (bytes, bytes, int, int, int, bytes, bytes, bytes, bytes, bytes, bytes, bytes, float, bytes, bool) -> PrimaryOrSupplementaryVD", "svd", "=", "PrimaryOrSupplementaryVD", "(", "VOLUME_DESCRIPTOR_TYPE_SUPPLEMENTARY", ")", "svd", ".", "new", "(", "0", ",", "sys_ident", ",", "vol_ident", ",", "set_size", ",", "seqnum", ",", "log_block_size", ",", "vol_set_ident", ",", "pub_ident_str", ",", "preparer_ident_str", ",", "app_ident_str", ",", "copyright_file", ",", "abstract_file", ",", "bibli_file", ",", "vol_expire_date", ",", "app_use", ",", "xa", ",", "2", ",", "b''", ")", "return", "svd" ]
Adds widget attributes to a bound form field .
def add_form_widget_attr ( field , attr_name , attr_value , replace = 0 ) : if not replace : attr = field . field . widget . attrs . get ( attr_name , '' ) attr += force_text ( attr_value ) field . field . widget . attrs [ attr_name ] = attr return field else : field . field . widget . attrs [ attr_name ] = attr_value return field
1,670
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L32-L60
[ "def", "remove_stale_indexes_from_bika_catalog", "(", "portal", ")", ":", "logger", ".", "info", "(", "\"Removing stale indexes and metadata from bika_catalog ...\"", ")", "cat_id", "=", "\"bika_catalog\"", "indexes_to_remove", "=", "[", "\"getAnalyst\"", ",", "\"getAnalysts\"", ",", "\"getAnalysisService\"", ",", "\"getClientOrderNumber\"", ",", "\"getClientReference\"", ",", "\"getClientSampleID\"", ",", "\"getContactTitle\"", ",", "\"getDateDisposed\"", ",", "\"getDateExpired\"", ",", "\"getDateOpened\"", ",", "\"getDatePublished\"", ",", "\"getInvoiced\"", ",", "\"getPreserver\"", ",", "\"getSamplePointTitle\"", ",", "\"getSamplePointUID\"", ",", "\"getSampler\"", ",", "\"getScheduledSamplingSampler\"", ",", "\"getSamplingDate\"", ",", "\"getWorksheetTemplateTitle\"", ",", "\"BatchUID\"", ",", "]", "metadata_to_remove", "=", "[", "\"getAnalysts\"", ",", "\"getClientOrderNumber\"", ",", "\"getClientReference\"", ",", "\"getClientSampleID\"", ",", "\"getContactTitle\"", ",", "\"getSamplePointTitle\"", ",", "\"getAnalysisService\"", ",", "\"getDatePublished\"", ",", "]", "for", "index", "in", "indexes_to_remove", ":", "del_index", "(", "portal", ",", "cat_id", ",", "index", ")", "for", "metadata", "in", "metadata_to_remove", ":", "del_metadata", "(", "portal", ",", "cat_id", ",", "metadata", ")", "commit_transaction", "(", "portal", ")" ]
Turn any template filter into a blocktag .
def block_anyfilter ( parser , token ) : bits = token . contents . split ( ) nodelist = parser . parse ( ( 'endblockanyfilter' , ) ) parser . delete_first_token ( ) return BlockAnyFilterNode ( nodelist , bits [ 1 ] , * bits [ 2 : ] )
1,671
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L64-L79
[ "def", "k_array_rank_jit", "(", "a", ")", ":", "k", "=", "len", "(", "a", ")", "idx", "=", "a", "[", "0", "]", "for", "i", "in", "range", "(", "1", ",", "k", ")", ":", "idx", "+=", "comb_jit", "(", "a", "[", "i", "]", ",", "i", "+", "1", ")", "return", "idx" ]
Returns the thumbnail dimensions depending on the images format .
def calculate_dimensions ( image , long_side , short_side ) : if image . width >= image . height : return '{0}x{1}' . format ( long_side , short_side ) return '{0}x{1}' . format ( short_side , long_side )
1,672
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L95-L99
[ "def", "parseStr", "(", "self", ",", "st", ")", ":", "self", ".", "data", "=", "st", ".", "replace", "(", "'\\r'", ",", "'\\n'", ")", "self", ".", "data", "=", "self", ".", "data", ".", "replace", "(", "'\\n\\n'", ",", "'\\n'", ")", "self", ".", "data", "=", "self", ".", "data", ".", "split", "(", "'\\n'", ")" ]
Allows to call any method of any object with parameters .
def call ( obj , method , * args , * * kwargs ) : function_or_dict_or_member = getattr ( obj , method ) if callable ( function_or_dict_or_member ) : # If it is a function, let's call it return function_or_dict_or_member ( * args , * * kwargs ) if not len ( args ) : # If it is a member, lets return it return function_or_dict_or_member # If it is a dict, let's access one of it's keys return function_or_dict_or_member [ args [ 0 ] ]
1,673
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L103-L129
[ "def", "sort_values", "(", "self", ",", "ascending", "=", "False", ")", ":", "if", "self", ".", "index_type", "is", "not", "None", ":", "index_expr", "=", "grizzly_impl", ".", "get_field", "(", "self", ".", "expr", ",", "0", ")", "column_expr", "=", "grizzly_impl", ".", "get_field", "(", "self", ".", "expr", ",", "1", ")", "zip_expr", "=", "grizzly_impl", ".", "zip_columns", "(", "[", "index_expr", ",", "column_expr", "]", ")", "result_expr", "=", "grizzly_impl", ".", "sort", "(", "zip_expr", ",", "1", ",", "self", ".", "weld_type", ",", "ascending", ")", "unzip_expr", "=", "grizzly_impl", ".", "unzip_columns", "(", "result_expr", ",", "[", "self", ".", "index_type", ",", "self", ".", "weld_type", "]", ")", "return", "SeriesWeld", "(", "unzip_expr", ",", "self", ".", "weld_type", ",", "self", ".", "df", ",", "self", ".", "column_name", ",", "self", ".", "index_type", ",", "self", ".", "index_name", ")", "else", ":", "result_expr", "=", "grizzly_impl", ".", "sort", "(", "self", ".", "expr", ")" ]
Concatenates the given strings .
def concatenate ( * args , * * kwargs ) : divider = kwargs . get ( 'divider' , '' ) result = '' for arg in args : if result == '' : result += arg else : result += '{0}{1}' . format ( divider , arg ) return result
1,674
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L133-L153
[ "def", "multivariate_neg_logposterior", "(", "self", ",", "beta", ")", ":", "post", "=", "self", ".", "neg_loglik", "(", "beta", ")", "for", "k", "in", "range", "(", "0", ",", "self", ".", "z_no", ")", ":", "if", "self", ".", "latent_variables", ".", "z_list", "[", "k", "]", ".", "prior", ".", "covariance_prior", "is", "True", ":", "post", "+=", "-", "self", ".", "latent_variables", ".", "z_list", "[", "k", "]", ".", "prior", ".", "logpdf", "(", "self", ".", "custom_covariance", "(", "beta", ")", ")", "break", "else", ":", "post", "+=", "-", "self", ".", "latent_variables", ".", "z_list", "[", "k", "]", ".", "prior", ".", "logpdf", "(", "beta", "[", "k", "]", ")", "return", "post" ]
Returns the content type of an object .
def get_content_type ( obj , field_name = False ) : content_type = ContentType . objects . get_for_model ( obj ) if field_name : return getattr ( content_type , field_name , '' ) return content_type
1,675
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L157-L168
[ "def", "_remove_persistent_module", "(", "mod", ",", "comment", ")", ":", "if", "not", "mod", "or", "mod", "not", "in", "mod_list", "(", "True", ")", ":", "return", "set", "(", ")", "if", "comment", ":", "__salt__", "[", "'file.comment'", "]", "(", "_LOADER_CONF", ",", "_MODULE_RE", ".", "format", "(", "mod", ")", ")", "else", ":", "__salt__", "[", "'file.sed'", "]", "(", "_LOADER_CONF", ",", "_MODULE_RE", ".", "format", "(", "mod", ")", ",", "''", ")", "return", "set", "(", "[", "mod", "]", ")" ]
Returns the verbose name of an object s field .
def get_verbose ( obj , field_name = "" ) : if hasattr ( obj , "_meta" ) and hasattr ( obj . _meta , "get_field_by_name" ) : try : return obj . _meta . get_field ( field_name ) . verbose_name except FieldDoesNotExist : pass return ""
1,676
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L200-L213
[ "def", "unbind", "(", "self", ",", "devices_to_unbind", ")", ":", "if", "self", ".", "entity_api_key", "==", "\"\"", ":", "return", "{", "'status'", ":", "'failure'", ",", "'response'", ":", "'No API key found in request'", "}", "url", "=", "self", ".", "base_url", "+", "\"api/0.1.0/subscribe/unbind\"", "headers", "=", "{", "\"apikey\"", ":", "self", ".", "entity_api_key", "}", "data", "=", "{", "\"exchange\"", ":", "\"amq.topic\"", ",", "\"keys\"", ":", "devices_to_unbind", ",", "\"queue\"", ":", "self", ".", "entity_id", "}", "with", "self", ".", "no_ssl_verification", "(", ")", ":", "r", "=", "requests", ".", "delete", "(", "url", ",", "json", "=", "data", ",", "headers", "=", "headers", ")", "print", "(", "r", ")", "response", "=", "dict", "(", ")", "if", "\"No API key\"", "in", "str", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", ":", "response", "[", "\"status\"", "]", "=", "\"failure\"", "r", "=", "json", ".", "loads", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", "[", "'message'", "]", "elif", "'unbind'", "in", "str", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", ":", "response", "[", "\"status\"", "]", "=", "\"success\"", "r", "=", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "else", ":", "response", "[", "\"status\"", "]", "=", "\"failure\"", "r", "=", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "response", "[", "\"response\"", "]", "=", "str", "(", "r", ")", "return", "response" ]
Allows to change one of the URL get parameter while keeping all the others .
def get_query_params ( request , * args ) : query = request . GET . copy ( ) index = 1 key = '' for arg in args : if index % 2 != 0 : key = arg else : if arg == "!remove" : try : query . pop ( key ) except KeyError : pass else : query [ key ] = arg index += 1 return query . urlencode ( )
1,677
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L217-L258
[ "def", "_error_messages", "(", "self", ",", "driver_id", ")", ":", "assert", "isinstance", "(", "driver_id", ",", "ray", ".", "DriverID", ")", "message", "=", "self", ".", "redis_client", ".", "execute_command", "(", "\"RAY.TABLE_LOOKUP\"", ",", "ray", ".", "gcs_utils", ".", "TablePrefix", ".", "ERROR_INFO", ",", "\"\"", ",", "driver_id", ".", "binary", "(", ")", ")", "# If there are no errors, return early.", "if", "message", "is", "None", ":", "return", "[", "]", "gcs_entries", "=", "ray", ".", "gcs_utils", ".", "GcsTableEntry", ".", "GetRootAsGcsTableEntry", "(", "message", ",", "0", ")", "error_messages", "=", "[", "]", "for", "i", "in", "range", "(", "gcs_entries", ".", "EntriesLength", "(", ")", ")", ":", "error_data", "=", "ray", ".", "gcs_utils", ".", "ErrorTableData", ".", "GetRootAsErrorTableData", "(", "gcs_entries", ".", "Entries", "(", "i", ")", ",", "0", ")", "assert", "driver_id", ".", "binary", "(", ")", "==", "error_data", ".", "DriverId", "(", ")", "error_message", "=", "{", "\"type\"", ":", "decode", "(", "error_data", ".", "Type", "(", ")", ")", ",", "\"message\"", ":", "decode", "(", "error_data", ".", "ErrorMessage", "(", ")", ")", ",", "\"timestamp\"", ":", "error_data", ".", "Timestamp", "(", ")", ",", "}", "error_messages", ".", "append", "(", "error_message", ")", "return", "error_messages" ]
Returns active if the given URL is in the url path otherwise .
def navactive ( request , url , exact = 0 , use_resolver = 1 ) : if use_resolver : try : if url == resolve ( request . path ) . url_name : # Checks the url pattern in case a view_name is posted return 'active' elif url == request . path : # Workaround to catch URLs with more than one part, which don't # raise a Resolver404 (e.g. '/index/info/') match = request . path else : return '' except Resolver404 : # Indicates, that a simple url string is used (e.g. '/index/') match = request . path else : match = request . path if exact and url == match : return 'active' elif not exact and url in request . path : return 'active' return ''
1,678
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L290-L331
[ "def", "write_result_stream", "(", "result_stream", ",", "filename_prefix", "=", "None", ",", "results_per_file", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "result_stream", ",", "types", ".", "GeneratorType", ")", ":", "stream", "=", "result_stream", "else", ":", "stream", "=", "result_stream", ".", "stream", "(", ")", "file_time_formatter", "=", "\"%Y-%m-%dT%H_%M_%S\"", "if", "filename_prefix", "is", "None", ":", "filename_prefix", "=", "\"twitter_search_results\"", "if", "results_per_file", ":", "logger", ".", "info", "(", "\"chunking result stream to files with {} tweets per file\"", ".", "format", "(", "results_per_file", ")", ")", "chunked_stream", "=", "partition", "(", "stream", ",", "results_per_file", ",", "pad_none", "=", "True", ")", "for", "chunk", "in", "chunked_stream", ":", "chunk", "=", "filter", "(", "lambda", "x", ":", "x", "is", "not", "None", ",", "chunk", ")", "curr_datetime", "=", "(", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "strftime", "(", "file_time_formatter", ")", ")", "_filename", "=", "\"{}_{}.json\"", ".", "format", "(", "filename_prefix", ",", "curr_datetime", ")", "yield", "from", "write_ndjson", "(", "_filename", ",", "chunk", ")", "else", ":", "curr_datetime", "=", "(", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "strftime", "(", "file_time_formatter", ")", ")", "_filename", "=", "\"{}.json\"", ".", "format", "(", "filename_prefix", ")", "yield", "from", "write_ndjson", "(", "_filename", ",", "stream", ")" ]
Returns a range of numbers around the given number .
def get_range_around ( range_value , current_item , padding ) : total_items = 1 + padding * 2 left_bound = padding right_bound = range_value - padding if range_value <= total_items : range_items = range ( 1 , range_value + 1 ) return { 'range_items' : range_items , 'left_padding' : False , 'right_padding' : False , } if current_item <= left_bound : range_items = range ( 1 , range_value + 1 ) [ : total_items ] return { 'range_items' : range_items , 'left_padding' : range_items [ 0 ] > 1 , 'right_padding' : range_items [ - 1 ] < range_value , } if current_item >= right_bound : range_items = range ( 1 , range_value + 1 ) [ - total_items : ] return { 'range_items' : range_items , 'left_padding' : range_items [ 0 ] > 1 , 'right_padding' : range_items [ - 1 ] < range_value , } range_items = range ( current_item - padding , current_item + padding + 1 ) return { 'range_items' : range_items , 'left_padding' : True , 'right_padding' : True , }
1,679
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L364-L420
[ "def", "merge_entities", "(", "self", ",", "from_entity_ids", ",", "to_entity_id", ",", "force", "=", "False", ",", "mount_point", "=", "DEFAULT_MOUNT_POINT", ")", ":", "params", "=", "{", "'from_entity_ids'", ":", "from_entity_ids", ",", "'to_entity_id'", ":", "to_entity_id", ",", "'force'", ":", "force", ",", "}", "api_path", "=", "'/v1/{mount_point}/entity/merge'", ".", "format", "(", "mount_point", "=", "mount_point", ")", "return", "self", ".", "_adapter", ".", "post", "(", "url", "=", "api_path", ",", "json", "=", "params", ",", ")" ]
Adds the given value to the total value currently held in key .
def sum ( context , key , value , multiplier = 1 ) : if key not in context . dicts [ 0 ] : context . dicts [ 0 ] [ key ] = 0 context . dicts [ 0 ] [ key ] += value * multiplier return ''
1,680
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L468-L484
[ "def", "error", "(", "self", ",", "id", ",", "errorCode", ",", "errorString", ")", ":", "if", "errorCode", "==", "165", ":", "# Historical data sevice message", "sys", ".", "stderr", ".", "write", "(", "\"TWS INFO - %s: %s\\n\"", "%", "(", "errorCode", ",", "errorString", ")", ")", "elif", "errorCode", ">=", "501", "and", "errorCode", "<", "600", ":", "# Socket read failed", "sys", ".", "stderr", ".", "write", "(", "\"TWS CLIENT-ERROR - %s: %s\\n\"", "%", "(", "errorCode", ",", "errorString", ")", ")", "elif", "errorCode", ">=", "100", "and", "errorCode", "<", "1100", ":", "sys", ".", "stderr", ".", "write", "(", "\"TWS ERROR - %s: %s\\n\"", "%", "(", "errorCode", ",", "errorString", ")", ")", "elif", "errorCode", ">=", "1100", "and", "errorCode", "<", "2100", ":", "sys", ".", "stderr", ".", "write", "(", "\"TWS SYSTEM-ERROR - %s: %s\\n\"", "%", "(", "errorCode", ",", "errorString", ")", ")", "elif", "errorCode", "in", "(", "2104", ",", "2106", ",", "2108", ")", ":", "sys", ".", "stderr", ".", "write", "(", "\"TWS INFO - %s: %s\\n\"", "%", "(", "errorCode", ",", "errorString", ")", ")", "elif", "errorCode", ">=", "2100", "and", "errorCode", "<=", "2110", ":", "sys", ".", "stderr", ".", "write", "(", "\"TWS WARNING - %s: %s\\n\"", "%", "(", "errorCode", ",", "errorString", ")", ")", "else", ":", "sys", ".", "stderr", ".", "write", "(", "\"TWS ERROR - %s: %s\\n\"", "%", "(", "errorCode", ",", "errorString", ")", ")" ]
Tag to render x - tmpl templates with Django template code .
def verbatim ( parser , token ) : text = [ ] while 1 : token = parser . tokens . pop ( 0 ) if token . contents == 'endverbatim' : break if token . token_type == TOKEN_VAR : text . append ( '{{ ' ) elif token . token_type == TOKEN_BLOCK : text . append ( '{%' ) text . append ( token . contents ) if token . token_type == TOKEN_VAR : text . append ( ' }}' ) elif token . token_type == TOKEN_BLOCK : if not text [ - 1 ] . startswith ( '=' ) : text [ - 1 : - 1 ] = [ ' ' ] text . append ( ' %}' ) return VerbatimNode ( '' . join ( text ) )
1,681
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L502-L520
[ "def", "split", "(", "self", ",", "verbose", "=", "None", ",", "end_in_new_line", "=", "None", ")", ":", "elapsed_time", "=", "self", ".", "get_elapsed_time", "(", ")", "self", ".", "split_elapsed_time", ".", "append", "(", "elapsed_time", ")", "self", ".", "_cumulative_elapsed_time", "+=", "elapsed_time", "self", ".", "_elapsed_time", "=", "datetime", ".", "timedelta", "(", ")", "if", "verbose", "is", "None", ":", "verbose", "=", "self", ".", "verbose_end", "if", "verbose", ":", "if", "end_in_new_line", "is", "None", ":", "end_in_new_line", "=", "self", ".", "end_in_new_line", "if", "end_in_new_line", ":", "self", ".", "log", "(", "\"{} done in {}\"", ".", "format", "(", "self", ".", "description", ",", "elapsed_time", ")", ")", "else", ":", "self", ".", "log", "(", "\" done in {}\"", ".", "format", "(", "elapsed_time", ")", ")", "self", ".", "_start_time", "=", "datetime", ".", "datetime", ".", "now", "(", ")" ]
Adds the possessive s after a string .
def append_s ( value ) : if value . endswith ( 's' ) : return u"{0}'" . format ( value ) else : return u"{0}'s" . format ( value )
1,682
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L566-L577
[ "def", "extract_bus_routine", "(", "page", ")", ":", "if", "not", "isinstance", "(", "page", ",", "pq", ")", ":", "page", "=", "pq", "(", "page", ")", "stations", "=", "extract_stations", "(", "page", ")", "return", "{", "# Routine name.", "'name'", ":", "extract_routine_name", "(", "page", ")", ",", "# Bus stations.", "'stations'", ":", "stations", ",", "# Current routine.", "'current'", ":", "extract_current_routine", "(", "page", ",", "stations", ")", "}" ]
Return the URL patterns for the logs views .
def logs_urlpatterns ( admin_view = lambda x : x ) : return [ url ( r'^$' , admin_view ( LogsMenu . as_view ( ) ) , name = 'logs' ) , url ( r'^status_codes$' , admin_view ( LogsStatusCodes . as_view ( ) ) , name = 'logs_status_codes' ) , url ( r'^status_codes_by_date$' , admin_view ( LogsStatusCodesByDate . as_view ( ) ) , name = 'logs_status_codes_by_date' ) , url ( r'^most_visited_pages$' , admin_view ( LogsMostVisitedPages . as_view ( ) ) , name = 'logs_most_visited_pages' ) ]
1,683
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/urls.py#L11-L34
[ "def", "modify_ack_deadline", "(", "self", ",", "seconds", ")", ":", "self", ".", "_request_queue", ".", "put", "(", "requests", ".", "ModAckRequest", "(", "ack_id", "=", "self", ".", "_ack_id", ",", "seconds", "=", "seconds", ")", ")" ]
Get information about an IP .
def _get ( self , ip ) : # Geoloc updated up to once a week: # http://ipinfo.io/developers/data#geolocation-data retries = 10 for retry in range ( retries ) : try : response = requests . get ( 'http://ipinfo.io/%s/json' % ip , verify = False , timeout = 1 ) # nosec if response . status_code == 429 : raise RateExceededError return response . json ( ) except ( requests . ReadTimeout , requests . ConnectTimeout ) : pass return { }
1,684
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/ip_info.py#L100-L122
[ "def", "merge_entities", "(", "self", ",", "from_entity_ids", ",", "to_entity_id", ",", "force", "=", "False", ",", "mount_point", "=", "DEFAULT_MOUNT_POINT", ")", ":", "params", "=", "{", "'from_entity_ids'", ":", "from_entity_ids", ",", "'to_entity_id'", ":", "to_entity_id", ",", "'force'", ":", "force", ",", "}", "api_path", "=", "'/v1/{mount_point}/entity/merge'", ".", "format", "(", "mount_point", "=", "mount_point", ")", "return", "self", ".", "_adapter", ".", "post", "(", "url", "=", "api_path", ",", "json", "=", "params", ",", ")" ]
Parses a raw datagram and return the right type of message
def parse ( data ) : # convert to string data = data . decode ( "ascii" ) if len ( data ) == 2 and data == "A5" : return AckMessage ( ) # split into bytes raw = [ data [ i : i + 2 ] for i in range ( len ( data ) ) if i % 2 == 0 ] if len ( raw ) != 7 : return UnknownMessage ( raw ) if raw [ 1 ] == "B8" : return StateMessage ( raw ) elif raw [ 3 ] == "12" : return CommandMessage ( raw ) elif raw [ 3 ] == "14" : return ScenarioTriggeredMessage ( raw ) elif raw [ 3 ] == "15" : return RequestStatusMessage ( raw ) else : return UnknownMessage ( raw )
1,685
https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/messages.py#L213-L237
[ "def", "assert_coordinate_consistent", "(", "obj", ",", "coords", ")", ":", "for", "k", "in", "obj", ".", "dims", ":", "# make sure there are no conflict in dimension coordinates", "if", "k", "in", "coords", "and", "k", "in", "obj", ".", "coords", ":", "if", "not", "coords", "[", "k", "]", ".", "equals", "(", "obj", "[", "k", "]", ".", "variable", ")", ":", "raise", "IndexError", "(", "'dimension coordinate {!r} conflicts between '", "'indexed and indexing objects:\\n{}\\nvs.\\n{}'", ".", "format", "(", "k", ",", "obj", "[", "k", "]", ",", "coords", "[", "k", "]", ")", ")" ]
Returns a XOR of all the bytes specified inside of the given list
def checksum_bytes ( data ) : int_values = [ int ( x , 16 ) for x in data ] int_xor = reduce ( lambda x , y : x ^ y , int_values ) hex_xor = "{:X}" . format ( int_xor ) if len ( hex_xor ) % 2 != 0 : hex_xor = "0" + hex_xor return str . encode ( hex_xor )
1,686
https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/messages.py#L240-L249
[ "def", "drdpgr", "(", "body", ",", "lon", ",", "lat", ",", "alt", ",", "re", ",", "f", ")", ":", "body", "=", "stypes", ".", "stringToCharP", "(", "body", ")", "lon", "=", "ctypes", ".", "c_double", "(", "lon", ")", "lat", "=", "ctypes", ".", "c_double", "(", "lat", ")", "alt", "=", "ctypes", ".", "c_double", "(", "alt", ")", "re", "=", "ctypes", ".", "c_double", "(", "re", ")", "f", "=", "ctypes", ".", "c_double", "(", "f", ")", "jacobi", "=", "stypes", ".", "emptyDoubleMatrix", "(", ")", "libspice", ".", "drdpgr_c", "(", "body", ",", "lon", ",", "lat", ",", "alt", ",", "re", ",", "f", ",", "jacobi", ")", "return", "stypes", ".", "cMatrixToNumpy", "(", "jacobi", ")" ]
Compose a SCS message
def compose_telegram ( body ) : msg = [ b"A8" ] + body + [ checksum_bytes ( body ) ] + [ b"A3" ] return str . encode ( "" . join ( [ x . decode ( ) for x in msg ] ) )
1,687
https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/messages.py#L252-L260
[ "def", "_openResources", "(", "self", ")", ":", "try", ":", "rate", ",", "data", "=", "scipy", ".", "io", ".", "wavfile", ".", "read", "(", "self", ".", "_fileName", ",", "mmap", "=", "True", ")", "except", "Exception", "as", "ex", ":", "logger", ".", "warning", "(", "ex", ")", "logger", ".", "warning", "(", "\"Unable to read wav with memmory mapping. Trying without now.\"", ")", "rate", ",", "data", "=", "scipy", ".", "io", ".", "wavfile", ".", "read", "(", "self", ".", "_fileName", ",", "mmap", "=", "False", ")", "self", ".", "_array", "=", "data", "self", ".", "attributes", "[", "'rate'", "]", "=", "rate" ]
Sends an email based on templates for subject and body .
def send_email ( request , context , subject_template , body_template , from_email , recipients , priority = "medium" , reply_to = None , headers = None , cc = None , bcc = None ) : headers = headers or { } if not reply_to : reply_to = from_email # Add additional context if hasattr ( settings , 'DJANGO_LIBS_EMAIL_CONTEXT' ) : context_fn = load_member_from_setting ( 'DJANGO_LIBS_EMAIL_CONTEXT' ) context . update ( context_fn ( request ) ) if request and request . get_host ( ) : domain = request . get_host ( ) protocol = 'https://' if request . is_secure ( ) else 'http://' else : domain = getattr ( settings , 'DOMAIN' , Site . objects . get_current ( ) . domain ) protocol = getattr ( settings , 'PROTOCOL' , 'http://' ) context . update ( { 'domain' : domain , 'protocol' : protocol , } ) subject = render_to_string ( template_name = subject_template , context = context , request = request ) subject = '' . join ( subject . splitlines ( ) ) message_html = render_to_string ( template_name = body_template , context = context , request = request ) message_plaintext = html_to_plain_text ( message_html ) subject = force_text ( subject ) message = force_text ( message_plaintext ) email = EmailMultiAlternatives ( subject = subject , body = message , from_email = from_email , to = recipients , cc = cc , bcc = bcc , headers = headers , reply_to = [ reply_to ] , ) email . attach_alternative ( message_html , "text/html" ) if settings . EMAIL_BACKEND == 'mailer.backend.DbBackend' : # We customize `mailer.send_html_mail` to enable CC and BCC priority = mailer . get_priority ( priority ) msg = make_message ( subject = subject , body = message , from_email = from_email , to = recipients , priority = priority , ) msg . email = email msg . save ( ) else : email . send ( )
1,688
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/utils/email.py#L18-L92
[ "def", "_getLPA", "(", "self", ")", ":", "return", "str", "(", "self", ".", "line", ")", "+", "\":\"", "+", "str", "(", "self", ".", "pos", ")", "+", "\":\"", "+", "str", "(", "self", ".", "absPosition", ")" ]
Check if URL is part of the current project s URLs .
def url_is_project ( url , default = 'not_a_func' ) : try : u = resolve ( url ) if u and u . func != default : return True except Resolver404 : static_url = settings . STATIC_URL static_url_wd = static_url . lstrip ( '/' ) if url . startswith ( static_url ) : url = url [ len ( static_url ) : ] elif url . startswith ( static_url_wd ) : url = url [ len ( static_url_wd ) : ] else : return False if finders . find ( url ) : return True return False
1,689
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/url.py#L14-L40
[ "def", "read_tabular", "(", "filename", ",", "dtype_conversion", "=", "None", ")", ":", "if", "dtype_conversion", "is", "None", ":", "dtype_conversion", "=", "{", "}", "name", ",", "ext", "=", "filename", ".", "split", "(", "\".\"", ",", "1", ")", "ext", "=", "ext", ".", "lower", "(", ")", "# Completely empty columns are interpreted as float by default.", "dtype_conversion", "[", "\"comment\"", "]", "=", "str", "if", "\"csv\"", "in", "ext", ":", "df", "=", "pd", ".", "read_csv", "(", "filename", ",", "dtype", "=", "dtype_conversion", ",", "encoding", "=", "\"utf-8\"", ")", "elif", "\"tsv\"", "in", "ext", ":", "df", "=", "pd", ".", "read_table", "(", "filename", ",", "dtype", "=", "dtype_conversion", ",", "encoding", "=", "\"utf-8\"", ")", "elif", "\"xls\"", "in", "ext", "or", "\"xlsx\"", "in", "ext", ":", "df", "=", "pd", ".", "read_excel", "(", "filename", ",", "dtype", "=", "dtype_conversion", ",", "encoding", "=", "\"utf-8\"", ")", "# TODO: Add a function to parse ODS data into a pandas data frame.", "else", ":", "raise", "ValueError", "(", "\"Unknown file format '{}'.\"", ".", "format", "(", "ext", ")", ")", "return", "df" ]
Function generator .
def url_is ( white_list ) : def func ( url ) : prefixes = white_list . get ( 'PREFIXES' , ( ) ) for prefix in prefixes : if url . startswith ( prefix ) : return True constants = white_list . get ( 'CONSTANTS' , ( ) ) for exact_url in constants : if url == exact_url : return True return False return func
1,690
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/url.py#L43-L63
[ "def", "_add_dependency", "(", "self", ",", "dependency", ",", "var_name", "=", "None", ")", ":", "if", "var_name", "is", "None", ":", "var_name", "=", "next", "(", "self", ".", "temp_var_names", ")", "# Don't add duplicate dependencies", "if", "(", "dependency", ",", "var_name", ")", "not", "in", "self", ".", "dependencies", ":", "self", ".", "dependencies", ".", "append", "(", "(", "dependency", ",", "var_name", ")", ")", "return", "var_name" ]
Save a collection of records
def save_records ( self , records ) : for record in records : if not isinstance ( record , Record ) : record = Record ( * record ) self . save_record ( * record )
1,691
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/history.py#L70-L77
[ "def", "create_experiment", "(", "args", ")", ":", "config_file_name", "=", "''", ".", "join", "(", "random", ".", "sample", "(", "string", ".", "ascii_letters", "+", "string", ".", "digits", ",", "8", ")", ")", "nni_config", "=", "Config", "(", "config_file_name", ")", "config_path", "=", "os", ".", "path", ".", "abspath", "(", "args", ".", "config", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "config_path", ")", ":", "print_error", "(", "'Please set correct config path!'", ")", "exit", "(", "1", ")", "experiment_config", "=", "get_yml_content", "(", "config_path", ")", "validate_all_content", "(", "experiment_config", ",", "config_path", ")", "nni_config", ".", "set_config", "(", "'experimentConfig'", ",", "experiment_config", ")", "launch_experiment", "(", "args", ",", "experiment_config", ",", "'new'", ",", "config_file_name", ")", "nni_config", ".", "set_config", "(", "'restServerPort'", ",", "args", ".", "port", ")" ]
Save a collection of records to the database . Database writes are cached .
def save_record ( self , agent_id , t_step , key , value ) : value = self . convert ( key , value ) self . _tups . append ( Record ( agent_id = agent_id , t_step = t_step , key = key , value = value ) ) if len ( self . _tups ) > 100 : self . flush_cache ( )
1,692
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/history.py#L79-L90
[ "def", "start", "(", "self", ")", ":", "t", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_consume", ")", "t", ".", "start", "(", ")" ]
Get the serialized value for a given key .
def convert ( self , key , value ) : if key not in self . _dtypes : self . read_types ( ) if key not in self . _dtypes : name = utils . name ( value ) serializer = utils . serializer ( name ) deserializer = utils . deserializer ( name ) self . _dtypes [ key ] = ( name , serializer , deserializer ) with self . db : self . db . execute ( "replace into value_types (key, value_type) values (?, ?)" , ( key , name ) ) return self . _dtypes [ key ] [ 1 ] ( value )
1,693
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/history.py#L92-L103
[ "def", "onboarding_message", "(", "*", "*", "payload", ")", ":", "# Get WebClient so you can communicate back to Slack.", "web_client", "=", "payload", "[", "\"web_client\"", "]", "# Get the id of the Slack user associated with the incoming event", "user_id", "=", "payload", "[", "\"data\"", "]", "[", "\"user\"", "]", "[", "\"id\"", "]", "# Open a DM with the new user.", "response", "=", "web_client", ".", "im_open", "(", "user_id", ")", "channel", "=", "response", "[", "\"channel\"", "]", "[", "\"id\"", "]", "# Post the onboarding message.", "start_onboarding", "(", "web_client", ",", "user_id", ",", "channel", ")" ]
Get the deserialized value for a given key and the serialized version .
def recover ( self , key , value ) : if key not in self . _dtypes : self . read_types ( ) if key not in self . _dtypes : raise ValueError ( "Unknown datatype for {} and {}" . format ( key , value ) ) return self . _dtypes [ key ] [ 2 ] ( value )
1,694
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/history.py#L105-L111
[ "def", "add_metadata", "(", "file_name", ",", "title", ",", "artist", ",", "album", ")", ":", "tags", "=", "EasyMP3", "(", "file_name", ")", "if", "title", ":", "tags", "[", "\"title\"", "]", "=", "title", "if", "artist", ":", "tags", "[", "\"artist\"", "]", "=", "artist", "if", "album", ":", "tags", "[", "\"album\"", "]", "=", "album", "tags", ".", "save", "(", ")", "return", "file_name" ]
Use a cache to save state changes to avoid opening a session for every change . The cache will be flushed at the end of the simulation and when history is accessed .
def flush_cache ( self ) : logger . debug ( 'Flushing cache {}' . format ( self . db_path ) ) with self . db : for rec in self . _tups : self . db . execute ( "replace into history(agent_id, t_step, key, value) values (?, ?, ?, ?)" , ( rec . agent_id , rec . t_step , rec . key , rec . value ) ) self . _tups = list ( )
1,695
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/history.py#L114-L123
[ "def", "crypto_pairing", "(", "pairing_data", ")", ":", "message", "=", "create", "(", "protobuf", ".", "CRYPTO_PAIRING_MESSAGE", ")", "crypto", "=", "message", ".", "inner", "(", ")", "crypto", ".", "status", "=", "0", "crypto", ".", "pairingData", "=", "tlv8", ".", "write_tlv", "(", "pairing_data", ")", "return", "message" ]
Load records .
def records ( ) : import pkg_resources import uuid from dojson . contrib . marc21 import marc21 from dojson . contrib . marc21 . utils import create_record , split_blob from invenio_pidstore import current_pidstore from invenio_records . api import Record # pkg resources the demodata data_path = pkg_resources . resource_filename ( 'invenio_records' , 'data/marc21/bibliographic.xml' ) with open ( data_path ) as source : indexer = RecordIndexer ( ) with db . session . begin_nested ( ) : for index , data in enumerate ( split_blob ( source . read ( ) ) , start = 1 ) : # create uuid rec_uuid = uuid . uuid4 ( ) # do translate record = marc21 . do ( create_record ( data ) ) # create PID current_pidstore . minters [ 'recid' ] ( rec_uuid , record ) # create record indexer . index ( Record . create ( record , id_ = rec_uuid ) ) db . session . commit ( )
1,696
https://github.com/inveniosoftware/invenio-search-ui/blob/4b61737f938cbfdc1aad6602a73f3a24d53b3312/examples/app.py#L206-L233
[ "def", "_add_dependency", "(", "self", ",", "dependency", ",", "var_name", "=", "None", ")", ":", "if", "var_name", "is", "None", ":", "var_name", "=", "next", "(", "self", ".", "temp_var_names", ")", "# Don't add duplicate dependencies", "if", "(", "dependency", ",", "var_name", ")", "not", "in", "self", ".", "dependencies", ":", "self", ".", "dependencies", ".", "append", "(", "(", "dependency", ",", "var_name", ")", ")", "return", "var_name" ]
A wrapper for run_trial that catches exceptions and returns them . It is meant for async simulations
def run_trial_exceptions ( self , * args , * * kwargs ) : try : return self . run_trial ( * args , * * kwargs ) except Exception as ex : c = ex . __cause__ c . message = '' . join ( traceback . format_exception ( type ( c ) , c , c . __traceback__ ) [ : ] ) return c
1,697
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/simulation.py#L196-L206
[ "def", "set_digest", "(", "self", ",", "realm", ",", "nonce", ",", "qop", "=", "(", "\"auth\"", ",", ")", ",", "opaque", "=", "None", ",", "algorithm", "=", "None", ",", "stale", "=", "False", ")", ":", "d", "=", "{", "\"__auth_type__\"", ":", "\"digest\"", ",", "\"realm\"", ":", "realm", ",", "\"nonce\"", ":", "nonce", ",", "\"qop\"", ":", "dump_header", "(", "qop", ")", ",", "}", "if", "stale", ":", "d", "[", "\"stale\"", "]", "=", "\"TRUE\"", "if", "opaque", "is", "not", "None", ":", "d", "[", "\"opaque\"", "]", "=", "opaque", "if", "algorithm", "is", "not", "None", ":", "d", "[", "\"algorithm\"", "]", "=", "algorithm", "dict", ".", "clear", "(", "self", ")", "dict", ".", "update", "(", "self", ",", "d", ")", "if", "self", ".", "on_update", ":", "self", ".", "on_update", "(", "self", ")" ]
Search the ORCID public API
def search_orcid ( orcid ) : url = 'https://pub.orcid.org/v2.1/{orcid}/person' . format ( orcid = orcid ) r = requests . get ( url , headers = headers ) if r . status_code != 200 : r . raise_for_status ( ) return r . json ( )
1,698
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/orcid.py#L8-L29
[ "def", "swap_vertices", "(", "self", ",", "i", ",", "j", ")", ":", "store_vertex_i", "=", "self", ".", "vertices", "[", "i", "]", "store_vertex_j", "=", "self", ".", "vertices", "[", "j", "]", "self", ".", "vertices", "[", "j", "]", "=", "store_vertex_i", "self", ".", "vertices", "[", "i", "]", "=", "store_vertex_j", "for", "k", "in", "range", "(", "len", "(", "self", ".", "vertices", ")", ")", ":", "for", "swap_list", "in", "[", "self", ".", "vertices", "[", "k", "]", ".", "children", ",", "self", ".", "vertices", "[", "k", "]", ".", "parents", "]", ":", "if", "i", "in", "swap_list", ":", "swap_list", "[", "swap_list", ".", "index", "(", "i", ")", "]", "=", "-", "1", "if", "j", "in", "swap_list", ":", "swap_list", "[", "swap_list", ".", "index", "(", "j", ")", "]", "=", "i", "if", "-", "1", "in", "swap_list", ":", "swap_list", "[", "swap_list", ".", "index", "(", "-", "1", ")", "]", "=", "j" ]
Yield one date per day from starting date to ending date .
def daterange ( start_date , end_date ) : for n in range ( int ( ( end_date - start_date ) . days ) ) : yield start_date + timedelta ( n )
1,699
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/time.py#L21-L33
[ "def", "cli", "(", "env", ",", "crt", ",", "csr", ",", "icc", ",", "key", ",", "notes", ")", ":", "template", "=", "{", "'intermediateCertificate'", ":", "''", ",", "'certificateSigningRequest'", ":", "''", ",", "'notes'", ":", "notes", ",", "}", "template", "[", "'certificate'", "]", "=", "open", "(", "crt", ")", ".", "read", "(", ")", "template", "[", "'privateKey'", "]", "=", "open", "(", "key", ")", ".", "read", "(", ")", "if", "csr", ":", "body", "=", "open", "(", "csr", ")", ".", "read", "(", ")", "template", "[", "'certificateSigningRequest'", "]", "=", "body", "if", "icc", ":", "body", "=", "open", "(", "icc", ")", ".", "read", "(", ")", "template", "[", "'intermediateCertificate'", "]", "=", "body", "manager", "=", "SoftLayer", ".", "SSLManager", "(", "env", ".", "client", ")", "manager", ".", "add_certificate", "(", "template", ")" ]