idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
249,500
def _playlist_format_changed ( self ) : new_format = False for n in self . stations : if n [ 2 ] != '' : new_format = True break if self . new_format == new_format : return False else : return True
Check if we have new or old format and report if format has changed
55
14
249,501
def save_playlist_file ( self , stationFile = '' ) : if self . _playlist_format_changed ( ) : self . dirty_playlist = True self . new_format = not self . new_format if stationFile : st_file = stationFile else : st_file = self . stations_file if not self . dirty_playlist : if logger . isEnabledFor ( logging . DEBUG ) : ...
Save a playlist Create a txt file and write stations in it . Then rename it to final target
365
20
249,502
def _bytes_to_human ( self , B ) : KB = float ( 1024 ) MB = float ( KB ** 2 ) # 1,048,576 GB = float ( KB ** 3 ) # 1,073,741,824 TB = float ( KB ** 4 ) # 1,099,511,627,776 if B < KB : return '{0} B' . format ( B ) B = float ( B ) if KB <= B < MB : return '{0:.2f} KB' . format ( B / KB ) elif MB <= B < GB : return '{0:....
Return the given bytes as a human friendly KB MB GB or TB string
195
14
249,503
def append_station ( self , params , stationFile = '' ) : if self . new_format : if stationFile : st_file = stationFile else : st_file = self . stations_file st_file , ret = self . _get_playlist_abspath_from_data ( st_file ) if ret < - 1 : return ret try : with open ( st_file , 'a' ) as cfgfile : writter = csv . writer...
Append a station to csv file
213
8
249,504
def _check_config_file ( self , usr ) : package_config_file = path . join ( path . dirname ( __file__ ) , 'config' ) user_config_file = path . join ( usr , 'config' ) ''' restore config from bck file ''' if path . exists ( user_config_file + '.restore' ) : try : copyfile ( user_config_file + '.restore' , user_config_fi...
Make sure a config file exists in the config dir
160
10
249,505
def ctrl_c_handler ( self , signum , frame ) : self . ctrl_c_pressed = True if self . _cnf . dirty_playlist : """ Try to auto save playlist on exit Do not check result!!! """ self . saveCurrentPlaylist ( ) self . _cnf . save_config ( )
Try to auto save config on exit Do not check result!!!
71
12
249,506
def _goto_playing_station ( self , changing_playlist = False ) : if ( self . player . isPlaying ( ) or self . operation_mode == PLAYLIST_MODE ) and ( self . selection != self . playing or changing_playlist ) : if changing_playlist : self . startPos = 0 max_lines = self . bodyMaxY - 2 if logger . isEnabledFor ( logging ...
make sure playing station is visible
367
6
249,507
def setStation ( self , number ) : # If we press up at the first station, we go to the last one # and if we press down on the last one we go back to the first one. if number < 0 : number = len ( self . stations ) - 1 elif number >= len ( self . stations ) : number = 0 self . selection = number maxDisplayedItems = self ...
Select the given station number
138
5
249,508
def _format_playlist_line ( self , lineNum , pad , station ) : line = "{0}. {1}" . format ( str ( lineNum + self . startPos + 1 ) . rjust ( pad ) , station [ 0 ] ) f_data = ' [{0}, {1}]' . format ( station [ 2 ] , station [ 1 ] ) if version_info < ( 3 , 0 ) : if len ( line . decode ( 'utf-8' , 'replace' ) ) + len ( f_d...
format playlist line so that if fills self . maxX
590
11
249,509
def _resize ( self , init = False ) : col , row = self . _selection_to_col_row ( self . selection ) if not ( self . startPos <= row <= self . startPos + self . list_maxY - 1 ) : while row > self . startPos : self . startPos += 1 while row < self . startPos + self . list_maxY - 1 : self . startPos -= 1 if init and row >...
if the selection at the end of the list try to scroll down
182
13
249,510
def _get_char ( self , win , char ) : def get_check_next_byte ( ) : char = win . getch ( ) if 128 <= char <= 191 : return char else : raise UnicodeError bytes = [ ] if char <= 127 : # 1 bytes bytes . append ( char ) #elif 194 <= char <= 223: elif 192 <= char <= 223 : # 2 bytes bytes . append ( char ) bytes . append ( g...
no zero byte allowed
296
4
249,511
def _get_history_next ( self ) : if self . _has_history : ret = self . _input_history . return_history ( 1 ) self . string = ret self . _curs_pos = len ( ret )
callback function for key down
51
5
249,512
def apply_transformations ( collection , transformations , select = None ) : for t in transformations : kwargs = dict ( t ) func = kwargs . pop ( 'name' ) cols = kwargs . pop ( 'input' , None ) if isinstance ( func , string_types ) : if func in ( 'and' , 'or' ) : func += '_' if not hasattr ( transform , func ) : raise ...
Apply all transformations to the variables in the collection .
148
10
249,513
def setup ( self , steps = None , drop_na = False , * * kwargs ) : # In the beginning, there was nothing input_nodes = None # Use inputs from model, and update with kwargs selectors = self . model . get ( 'input' , { } ) . copy ( ) selectors . update ( kwargs ) for i , b in enumerate ( self . steps ) : # Skip any steps...
Set up the sequence of steps for analysis .
155
9
249,514
def setup ( self , input_nodes = None , drop_na = False , * * kwargs ) : self . output_nodes = [ ] input_nodes = input_nodes or self . input_nodes or [ ] # TODO: remove the scan_length argument entirely once we switch tests # to use the synthetic dataset with image headers. if self . level != 'run' : kwargs = kwargs . ...
Set up the Step and construct the design matrix .
388
10
249,515
def get_slice_info ( slice_times ) : # Slice order slice_times = remove_duplicates ( slice_times ) slice_order = sorted ( range ( len ( slice_times ) ) , key = lambda k : slice_times [ k ] ) if slice_order == range ( len ( slice_order ) ) : slice_order_name = 'sequential ascending' elif slice_order == reversed ( range ...
Extract slice order from slice timing info .
234
9
249,516
def get_sizestr ( img ) : n_x , n_y , n_slices = img . shape [ : 3 ] import numpy as np voxel_dims = np . array ( img . header . get_zooms ( ) [ : 3 ] ) matrix_size = '{0}x{1}' . format ( num_to_str ( n_x ) , num_to_str ( n_y ) ) voxel_size = 'x' . join ( [ num_to_str ( s ) for s in voxel_dims ] ) fov = [ n_x , n_y ] *...
Extract and reformat voxel size matrix size field of view and number of slices into pretty strings .
200
22
249,517
def add_config_paths ( * * kwargs ) : for k , path in kwargs . items ( ) : if not os . path . exists ( path ) : raise ValueError ( 'Configuration file "{}" does not exist' . format ( k ) ) if k in cf . get_option ( 'config_paths' ) : raise ValueError ( 'Configuration {!r} already exists' . format ( k ) ) kwargs . updat...
Add to the pool of available configuration files for BIDSLayout .
133
15
249,518
def add_derivatives ( self , path , * * kwargs ) : paths = listify ( path ) deriv_dirs = [ ] # Collect all paths that contain a dataset_description.json def check_for_description ( dir ) : dd = os . path . join ( dir , 'dataset_description.json' ) return os . path . exists ( dd ) for p in paths : p = os . path . abspat...
Add BIDS - Derivatives datasets to tracking .
601
11
249,519
def get_file ( self , filename , scope = 'all' ) : filename = os . path . abspath ( os . path . join ( self . root , filename ) ) layouts = self . _get_layouts_in_scope ( scope ) for ly in layouts : if filename in ly . files : return ly . files [ filename ] return None
Returns the BIDSFile object with the specified path .
75
11
249,520
def get_collections ( self , level , types = None , variables = None , merge = False , sampling_rate = None , skip_empty = False , * * kwargs ) : from bids . variables import load_variables index = load_variables ( self , types = types , levels = level , skip_empty = skip_empty , * * kwargs ) return index . get_collect...
Return one or more variable Collections in the BIDS project .
103
12
249,521
def get_metadata ( self , path , include_entities = False , * * kwargs ) : f = self . get_file ( path ) # For querying efficiency, store metadata in the MetadataIndex cache self . metadata_index . index_file ( f . path ) if include_entities : entities = f . entities results = entities else : results = { } results . upd...
Return metadata found in JSON sidecars for the specified file .
100
12
249,522
def get_bval ( self , path , * * kwargs ) : result = self . get_nearest ( path , extensions = 'bval' , suffix = 'dwi' , all_ = True , * * kwargs ) return listify ( result ) [ 0 ]
Get bval file for passed path .
62
8
249,523
def copy_files ( self , files = None , path_patterns = None , symbolic_links = True , root = None , conflicts = 'fail' , * * kwargs ) : _files = self . get ( return_type = 'objects' , * * kwargs ) if files : _files = list ( set ( files ) . intersection ( _files ) ) for f in _files : f . copy ( path_patterns , symbolic_...
Copies one or more BIDSFiles to new locations defined by each BIDSFile s entities and the specified path_patterns .
114
27
249,524
def index_file ( self , f , overwrite = False ) : if isinstance ( f , six . string_types ) : f = self . layout . get_file ( f ) if f . path in self . file_index and not overwrite : return if 'suffix' not in f . entities : # Skip files without suffixes return md = self . _get_metadata ( f . path ) for md_key , md_val in...
Index metadata for the specified file .
163
7
249,525
def search ( self , files = None , defined_fields = None , * * kwargs ) : if defined_fields is None : defined_fields = [ ] all_keys = set ( defined_fields ) | set ( kwargs . keys ( ) ) if not all_keys : raise ValueError ( "At least one field to search on must be passed." ) # If no list of files is passed, use all files...
Search files in the layout by metadata fields .
364
9
249,526
def auto_model ( layout , scan_length = None , one_vs_rest = False ) : base_name = split ( layout . root ) [ - 1 ] tasks = layout . entities [ 'task' ] . unique ( ) task_models = [ ] for task_name in tasks : # Populate model meta-data model = OrderedDict ( ) model [ "Name" ] = "_" . join ( [ base_name , task_name ] ) m...
Create a simple default model for each of the tasks in a BIDSLayout . Contrasts each trial type against all other trial types and trial types at the run level and then uses t - tests at each other level present to aggregate these results up .
843
52
249,527
def split ( self , grouper ) : data = self . to_df ( condition = True , entities = True ) data = data . drop ( 'condition' , axis = 1 ) subsets = [ ] for i , ( name , g ) in enumerate ( data . groupby ( grouper ) ) : name = '%s.%s' % ( self . name , name ) col = self . __class__ ( name = name , data = g , source = self...
Split the current SparseRunVariable into multiple columns .
133
11
249,528
def select_rows ( self , rows ) : self . values = self . values . iloc [ rows ] self . index = self . index . iloc [ rows , : ] for prop in self . _property_columns : vals = getattr ( self , prop ) [ rows ] setattr ( self , prop , vals )
Truncate internal arrays to keep only the specified rows .
72
12
249,529
def split ( self , grouper ) : values = grouper . values * self . values . values df = pd . DataFrame ( values , columns = grouper . columns ) return [ DenseRunVariable ( name = '%s.%s' % ( self . name , name ) , values = df [ name ] . values , run_info = self . run_info , source = self . source , sampling_rate = self ...
Split the current DenseRunVariable into multiple columns .
111
11
249,530
def _build_entity_index ( self , run_info , sampling_rate ) : index = [ ] interval = int ( round ( 1000. / sampling_rate ) ) _timestamps = [ ] for run in run_info : reps = int ( math . ceil ( run . duration * sampling_rate ) ) ent_vals = list ( run . entities . values ( ) ) df = pd . DataFrame ( [ ent_vals ] * reps , c...
Build the entity index from run information .
213
8
249,531
def resample ( self , sampling_rate , inplace = False , kind = 'linear' ) : if not inplace : var = self . clone ( ) var . resample ( sampling_rate , True , kind ) return var if sampling_rate == self . sampling_rate : return old_sr = self . sampling_rate n = len ( self . index ) self . index = self . _build_entity_index...
Resample the Variable to the specified sampling rate .
214
10
249,532
def to_df ( self , condition = True , entities = True , timing = True , sampling_rate = None ) : if sampling_rate not in ( None , self . sampling_rate ) : return self . resample ( sampling_rate ) . to_df ( condition , entities ) df = super ( DenseRunVariable , self ) . to_df ( condition , entities ) if timing : df [ 'o...
Convert to a DataFrame with columns for name and entities .
127
13
249,533
def get_collections ( self , unit , names = None , merge = False , sampling_rate = None , * * entities ) : nodes = self . get_nodes ( unit , entities ) var_sets = [ ] for n in nodes : var_set = list ( n . variables . values ( ) ) var_set = [ v for v in var_set if v . matches_entities ( entities ) ] if names is not None...
Retrieve variable data for a specified level in the Dataset .
269
14
249,534
def get_or_create_node ( self , level , entities , * args , * * kwargs ) : result = self . get_nodes ( level , entities ) if result : if len ( result ) > 1 : raise ValueError ( "More than one matching Node found! If you're" " expecting more than one Node, use " "get_nodes() instead of get_or_create_node()." ) return re...
Retrieves a child Node based on the specified criteria creating a new Node if necessary .
195
18
249,535
def merge_collections ( collections , force_dense = False , sampling_rate = 'auto' ) : if len ( listify ( collections ) ) == 1 : return collections levels = set ( [ c . level for c in collections ] ) if len ( levels ) > 1 : raise ValueError ( "At the moment, it's only possible to merge " "Collections at the same level ...
Merge two or more collections at the same level of analysis .
231
13
249,536
def merge_variables ( variables , * * kwargs ) : var_dict = OrderedDict ( ) for v in variables : if v . name not in var_dict : var_dict [ v . name ] = [ ] var_dict [ v . name ] . append ( v ) return [ merge_variables ( vars_ , * * kwargs ) for vars_ in list ( var_dict . values ( ) ) ]
Concatenates Variables along row axis .
97
10
249,537
def to_df ( self , variables = None , format = 'wide' , fillna = np . nan , * * kwargs ) : if variables is None : variables = list ( self . variables . keys ( ) ) # Can receive already-selected Variables from sub-classes if not isinstance ( variables [ 0 ] , BIDSVariable ) : variables = [ v for v in self . variables . ...
Merge variables into a single pandas DataFrame .
280
11
249,538
def from_df ( cls , data , entities = None , source = 'contrast' ) : variables = [ ] for col in data . columns : _data = pd . DataFrame ( data [ col ] . values , columns = [ 'amplitude' ] ) if entities is not None : _data = pd . concat ( [ _data , entities ] , axis = 1 , sort = True ) variables . append ( SimpleVariabl...
Create a Collection from a pandas DataFrame .
118
10
249,539
def clone ( self ) : clone = copy ( self ) clone . variables = { k : v . clone ( ) for ( k , v ) in self . variables . items ( ) } return clone
Returns a shallow copy of the current instance except that all variables are deep - cloned .
41
18
249,540
def _index_entities ( self ) : all_ents = pd . DataFrame . from_records ( [ v . entities for v in self . variables . values ( ) ] ) constant = all_ents . apply ( lambda x : x . nunique ( ) == 1 ) if constant . empty : self . entities = { } else : keep = all_ents . columns [ constant ] ents = { k : all_ents [ k ] . drop...
Sets current instance s entities based on the existing index .
141
12
249,541
def match_variables ( self , pattern , return_type = 'name' ) : pattern = re . compile ( pattern ) vars_ = [ v for v in self . variables . values ( ) if pattern . search ( v . name ) ] return vars_ if return_type . startswith ( 'var' ) else [ v . name for v in vars_ ]
Return columns whose names match the provided regex pattern .
82
10
249,542
def to_df ( self , variables = None , format = 'wide' , sparse = True , sampling_rate = None , include_sparse = True , include_dense = True , * * kwargs ) : if not include_sparse and not include_dense : raise ValueError ( "You can't exclude both dense and sparse " "variables! That leaves nothing!" ) if variables is Non...
Merge columns into a single pandas DataFrame .
298
11
249,543
def _transform ( self , var ) : self . collection . variables . pop ( var . name ) return var . values
Rename happens automatically in the base class so all we need to do is unset the original variable in the collection .
25
24
249,544
def replace_entities ( entities , pattern ) : ents = re . findall ( r'\{(.*?)\}' , pattern ) new_path = pattern for ent in ents : match = re . search ( r'([^|<]+)(<.*?>)?(\|.*)?' , ent ) if match is None : return None name , valid , default = match . groups ( ) default = default [ 1 : ] if default is not None else defa...
Replaces all entity names in a given pattern with the corresponding values provided by entities .
206
17
249,545
def write_contents_to_file ( path , contents = None , link_to = None , content_mode = 'text' , root = None , conflicts = 'fail' ) : if root is None and not isabs ( path ) : root = os . getcwd ( ) if root : path = join ( root , path ) if exists ( path ) or islink ( path ) : if conflicts == 'fail' : msg = 'A file at path...
Uses provided filename patterns to write contents to a new path given a corresponding entity map .
409
18
249,546
def generate ( self , * * kwargs ) : descriptions = [ ] subjs = self . layout . get_subjects ( * * kwargs ) kwargs = { k : v for k , v in kwargs . items ( ) if k != 'subject' } for sid in subjs : descriptions . append ( self . _report_subject ( subject = sid , * * kwargs ) ) counter = Counter ( descriptions ) print ( '...
Generate the methods section .
131
6
249,547
def _report_subject ( self , subject , * * kwargs ) : description_list = [ ] # Remove sess from kwargs if provided, else set sess as all available sessions = kwargs . pop ( 'session' , self . layout . get_sessions ( subject = subject , * * kwargs ) ) if not sessions : sessions = [ None ] elif not isinstance ( sessions ...
Write a report for a single subject .
344
8
249,548
def _gamma_difference_hrf ( tr , oversampling = 50 , time_length = 32. , onset = 0. , delay = 6 , undershoot = 16. , dispersion = 1. , u_dispersion = 1. , ratio = 0.167 ) : from scipy . stats import gamma dt = tr / oversampling time_stamps = np . linspace ( 0 , time_length , np . rint ( float ( time_length ) / dt ) . a...
Compute an hrf as the difference of two gamma functions
194
12
249,549
def spm_hrf ( tr , oversampling = 50 , time_length = 32. , onset = 0. ) : return _gamma_difference_hrf ( tr , oversampling , time_length , onset )
Implementation of the SPM hrf model
51
9
249,550
def glover_hrf ( tr , oversampling = 50 , time_length = 32. , onset = 0. ) : return _gamma_difference_hrf ( tr , oversampling , time_length , onset , delay = 6 , undershoot = 12. , dispersion = .9 , u_dispersion = .9 , ratio = .35 )
Implementation of the Glover hrf model
82
8
249,551
def spm_dispersion_derivative ( tr , oversampling = 50 , time_length = 32. , onset = 0. ) : dd = .01 dhrf = 1. / dd * ( - _gamma_difference_hrf ( tr , oversampling , time_length , onset , dispersion = 1. + dd ) + _gamma_difference_hrf ( tr , oversampling , time_length , onset ) ) return dhrf
Implementation of the SPM dispersion derivative hrf model
106
12
249,552
def glover_dispersion_derivative ( tr , oversampling = 50 , time_length = 32. , onset = 0. ) : dd = .01 dhrf = 1. / dd * ( - _gamma_difference_hrf ( tr , oversampling , time_length , onset , delay = 6 , undershoot = 12. , dispersion = .9 + dd , ratio = .35 ) + _gamma_difference_hrf ( tr , oversampling , time_length , o...
Implementation of the Glover dispersion derivative hrf model
144
11
249,553
def _sample_condition ( exp_condition , frame_times , oversampling = 50 , min_onset = - 24 ) : # Find the high-resolution frame_times n = frame_times . size min_onset = float ( min_onset ) n_hr = ( ( n - 1 ) * 1. / ( frame_times . max ( ) - frame_times . min ( ) ) * ( frame_times . max ( ) * ( 1 + 1. / ( n - 1 ) ) - fr...
Make a possibly oversampled event regressor from condition information .
494
13
249,554
def _resample_regressor ( hr_regressor , hr_frame_times , frame_times ) : from scipy . interpolate import interp1d f = interp1d ( hr_frame_times , hr_regressor ) return f ( frame_times ) . T
this function sub - samples the regressors at frame times
63
11
249,555
def _orthogonalize ( X ) : if X . size == X . shape [ 0 ] : return X from scipy . linalg import pinv , norm for i in range ( 1 , X . shape [ 1 ] ) : X [ : , i ] -= np . dot ( np . dot ( X [ : , i ] , X [ : , : i ] ) , pinv ( X [ : , : i ] ) ) # X[:, i] /= norm(X[:, i]) return X
Orthogonalize every column of design X w . r . t preceding columns
112
17
249,556
def _regressor_names ( con_name , hrf_model , fir_delays = None ) : if hrf_model in [ 'glover' , 'spm' , None ] : return [ con_name ] elif hrf_model in [ "glover + derivative" , 'spm + derivative' ] : return [ con_name , con_name + "_derivative" ] elif hrf_model in [ 'spm + derivative + dispersion' , 'glover + derivati...
Returns a list of regressor names computed from con - name and hrf type
178
16
249,557
def _hrf_kernel ( hrf_model , tr , oversampling = 50 , fir_delays = None ) : acceptable_hrfs = [ 'spm' , 'spm + derivative' , 'spm + derivative + dispersion' , 'fir' , 'glover' , 'glover + derivative' , 'glover + derivative + dispersion' , None ] if hrf_model == 'spm' : hkernel = [ spm_hrf ( tr , oversampling ) ] elif ...
Given the specification of the hemodynamic model and time parameters return the list of matching kernels
502
17
249,558
def compute_regressor ( exp_condition , hrf_model , frame_times , con_id = 'cond' , oversampling = 50 , fir_delays = None , min_onset = - 24 ) : # this is the average tr in this session, not necessarily the true tr tr = float ( frame_times . max ( ) ) / ( np . size ( frame_times ) - 1 ) # 1. create the high temporal re...
This is the main function to convolve regressors with hrf model
345
14
249,559
def matches_entities ( obj , entities , strict = False ) : if strict and set ( obj . entities . keys ( ) ) != set ( entities . keys ( ) ) : return False comm_ents = list ( set ( obj . entities . keys ( ) ) & set ( entities . keys ( ) ) ) for k in comm_ents : current = obj . entities [ k ] target = entities [ k ] if isi...
Checks whether an object s entities match the input .
118
11
249,560
def check_path_matches_patterns ( path , patterns ) : path = os . path . abspath ( path ) for patt in patterns : if isinstance ( patt , six . string_types ) : if path == patt : return True elif patt . search ( path ) : return True return False
Check if the path matches at least one of the provided patterns .
69
13
249,561
def count ( self , files = False ) : return len ( self . files ) if files else len ( self . unique ( ) )
Returns a count of unique values or files .
28
9
249,562
def general_acquisition_info ( metadata ) : out_str = ( 'MR data were acquired using a {tesla}-Tesla {manu} {model} ' 'MRI scanner.' ) out_str = out_str . format ( tesla = metadata . get ( 'MagneticFieldStrength' , 'UNKNOWN' ) , manu = metadata . get ( 'Manufacturer' , 'MANUFACTURER' ) , model = metadata . get ( 'Manuf...
General sentence on data acquisition . Should be first sentence in MRI data acquisition section .
117
16
249,563
def parse_niftis ( layout , niftis , subj , config , * * kwargs ) : kwargs = { k : v for k , v in kwargs . items ( ) if v is not None } description_list = [ ] skip_task = { } # Only report each task once for nifti_struct in niftis : nii_file = nifti_struct . path metadata = layout . get_metadata ( nii_file ) if not met...
Loop through niftis in a BIDSLayout and generate the appropriate description type for each scan . Compile all of the descriptions into a list .
694
32
249,564
def track_exception ( self , type = None , value = None , tb = None , properties = None , measurements = None ) : if not type or not value or not tb : type , value , tb = sys . exc_info ( ) if not type or not value or not tb : try : raise Exception ( NULL_CONSTANT_STRING ) except : type , value , tb = sys . exc_info ( ...
Send information about a single exception that occurred in the application .
321
12
249,565
def track_event ( self , name , properties = None , measurements = None ) : data = channel . contracts . EventData ( ) data . name = name or NULL_CONSTANT_STRING if properties : data . properties = properties if measurements : data . measurements = measurements self . track ( data , self . _context )
Send information about a single event that has occurred in the context of the application .
69
16
249,566
def track_metric ( self , name , value , type = None , count = None , min = None , max = None , std_dev = None , properties = None ) : dataPoint = channel . contracts . DataPoint ( ) dataPoint . name = name or NULL_CONSTANT_STRING dataPoint . value = value or 0 dataPoint . kind = type or channel . contracts . DataPoint...
Send information about a single metric data point that was captured for the application .
156
15
249,567
def track_trace ( self , name , properties = None , severity = None ) : data = channel . contracts . MessageData ( ) data . message = name or NULL_CONSTANT_STRING if properties : data . properties = properties if severity is not None : data . severity_level = channel . contracts . MessageData . PYTHON_LOGGING_LEVELS . ...
Sends a single trace statement .
97
7
249,568
def track_request ( self , name , url , success , start_time = None , duration = None , response_code = None , http_method = None , properties = None , measurements = None , request_id = None ) : data = channel . contracts . RequestData ( ) data . id = request_id or str ( uuid . uuid4 ( ) ) data . name = name data . ur...
Sends a single request that was captured for the application .
195
12
249,569
def track_dependency ( self , name , data , type = None , target = None , duration = None , success = None , result_code = None , properties = None , measurements = None , dependency_id = None ) : dependency_data = channel . contracts . RemoteDependencyData ( ) dependency_data . id = dependency_id or str ( uuid . uuid4...
Sends a single dependency telemetry that was captured for the application .
188
14
249,570
def dummy_client ( reason ) : sender = applicationinsights . channel . NullSender ( ) queue = applicationinsights . channel . SynchronousQueue ( sender ) channel = applicationinsights . channel . TelemetryChannel ( None , queue ) return applicationinsights . TelemetryClient ( "00000000-0000-0000-0000-000000000000" , ch...
Creates a dummy channel so even if we re not logging telemetry we can still send along the real object to things that depend on it to exist
76
30
249,571
def enable ( instrumentation_key , * args , * * kwargs ) : if not instrumentation_key : raise Exception ( 'Instrumentation key was required but not provided' ) global original_excepthook global telemetry_channel telemetry_channel = kwargs . get ( 'telemetry_channel' ) if not original_excepthook : original_excepthook = ...
Enables the automatic collection of unhandled exceptions . Captured exceptions will be sent to the Application Insights service before being re - thrown . Multiple calls to this function with different instrumentation keys result in multiple instances being submitted one for each key .
139
49
249,572
def init_app ( self , app ) : self . _key = app . config . get ( CONF_KEY ) or getenv ( CONF_KEY ) if not self . _key : return self . _endpoint_uri = app . config . get ( CONF_ENDPOINT_URI ) sender = AsynchronousSender ( self . _endpoint_uri ) queue = AsynchronousQueue ( sender ) self . _channel = TelemetryChannel ( No...
Initializes the extension for the provided Flask application .
140
10
249,573
def _init_request_logging ( self , app ) : enabled = not app . config . get ( CONF_DISABLE_REQUEST_LOGGING , False ) if not enabled : return self . _requests_middleware = WSGIApplication ( self . _key , app . wsgi_app , telemetry_channel = self . _channel ) app . wsgi_app = self . _requests_middleware
Sets up request logging unless APPINSIGHTS_DISABLE_REQUEST_LOGGING is set in the Flask config .
97
26
249,574
def _init_trace_logging ( self , app ) : enabled = not app . config . get ( CONF_DISABLE_TRACE_LOGGING , False ) if not enabled : return self . _trace_log_handler = LoggingHandler ( self . _key , telemetry_channel = self . _channel ) app . logger . addHandler ( self . _trace_log_handler )
Sets up trace logging unless APPINSIGHTS_DISABLE_TRACE_LOGGING is set in the Flask config .
87
26
249,575
def _init_exception_logging ( self , app ) : enabled = not app . config . get ( CONF_DISABLE_EXCEPTION_LOGGING , False ) if not enabled : return exception_telemetry_client = TelemetryClient ( self . _key , telemetry_channel = self . _channel ) @ app . errorhandler ( Exception ) def exception_handler ( exception ) : if ...
Sets up exception logging unless APPINSIGHTS_DISABLE_EXCEPTION_LOGGING is set in the Flask config .
143
27
249,576
def flush ( self ) : if self . _requests_middleware : self . _requests_middleware . flush ( ) if self . _trace_log_handler : self . _trace_log_handler . flush ( ) if self . _exception_telemetry_client : self . _exception_telemetry_client . flush ( )
Flushes the queued up telemetry to the service .
76
12
249,577
def get ( self ) : try : item = self . _queue . get_nowait ( ) except ( Empty , PersistEmpty ) : return None if self . _persistence_path : self . _queue . task_done ( ) return item
Gets a single item from the queue and returns it . If the queue is empty this method will return None .
53
23
249,578
def enable ( instrumentation_key , * args , * * kwargs ) : if not instrumentation_key : raise Exception ( 'Instrumentation key was required but not provided' ) if instrumentation_key in enabled_instrumentation_keys : logging . getLogger ( ) . removeHandler ( enabled_instrumentation_keys [ instrumentation_key ] ) async_...
Enables the Application Insights logging handler for the root logger for the supplied instrumentation key . Multiple calls to this function with different instrumentation keys result in multiple handler instances .
319
35
249,579
def start ( self ) : with self . _lock_send_remaining_time : if self . _send_remaining_time <= 0.0 : local_send_interval = self . _send_interval if self . _send_interval < 0.1 : local_send_interval = 0.1 self . _send_remaining_time = self . _send_time if self . _send_remaining_time < local_send_interval : self . _send_...
Starts a new sender thread if none is not already there
142
12
249,580
def device_initialize ( self ) : existing_device_initialize ( self ) self . type = 'Other' self . id = platform . node ( ) self . os_version = platform . version ( ) self . locale = locale . getdefaultlocale ( ) [ 0 ]
The device initializer used to assign special properties to all device context objects
60
14
249,581
def sign ( message : bytes , sign_key : SignKey ) -> Signature : logger = logging . getLogger ( __name__ ) logger . debug ( "Bls::sign: >>> message: %r, sign_key: %r" , message , sign_key ) c_instance = c_void_p ( ) do_call ( 'indy_crypto_bls_sign' , message , len ( message ) , sign_key . c_instance , byref ( c_instanc...
Signs the message and returns signature .
140
8
249,582
def verify ( signature : Signature , message : bytes , ver_key : VerKey , gen : Generator ) -> bool : logger = logging . getLogger ( __name__ ) logger . debug ( "Bls::verify: >>> signature: %r, message: %r, ver_key: %r, gen: %r" , signature , message , ver_key , gen ) valid = c_bool ( ) do_call ( 'indy_crypto_bsl_verif...
Verifies the message signature and returns true - if signature valid or false otherwise .
166
16
249,583
def verify_pop ( pop : ProofOfPossession , ver_key : VerKey , gen : Generator ) -> bool : logger = logging . getLogger ( __name__ ) logger . debug ( "Bls::verify_pop: >>> pop: %r, ver_key: %r, gen: %r" , pop , ver_key , gen ) valid = c_bool ( ) do_call ( 'indy_crypto_bsl_verify_pop' , pop . c_instance , ver_key . c_ins...
Verifies the proof of possession and returns true - if signature valid or false otherwise .
159
17
249,584
def verify_multi_sig ( multi_sig : MultiSignature , message : bytes , ver_keys : [ VerKey ] , gen : Generator ) -> bool : logger = logging . getLogger ( __name__ ) logger . debug ( "Bls::verify_multi_sig: >>> multi_sig: %r, message: %r, ver_keys: %r, gen: %r" , multi_sig , message , ver_keys , gen ) # noinspection PyCa...
Verifies the message multi signature and returns true - if signature valid or false otherwise .
284
17
249,585
def get_urls ( self ) : urls = [ url ( r'^publish/([0-9]+)/$' , self . admin_site . admin_view ( self . publish_post ) , name = 'djangocms_blog_publish_article' ) , ] urls . extend ( super ( PostAdmin , self ) . get_urls ( ) ) return urls
Customize the modeladmin urls
88
7
249,586
def publish_post ( self , request , pk ) : language = get_language_from_request ( request , check_path = True ) try : post = Post . objects . get ( pk = int ( pk ) ) post . publish = True post . save ( ) return HttpResponseRedirect ( post . get_absolute_url ( language ) ) except Exception : try : return HttpResponseRed...
Admin view to publish a single post
131
7
249,587
def has_restricted_sites ( self , request ) : sites = self . get_restricted_sites ( request ) return sites and sites . count ( ) == 1
Whether the current user has permission on one site only
34
10
249,588
def get_restricted_sites ( self , request ) : try : return request . user . get_sites ( ) except AttributeError : # pragma: no cover return Site . objects . none ( )
The sites on which the user has permission on .
43
10
249,589
def get_fieldsets ( self , request , obj = None ) : app_config_default = self . _app_config_select ( request , obj ) if app_config_default is None and request . method == 'GET' : return super ( PostAdmin , self ) . get_fieldsets ( request , obj ) if not obj : config = app_config_default else : config = obj . app_config...
Customize the fieldsets according to the app settings
456
10
249,590
def save_model ( self , request , obj , form , change ) : if 'config.menu_structure' in form . changed_data : from menus . menu_pool import menu_pool menu_pool . clear ( all = True ) return super ( BlogConfigAdmin , self ) . save_model ( request , obj , form , change )
Clear menu cache when changing menu structure
74
7
249,591
def clean_slug ( self ) : source = self . cleaned_data . get ( 'slug' , '' ) lang_choice = self . language_code if not source : source = slugify ( self . cleaned_data . get ( 'title' , '' ) ) qs = Post . _default_manager . active_translations ( lang_choice ) . language ( lang_choice ) used = list ( qs . values_list ( '...
Generate a valid slug in case the given one is taken
140
12
249,592
def tagged ( self , other_model = None , queryset = None ) : tags = self . _taglist ( other_model , queryset ) return self . get_queryset ( ) . filter ( tags__in = tags ) . distinct ( )
Restituisce una queryset di elementi del model taggati o con gli stessi tag di un model o un queryset
57
33
249,593
def _taglist ( self , other_model = None , queryset = None ) : from taggit . models import TaggedItem filter = None if queryset is not None : filter = set ( ) for item in queryset . all ( ) : filter . update ( item . tags . all ( ) ) filter = set ( [ tag . id for tag in filter ] ) elif other_model is not None : filter ...
Restituisce una lista di id di tag comuni al model corrente e al model o queryset passati come argomento
202
32
249,594
def tag_list ( self , other_model = None , queryset = None ) : from taggit . models import Tag return Tag . objects . filter ( id__in = self . _taglist ( other_model , queryset ) )
Restituisce un queryset di tag comuni al model corrente e al model o queryset passati come argomento
53
30
249,595
def liveblog_connect ( message , apphook , lang , post ) : try : post = Post . objects . namespace ( apphook ) . language ( lang ) . active_translations ( slug = post ) . get ( ) except Post . DoesNotExist : message . reply_channel . send ( { 'text' : json . dumps ( { 'error' : 'no_post' } ) , } ) return Group ( post ....
Connect users to the group of the given post according to the given language
123
14
249,596
def liveblog_disconnect ( message , apphook , lang , post ) : try : post = Post . objects . namespace ( apphook ) . language ( lang ) . active_translations ( slug = post ) . get ( ) except Post . DoesNotExist : message . reply_channel . send ( { 'text' : json . dumps ( { 'error' : 'no_post' } ) , } ) return Group ( pos...
Disconnect users to the group of the given post according to the given language
108
15
249,597
def video_in_option ( self , param , profile = 'Day' ) : if profile == 'Day' : field = param else : field = '{}Options.{}' . format ( profile , param ) return utils . pretty ( [ opt for opt in self . video_in_options . split ( ) if '].{}=' . format ( field ) in opt ] [ 0 ] )
Return video input option .
87
5
249,598
def _generate_token ( self ) : session = self . get_session ( ) url = self . __base_url ( 'magicBox.cgi?action=getMachineName' ) try : # try old basic method auth = requests . auth . HTTPBasicAuth ( self . _user , self . _password ) req = session . get ( url , auth = auth , timeout = self . _timeout_default ) if not re...
Create authentation to use with requests .
257
8
249,599
def _set_name ( self ) : try : self . _name = pretty ( self . machine_name ) self . _serial = self . serial_number except AttributeError : self . _name = None self . _serial = None
Set device name .
51
4