idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
22,900 | def _get_ants_args ( self ) : args = { 'moving_image' : self . inputs . moving_image , 'num_threads' : self . inputs . num_threads , 'float' : self . inputs . float , 'terminal_output' : 'file' , 'write_composite_transform' : True , 'initial_moving_transform' : self . inputs . initial_moving_transform } if isdefined ( ... | Moving image handling - The following truth table maps out the intended action sequence . Future refactoring may more directly encode this . |
22,901 | def dollars_to_math ( source ) : r s = "\n" . join ( source ) if s . find ( "$" ) == - 1 : return global _data _data = { } def repl ( matchobj ) : global _data s = matchobj . group ( 0 ) t = " XXX_REPL_%d " % len ( _data ) _data [ t ] = s return t s = re . sub ( r"({[^{}$]*\$[^{}$]*\$[^{}]*})" , repl , s ) dollars = re... | r Replace dollar signs with backticks . |
22,902 | def _post_run_hook ( self , runtime ) : self . _fixed_image = self . inputs . after self . _moving_image = self . inputs . before self . _contour = self . inputs . wm_seg if isdefined ( self . inputs . wm_seg ) else None NIWORKFLOWS_LOG . info ( 'Report - setting before (%s) and after (%s) images' , self . _fixed_image... | there is not inner interface to run |
22,903 | def _get_data_path ( data_dir = None ) : data_dir = data_dir or '' default_dirs = [ Path ( d ) . expanduser ( ) . resolve ( ) for d in os . getenv ( 'CRN_SHARED_DATA' , '' ) . split ( os . pathsep ) if d . strip ( ) ] default_dirs += [ Path ( d ) . expanduser ( ) . resolve ( ) for d in os . getenv ( 'CRN_DATA' , '' ) .... | Get data storage directory |
22,904 | def _get_dataset ( dataset_name , dataset_prefix = None , data_dir = None , default_paths = None , verbose = 1 ) : dataset_folder = dataset_name if not dataset_prefix else '%s%s' % ( dataset_prefix , dataset_name ) default_paths = default_paths or '' paths = [ p / dataset_folder for p in _get_data_path ( data_dir ) ] a... | Create if necessary and returns data directory of given dataset . |
22,905 | def _md5_sum_file ( path ) : with Path ( path ) . open ( 'rb' ) as fhandle : md5sum = hashlib . md5 ( ) while True : data = fhandle . read ( 8192 ) if not data : break md5sum . update ( data ) return md5sum . hexdigest ( ) | Calculates the MD5 sum of a file . |
22,906 | def _chunk_report_ ( bytes_so_far , total_size , initial_size , t_0 ) : if not total_size : sys . stderr . write ( "\rDownloaded {0:d} of ? bytes." . format ( bytes_so_far ) ) else : total_percent = float ( bytes_so_far ) / total_size current_download_size = bytes_so_far - initial_size bytes_remaining = total_size - by... | Show downloading percentage . |
22,907 | def refine_aseg ( aseg , ball_size = 4 ) : bmask = aseg . copy ( ) bmask [ bmask > 0 ] = 1 bmask = bmask . astype ( np . uint8 ) selem = sim . ball ( ball_size ) newmask = sim . binary_closing ( bmask , selem ) newmask = binary_fill_holes ( newmask . astype ( np . uint8 ) , selem ) . astype ( np . uint8 ) return newmas... | First step to reconcile ANTs and FreeSurfer s brain masks . |
22,908 | def grow_mask ( anat , aseg , ants_segs = None , ww = 7 , zval = 2.0 , bw = 4 ) : selem = sim . ball ( bw ) if ants_segs is None : ants_segs = np . zeros_like ( aseg , dtype = np . uint8 ) aseg [ aseg == 42 ] = 3 gm = anat . copy ( ) gm [ aseg != 3 ] = 0 refined = refine_aseg ( aseg ) newrefmask = sim . binary_dilation... | Grow mask including pixels that have a high likelihood . GM tissue parameters are sampled in image patches of ww size . |
22,909 | def medial_wall_to_nan ( in_file , subjects_dir , target_subject , newpath = None ) : import nibabel as nb import numpy as np import os fn = os . path . basename ( in_file ) if not target_subject . startswith ( 'fs' ) : return in_file cortex = nb . freesurfer . read_label ( os . path . join ( subjects_dir , target_subj... | Convert values on medial wall to NaNs |
22,910 | def make_link_node ( rawtext , app , type , slug , options ) : try : base = app . config . github_project_url if not base : raise AttributeError if not base . endswith ( '/' ) : base += '/' except AttributeError as err : raise ValueError ( 'github_project_url configuration value is not set (%s)' % str ( err ) ) ref = b... | Create a link to a github resource . |
22,911 | def ghissue_role ( name , rawtext , text , lineno , inliner , options = { } , content = [ ] ) : try : issue_num = int ( text ) if issue_num <= 0 : raise ValueError except ValueError : msg = inliner . reporter . error ( 'GitHub issue number must be a number greater than or equal to 1; ' '"%s" is invalid.' % text , line ... | Link to a GitHub issue . |
22,912 | def ghuser_role ( name , rawtext , text , lineno , inliner , options = { } , content = [ ] ) : app = inliner . document . settings . env . app ref = 'https://www.github.com/' + text node = nodes . reference ( rawtext , text , refuri = ref , ** options ) return [ node ] , [ ] | Link to a GitHub user . |
22,913 | def ghcommit_role ( name , rawtext , text , lineno , inliner , options = { } , content = [ ] ) : app = inliner . document . settings . env . app try : base = app . config . github_project_url if not base : raise AttributeError if not base . endswith ( '/' ) : base += '/' except AttributeError as err : raise ValueError ... | Link to a GitHub commit . |
22,914 | def _import ( self , name ) : mod = __import__ ( name ) components = name . split ( '.' ) for comp in components [ 1 : ] : mod = getattr ( mod , comp ) return mod | Import namespace package |
22,915 | def discover_modules ( self ) : modules = [ self . package_name ] for dirpath , dirnames , filenames in os . walk ( self . root_path ) : root_uri = self . _path2uri ( os . path . join ( self . root_path , dirpath ) ) filenames = [ f [ : - 3 ] for f in filenames if f . endswith ( '.py' ) and not f . startswith ( '__init... | Return module sequence discovered from self . package_name |
22,916 | def get_metadata_for_nifti ( in_file , bids_dir = None , validate = True ) : return _init_layout ( in_file , bids_dir , validate ) . get_metadata ( str ( in_file ) ) | Fetch metadata for a given nifti file |
22,917 | def group_multiecho ( bold_sess ) : from itertools import groupby def _grp_echos ( x ) : if '_echo-' not in x : return x echo = re . search ( "_echo-\\d*" , x ) . group ( 0 ) return x . replace ( echo , "_echo-?" ) ses_uids = [ ] for _ , bold in groupby ( bold_sess , key = _grp_echos ) : bold = list ( bold ) action = g... | Multiplexes multi - echo EPIs into arrays . Dual - echo is a special case of multi - echo which is treated as single - echo data . |
22,918 | def _define_variant ( self ) : space = None variants = { 'space1' : [ 'fsaverage5' , 'MNI152NLin2009cAsym' ] , 'space2' : [ 'fsaverage6' , 'MNI152NLin2009cAsym' ] , } for sp , targets in variants . items ( ) : if all ( target in targets for target in [ self . inputs . surface_target , self . inputs . volume_target ] ) ... | Assign arbitrary label to combination of CIFTI spaces |
22,919 | def _fetch_data ( self ) : if ( self . inputs . surface_target == "fsnative" or self . inputs . volume_target != "MNI152NLin2009cAsym" ) : raise NotImplementedError annotation_files = sorted ( glob ( os . path . join ( self . inputs . subjects_dir , self . inputs . surface_target , 'label' , '*h.aparc.annot' ) ) ) if n... | Converts inputspec to files |
22,920 | def reorient ( in_file , newpath = None ) : out_file = fname_presuffix ( in_file , suffix = '_ras' , newpath = newpath ) nb . as_closest_canonical ( nb . load ( in_file ) ) . to_filename ( out_file ) return out_file | Reorient Nifti files to RAS |
22,921 | def normalize_xform ( img ) : tmp_header = img . header . copy ( ) tmp_header . set_qform ( img . affine ) xform = tmp_header . get_qform ( ) xform_code = 2 qform , qform_code = img . get_qform ( coded = True ) sform , sform_code = img . get_sform ( coded = True ) if all ( ( qform is not None and np . allclose ( qform ... | Set identical valid qform and sform matrices in an image |
22,922 | def demean ( in_file , in_mask , only_mask = False , newpath = None ) : import os import numpy as np import nibabel as nb from nipype . utils . filemanip import fname_presuffix out_file = fname_presuffix ( in_file , suffix = '_demeaned' , newpath = os . getcwd ( ) ) nii = nb . load ( in_file ) msk = nb . load ( in_mask... | Demean in_file within the mask defined by in_mask |
22,923 | def nii_ones_like ( in_file , value , dtype , newpath = None ) : import os import numpy as np import nibabel as nb nii = nb . load ( in_file ) data = np . ones ( nii . shape , dtype = float ) * value out_file = os . path . join ( newpath or os . getcwd ( ) , "filled.nii.gz" ) nii = nb . Nifti1Image ( data , nii . affin... | Create a NIfTI file filled with value matching properties of in_file |
22,924 | def reorient_wf ( name = 'ReorientWorkflow' ) : workflow = pe . Workflow ( name = name ) inputnode = pe . Node ( niu . IdentityInterface ( fields = [ 'in_file' ] ) , name = 'inputnode' ) outputnode = pe . Node ( niu . IdentityInterface ( fields = [ 'out_file' ] ) , name = 'outputnode' ) deoblique = pe . Node ( afni . R... | A workflow to reorient images to RPI orientation |
22,925 | def _tsv2json ( in_tsv , out_json , index_column , additional_metadata = None , drop_columns = None , enforce_case = True ) : import pandas as pd re_to_camel = r'(.*?)_([a-zA-Z0-9])' re_to_snake = r'(^.+?|.*?)((?<![_A-Z])[A-Z]|(?<![_0-9])[0-9]+)' def snake ( match ) : return '{}_{}' . format ( match . group ( 1 ) . low... | Convert metadata from TSV format to JSON format . |
22,926 | def _tpm2roi ( in_tpm , in_mask , mask_erosion_mm = None , erosion_mm = None , mask_erosion_prop = None , erosion_prop = None , pthres = 0.95 , newpath = None ) : tpm_img = nb . load ( in_tpm ) roi_mask = ( tpm_img . get_data ( ) >= pthres ) . astype ( np . uint8 ) eroded_mask_file = None erode_in = ( mask_erosion_mm i... | Generate a mask from a tissue probability map |
22,927 | def run_reports ( reportlets_dir , out_dir , subject_label , run_uuid , config = None , packagename = None ) : report = Report ( Path ( reportlets_dir ) , out_dir , run_uuid , config = config , subject_id = subject_label , packagename = packagename ) return report . generate_report ( ) | Runs the reports |
22,928 | def generate_reports ( subject_list , output_dir , work_dir , run_uuid , config = None , packagename = None ) : reports_dir = str ( Path ( work_dir ) / 'reportlets' ) report_errors = [ run_reports ( reports_dir , output_dir , subject_label , run_uuid , config , packagename = packagename ) for subject_label in subject_l... | A wrapper to run_reports on a given subject_list |
22,929 | def index ( self , config ) : for subrep_cfg in config : orderings = [ s for s in subrep_cfg . get ( 'ordering' , '' ) . strip ( ) . split ( ',' ) if s ] queries = [ ] for key in orderings : values = getattr ( self . layout , 'get_%s%s' % ( key , PLURAL_SUFFIX [ key ] ) ) ( ) if values : queries . append ( ( key , valu... | Traverse the reports config definition and instantiate reportlets . This method also places figures in their final location . |
22,930 | def generate_report ( self ) : logs_path = self . out_dir / 'logs' boilerplate = [ ] boiler_idx = 0 if ( logs_path / 'CITATION.html' ) . exists ( ) : text = ( logs_path / 'CITATION.html' ) . read_text ( encoding = 'UTF-8' ) text = '<div class="boiler-html">%s</div>' % re . compile ( '<body>(.*?)</body>' , re . DOTALL |... | Once the Report has been indexed the final HTML can be generated |
22,931 | def _applytfms ( args ) : import nibabel as nb from nipype . utils . filemanip import fname_presuffix from niworkflows . interfaces . fixes import FixHeaderApplyTransforms as ApplyTransforms in_file , in_xform , ifargs , index , newpath = args out_file = fname_presuffix ( in_file , suffix = '_xform-%05d' % index , newp... | Applies ANTs antsApplyTransforms to the input image . All inputs are zipped in one tuple to make it digestible by multiprocessing s map |
22,932 | def _arrange_xfms ( transforms , num_files , tmp_folder ) : base_xform = [ '#Insight Transform File V1.0' , '#Transform 0' ] xfms_T = [ ] for i , tf_file in enumerate ( transforms ) : if guess_type ( tf_file ) [ 0 ] != 'text/plain' : xfms_T . append ( [ tf_file ] * num_files ) continue with open ( tf_file ) as tf_fh : ... | Convenience method to arrange the list of transforms that should be applied to each input file |
22,933 | def normalize_surfs ( in_file , transform_file , newpath = None ) : img = nb . load ( in_file ) transform = load_transform ( transform_file ) pointset = img . get_arrays_from_intent ( 'NIFTI_INTENT_POINTSET' ) [ 0 ] coords = pointset . data . T c_ras_keys = ( 'VolGeomC_R' , 'VolGeomC_A' , 'VolGeomC_S' ) ras = np . arra... | Re - center GIFTI coordinates to fit align to native T1 space |
22,934 | def load_transform ( fname ) : if fname is None : return np . eye ( 4 ) if fname . endswith ( '.mat' ) : return np . loadtxt ( fname ) elif fname . endswith ( '.lta' ) : with open ( fname , 'rb' ) as fobj : for line in fobj : if line . startswith ( b'1 4 4' ) : break lines = fobj . readlines ( ) [ : 4 ] return np . gen... | Load affine transform from file |
22,935 | def vertex_normals ( vertices , faces ) : def normalize_v3 ( arr ) : lens = np . sqrt ( arr [ : , 0 ] ** 2 + arr [ : , 1 ] ** 2 + arr [ : , 2 ] ** 2 ) arr /= lens [ : , np . newaxis ] tris = vertices [ faces ] facenorms = np . cross ( tris [ : : , 1 ] - tris [ : : , 0 ] , tris [ : : , 2 ] - tris [ : : , 0 ] ) normalize... | Calculates the normals of a triangular mesh |
22,936 | def pointcloud2ply ( vertices , normals , out_file = None ) : from pathlib import Path import pandas as pd from pyntcloud import PyntCloud df = pd . DataFrame ( np . hstack ( ( vertices , normals ) ) ) df . columns = [ 'x' , 'y' , 'z' , 'nx' , 'ny' , 'nz' ] cloud = PyntCloud ( df ) if out_file is None : out_file = Path... | Converts the file to PLY format |
22,937 | def ply2gii ( in_file , metadata , out_file = None ) : from pathlib import Path from numpy import eye from nibabel . gifti import ( GiftiMetaData , GiftiCoordSystem , GiftiImage , GiftiDataArray , ) from pyntcloud import PyntCloud in_file = Path ( in_file ) surf = PyntCloud . from_file ( str ( in_file ) ) metadata . up... | Convert from ply to GIfTI |
22,938 | def fix_multi_T1w_source_name ( in_files ) : import os from nipype . utils . filemanip import filename_to_list base , in_file = os . path . split ( filename_to_list ( in_files ) [ 0 ] ) subject_label = in_file . split ( "_" , 1 ) [ 0 ] . split ( "-" ) [ 1 ] return os . path . join ( base , "sub-%s_T1w.nii.gz" % subject... | Make up a generic source name when there are multiple T1s |
22,939 | def add_suffix ( in_files , suffix ) : import os . path as op from nipype . utils . filemanip import fname_presuffix , filename_to_list return op . basename ( fname_presuffix ( filename_to_list ( in_files ) [ 0 ] , suffix = suffix ) ) | Wrap nipype s fname_presuffix to conveniently just add a prefix |
22,940 | def _read_txt ( path ) : from pathlib import Path lines = Path ( path ) . read_text ( ) . splitlines ( ) data = { 'file' : str ( path ) } traceback_start = 0 if lines [ 0 ] . startswith ( 'Node' ) : data [ 'node' ] = lines [ 0 ] . split ( ': ' , 1 ) [ 1 ] . strip ( ) data [ 'node_dir' ] = lines [ 1 ] . split ( ': ' , 1... | Read a txt crashfile |
22,941 | def _conform_mask ( in_mask , in_reference ) : from pathlib import Path import nibabel as nb from nipype . utils . filemanip import fname_presuffix ref = nb . load ( in_reference ) nii = nb . load ( in_mask ) hdr = nii . header . copy ( ) hdr . set_data_dtype ( 'int16' ) hdr . set_slope_inter ( 1 , 0 ) qform , qcode = ... | Ensures the mask headers make sense and match those of the T1w |
22,942 | def get_template ( template_name , data_dir = None , url = None , resume = True , verbose = 1 ) : warn ( DEPRECATION_MSG ) if template_name . startswith ( 'tpl-' ) : template_name = template_name [ 4 : ] template_name = TEMPLATE_ALIASES . get ( template_name , template_name ) return get_dataset ( template_name , datase... | Download and load a template |
22,943 | def get_bids_examples ( data_dir = None , url = None , resume = True , verbose = 1 , variant = 'BIDS-examples-1-1.0.0-rc3u5' ) : warn ( DEPRECATION_MSG ) variant = 'BIDS-examples-1-1.0.0-rc3u5' if variant not in BIDS_EXAMPLES else variant if url is None : url = BIDS_EXAMPLES [ variant ] [ 0 ] md5 = BIDS_EXAMPLES [ vari... | Download BIDS - examples - 1 |
22,944 | def svg2str ( display_object , dpi = 300 ) : from io import StringIO image_buf = StringIO ( ) display_object . frame_axes . figure . savefig ( image_buf , dpi = dpi , format = 'svg' , facecolor = 'k' , edgecolor = 'k' ) return image_buf . getvalue ( ) | Serializes a nilearn display object as a string |
22,945 | def extract_svg ( display_object , dpi = 300 , compress = 'auto' ) : image_svg = svg2str ( display_object , dpi ) if compress is True or compress == 'auto' : image_svg = svg_compress ( image_svg , compress ) image_svg = re . sub ( ' height="[0-9]+[a-z]*"' , '' , image_svg , count = 1 ) image_svg = re . sub ( ' width="[... | Removes the preamble of the svg files generated with nilearn |
22,946 | def cuts_from_bbox ( mask_nii , cuts = 3 ) : from nibabel . affines import apply_affine mask_data = mask_nii . get_data ( ) > 0.0 ijk_counts = [ mask_data . sum ( 2 ) . sum ( 1 ) , mask_data . sum ( 2 ) . sum ( 0 ) , mask_data . sum ( 1 ) . sum ( 0 ) , ] ijk_th = [ int ( ( mask_data . shape [ 1 ] * mask_data . shape [ ... | Finds equi - spaced cuts for presenting images |
22,947 | def _3d_in_file ( in_file ) : in_file = filemanip . filename_to_list ( in_file ) [ 0 ] try : in_file = nb . load ( in_file ) except AttributeError : in_file = in_file if in_file . get_data ( ) . ndim == 3 : return in_file return nlimage . index_img ( in_file , 0 ) | if self . inputs . in_file is 3d return it . if 4d pick an arbitrary volume and return that . |
22,948 | def transform_to_2d ( data , max_axis ) : import numpy as np new_shape = list ( data . shape ) del new_shape [ max_axis ] a1 , a2 = np . indices ( new_shape ) inds = [ a1 , a2 ] inds . insert ( max_axis , np . abs ( data ) . argmax ( axis = max_axis ) ) maximum_intensity_data = data [ inds ] return np . rot90 ( maximum... | Projects 3d data cube along one axis using maximum intensity with preservation of the signs . Adapted from nilearn . |
22,949 | def main ( ) : from os import path as op from inspect import getfile , currentframe from setuptools import setup , find_packages from niworkflows . __about__ import ( __packagename__ , __author__ , __email__ , __maintainer__ , __license__ , __description__ , __longdesc__ , __url__ , DOWNLOAD_URL , CLASSIFIERS , REQUIRE... | Install entry - point |
22,950 | def afni_wf ( name = 'AFNISkullStripWorkflow' , unifize = False , n4_nthreads = 1 ) : workflow = pe . Workflow ( name = name ) inputnode = pe . Node ( niu . IdentityInterface ( fields = [ 'in_file' ] ) , name = 'inputnode' ) outputnode = pe . Node ( niu . IdentityInterface ( fields = [ 'bias_corrected' , 'out_file' , '... | Skull - stripping workflow |
22,951 | def _get ( url , headers = { } , params = None ) : param_string = _foursquare_urlencode ( params ) for i in xrange ( NUM_REQUEST_RETRIES ) : try : try : response = requests . get ( url , headers = headers , params = param_string , verify = VERIFY_SSL ) return _process_response ( response ) except requests . exceptions ... | Tries to GET data from an endpoint using retries |
22,952 | def _post ( url , headers = { } , data = None , files = None ) : try : response = requests . post ( url , headers = headers , data = data , files = files , verify = VERIFY_SSL ) return _process_response ( response ) except requests . exceptions . RequestException as e : _log_and_raise_exception ( 'Error connecting with... | Tries to POST data to an endpoint |
22,953 | def _process_response ( response ) : try : data = response . json ( ) except ValueError : _log_and_raise_exception ( 'Invalid response' , response . text ) if response . status_code == 200 : return { 'headers' : response . headers , 'data' : data } return _raise_error_from_response ( data ) | Make the request and handle exception processing |
22,954 | def _raise_error_from_response ( data ) : meta = data . get ( 'meta' ) if meta : if meta . get ( 'code' ) in ( 200 , 409 ) : return data exc = error_types . get ( meta . get ( 'errorType' ) ) if exc : raise exc ( meta . get ( 'errorDetail' ) ) else : _log_and_raise_exception ( 'Unknown error. meta' , meta ) else : _log... | Processes the response data |
22,955 | def _foursquare_urlencode ( query , doseq = 0 , safe_chars = "&/,+" ) : if hasattr ( query , "items" ) : query = query . items ( ) else : try : if len ( query ) and not isinstance ( query [ 0 ] , tuple ) : raise TypeError except TypeError : ty , va , tb = sys . exc_info ( ) raise TypeError ( "not a valid non-string seq... | Gnarly hack because Foursquare doesn t properly handle standard url encoding |
22,956 | def _attach_endpoints ( self ) : for name , endpoint in inspect . getmembers ( self ) : if inspect . isclass ( endpoint ) and issubclass ( endpoint , self . _Endpoint ) and ( endpoint is not self . _Endpoint ) : endpoint_instance = endpoint ( self . base_requester ) setattr ( self , endpoint_instance . endpoint , endpo... | Dynamically attach endpoint callables to this client |
22,957 | def register ( self , widget , basename , ** parameters ) : self . registry . append ( ( widget , basename , parameters ) ) | Register a widget URL basename and any optional URL parameters . |
22,958 | def iterator ( self ) : for obj in ( self . execute ( ) . json ( ) . get ( "items" ) or [ ] ) : yield self . api_obj_class ( self . api , obj ) | Execute the API request and return an iterator over the objects . This method does not use the query cache . |
22,959 | def version ( self ) : response = self . get ( version = "" , base = "/version" ) response . raise_for_status ( ) data = response . json ( ) return ( data [ "major" ] , data [ "minor" ] ) | Get Kubernetes API version |
22,960 | def get_kwargs ( self , ** kwargs ) : version = kwargs . pop ( "version" , "v1" ) if version == "v1" : base = kwargs . pop ( "base" , "/api" ) elif "/" in version : base = kwargs . pop ( "base" , "/apis" ) else : if "base" not in kwargs : raise TypeError ( "unknown API version; base kwarg must be specified." ) base = k... | Creates a full URL to request based on arguments . |
22,961 | def request ( self , * args , ** kwargs ) : return self . session . request ( * args , ** self . get_kwargs ( ** kwargs ) ) | Makes an API request based on arguments . |
22,962 | def get ( self , * args , ** kwargs ) : return self . session . get ( * args , ** self . get_kwargs ( ** kwargs ) ) | Executes an HTTP GET . |
22,963 | def options ( self , * args , ** kwargs ) : return self . session . options ( * args , ** self . get_kwargs ( ** kwargs ) ) | Executes an HTTP OPTIONS . |
22,964 | def head ( self , * args , ** kwargs ) : return self . session . head ( * args , ** self . get_kwargs ( ** kwargs ) ) | Executes an HTTP HEAD . |
22,965 | def post ( self , * args , ** kwargs ) : return self . session . post ( * args , ** self . get_kwargs ( ** kwargs ) ) | Executes an HTTP POST . |
22,966 | def put ( self , * args , ** kwargs ) : return self . session . put ( * args , ** self . get_kwargs ( ** kwargs ) ) | Executes an HTTP PUT . |
22,967 | def patch ( self , * args , ** kwargs ) : return self . session . patch ( * args , ** self . get_kwargs ( ** kwargs ) ) | Executes an HTTP PATCH . |
22,968 | def delete ( self , * args , ** kwargs ) : return self . session . delete ( * args , ** self . get_kwargs ( ** kwargs ) ) | Executes an HTTP DELETE . |
22,969 | def from_file ( cls , filename , ** kwargs ) : filename = os . path . expanduser ( filename ) if not os . path . isfile ( filename ) : raise exceptions . PyKubeError ( "Configuration file {} not found" . format ( filename ) ) with open ( filename ) as f : doc = yaml . safe_load ( f . read ( ) ) self = cls ( doc , ** kw... | Creates an instance of the KubeConfig class from a kubeconfig file . |
22,970 | def clusters ( self ) : if not hasattr ( self , "_clusters" ) : cs = { } for cr in self . doc [ "clusters" ] : cs [ cr [ "name" ] ] = c = copy . deepcopy ( cr [ "cluster" ] ) if "server" not in c : c [ "server" ] = "http://localhost" BytesOrFile . maybe_set ( c , "certificate-authority" ) self . _clusters = cs return s... | Returns known clusters by exposing as a read - only property . |
22,971 | def users ( self ) : if not hasattr ( self , "_users" ) : us = { } if "users" in self . doc : for ur in self . doc [ "users" ] : us [ ur [ "name" ] ] = u = copy . deepcopy ( ur [ "user" ] ) BytesOrFile . maybe_set ( u , "client-certificate" ) BytesOrFile . maybe_set ( u , "client-key" ) self . _users = us return self .... | Returns known users by exposing as a read - only property . |
22,972 | def contexts ( self ) : if not hasattr ( self , "_contexts" ) : cs = { } for cr in self . doc [ "contexts" ] : cs [ cr [ "name" ] ] = copy . deepcopy ( cr [ "context" ] ) self . _contexts = cs return self . _contexts | Returns known contexts by exposing as a read - only property . |
22,973 | def user ( self ) : return self . users . get ( self . contexts [ self . current_context ] . get ( "user" , "" ) , { } ) | Returns the current user set by current context |
22,974 | def bytes ( self ) : if self . _filename : with open ( self . _filename , "rb" ) as f : return f . read ( ) else : return self . _bytes | Returns the provided data as bytes . |
22,975 | def filename ( self ) : if self . _filename : return self . _filename else : with tempfile . NamedTemporaryFile ( delete = False ) as f : f . write ( self . _bytes ) return f . name | Returns the provided data as a file location . |
22,976 | def object_factory ( api , api_version , kind ) : resource_list = api . resource_list ( api_version ) resource = next ( ( resource for resource in resource_list [ "resources" ] if resource [ "kind" ] == kind ) , None ) base = NamespacedAPIObject if resource [ "namespaced" ] else APIObject return type ( kind , ( base , ... | Dynamically builds a Python class for the given Kubernetes object in an API . |
22,977 | def _handle_info ( self , * args , ** kwargs ) : if 'version' in kwargs : self . api_version = kwargs [ 'version' ] print ( "Initialized API with version %s" % self . api_version ) return try : info_code = str ( kwargs [ 'code' ] ) except KeyError : raise FaultyPayloadError ( "_handle_info: %s" % kwargs ) if not info_c... | Handles info messages and executed corresponding code |
22,978 | def setup ( app ) : global _is_sphinx _is_sphinx = True app . add_config_value ( 'no_underscore_emphasis' , False , 'env' ) app . add_config_value ( 'm2r_parse_relative_links' , False , 'env' ) app . add_config_value ( 'm2r_anonymous_references' , False , 'env' ) app . add_config_value ( 'm2r_disable_inline_math' , Fal... | When used for sphinx extension . |
22,979 | def link ( self , link , title , text ) : if self . anonymous_references : underscore = '__' else : underscore = '_' if title : return self . _raw_html ( '<a href="{link}" title="{title}">{text}</a>' . format ( link = link , title = title , text = text ) ) if not self . parse_relative_links : return '\ `{text} <{target... | Rendering a given link with content and title . |
22,980 | def events ( url = None , file = None , string_content = None , start = None , end = None , fix_apple = False ) : found_events = [ ] content = None if url : content = ICalDownload ( ) . data_from_url ( url , apple_fix = fix_apple ) if not content and file : content = ICalDownload ( ) . data_from_file ( file , apple_fix... | Get all events form the given iCal URL occurring in the given time range . |
22,981 | def request_data ( key , url , file , string_content , start , end , fix_apple ) : data = [ ] try : data += events ( url = url , file = file , string_content = string_content , start = start , end = end , fix_apple = fix_apple ) finally : update_events ( key , data ) request_finished ( key ) | Request data update local data cache and remove this Thread form queue . |
22,982 | def events_async ( key , url = None , file = None , start = None , string_content = None , end = None , fix_apple = False ) : t = Thread ( target = request_data , args = ( key , url , file , string_content , start , end , fix_apple ) ) with event_lock : if key not in threads : threads [ key ] = [ ] threads [ key ] . ap... | Trigger an asynchronous data request . |
22,983 | def request_finished ( key ) : with event_lock : threads [ key ] = threads [ key ] [ 1 : ] if threads [ key ] : threads [ key ] [ 0 ] . run ( ) | Remove finished Thread from queue . |
22,984 | def data_from_url ( self , url , apple_fix = False ) : if apple_fix : url = apple_url_fix ( url ) _ , content = self . http . request ( url ) if not content : raise ConnectionError ( 'Could not get data from %s!' % url ) return self . decode ( content , apple_fix = apple_fix ) | Download iCal data from URL . |
22,985 | def data_from_file ( self , file , apple_fix = False ) : with open ( file , mode = 'rb' ) as f : content = f . read ( ) if not content : raise IOError ( "File %f is not readable or is empty!" % file ) return self . decode ( content , apple_fix = apple_fix ) | Read iCal data from file . |
22,986 | def decode ( self , content , apple_fix = False ) : content = content . decode ( self . encoding ) content = content . replace ( '\r' , '' ) if apple_fix : content = apple_data_fix ( content ) return content | Decode content using the set charset . |
22,987 | def create_event ( component , tz = UTC ) : event = Event ( ) event . start = normalize ( component . get ( 'dtstart' ) . dt , tz = tz ) if component . get ( 'dtend' ) : event . end = normalize ( component . get ( 'dtend' ) . dt , tz = tz ) elif component . get ( 'duration' ) : event . end = event . start + component .... | Create an event from its iCal representation . |
22,988 | def normalize ( dt , tz = UTC ) : if type ( dt ) is date : dt = dt + relativedelta ( hour = 0 ) elif type ( dt ) is datetime : pass else : raise ValueError ( "unknown type %s" % type ( dt ) ) if dt . tzinfo : dt = dt . astimezone ( tz ) else : dt = dt . replace ( tzinfo = tz ) return dt | Convert date or datetime to datetime with timezone . |
22,989 | def parse_events ( content , start = None , end = None , default_span = timedelta ( days = 7 ) ) : if not start : start = now ( ) if not end : end = start + default_span if not content : raise ValueError ( 'Content is invalid!' ) calendar = Calendar . from_ical ( content ) for c in calendar . walk ( ) : if c . name == ... | Query the events occurring in a given time range . |
22,990 | def copy_to ( self , new_start = None , uid = None ) : if not new_start : new_start = self . start if not uid : uid = "%s_%d" % ( self . uid , randint ( 0 , 1000000 ) ) ne = Event ( ) ne . summary = self . summary ne . description = self . description ne . start = new_start if self . end : duration = self . end - self ... | Create a new event equal to this with new start date . |
22,991 | def fetch_public_key ( repo ) : keyurl = 'https://api.travis-ci.org/repos/{0}/key' . format ( repo ) data = json . loads ( urlopen ( keyurl ) . read ( ) ) if 'key' not in data : errmsg = "Could not find public key for repo: {}.\n" . format ( repo ) errmsg += "Have you already added your GitHub repo to Travis?" raise Va... | Download RSA public key Travis will use for this repo . |
22,992 | def kill_the_system ( self , warning : str ) : log . critical ( 'Kill reason: ' + warning ) if self . DEBUG : return try : self . mail_this ( warning ) except socket . gaierror : current_time = time . localtime ( ) formatted_time = time . strftime ( '%Y-%m-%d %I:%M:%S%p' , current_time ) with open ( self . config [ 'gl... | Send an e - mail and then shut the system down quickly . |
22,993 | def get_killer ( args ) : if POSIX : log . debug ( 'Platform: POSIX' ) from killer . killer_posix import KillerPosix return KillerPosix ( config_path = args . config , debug = args . debug ) elif WINDOWS : log . debug ( 'Platform: Windows' ) from killer . killer_windows import KillerWindows return KillerWindows ( confi... | Returns a KillerBase instance subclassed based on the OS . |
22,994 | def get_devices ( device_type : DeviceType ) -> Iterator [ str ] : for device in BASE_PATH . iterdir ( ) : with open ( str ( Path ( device , 'type' ) ) ) as type_file : if type_file . readline ( ) . strip ( ) == device_type . value : yield device . name | Gets names of power devices of the specified type . |
22,995 | def _get_property ( device_path : Union [ Path , str ] , property_name : str ) -> str : with open ( str ( Path ( device_path , property_name ) ) ) as file : return file . readline ( ) . strip ( ) | Gets the given property for a device . |
22,996 | def get_power_status ( ) -> SystemPowerStatus : get_system_power_status = ctypes . windll . kernel32 . GetSystemPowerStatus get_system_power_status . argtypes = [ ctypes . POINTER ( SystemPowerStatus ) ] get_system_power_status . restype = wintypes . BOOL status = SystemPowerStatus ( ) if not get_system_power_status ( ... | Retrieves the power status of the system . |
22,997 | def abilities ( api_key = None , add_headers = None ) : client = ClientMixin ( api_key = api_key ) result = client . request ( 'GET' , endpoint = 'abilities' , add_headers = add_headers , ) return result [ 'abilities' ] | Fetch a list of permission - like strings for this account . |
22,998 | def can ( ability , add_headers = None ) : client = ClientMixin ( api_key = None ) try : client . request ( 'GET' , endpoint = 'abilities/%s' % ability , add_headers = add_headers ) return True except Exception : pass return False | Test whether an ability is allowed . |
22,999 | def set_api_key_from_file ( path , set_global = True ) : with open ( path , 'r+b' ) as f : global api_key api_key = f . read ( ) . strip ( ) return api_key | Set the global api_key from a file path . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.