idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
61,000 | def parse_version ( output ) : for x in output . splitlines ( ) : match = VERSION_PATTERN . match ( x ) if match : return match . group ( 'version' ) . strip ( ) return None | Parses the supplied output and returns the version string . |
61,001 | def parse_alert ( output ) : for x in output . splitlines ( ) : match = ALERT_PATTERN . match ( x ) if match : rec = { 'timestamp' : datetime . strptime ( match . group ( 'timestamp' ) , '%m/%d/%y-%H:%M:%S.%f' ) , 'sid' : int ( match . group ( 'sid' ) ) , 'revision' : int ( match . group ( 'revision' ) ) , 'priority' : int ( match . group ( 'priority' ) ) , 'message' : match . group ( 'message' ) , 'source' : match . group ( 'src' ) , 'destination' : match . group ( 'dest' ) , 'protocol' : match . group ( 'protocol' ) , } if match . group ( 'classtype' ) : rec [ 'classtype' ] = match . group ( 'classtype' ) yield rec | Parses the supplied output and yields any alerts . |
61,002 | def run ( self , pcap ) : proc = Popen ( self . _snort_cmd ( pcap ) , stdout = PIPE , stderr = PIPE , universal_newlines = True ) stdout , stderr = proc . communicate ( ) if proc . returncode != 0 : raise Exception ( "\n" . join ( [ "Execution failed return code: {0}" . format ( proc . returncode ) , stderr or "" ] ) ) return ( parse_version ( stderr ) , [ x for x in parse_alert ( stdout ) ] ) | Runs snort against the supplied pcap . |
61,003 | def run ( self , pcap ) : tmpdir = None try : tmpdir = tempfile . mkdtemp ( prefix = 'tmpsuri' ) proc = Popen ( self . _suri_cmd ( pcap , tmpdir ) , stdout = PIPE , stderr = PIPE , universal_newlines = True ) stdout , stderr = proc . communicate ( ) if proc . returncode != 0 : raise Exception ( "\n" . join ( [ "Execution failed return code: {0}" . format ( proc . returncode ) , stderr or "" ] ) ) with open ( os . path . join ( tmpdir , 'fast.log' ) ) as tmp : return ( parse_version ( stdout ) , [ x for x in parse_alert ( tmp . read ( ) ) ] ) finally : if tmpdir : shutil . rmtree ( tmpdir ) | Runs suricata against the supplied pcap . |
61,004 | def analyse_pcap ( infile , filename ) : tmp = tempfile . NamedTemporaryFile ( suffix = ".pcap" , delete = False ) m = hashlib . md5 ( ) results = { 'filename' : filename , 'status' : 'Failed' , 'apiversion' : __version__ , } try : size = 0 while True : buf = infile . read ( 16384 ) if not buf : break tmp . write ( buf ) size += len ( buf ) m . update ( buf ) tmp . close ( ) results [ 'md5' ] = m . hexdigest ( ) results [ 'filesize' ] = size results . update ( runner . run ( tmp . name ) ) except OSError as ex : results [ 'stderr' ] = str ( ex ) finally : os . remove ( tmp . name ) return results | Run IDS across the supplied file . |
61,005 | def submit_and_render ( ) : data = request . files . file template = env . get_template ( "results.html" ) if not data : pass results = analyse_pcap ( data . file , data . filename ) results . update ( base ) return template . render ( results ) | Blocking POST handler for file submission . Runs snort on supplied file and returns results as rendered html . |
61,006 | def api_submit ( ) : data = request . files . file response . content_type = 'application/json' if not data or not hasattr ( data , 'file' ) : return json . dumps ( { "status" : "Failed" , "stderr" : "Missing form params" } ) return json . dumps ( analyse_pcap ( data . file , data . filename ) , default = jsondate , indent = 4 ) | Blocking POST handler for file submission . Runs snort on supplied file and returns results as json text . |
61,007 | def main ( ) : parser = argparse . ArgumentParser ( ) parser . add_argument ( "-H" , "--host" , help = "Web server Host address to bind to" , default = "0.0.0.0" , action = "store" , required = False ) parser . add_argument ( "-p" , "--port" , help = "Web server Port to bind to" , default = 8080 , action = "store" , required = False ) args = parser . parse_args ( ) logging . basicConfig ( ) run ( host = args . host , port = args . port , reloader = True , server = SERVER ) | Main entrypoint for command - line webserver . |
61,008 | def is_pcap ( pcap ) : with open ( pcap , 'rb' ) as tmp : header = tmp . read ( 4 ) if header == b"\xa1\xb2\xc3\xd4" or header == b"\xd4\xc3\xb2\xa1" : return True return False | Simple test for pcap magic bytes in supplied file . |
61,009 | def _run_ids ( runner , pcap ) : run = { 'name' : runner . conf . get ( 'name' ) , 'module' : runner . conf . get ( 'module' ) , 'ruleset' : runner . conf . get ( 'ruleset' , 'default' ) , 'status' : STATUS_FAILED , } try : run_start = datetime . now ( ) version , alerts = runner . run ( pcap ) run [ 'version' ] = version or 'Unknown' run [ 'status' ] = STATUS_SUCCESS run [ 'alerts' ] = alerts except Exception as ex : run [ 'error' ] = str ( ex ) finally : run [ 'duration' ] = duration ( run_start ) return run | Runs the specified IDS runner . |
61,010 | def run ( pcap ) : start = datetime . now ( ) errors = [ ] status = STATUS_FAILED analyses = [ ] pool = ThreadPool ( MAX_THREADS ) try : if not is_pcap ( pcap ) : raise Exception ( "Not a valid pcap file" ) runners = [ ] for conf in Config ( ) . modules . values ( ) : runner = registry . get ( conf [ 'module' ] ) if not runner : raise Exception ( "No module named: '{0}' found registered" . format ( conf [ 'module' ] ) ) runners . append ( runner ( conf ) ) analyses = [ pool . apply_async ( _run_ids , ( runner , pcap ) ) for runner in runners ] analyses = [ x . get ( ) for x in analyses ] if all ( [ x [ 'status' ] == STATUS_SUCCESS for x in analyses ] ) : status = STATUS_SUCCESS for run in [ x for x in analyses if x [ 'status' ] != STATUS_SUCCESS ] : errors . append ( "Failed to run {0}: {1}" . format ( run [ 'name' ] , run [ 'error' ] ) ) except Exception as ex : errors . append ( str ( ex ) ) return { 'start' : start , 'duration' : duration ( start ) , 'status' : status , 'analyses' : analyses , 'errors' : errors , } | Runs all configured IDS instances against the supplied pcap . |
61,011 | def _set_up_pool_config ( self ) : self . _max_conns = self . settings_dict [ 'OPTIONS' ] . get ( 'MAX_CONNS' , pool_config_defaults [ 'MAX_CONNS' ] ) self . _min_conns = self . settings_dict [ 'OPTIONS' ] . get ( 'MIN_CONNS' , self . _max_conns ) self . _test_on_borrow = self . settings_dict [ "OPTIONS" ] . get ( 'TEST_ON_BORROW' , pool_config_defaults [ 'TEST_ON_BORROW' ] ) if self . _test_on_borrow : self . _test_on_borrow_query = self . settings_dict [ "OPTIONS" ] . get ( 'TEST_ON_BORROW_QUERY' , pool_config_defaults [ 'TEST_ON_BORROW_QUERY' ] ) else : self . _test_on_borrow_query = None | Helper to configure pool options during DatabaseWrapper initialization . |
61,012 | def _create_connection_pool ( self , conn_params ) : connection_pools_lock . acquire ( ) try : if ( self . alias not in connection_pools or connection_pools [ self . alias ] [ 'settings' ] != self . settings_dict ) : logger . info ( "Creating connection pool for db alias %s" % self . alias ) logger . info ( " using MIN_CONNS = %s, MAX_CONNS = %s, TEST_ON_BORROW = %s" % ( self . _min_conns , self . _max_conns , self . _test_on_borrow ) ) from psycopg2 import pool connection_pools [ self . alias ] = { 'pool' : pool . ThreadedConnectionPool ( self . _min_conns , self . _max_conns , ** conn_params ) , 'settings' : dict ( self . settings_dict ) , } finally : connection_pools_lock . release ( ) | Helper to initialize the connection pool . |
61,013 | def close ( self ) : if self . _wrapped_connection and self . _pool : logger . debug ( "Returning connection %s to pool %s" % ( self . _wrapped_connection , self . _pool ) ) self . _pool . putconn ( self . _wrapped_connection ) self . _wrapped_connection = None | Override to return the connection to the pool rather than closing it . |
61,014 | def b58encode_int ( i , default_one = True ) : if not i and default_one : return alphabet [ 0 ] string = "" while i : i , idx = divmod ( i , 58 ) string = alphabet [ idx ] + string return string | Encode an integer using Base58 |
61,015 | def breadcrumb_safe ( context , label , viewname , * args , ** kwargs ) : append_breadcrumb ( context , _ ( label ) , viewname , args , kwargs ) return '' | Same as breadcrumb but label is not escaped . |
61,016 | def breadcrumb_raw ( context , label , viewname , * args , ** kwargs ) : append_breadcrumb ( context , escape ( label ) , viewname , args , kwargs ) return '' | Same as breadcrumb but label is not translated . |
61,017 | def breadcrumb_raw_safe ( context , label , viewname , * args , ** kwargs ) : append_breadcrumb ( context , label , viewname , args , kwargs ) return '' | Same as breadcrumb but label is not escaped and translated . |
61,018 | def render_breadcrumbs ( context , * args ) : try : template_path = args [ 0 ] except IndexError : template_path = getattr ( settings , 'BREADCRUMBS_TEMPLATE' , 'django_bootstrap_breadcrumbs/bootstrap2.html' ) links = [ ] for ( label , viewname , view_args , view_kwargs ) in context [ 'request' ] . META . get ( CONTEXT_KEY , [ ] ) : if isinstance ( viewname , Model ) and hasattr ( viewname , 'get_absolute_url' ) and ismethod ( viewname . get_absolute_url ) : url = viewname . get_absolute_url ( * view_args , ** view_kwargs ) else : try : try : current_app = context [ 'request' ] . resolver_match . namespace except AttributeError : try : resolver_match = resolve ( context [ 'request' ] . path ) current_app = resolver_match . namespace except Resolver404 : current_app = None url = reverse ( viewname = viewname , args = view_args , kwargs = view_kwargs , current_app = current_app ) except NoReverseMatch : url = viewname links . append ( ( url , smart_text ( label ) if label else label ) ) if not links : return '' if VERSION > ( 1 , 8 ) : context = context . flatten ( ) context [ 'breadcrumbs' ] = links context [ 'breadcrumbs_total' ] = len ( links ) return mark_safe ( template . loader . render_to_string ( template_path , context ) ) | Render breadcrumbs html using bootstrap css classes . |
61,019 | def _find_symbol ( self , module , name , fallback = None ) : if not hasattr ( module , name ) and fallback : return self . _find_symbol ( module , fallback , None ) return getattr ( module , name ) | Find the symbol of the specified name inside the module or raise an exception . |
61,020 | def apply ( self , incoming ) : assert len ( incoming ) == self . size self . incoming = incoming outgoing = self . activation ( self . incoming ) assert len ( outgoing ) == self . size self . outgoing = outgoing | Store the incoming activation apply the activation function and store the result as outgoing activation . |
61,021 | def delta ( self , above ) : return self . activation . delta ( self . incoming , self . outgoing , above ) | The derivative of the activation function at the current state . |
61,022 | def feed ( self , weights , data ) : assert len ( data ) == self . layers [ 0 ] . size self . layers [ 0 ] . apply ( data ) connections = zip ( self . layers [ : - 1 ] , weights , self . layers [ 1 : ] ) for previous , weight , current in connections : incoming = self . forward ( weight , previous . outgoing ) current . apply ( incoming ) return self . layers [ - 1 ] . outgoing | Evaluate the network with alternative weights on the input data and return the output activation . |
61,023 | def _init_network ( self ) : self . network = Network ( self . problem . layers ) self . weights = Matrices ( self . network . shapes ) if self . load : loaded = np . load ( self . load ) assert loaded . shape == self . weights . shape , ( 'weights to load must match problem definition' ) self . weights . flat = loaded else : self . weights . flat = np . random . normal ( self . problem . weight_mean , self . problem . weight_scale , len ( self . weights . flat ) ) | Define model and initialize weights . |
61,024 | def _init_training ( self ) : if self . check : self . backprop = CheckedBackprop ( self . network , self . problem . cost ) else : self . backprop = BatchBackprop ( self . network , self . problem . cost ) self . momentum = Momentum ( ) self . decent = GradientDecent ( ) self . decay = WeightDecay ( ) self . tying = WeightTying ( * self . problem . weight_tying ) self . weights = self . tying ( self . weights ) | Classes needed during training . |
61,025 | def _every ( times , step_size , index ) : current = index * step_size step = current // times * times reached = current >= step overshot = current >= step + step_size return current and reached and not overshot | Given a loop over batches of an iterable and an operation that should be performed every few elements . Determine whether the operation should be called for the current index . |
61,026 | def parse_tax_lvl ( entry , tax_lvl_depth = [ ] ) : depth_and_name = re . match ( '^( *)(.*)' , entry [ 'sci_name' ] ) depth = len ( depth_and_name . group ( 1 ) ) // 2 name = depth_and_name . group ( 2 ) del tax_lvl_depth [ depth : ] tax_lvl_depth . append ( ( entry [ 'rank' ] , name ) ) tax_lvl = { x [ 0 ] : x [ 1 ] for x in tax_lvl_depth if x [ 0 ] in ranks } return ( tax_lvl ) | Parse a single kraken - report entry and return a dictionary of taxa for its named ranks . |
61,027 | def parse_kraken_report ( kdata , max_rank , min_rank ) : taxa = OrderedDict ( ) counts = OrderedDict ( ) r = 0 max_rank_idx = ranks . index ( max_rank ) min_rank_idx = ranks . index ( min_rank ) for entry in kdata : erank = entry [ 'rank' ] . strip ( ) if erank in ranks : r = ranks . index ( erank ) tax_lvl = parse_tax_lvl ( entry ) if erank in ranks and min_rank_idx >= ranks . index ( entry [ 'rank' ] ) >= max_rank_idx : taxon_reads = int ( entry [ "taxon_reads" ] ) clade_reads = int ( entry [ "clade_reads" ] ) if taxon_reads > 0 or ( clade_reads > 0 and entry [ 'rank' ] == min_rank ) : taxa [ entry [ 'ncbi_tax' ] ] = tax_fmt ( tax_lvl , r ) if entry [ 'rank' ] == min_rank : counts [ entry [ 'ncbi_tax' ] ] = clade_reads else : counts [ entry [ 'ncbi_tax' ] ] = taxon_reads return counts , taxa | Parse a single output file from the kraken - report tool . Return a list of counts at each of the acceptable taxonomic levels and a list of NCBI IDs and a formatted string representing their taxonomic hierarchies . |
61,028 | def process_samples ( kraken_reports_fp , max_rank , min_rank ) : taxa = OrderedDict ( ) sample_counts = OrderedDict ( ) for krep_fp in kraken_reports_fp : if not osp . isfile ( krep_fp ) : raise RuntimeError ( "ERROR: File '{}' not found." . format ( krep_fp ) ) sample_id = osp . splitext ( osp . split ( krep_fp ) [ 1 ] ) [ 0 ] with open ( krep_fp , "rt" ) as kf : try : kdr = csv . DictReader ( kf , fieldnames = field_names , delimiter = "\t" ) kdata = [ entry for entry in kdr ] [ 1 : ] except OSError as oe : raise RuntimeError ( "ERROR: {}" . format ( oe ) ) scounts , staxa = parse_kraken_report ( kdata , max_rank = max_rank , min_rank = min_rank ) taxa . update ( staxa ) sample_counts [ sample_id ] = scounts return sample_counts , taxa | Parse all kraken - report data files into sample counts dict and store global taxon id - > taxonomy data |
61,029 | def create_biom_table ( sample_counts , taxa ) : data = [ [ 0 if taxid not in sample_counts [ sid ] else sample_counts [ sid ] [ taxid ] for sid in sample_counts ] for taxid in taxa ] data = np . array ( data , dtype = int ) tax_meta = [ { 'taxonomy' : taxa [ taxid ] } for taxid in taxa ] gen_str = "kraken-biom v{} ({})" . format ( __version__ , __url__ ) return Table ( data , list ( taxa ) , list ( sample_counts ) , tax_meta , type = "OTU table" , create_date = str ( dt . now ( ) . isoformat ( ) ) , generated_by = gen_str , input_is_dense = True ) | Create a BIOM table from sample counts and taxonomy metadata . |
61,030 | def write_biom ( biomT , output_fp , fmt = "hdf5" , gzip = False ) : opener = open mode = 'w' if gzip and fmt != "hdf5" : if not output_fp . endswith ( ".gz" ) : output_fp += ".gz" opener = gzip_open mode = 'wt' if fmt == "hdf5" : opener = h5py . File with opener ( output_fp , mode ) as biom_f : if fmt == "json" : biomT . to_json ( biomT . generated_by , direct_io = biom_f ) elif fmt == "tsv" : biom_f . write ( biomT . to_tsv ( ) ) else : biomT . to_hdf5 ( biom_f , biomT . generated_by ) return output_fp | Write the BIOM table to a file . |
61,031 | def write_otu_file ( otu_ids , fp ) : fpdir = osp . split ( fp ) [ 0 ] if not fpdir == "" and not osp . isdir ( fpdir ) : raise RuntimeError ( "Specified path does not exist: {}" . format ( fpdir ) ) with open ( fp , 'wt' ) as outf : outf . write ( '\n' . join ( otu_ids ) ) | Write out a file containing only the list of OTU IDs from the kraken data . One line per ID . |
61,032 | def transform ( self , X ) : assert np . shape ( X ) [ 0 ] == len ( self . _weights ) , ( 'BlendingOptimizer: Number of models to blend its predictions and weights does not match: ' 'n_models={}, weights_len={}' . format ( np . shape ( X ) [ 0 ] , len ( self . _weights ) ) ) blended_predictions = np . average ( np . power ( X , self . _power ) , weights = self . _weights , axis = 0 ) ** ( 1.0 / self . _power ) return { 'y_pred' : blended_predictions } | Performs predictions blending using the trained weights . |
61,033 | def fit_transform ( self , X , y , step_size = 0.1 , init_weights = None , warm_start = False ) : self . fit ( X = X , y = y , step_size = step_size , init_weights = init_weights , warm_start = warm_start ) return self . transform ( X = X ) | Fit optimizer to X then transforms X . See fit and transform for further explanation . |
61,034 | def escape_tags ( value , valid_tags ) : value = conditional_escape ( value ) if valid_tags : tag_re = re . compile ( r'<(\s*/?\s*(%s))(.*?\s*)>' % '|' . join ( re . escape ( tag ) for tag in valid_tags ) ) value = tag_re . sub ( _replace_quot , value ) value = value . replace ( "<!--" , "<!--" ) . replace ( "-->" , " ) return mark_safe ( value ) | Strips text from the given html string leaving only tags . This functionality requires BeautifulSoup nothing will be done otherwise . |
61,035 | def _get_seo_content_types ( seo_models ) : try : return [ ContentType . objects . get_for_model ( m ) . id for m in seo_models ] except Exception : return [ ] | Returns a list of content types from the models defined in settings . |
61,036 | def register_seo_admin ( admin_site , metadata_class ) : if metadata_class . _meta . use_sites : path_admin = SitePathMetadataAdmin model_instance_admin = SiteModelInstanceMetadataAdmin model_admin = SiteModelMetadataAdmin view_admin = SiteViewMetadataAdmin else : path_admin = PathMetadataAdmin model_instance_admin = ModelInstanceMetadataAdmin model_admin = ModelMetadataAdmin view_admin = ViewMetadataAdmin def get_list_display ( ) : return tuple ( name for name , obj in metadata_class . _meta . elements . items ( ) if obj . editable ) backends = metadata_class . _meta . backends if 'model' in backends : class ModelAdmin ( model_admin ) : form = get_model_form ( metadata_class ) list_display = model_admin . list_display + get_list_display ( ) _register_admin ( admin_site , metadata_class . _meta . get_model ( 'model' ) , ModelAdmin ) if 'view' in backends : class ViewAdmin ( view_admin ) : form = get_view_form ( metadata_class ) list_display = view_admin . list_display + get_list_display ( ) _register_admin ( admin_site , metadata_class . _meta . get_model ( 'view' ) , ViewAdmin ) if 'path' in backends : class PathAdmin ( path_admin ) : form = get_path_form ( metadata_class ) list_display = path_admin . list_display + get_list_display ( ) _register_admin ( admin_site , metadata_class . _meta . get_model ( 'path' ) , PathAdmin ) if 'modelinstance' in backends : class ModelInstanceAdmin ( model_instance_admin ) : form = get_modelinstance_form ( metadata_class ) list_display = ( model_instance_admin . list_display + get_list_display ( ) ) _register_admin ( admin_site , metadata_class . _meta . get_model ( 'modelinstance' ) , ModelInstanceAdmin ) | Register the backends specified in Meta . backends with the admin . |
61,037 | def _construct_form ( self , i , ** kwargs ) : form = super ( MetadataFormset , self ) . _construct_form ( i , ** kwargs ) form . empty_permitted = False form . has_changed = lambda : True if self . instance : self . instance . __seo_metadata_handled = True return form | Override the method to change the form attribute empty_permitted . |
61,038 | def _get_metadata_model ( name = None ) : if name is not None : try : return registry [ name ] except KeyError : if len ( registry ) == 1 : valid_names = 'Try using the name "%s" or simply leaving it ' 'out altogether.' % list ( registry ) [ 0 ] else : valid_names = "Valid names are " + ", " . join ( '"%s"' % k for k in list ( registry ) ) raise Exception ( "Metadata definition with name \"%s\" does not exist.\n%s" % ( name , valid_names ) ) else : assert len ( registry ) == 1 , "You must have exactly one Metadata class, if using " "get_metadata() without a 'name' parameter." return list ( registry . values ( ) ) [ 0 ] | Find registered Metadata object . |
61,039 | def _resolve_value ( self , name ) : name = str ( name ) if name in self . _metadata . _meta . elements : element = self . _metadata . _meta . elements [ name ] if element . editable : value = getattr ( self , name ) if value : return value populate_from = element . populate_from if isinstance ( populate_from , collections . Callable ) : return populate_from ( self , ** self . _populate_from_kwargs ( ) ) elif isinstance ( populate_from , Literal ) : return populate_from . value elif populate_from is not NotSet : return self . _resolve_value ( populate_from ) try : value = getattr ( self . _metadata , name ) except AttributeError : pass else : if isinstance ( value , collections . Callable ) : if getattr ( value , '__self__' , None ) : return value ( self ) else : return value ( self . _metadata , obj = self ) return value | Returns an appropriate value for the given name . |
61,040 | def _urls_for_js ( urls = None ) : if urls is None : from . urls import urlpatterns urls = [ url . name for url in urlpatterns if getattr ( url , 'name' , None ) ] urls = dict ( zip ( urls , [ get_uri_template ( url ) for url in urls ] ) ) urls . update ( getattr ( settings , 'LEAFLET_STORAGE_EXTRA_URLS' , { } ) ) return urls | Return templated URLs prepared for javascript . |
61,041 | def decorated_patterns ( func , * urls ) : def decorate ( urls , func ) : for url in urls : if isinstance ( url , RegexURLPattern ) : url . __class__ = DecoratedURLPattern if not hasattr ( url , "_decorate_with" ) : setattr ( url , "_decorate_with" , [ ] ) url . _decorate_with . append ( func ) elif isinstance ( url , RegexURLResolver ) : for pp in url . url_patterns : if isinstance ( pp , RegexURLPattern ) : pp . __class__ = DecoratedURLPattern if not hasattr ( pp , "_decorate_with" ) : setattr ( pp , "_decorate_with" , [ ] ) pp . _decorate_with . append ( func ) if func : if not isinstance ( func , ( list , tuple ) ) : func = [ func ] for f in func : decorate ( urls , f ) return urls | Utility function to decorate a group of url in urls . py |
61,042 | def get_custom_fields ( self ) : return CustomField . objects . filter ( content_type = ContentType . objects . get_for_model ( self ) ) | Return a list of custom fields for this model |
61,043 | def get_custom_field ( self , field_name ) : content_type = ContentType . objects . get_for_model ( self ) return CustomField . objects . get ( content_type = content_type , name = field_name ) | Get a custom field object for this model field_name - Name of the custom field you want . |
61,044 | def get_custom_value ( self , field_name ) : custom_field = self . get_custom_field ( field_name ) return CustomFieldValue . objects . get_or_create ( field = custom_field , object_id = self . id ) [ 0 ] . value | Get a value for a specified custom field field_name - Name of the custom field you want . |
61,045 | def set_custom_value ( self , field_name , value ) : custom_field = self . get_custom_field ( field_name ) custom_value = CustomFieldValue . objects . get_or_create ( field = custom_field , object_id = self . id ) [ 0 ] custom_value . value = value custom_value . save ( ) | Set a value for a specified custom field field_name - Name of the custom field you want . value - Value to set it to |
61,046 | def assign_item ( self , item , origin ) : closest_cluster = origin for cluster in self . __clusters : if self . distance ( item , centroid ( cluster ) ) < self . distance ( item , centroid ( closest_cluster ) ) : closest_cluster = cluster if id ( closest_cluster ) != id ( origin ) : self . move_item ( item , origin , closest_cluster ) return True else : return False | Assigns an item from a given cluster to the closest located cluster . |
61,047 | def move_item ( self , item , origin , destination ) : if self . equality : item_index = 0 for i , element in enumerate ( origin ) : if self . equality ( element , item ) : item_index = i break else : item_index = origin . index ( item ) destination . append ( origin . pop ( item_index ) ) | Moves an item from one cluster to anoter cluster . |
61,048 | def initialise_clusters ( self , input_ , clustercount ) : self . __clusters = [ ] for _ in range ( clustercount ) : self . __clusters . append ( [ ] ) count = 0 for item in input_ : self . __clusters [ count % clustercount ] . append ( item ) count += 1 | Initialises the clusters by distributing the items from the data . evenly across n clusters |
61,049 | def publish_progress ( self , total , current ) : if self . progress_callback : self . progress_callback ( total , current ) | If a progress function was supplied this will call that function with the total number of elements and the remaining number of elements . |
61,050 | def set_linkage_method ( self , method ) : if method == 'single' : self . linkage = single elif method == 'complete' : self . linkage = complete elif method == 'average' : self . linkage = average elif method == 'uclus' : self . linkage = uclus elif hasattr ( method , '__call__' ) : self . linkage = method else : raise ValueError ( 'distance method must be one of single, ' 'complete, average of uclus' ) | Sets the method to determine the distance between two clusters . |
61,051 | def cluster ( self , matrix = None , level = None , sequence = None ) : logger . info ( "Performing cluster()" ) if matrix is None : level = 0 sequence = 0 matrix = [ ] linkage = partial ( self . linkage , distance_function = self . distance ) initial_element_count = len ( self . _data ) while len ( matrix ) > 2 or matrix == [ ] : item_item_matrix = Matrix ( self . _data , linkage , True , 0 ) item_item_matrix . genmatrix ( self . num_processes ) matrix = item_item_matrix . matrix smallestpair = None mindistance = None rowindex = 0 for row in matrix : cellindex = 0 for cell in row : cell_lt_mdist = cell < mindistance if mindistance else False if ( ( rowindex != cellindex ) and ( cell_lt_mdist or smallestpair is None ) ) : smallestpair = ( rowindex , cellindex ) mindistance = cell cellindex += 1 rowindex += 1 sequence += 1 level = matrix [ smallestpair [ 1 ] ] [ smallestpair [ 0 ] ] cluster = Cluster ( level , self . _data [ smallestpair [ 0 ] ] , self . _data [ smallestpair [ 1 ] ] ) self . _data . remove ( self . _data [ max ( smallestpair [ 0 ] , smallestpair [ 1 ] ) ] ) self . _data . remove ( self . _data [ min ( smallestpair [ 0 ] , smallestpair [ 1 ] ) ] ) self . _data . append ( cluster ) self . publish_progress ( initial_element_count , len ( self . _data ) ) self . __cluster_created = True logger . info ( "Call to cluster() is complete" ) return | Perform hierarchical clustering . |
61,052 | def flatten ( L ) : if not isinstance ( L , list ) : return [ L ] if L == [ ] : return L return flatten ( L [ 0 ] ) + flatten ( L [ 1 : ] ) | Flattens a list . |
61,053 | def fullyflatten ( container ) : flattened_items = [ ] for item in container : if hasattr ( item , 'items' ) : flattened_items = flattened_items + fullyflatten ( item . items ) else : flattened_items . append ( item ) return flattened_items | Completely flattens out a cluster and returns a one - dimensional set containing the cluster s items . This is useful in cases where some items of the cluster are clusters in their own right and you only want the items . |
61,054 | def minkowski_distance ( x , y , p = 2 ) : from math import pow assert len ( y ) == len ( x ) assert len ( x ) >= 1 sum = 0 for i in range ( len ( x ) ) : sum += abs ( x [ i ] - y [ i ] ) ** p return pow ( sum , 1.0 / float ( p ) ) | Calculates the minkowski distance between two points . |
61,055 | def magnitude ( a ) : "calculates the magnitude of a vecor" from math import sqrt sum = 0 for coord in a : sum += coord ** 2 return sqrt ( sum ) | calculates the magnitude of a vecor |
61,056 | def dotproduct ( a , b ) : "Calculates the dotproduct between two vecors" assert ( len ( a ) == len ( b ) ) out = 0 for i in range ( len ( a ) ) : out += a [ i ] * b [ i ] return out | Calculates the dotproduct between two vecors |
61,057 | def centroid ( data , method = median ) : "returns the central vector of a list of vectors" out = [ ] for i in range ( len ( data [ 0 ] ) ) : out . append ( method ( [ x [ i ] for x in data ] ) ) return tuple ( out ) | returns the central vector of a list of vectors |
61,058 | def display ( self , depth = 0 ) : print ( depth * " " + "[level %s]" % self . level ) for item in self . items : if isinstance ( item , Cluster ) : item . display ( depth + 1 ) else : print ( depth * " " + "%s" % item ) | Pretty - prints this cluster . Useful for debuging . |
61,059 | def getlevel ( self , threshold ) : left = self . items [ 0 ] right = self . items [ 1 ] if self . level <= threshold : return [ fullyflatten ( self . items ) ] if isinstance ( left , Cluster ) and left . level <= threshold : if isinstance ( right , Cluster ) : return [ fullyflatten ( left . items ) ] + right . getlevel ( threshold ) else : return [ fullyflatten ( left . items ) ] + [ [ right ] ] elif isinstance ( right , Cluster ) and right . level <= threshold : if isinstance ( left , Cluster ) : return left . getlevel ( threshold ) + [ fullyflatten ( right . items ) ] else : return [ [ left ] ] + [ fullyflatten ( right . items ) ] if isinstance ( left , Cluster ) and isinstance ( right , Cluster ) : return left . getlevel ( threshold ) + right . getlevel ( threshold ) elif isinstance ( left , Cluster ) : return left . getlevel ( threshold ) + [ [ right ] ] elif isinstance ( right , Cluster ) : return [ [ left ] ] + right . getlevel ( threshold ) else : return [ [ left ] , [ right ] ] | Retrieve all clusters up to a specific level threshold . This level - threshold represents the maximum distance between two clusters . So the lower you set this threshold the more clusters you will receive and the higher you set it you will receive less but bigger clusters . |
61,060 | def jsmin ( js , ** kwargs ) : if not is_3 : if cStringIO and not isinstance ( js , unicode ) : klass = cStringIO . StringIO else : klass = StringIO . StringIO else : klass = io . StringIO ins = klass ( js ) outs = klass ( ) JavascriptMinify ( ins , outs , ** kwargs ) . minify ( ) return outs . getvalue ( ) | returns a minified version of the javascript string |
61,061 | def cached ( fun ) : _cache = { } @ wraps ( fun ) def newfun ( a , b , distance_function ) : frozen_a = frozenset ( a ) frozen_b = frozenset ( b ) if ( frozen_a , frozen_b ) not in _cache : result = fun ( a , b , distance_function ) _cache [ ( frozen_a , frozen_b ) ] = result return _cache [ ( frozen_a , frozen_b ) ] return newfun | memoizing decorator for linkage functions . |
61,062 | def single ( a , b , distance_function ) : left_a , right_a = min ( a ) , max ( a ) left_b , right_b = min ( b ) , max ( b ) result = min ( distance_function ( left_a , right_b ) , distance_function ( left_b , right_a ) ) return result | Given two collections a and b this will return the distance of the points which are closest together . distance_function is used to determine the distance between two elements . |
61,063 | def average ( a , b , distance_function ) : distances = [ distance_function ( x , y ) for x in a for y in b ] return sum ( distances ) / len ( distances ) | Given two collections a and b this will return the mean of all distances . distance_function is used to determine the distance between two elements . |
61,064 | def worker ( self ) : tasks_completed = 0 for task in iter ( self . task_queue . get , 'STOP' ) : col_index , item , item2 = task if not hasattr ( item , '__iter__' ) or isinstance ( item , tuple ) : item = [ item ] if not hasattr ( item2 , '__iter__' ) or isinstance ( item2 , tuple ) : item2 = [ item2 ] result = ( col_index , self . combinfunc ( item , item2 ) ) self . done_queue . put ( result ) tasks_completed += 1 logger . info ( "Worker %s performed %s tasks" , current_process ( ) . name , tasks_completed ) | Multiprocessing task function run by worker processes |
61,065 | def genmatrix ( self , num_processes = 1 ) : use_multiprocessing = num_processes > 1 if use_multiprocessing : self . task_queue = Queue ( ) self . done_queue = Queue ( ) self . matrix = [ ] logger . info ( "Generating matrix for %s items - O(n^2)" , len ( self . data ) ) if use_multiprocessing : logger . info ( "Using multiprocessing on %s processes!" , num_processes ) if use_multiprocessing : logger . info ( "Spinning up %s workers" , num_processes ) processes = [ Process ( target = self . worker ) for i in range ( num_processes ) ] [ process . start ( ) for process in processes ] for row_index , item in enumerate ( self . data ) : logger . debug ( "Generating row %s/%s (%0.2f%%)" , row_index , len ( self . data ) , 100.0 * row_index / len ( self . data ) ) row = { } if use_multiprocessing : num_tasks_queued = num_tasks_completed = 0 for col_index , item2 in enumerate ( self . data ) : if self . diagonal is not None and col_index == row_index : row [ col_index ] = self . diagonal elif self . symmetric and col_index < row_index : pass elif use_multiprocessing : self . task_queue . put ( ( col_index , item , item2 ) ) num_tasks_queued += 1 if num_tasks_queued > num_processes : col_index , result = self . done_queue . get ( ) row [ col_index ] = result num_tasks_completed += 1 else : item = _encapsulate_item_for_combinfunc ( item ) item2 = _encapsulate_item_for_combinfunc ( item2 ) row [ col_index ] = self . combinfunc ( item , item2 ) if self . symmetric : for col_index , item2 in enumerate ( self . data ) : if col_index >= row_index : break row [ col_index ] = self . matrix [ col_index ] [ row_index ] if use_multiprocessing : while num_tasks_completed < num_tasks_queued : col_index , result = self . done_queue . get ( ) row [ col_index ] = result num_tasks_completed += 1 row_indexed = [ row [ index ] for index in range ( len ( self . data ) ) ] self . matrix . append ( row_indexed ) if use_multiprocessing : logger . info ( "Stopping/joining %s workers" , num_processes ) [ self . task_queue . put ( 'STOP' ) for i in range ( num_processes ) ] [ process . join ( ) for process in processes ] logger . info ( "Matrix generated" ) | Actually generate the matrix |
61,066 | def validate ( fname ) : validation = { "errors" : [ ] , "warnings" : [ ] } for line in _process ( fname ) : kind , message = _determine ( line ) if kind in validation : validation [ kind ] . append ( message ) return validation | This function uses dciodvfy to generate a list of warnings and errors discovered within the DICOM file . |
61,067 | def numpy ( self ) : image_reader = gdcm . ImageReader ( ) image_reader . SetFileName ( self . fname ) if not image_reader . Read ( ) : raise IOError ( "Could not read DICOM image" ) pixel_array = self . _gdcm_to_numpy ( image_reader . GetImage ( ) ) return pixel_array | Grabs image data and converts it to a numpy array |
61,068 | def _gdcm_to_numpy ( self , image ) : gdcm_typemap = { gdcm . PixelFormat . INT8 : numpy . int8 , gdcm . PixelFormat . UINT8 : numpy . uint8 , gdcm . PixelFormat . UINT16 : numpy . uint16 , gdcm . PixelFormat . INT16 : numpy . int16 , gdcm . PixelFormat . UINT32 : numpy . uint32 , gdcm . PixelFormat . INT32 : numpy . int32 , gdcm . PixelFormat . FLOAT32 : numpy . float32 , gdcm . PixelFormat . FLOAT64 : numpy . float64 } pixel_format = image . GetPixelFormat ( ) . GetScalarType ( ) if pixel_format in gdcm_typemap : self . data_type = gdcm_typemap [ pixel_format ] else : raise KeyError ( '' . join ( pixel_format , " is not a supported pixel format" ) ) self . dimensions = image . GetDimension ( 1 ) , image . GetDimension ( 0 ) gdcm_array = image . GetBuffer ( ) if sys . version_info >= ( 3 , 0 ) : gdcm_array = gdcm_array . encode ( sys . getfilesystemencoding ( ) , "surrogateescape" ) dimensions = image . GetDimensions ( ) result = numpy . frombuffer ( gdcm_array , dtype = self . data_type ) . astype ( float ) if len ( dimensions ) == 3 : result . shape = dimensions [ 2 ] , dimensions [ 0 ] , dimensions [ 1 ] else : result . shape = dimensions return result | Converts a GDCM image to a numpy array . |
61,069 | def save_as_plt ( self , fname , pixel_array = None , vmin = None , vmax = None , cmap = None , format = None , origin = None ) : from matplotlib . backends . backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib . figure import Figure from pylab import cm if pixel_array is None : pixel_array = self . numpy if cmap is None : cmap = cm . bone fig = Figure ( figsize = pixel_array . shape [ : : - 1 ] , dpi = 1 , frameon = False ) canvas = FigureCanvas ( fig ) fig . figimage ( pixel_array , cmap = cmap , vmin = vmin , vmax = vmax , origin = origin ) fig . savefig ( fname , dpi = 1 , format = format ) return True | This method saves the image from a numpy array using matplotlib |
61,070 | def read ( self ) : def ds ( data_element ) : value = self . _str_filter . ToStringPair ( data_element . GetTag ( ) ) if value [ 1 ] : return DataElement ( data_element , value [ 0 ] . strip ( ) , value [ 1 ] . strip ( ) ) results = [ data for data in self . walk ( ds ) if data is not None ] return results | Returns array of dictionaries containing all the data elements in the DICOM file . |
61,071 | def walk ( self , fn ) : if not hasattr ( fn , "__call__" ) : raise TypeError ( ) dataset = self . _dataset iterator = dataset . GetDES ( ) . begin ( ) while ( not iterator . equal ( dataset . GetDES ( ) . end ( ) ) ) : data_element = iterator . next ( ) yield fn ( data_element ) header = self . _header iterator = header . GetDES ( ) . begin ( ) while ( not iterator . equal ( header . GetDES ( ) . end ( ) ) ) : data_element = iterator . next ( ) yield fn ( data_element ) | Loops through all data elements and allows a function to interact with each data element . Uses a generator to improve iteration . |
61,072 | def find ( self , group = None , element = None , name = None , VR = None ) : results = self . read ( ) if name is not None : def find_name ( data_element ) : return data_element . name . lower ( ) == name . lower ( ) return filter ( find_name , results ) if group is not None : def find_group ( data_element ) : return ( data_element . tag [ 'group' ] == group or int ( data_element . tag [ 'group' ] , 16 ) == group ) results = filter ( find_group , results ) if element is not None : def find_element ( data_element ) : return ( data_element . tag [ 'element' ] == element or int ( data_element . tag [ 'element' ] , 16 ) == element ) results = filter ( find_element , results ) if VR is not None : def find_VR ( data_element ) : return data_element . VR . lower ( ) == VR . lower ( ) results = filter ( find_VR , results ) return results | Searches for data elements in the DICOM file given the filters supplied to this method . |
61,073 | def anonymize ( self ) : self . _anon_obj = gdcm . Anonymizer ( ) self . _anon_obj . SetFile ( self . _file ) self . _anon_obj . RemoveGroupLength ( ) if self . _anon_tags is None : self . _anon_tags = get_anon_tags ( ) for tag in self . _anon_tags : cur_tag = tag [ 'Tag' ] . replace ( "(" , "" ) cur_tag = cur_tag . replace ( ")" , "" ) name = tag [ "Attribute Name" ] . replace ( " " , "" ) . encode ( "utf8" ) group , element = cur_tag . split ( "," , 1 ) if ( "xx" not in group and "gggg" not in group and "eeee" not in group ) : group = int ( group , 16 ) element = int ( element , 16 ) if self . find ( group = group , element = element ) : self . _anon_obj . Replace ( gdcm . Tag ( group , element ) , "Anon" + name ) return self . _anon_obj | According to PS 3 . 15 - 2008 basic application level De - Indentification of a DICOM file requires replacing the values of a set of data elements |
61,074 | def image ( self ) : if self . _image is None : self . _image = Image ( self . fname ) return self . _image | Read the loaded DICOM image data |
61,075 | def repo_name ( self ) : ds = [ [ x . repo_name ] for x in self . repos ] df = pd . DataFrame ( ds , columns = [ 'repository' ] ) return df | Returns a DataFrame of the repo names present in this project directory |
61,076 | def command ( self ) : print ( 'pynYNAB CSV import' ) args = self . parser . parse_args ( ) verify_common_args ( args ) verify_csvimport ( args . schema , args . accountname ) client = clientfromkwargs ( ** args ) delta = do_csvimport ( args , client ) client . push ( expected_delta = delta ) | Manually import a CSV into a nYNAB budget |
61,077 | def command ( self ) : print ( 'pynYNAB OFX import' ) args = self . parser . parse_args ( ) verify_common_args ( args ) client = clientfromkwargs ( ** args ) delta = do_ofximport ( args . file , client ) client . push ( expected_delta = delta ) | Manually import an OFX into a nYNAB budget |
61,078 | def default_listener ( col_attr , default ) : @ event . listens_for ( col_attr , "init_scalar" , retval = True , propagate = True ) def init_scalar ( target , value , dict_ ) : if default . is_callable : value = default . arg ( None ) elif default . is_scalar : value = default . arg else : raise NotImplementedError ( "Can't invoke pre-default for a SQL-level column default" ) dict_ [ col_attr . key ] = value return value | Establish a default - setting listener . |
61,079 | def has_coverage ( self ) : if os . path . exists ( self . git_dir + os . sep + '.coverage' ) : try : with open ( self . git_dir + os . sep + '.coverage' , 'r' ) as f : blob = f . read ( ) blob = blob . split ( '!' ) [ 2 ] json . loads ( blob ) return True except Exception : return False else : return False | Returns a boolean for is a parseable . coverage file can be found in the repository |
61,080 | def __check_extension ( files , ignore_globs = None , include_globs = None ) : if include_globs is None or include_globs == [ ] : include_globs = [ '*' ] out = { } for key in files . keys ( ) : if ignore_globs is not None : count_exclude = sum ( [ 1 if fnmatch . fnmatch ( key , g ) else 0 for g in ignore_globs ] ) else : count_exclude = 0 count_include = sum ( [ 1 if fnmatch . fnmatch ( key , g ) else 0 for g in include_globs ] ) if count_include > 0 and count_exclude == 0 : out [ key ] = files [ key ] return out | Internal method to filter a list of file changes by extension and ignore_dirs . |
61,081 | def _repo_name ( self ) : if self . _git_repo_name is not None : return self . _git_repo_name else : reponame = self . repo . git_dir . split ( os . sep ) [ - 2 ] if reponame . strip ( ) == '' : return 'unknown_repo' return reponame | Returns the name of the repository using the local directory name . |
61,082 | def _decode ( self , obj , context ) : return b'' . join ( map ( int2byte , [ c + 0x60 for c in bytearray ( obj ) ] ) ) . decode ( "utf8" ) | Get the python representation of the obj |
61,083 | def update ( self , instance , validated_data ) : model = self . Meta . model meta = self . Meta . model . _meta original_virtual_fields = list ( meta . virtual_fields ) if hasattr ( model , '_hstore_virtual_fields' ) : for field in model . _hstore_virtual_fields . values ( ) : meta . virtual_fields . remove ( field ) instance = super ( HStoreSerializer , self ) . update ( instance , validated_data ) if hasattr ( model , '_hstore_virtual_fields' ) : meta . virtual_fields = original_virtual_fields return instance | temporarily remove hstore virtual fields otherwise DRF considers them many2many |
61,084 | def update_image ( self , data ) : if 1 in data . shape : data = data . squeeze ( ) if self . conf . contrast_level is not None : clevels = [ self . conf . contrast_level , 100.0 - self . conf . contrast_level ] imin , imax = np . percentile ( data , clevels ) data = np . clip ( ( data - imin ) / ( imax - imin + 1.e-8 ) , 0 , 1 ) self . axes . images [ 0 ] . set_data ( data ) self . canvas . draw ( ) | update image on panel as quickly as possible |
61,085 | def set_viewlimits ( self , axes = None ) : if axes is None : axes = self . axes xmin , xmax , ymin , ymax = self . data_range if len ( self . conf . zoom_lims ) > 1 : zlims = self . conf . zoom_lims [ - 1 ] if axes in zlims : xmin , xmax , ymin , ymax = zlims [ axes ] xmin = max ( self . data_range [ 0 ] , xmin ) xmax = min ( self . data_range [ 1 ] , xmax ) ymin = max ( self . data_range [ 2 ] , ymin ) ymax = min ( self . data_range [ 3 ] , ymax ) if ( xmax < self . data_range [ 0 ] or xmin > self . data_range [ 1 ] or ymax < self . data_range [ 2 ] or ymin > self . data_range [ 3 ] ) : self . conf . zoom_lims . pop ( ) return if abs ( xmax - xmin ) < 2 : xmin = int ( 0.5 * ( xmax + xmin ) - 1 ) xmax = xmin + 2 if abs ( ymax - ymin ) < 2 : ymin = int ( 0.5 * ( ymax + xmin ) - 1 ) ymax = ymin + 2 self . axes . set_xlim ( ( xmin , xmax ) , emit = True ) self . axes . set_ylim ( ( ymin , ymax ) , emit = True ) self . axes . update_datalim ( ( ( xmin , ymin ) , ( xmax , ymax ) ) ) self . conf . datalimits = [ xmin , xmax , ymin , ymax ] self . redraw ( ) | update xy limits of a plot |
61,086 | def zoom_leftup ( self , event = None ) : if self . zoom_ini is None : return ini_x , ini_y , ini_xd , ini_yd = self . zoom_ini try : dx = abs ( ini_x - event . x ) dy = abs ( ini_y - event . y ) except : dx , dy = 0 , 0 t0 = time . time ( ) self . rbbox = None self . zoom_ini = None if ( dx > 3 ) and ( dy > 3 ) and ( t0 - self . mouse_uptime ) > 0.1 : self . mouse_uptime = t0 zlims , tlims = { } , { } ax = self . axes xmin , xmax = ax . get_xlim ( ) ymin , ymax = ax . get_ylim ( ) zlims [ ax ] = [ xmin , xmax , ymin , ymax ] if len ( self . conf . zoom_lims ) == 0 : self . conf . zoom_lims . append ( zlims ) ax_inv = ax . transData . inverted try : x1 , y1 = ax_inv ( ) . transform ( ( event . x , event . y ) ) except : x1 , y1 = self . x_lastmove , self . y_lastmove try : x0 , y0 = ax_inv ( ) . transform ( ( ini_x , ini_y ) ) except : x0 , y0 = ini_xd , ini_yd tlims [ ax ] = [ int ( round ( min ( x0 , x1 ) ) ) , int ( round ( max ( x0 , x1 ) ) ) , int ( round ( min ( y0 , y1 ) ) ) , int ( round ( max ( y0 , y1 ) ) ) ] self . conf . zoom_lims . append ( tlims ) self . set_viewlimits ( ) if callable ( self . zoom_callback ) : self . zoom_callback ( wid = self . GetId ( ) , limits = tlims [ ax ] ) | leftup event handler for zoom mode in images |
61,087 | def collect_directories ( self , directories ) : directories = util . to_absolute_paths ( directories ) if not self . recursive : return self . _remove_blacklisted ( directories ) recursive_dirs = set ( ) for dir_ in directories : walk_iter = os . walk ( dir_ , followlinks = True ) walk_iter = [ w [ 0 ] for w in walk_iter ] walk_iter = util . to_absolute_paths ( walk_iter ) walk_iter = self . _remove_blacklisted ( walk_iter ) recursive_dirs . update ( walk_iter ) return recursive_dirs | Collects all the directories into a set object . |
61,088 | def remove_directories ( self , directories ) : directories = util . to_absolute_paths ( directories ) self . plugin_directories = util . remove_from_set ( self . plugin_directories , directories ) | Removes any directories from the set of plugin directories . |
61,089 | def remove_blacklisted_directories ( self , directories ) : directories = util . to_absolute_paths ( directories ) black_dirs = self . blacklisted_directories black_dirs = util . remove_from_set ( black_dirs , directories ) | Attempts to remove the directories from the set of blacklisted directories . If a particular directory is not found in the set of blacklisted method will continue on silently . |
61,090 | def _remove_blacklisted ( self , directories ) : directories = util . to_absolute_paths ( directories ) directories = util . remove_from_set ( directories , self . blacklisted_directories ) return directories | Attempts to remove the blacklisted directories from directories and then returns whatever is left in the set . |
61,091 | def imread ( filename , * args , ** kwargs ) : with TIFFfile ( filename ) as tif : return tif . asarray ( * args , ** kwargs ) | Return image data from TIFF file as numpy array . |
61,092 | def read_nih_image_header ( fd , byte_order , dtype , count ) : fd . seek ( 12 , 1 ) return { 'version' : struct . unpack ( byte_order + 'H' , fd . read ( 2 ) ) [ 0 ] } | Read NIH_IMAGE_HEADER tag from file and return as dictionary . |
61,093 | def read_mm_header ( fd , byte_order , dtype , count ) : return numpy . rec . fromfile ( fd , MM_HEADER , 1 , byteorder = byte_order ) [ 0 ] | Read MM_HEADER tag from file and return as numpy . rec . array . |
61,094 | def read_mm_uic1 ( fd , byte_order , dtype , count ) : t = fd . read ( 8 * count ) t = struct . unpack ( '%s%iI' % ( byte_order , 2 * count ) , t ) return dict ( ( MM_TAG_IDS [ k ] , v ) for k , v in zip ( t [ : : 2 ] , t [ 1 : : 2 ] ) if k in MM_TAG_IDS ) | Read MM_UIC1 tag from file and return as dictionary . |
61,095 | def read_mm_uic2 ( fd , byte_order , dtype , count ) : result = { 'number_planes' : count } values = numpy . fromfile ( fd , byte_order + 'I' , 6 * count ) result [ 'z_distance' ] = values [ 0 : : 6 ] // values [ 1 : : 6 ] return result | Read MM_UIC2 tag from file and return as dictionary . |
61,096 | def read_mm_uic3 ( fd , byte_order , dtype , count ) : t = numpy . fromfile ( fd , byte_order + 'I' , 2 * count ) return { 'wavelengths' : t [ 0 : : 2 ] // t [ 1 : : 2 ] } | Read MM_UIC3 tag from file and return as dictionary . |
61,097 | def read_cz_lsm_info ( fd , byte_order , dtype , count ) : result = numpy . rec . fromfile ( fd , CZ_LSM_INFO , 1 , byteorder = byte_order ) [ 0 ] { 50350412 : '1.3' , 67127628 : '2.0' } [ result . magic_number ] return result | Read CS_LSM_INFO tag from file and return as numpy . rec . array . |
61,098 | def read_cz_lsm_scan_info ( fd , byte_order ) : block = Record ( ) blocks = [ block ] unpack = struct . unpack if 0x10000000 != struct . unpack ( byte_order + "I" , fd . read ( 4 ) ) [ 0 ] : raise ValueError ( "not a lsm_scan_info structure" ) fd . read ( 8 ) while True : entry , dtype , size = unpack ( byte_order + "III" , fd . read ( 12 ) ) if dtype == 2 : value = stripnull ( fd . read ( size ) ) elif dtype == 4 : value = unpack ( byte_order + "i" , fd . read ( 4 ) ) [ 0 ] elif dtype == 5 : value = unpack ( byte_order + "d" , fd . read ( 8 ) ) [ 0 ] else : value = 0 if entry in CZ_LSM_SCAN_INFO_ARRAYS : blocks . append ( block ) name = CZ_LSM_SCAN_INFO_ARRAYS [ entry ] newobj = [ ] setattr ( block , name , newobj ) block = newobj elif entry in CZ_LSM_SCAN_INFO_STRUCTS : blocks . append ( block ) newobj = Record ( ) block . append ( newobj ) block = newobj elif entry in CZ_LSM_SCAN_INFO_ATTRIBUTES : name = CZ_LSM_SCAN_INFO_ATTRIBUTES [ entry ] setattr ( block , name , value ) elif entry == 0xffffffff : block = blocks . pop ( ) else : setattr ( block , "unknown_%x" % entry , value ) if not blocks : break return block | Read LSM scan information from file and return as Record . |
61,099 | def _replace_by ( module_function , warn = False ) : def decorate ( func , module_function = module_function , warn = warn ) : sys . path . append ( os . path . dirname ( __file__ ) ) try : module , function = module_function . split ( '.' ) func , oldfunc = getattr ( __import__ ( module ) , function ) , func globals ( ) [ '__old_' + func . __name__ ] = oldfunc except Exception : if warn : warnings . warn ( "failed to import %s" % module_function ) sys . path . pop ( ) return func return decorate | Try replace decorated function by module . function . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.