idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
8,300 | def _read_file ( filename ) : # read data with open ( filename , 'r' ) as fid2 : abem_data_orig = fid2 . read ( ) fid = StringIO ( ) fid . write ( abem_data_orig ) fid . seek ( 0 ) # determine type of array fid . readline ( ) fid . readline ( ) file_type = int ( fid . readline ( ) . strip ( ) ) # reset file pointer fid... | Read a res2dinv - file and return the header | 111 | 12 |
8,301 | def add_dat_file ( filename , settings , container = None , * * kwargs ) : # each type is read by a different function importers = { # general array type 11 : _read_general_type , } file_type , content = _read_file ( filename ) if file_type not in importers : raise Exception ( 'type of RES2DINV data file not recognized... | Read a RES2DINV - style file produced by the ABEM export program . | 183 | 18 |
8,302 | def console_input ( default , validation = None , allow_empty = False ) : value = raw_input ( "> " ) or default if value == "" and not allow_empty : print "Invalid: Empty value is not permitted." return console_input ( default , validation ) if validation : try : return validation ( value ) except ValidationError , e :... | Get user input value from stdin | 94 | 7 |
8,303 | def correct ( self , calib , temp , we_t , ae_t ) : if not A4TempComp . in_range ( temp ) : return None if self . __algorithm == 1 : return self . __eq1 ( temp , we_t , ae_t ) if self . __algorithm == 2 : return self . __eq2 ( temp , we_t , ae_t , calib . we_cal_mv , calib . ae_cal_mv ) if self . __algorithm == 3 : ret... | Compute weC from weT aeT | 211 | 10 |
8,304 | def cf_t ( self , temp ) : index = int ( ( temp - A4TempComp . __MIN_TEMP ) // A4TempComp . __INTERVAL ) # index of start of interval # on boundary... if temp % A4TempComp . __INTERVAL == 0 : return self . __values [ index ] # all others... y1 = self . __values [ index ] # y value at start of interval y2 = self . __val... | Compute the linear - interpolated temperature compensation factor . | 257 | 11 |
8,305 | def run_once ( function , state = { } , errors = { } ) : @ six . wraps ( function ) def _wrapper ( * args , * * kwargs ) : if function in errors : # Deliberate use of LBYL. six . reraise ( * errors [ function ] ) try : return state [ function ] except KeyError : try : state [ function ] = result = function ( * args , *... | A memoization decorator whose purpose is to cache calls . | 117 | 12 |
8,306 | def _session ( self ) : if self . _http_session is None : self . _http_session = requests . Session ( ) self . _http_session . headers . update ( self . _get_headers ( ) ) self . _http_session . verify = self . _verify_https_request ( ) if all ( self . _credentials ) : username , password = self . _credentials self . _... | The current session used by the client . | 127 | 8 |
8,307 | def get_resource ( self , path ) : response = self . _http_request ( path ) try : return response . json ( ) except ValueError : raise exception . ServiceException ( "Invalid service response." ) | Getting the required information from the API . | 45 | 8 |
8,308 | def update_resource ( self , path , data , if_match = None ) : response = self . _http_request ( resource = path , method = "PUT" , body = data , if_match = if_match ) try : return response . json ( ) except ValueError : raise exception . ServiceException ( "Invalid service response." ) | Update the required resource . | 73 | 5 |
8,309 | def summarize ( self ) : s = str ( self . allval ( ) ) return self . parse ( s [ : 2 ] + '' . join ( [ 'Z' ] * len ( s [ 2 : ] ) ) ) | Convert all of the values to their max values . This form is used to represent the summary level | 48 | 20 |
8,310 | def _filter_schlumberger ( configs ) : # sort configs configs_sorted = np . hstack ( ( np . sort ( configs [ : , 0 : 2 ] , axis = 1 ) , np . sort ( configs [ : , 2 : 4 ] , axis = 1 ) , ) ) . astype ( int ) # determine unique voltage dipoles MN = configs_sorted [ : , 2 : 4 ] . copy ( ) MN_unique = np . unique ( MN . vie... | Filter Schlumberger configurations | 557 | 5 |
8,311 | def _filter_dipole_dipole ( configs ) : # check that dipoles have equal size dist_ab = np . abs ( configs [ : , 0 ] - configs [ : , 1 ] ) dist_mn = np . abs ( configs [ : , 2 ] - configs [ : , 3 ] ) distances_equal = ( dist_ab == dist_mn ) # check that they are not overlapping not_overlapping = ( # either a,b < m,n ( (... | Filter dipole - dipole configurations | 373 | 7 |
8,312 | def _sort_dd_skips ( configs , dd_indices_all ) : config_current_skips = np . abs ( configs [ : , 1 ] - configs [ : , 0 ] ) if np . all ( np . isnan ( config_current_skips ) ) : return { 0 : [ ] } # determine skips available_skips_raw = np . unique ( config_current_skips ) available_skips = available_skips_raw [ ~ np .... | Given a set of dipole - dipole configurations sort them according to their current skip . | 198 | 18 |
8,313 | def filter ( configs , settings ) : if isinstance ( configs , pd . DataFrame ) : configs = configs [ [ 'a' , 'b' , 'm' , 'n' ] ] . values # assign short labels to Python functions filter_funcs = { 'dd' : _filter_dipole_dipole , 'schlumberger' : _filter_schlumberger , } # we need a list to fix the call order of filter f... | Main entry function to filtering configuration types | 302 | 7 |
8,314 | def save_block_to_crt ( filename , group , norrec = 'all' , store_errors = False ) : if norrec != 'all' : group = group . query ( 'norrec == "{0}"' . format ( norrec ) ) # todo: we need to fix the global naming scheme for columns! with open ( filename , 'wb' ) as fid : fid . write ( bytes ( '{0}\n' . format ( len ( gro... | Save a dataset to a CRTomo - compatible . crt file | 308 | 14 |
8,315 | def get_label ( parameter , ptype , flavor = None , mpl = None ) : # determine flavor if flavor is not None : if flavor not in ( 'latex' , 'mathml' ) : raise Exception ( 'flavor not recognized: {}' . format ( flavor ) ) else : if mpl is None : raise Exception ( 'either the flavor or mpl must be provided' ) rendering = ... | Return the label of a given SIP parameter | 198 | 9 |
8,316 | def _add_labels ( self , axes , dtype ) : for ax in axes [ 1 , : ] . flat : ax . set_xlabel ( 'frequency [Hz]' ) if dtype == 'rho' : axes [ 0 , 0 ] . set_ylabel ( r'$|\rho| [\Omega m]$' ) axes [ 0 , 1 ] . set_ylabel ( r'$-\phi [mrad]$' ) axes [ 1 , 0 ] . set_ylabel ( r"$\sigma' [S/m]$" ) axes [ 1 , 1 ] . set_ylabel ( r... | Given a 2x2 array of axes add x and y labels | 283 | 13 |
8,317 | def add ( self , response , label = None ) : if not isinstance ( response , sip_response . sip_response ) : raise Exception ( 'can only add sip_reponse.sip_response objects' ) self . objects . append ( response ) if label is None : self . labels . append ( 'na' ) else : self . labels . append ( label ) | add one response object to the list | 80 | 7 |
8,318 | def split_data ( data , squeeze = False ) : vdata = np . atleast_2d ( data ) nr_freqs = int ( vdata . shape [ 1 ] / 2 ) part1 = vdata [ : , 0 : nr_freqs ] part2 = vdata [ : , nr_freqs : ] if ( squeeze ) : part1 = part1 . squeeze ( ) part2 = part2 . squeeze ( ) return part1 , part2 | Split 1D or 2D into two parts using the last axis | 104 | 13 |
8,319 | def convert ( input_format , output_format , data , one_spectrum = False ) : if input_format == output_format : return data if input_format not in from_converters : raise KeyError ( 'Input format {0} not known!' . format ( input_format ) ) if output_format not in to_converters : raise KeyError ( 'Output format {0} not ... | Convert from the given format to the requested format | 309 | 10 |
8,320 | def search ( self , params , standardize = False ) : resp = self . _request ( ENDPOINTS [ 'SEARCH' ] , params ) if not standardize : return resp # Standardization logic for res in resp [ 'result_data' ] : res = self . standardize ( res ) return resp | Get a list of person objects for the given search params . | 68 | 12 |
8,321 | def detail_search ( self , params , standardize = False ) : response = self . _request ( ENDPOINTS [ 'SEARCH' ] , params ) result_data = [ ] for person in response [ 'result_data' ] : try : detail = self . person_details ( person [ 'person_id' ] , standardize = standardize ) except ValueError : pass else : result_data ... | Get a detailed list of person objects for the given search params . | 108 | 13 |
8,322 | def person_details ( self , person_id , standardize = False ) : resp = self . _request ( path . join ( ENDPOINTS [ 'DETAILS' ] , person_id ) ) if standardize : resp [ 'result_data' ] = [ self . standardize ( res ) for res in resp [ 'result_data' ] ] return resp | Get a detailed person object | 81 | 5 |
8,323 | def plot_ps_extra ( dataobj , key , * * kwargs ) : if isinstance ( dataobj , pd . DataFrame ) : df_raw = dataobj else : df_raw = dataobj . data if kwargs . get ( 'subquery' , False ) : df = df_raw . query ( kwargs . get ( 'subquery' ) ) else : df = df_raw def fancyfy ( axes , N ) : for ax in axes [ 0 : - 1 , : ] . flat... | Create grouped pseudoplots for one or more time steps | 488 | 11 |
8,324 | def twisted_absolute_path ( path , request ) : parsed = urlparse . urlparse ( request . uri ) if parsed . scheme != '' : path_parts = parsed . path . lstrip ( '/' ) . split ( '/' ) request . prepath = path_parts [ 0 : 1 ] request . postpath = path_parts [ 1 : ] path = request . prepath [ 0 ] return path , request | Hack to fix twisted not accepting absolute URIs | 90 | 9 |
8,325 | def _add_rhoa ( df , spacing ) : df [ 'k' ] = redaK . compute_K_analytical ( df , spacing = spacing ) df [ 'rho_a' ] = df [ 'r' ] * df [ 'k' ] if 'Zt' in df . columns : df [ 'rho_a_complex' ] = df [ 'Zt' ] * df [ 'k' ] return df | a simple wrapper to compute K factors and add rhoa | 98 | 12 |
8,326 | def simplify ( geoids ) : from collections import defaultdict aggregated = defaultdict ( set ) d = { } for g in geoids : if not bool ( g ) : continue av = g . allval ( ) d [ av ] = None aggregated [ av ] . add ( g ) compiled = set ( ) for k , v in aggregated . items ( ) : if len ( v ) >= 5 : compiled . add ( k ) compil... | Given a list of geoids reduce it to a simpler set . If there are five or more geoids at one summary level convert them to a single geoid at the higher level . | 111 | 37 |
8,327 | def isimplify ( geoids ) : s0 = list ( geoids ) for i in range ( 10 ) : s1 = simplify ( s0 ) if len ( s1 ) == len ( s0 ) : return s1 s0 = s1 | Iteratively simplify until the set stops getting smaller . | 54 | 10 |
8,328 | def regenerate_thumbs ( self ) : Model = self . model instances = Model . objects . all ( ) num_instances = instances . count ( ) # Filenames are keys in here, to help avoid re-genning something that # we have already done. regen_tracker = { } counter = 1 for instance in instances : file = getattr ( instance , self . f... | Handle re - generating the thumbnails . All this involves is reading the original file then saving the same exact thing . Kind of annoying but it s simple . | 478 | 31 |
8,329 | def count_vowels ( text ) : count = 0 for i in text : if i . lower ( ) in config . AVRO_VOWELS : count += 1 return count | Count number of occurrences of vowels in a given string | 40 | 11 |
8,330 | def count_consonants ( text ) : count = 0 for i in text : if i . lower ( ) in config . AVRO_CONSONANTS : count += 1 return count | Count number of occurrences of consonants in a given string | 41 | 11 |
8,331 | def _pseudodepths_wenner ( configs , spacing = 1 , grid = None ) : if grid is None : xpositions = ( configs - 1 ) * spacing else : xpositions = grid . get_electrode_positions ( ) [ configs - 1 , 0 ] z = np . abs ( np . max ( xpositions , axis = 1 ) - np . min ( xpositions , axis = 1 ) ) * - 0.11 x = np . mean ( xpositi... | Given distances between electrodes compute Wenner pseudo depths for the provided configuration | 121 | 13 |
8,332 | def plot_pseudodepths ( configs , nr_electrodes , spacing = 1 , grid = None , ctypes = None , dd_merge = False , * * kwargs ) : # for each configuration type we have different ways of computing # pseudodepths pseudo_d_functions = { 'dd' : _pseudodepths_dd_simple , 'schlumberger' : _pseudodepths_schlumberger , 'wenner' ... | Plot pseudodepths for the measurements . If grid is given then the actual electrode positions are used and the parameter spacing is ignored | 765 | 26 |
8,333 | def matplot ( x , y , z , ax = None , colorbar = True , * * kwargs ) : xmin = x . min ( ) xmax = x . max ( ) dx = np . abs ( x [ 0 , 1 ] - x [ 0 , 0 ] ) ymin = y . min ( ) ymax = y . max ( ) dy = np . abs ( y [ 1 , 0 ] - y [ 0 , 0 ] ) x2 , y2 = np . meshgrid ( np . arange ( xmin , xmax + 2 * dx , dx ) - dx / 2. , np . ... | Plot x y z as expected with correct axis labels . | 310 | 11 |
8,334 | def summary ( self ) : return "\n" . join ( [ "Transaction:" , " When: " + self . date . strftime ( "%a %d %b %Y" ) , " Description: " + self . desc . replace ( '\n' , ' ' ) , " For amount: {}" . format ( self . amount ) , " From: {}" . format ( ", " . join ( map ( lambda x : x . account , self . src ) ) if self . src ... | Return a string summary of transaction | 154 | 6 |
8,335 | def check ( self ) : if not self . date : raise XnDataError ( "Missing date" ) if not self . desc : raise XnDataError ( "Missing description" ) if not self . dst : raise XnDataError ( "No destination accounts" ) if not self . src : raise XnDataError ( "No source accounts" ) if not self . amount : raise XnDataError ( "N... | Check this transaction for completeness | 94 | 6 |
8,336 | def balance ( self ) : self . check ( ) if not sum ( map ( lambda x : x . amount , self . src ) ) == - self . amount : raise XnBalanceError ( "Sum of source amounts " "not equal to transaction amount" ) if not sum ( map ( lambda x : x . amount , self . dst ) ) == self . amount : raise XnBalanceError ( "Sum of destinati... | Check this transaction for correctness | 100 | 5 |
8,337 | def match_rules ( self , rules ) : try : self . check ( ) return None except XnDataError : pass scores = { } for r in rules : outcomes = r . match ( self ) if not outcomes : continue for outcome in outcomes : if isinstance ( outcome , rule . SourceOutcome ) : key = 'src' elif isinstance ( outcome , rule . DestinationOu... | Process this transaction against the given ruleset | 196 | 8 |
8,338 | def complete ( self , uio , dropped = False ) : if self . dropped and not dropped : # do nothing for dropped xn, unless specifically told to return for end in [ 'src' , 'dst' ] : if getattr ( self , end ) : continue # we have this information uio . show ( '\nEnter ' + end + ' for transaction:' ) uio . show ( '' ) uio .... | Query for all missing information in the transaction | 259 | 8 |
8,339 | def process ( self , rules , uio , prevxn = None ) : self . apply_outcomes ( self . match_rules ( rules ) , uio , prevxn = prevxn ) | Matches rules and applies outcomes | 44 | 6 |
8,340 | def plot_quadpole_evolution ( dataobj , quadpole , cols , threshold = 5 , rolling = False , ax = None ) : if isinstance ( dataobj , pd . DataFrame ) : df = dataobj else : df = dataobj . data subquery = df . query ( 'a == {0} and b == {1} and m == {2} and n == {3}' . format ( * quadpole ) ) # rhoa = subquery['rho_a'].va... | Visualize time - lapse evolution of a single quadropole . | 592 | 13 |
8,341 | def visitSenseFlags ( self , ctx : ShExDocParser . SenseFlagsContext ) : if '!' in ctx . getText ( ) : self . expression . negated = True if '^' in ctx . getText ( ) : self . expression . inverse = True | ! ^ ? | ^ ! ? | 60 | 7 |
8,342 | def as_tuple ( self ) : if self . _tuple is None : # extract leading digits from year year = 9999 if self . year : m = self . DIGITS . match ( self . year ) if m : year = int ( m . group ( 0 ) ) month = self . month_num or 99 day = self . day if self . day is not None else 99 # should we include calendar name in tuple ... | Date as three - tuple of numbers | 111 | 7 |
8,343 | def _cmp_date ( self ) : dates = sorted ( val for val in self . kw . values ( ) if isinstance ( val , CalendarDate ) ) if dates : return dates [ 0 ] # return date very far in the future return CalendarDate ( ) | Returns Calendar date used for comparison . | 56 | 7 |
8,344 | def better_sentences ( func ) : @ wraps ( func ) def wrapped ( * args ) : sentences = func ( * args ) new_sentences = [ ] for i , l in enumerate ( sentences ) : if '\n\n' in l : splits = l . split ( '\n\n' ) if len ( splits ) > 1 : for ind , spl in enumerate ( splits ) : if len ( spl ) < 20 : #if DEBUG: print "Discardi... | takes care of some edge cases of sentence tokenization for cases when websites don t close sentences properly usually after blockquotes image captions or attributions | 139 | 31 |
8,345 | def __we_c ( cls , calib , tc , temp , we_v ) : offset_v = calib . pid_elc_mv / 1000.0 response_v = we_v - offset_v # remove electronic zero response_c = tc . correct ( temp , response_v ) # correct the response component if response_c is None : return None we_c = response_c + offset_v # replace electronic zero return ... | Compute weC from sensor temperature compensation of weV | 99 | 11 |
8,346 | def __cnc ( cls , calib , we_c ) : if we_c is None : return None offset_v = calib . pid_elc_mv / 1000.0 response_c = we_c - offset_v # remove electronic zero cnc = response_c / calib . pid_sens_mv # pid_sens_mv set for ppb or ppm - see PID.init() return cnc | Compute cnc from weC | 95 | 7 |
8,347 | def add_to_class ( self , model_class ) : model_class . _meta . add_field ( self ) setattr ( model_class , self . name , _FieldDescriptor ( self ) ) | Replace the Field attribute with a named _FieldDescriptor . | 47 | 14 |
8,348 | def add_field ( self , field ) : self . remove_field ( field . name ) self . _fields [ field . name ] = field if field . default is not None : if six . callable ( field . default ) : self . _default_callables [ field . key ] = field . default else : self . _defaults [ field . key ] = field . default | Add the received field to the model . | 82 | 8 |
8,349 | def remove_field ( self , field_name ) : field = self . _fields . pop ( field_name , None ) if field is not None and field . default is not None : if six . callable ( field . default ) : self . _default_callables . pop ( field . key , None ) else : self . _defaults . pop ( field . key , None ) | Remove the field with the received field name from model . | 83 | 11 |
8,350 | def get_defaults ( self ) : defaults = self . _defaults . copy ( ) for field_key , default in self . _default_callables . items ( ) : defaults [ field_key ] = default ( ) return defaults | Get a dictionary that contains all the available defaults . | 51 | 10 |
8,351 | def speak ( self , textstr , lang = 'en-US' , gender = 'female' , format = 'riff-16khz-16bit-mono-pcm' ) : # print("speak(textstr=%s, lang=%s, gender=%s, format=%s)" % (textstr, lang, gender, format)) concatkey = '%s-%s-%s-%s' % ( textstr , lang . lower ( ) , gender . lower ( ) , format ) key = self . tts_engine + '' +... | Run will call Microsoft Translate API and and produce audio | 238 | 11 |
8,352 | def call ( args ) : b = StringIO ( ) p = subprocess . Popen ( args , stdout = subprocess . PIPE , stderr = subprocess . STDOUT ) encoding = getattr ( sys . stdout , 'encoding' , None ) or 'utf-8' # old python has bug in p.stdout, so the following little # hack is required. for stdout in iter ( p . stdout . readline , '... | Call terminal command and return exit_code and stdout | 204 | 11 |
8,353 | def get_command_str ( args ) : single_quote = "'" double_quote = '"' for i , value in enumerate ( args ) : if " " in value and double_quote not in value : args [ i ] = '"%s"' % value elif " " in value and single_quote not in value : args [ i ] = "'%s'" % value return " " . join ( args ) | Get terminal command string from list of command and arguments | 91 | 10 |
8,354 | def receive_data_chunk ( self , raw_data , start ) : self . file . write ( raw_data ) # CHANGED: This un-hangs us long enough to keep things rolling. eventlet . sleep ( 0 ) | Over - ridden method to circumvent the worker timeouts on large uploads . | 52 | 15 |
8,355 | def stoptimes ( self , start_date , end_date ) : params = { 'start' : self . format_date ( start_date ) , 'end' : self . format_date ( end_date ) } response = self . _request ( ENDPOINTS [ 'STOPTIMES' ] , params ) return response | Return all stop times in the date range | 74 | 8 |
8,356 | def setup_logger ( self ) : self . log_list = [ ] handler = ListHandler ( self . log_list ) formatter = logging . Formatter ( '%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) handler . setFormatter ( formatter ) logger = logging . getLogger ( ) logger . addHandler ( handler ) logger . setLevel ( logging . INFO ... | Setup a logger | 109 | 3 |
8,357 | def match_to_dict ( match ) : balance , indent , account_fragment = match . group ( 1 , 2 , 3 ) return { 'balance' : decimal . Decimal ( balance ) , 'indent' : len ( indent ) , 'account_fragment' : account_fragment , 'parent' : None , 'children' : [ ] , } | Convert a match object into a dict . | 82 | 9 |
8,358 | def balance ( output ) : lines = map ( pattern . search , output . splitlines ( ) ) stack = [ ] top = [ ] for item in map ( match_to_dict , itertools . takewhile ( lambda x : x , lines ) ) : # pop items off stack while current item has indent <= while stack and item [ 'indent' ] <= stack [ - 1 ] [ 'indent' ] : stack . ... | Convert ledger balance output into an hierarchical data structure . | 158 | 11 |
8,359 | def is_punctuation ( text ) : return not ( text . lower ( ) in config . AVRO_VOWELS or text . lower ( ) in config . AVRO_CONSONANTS ) | Check if given string is a punctuation | 46 | 8 |
8,360 | def is_exact ( needle , haystack , start , end , matchnot ) : return ( ( start >= 0 and end < len ( haystack ) and haystack [ start : end ] == needle ) ^ matchnot ) | Check exact occurrence of needle in haystack | 48 | 8 |
8,361 | def fix_string_case ( text ) : fixed = [ ] for i in text : if is_case_sensitive ( i ) : fixed . append ( i ) else : fixed . append ( i . lower ( ) ) return '' . join ( fixed ) | Converts case - insensitive characters to lower case | 54 | 9 |
8,362 | def _crmod_to_abmn ( self , configs ) : A = configs [ : , 0 ] % 1e4 B = np . floor ( configs [ : , 0 ] / 1e4 ) . astype ( int ) M = configs [ : , 1 ] % 1e4 N = np . floor ( configs [ : , 1 ] / 1e4 ) . astype ( int ) ABMN = np . hstack ( ( A [ : , np . newaxis ] , B [ : , np . newaxis ] , M [ : , np . newaxis ] , N [ : ... | convert crmod - style configurations to a Nx4 array | 149 | 13 |
8,363 | def load_crmod_config ( self , filename ) : with open ( filename , 'r' ) as fid : nr_of_configs = int ( fid . readline ( ) . strip ( ) ) configs = np . loadtxt ( fid ) print ( 'loaded configs:' , configs . shape ) if nr_of_configs != configs . shape [ 0 ] : raise Exception ( 'indicated number of measurements does not e... | Load a CRMod configuration file | 139 | 6 |
8,364 | def _get_crmod_abmn ( self ) : ABMN = np . vstack ( ( self . configs [ : , 0 ] * 1e4 + self . configs [ : , 1 ] , self . configs [ : , 2 ] * 1e4 + self . configs [ : , 3 ] , ) ) . T . astype ( int ) return ABMN | return a Nx2 array with the measurement configurations formatted CRTomo style | 83 | 15 |
8,365 | def write_crmod_volt ( self , filename , mid ) : ABMN = self . _get_crmod_abmn ( ) if isinstance ( mid , ( list , tuple ) ) : mag_data = self . measurements [ mid [ 0 ] ] pha_data = self . measurements [ mid [ 1 ] ] else : mag_data = self . measurements [ mid ] pha_data = np . zeros ( mag_data . shape ) all_data = np .... | Write the measurements to the output file in the volt . dat file format that can be read by CRTomo . | 205 | 23 |
8,366 | def write_crmod_config ( self , filename ) : ABMN = self . _get_crmod_abmn ( ) with open ( filename , 'wb' ) as fid : fid . write ( bytes ( '{0}\n' . format ( ABMN . shape [ 0 ] ) , 'utf-8' , ) ) np . savetxt ( fid , ABMN . astype ( int ) , fmt = '%i %i' ) | Write the configurations to a configuration file in the CRMod format All configurations are merged into one previor to writing to file | 97 | 24 |
8,367 | def gen_dipole_dipole ( self , skipc , skipv = None , stepc = 1 , stepv = 1 , nr_voltage_dipoles = 10 , before_current = False , start_skip = 0 , N = None ) : if N is None and self . nr_electrodes is None : raise Exception ( 'You must provide the number of electrodes' ) elif N is None : N = self . nr_electrodes # by de... | Generate dipole - dipole configurations | 408 | 8 |
8,368 | def gen_gradient ( self , skip = 0 , step = 1 , vskip = 0 , vstep = 1 ) : N = self . nr_electrodes quadpoles = [ ] for a in range ( 1 , N - skip , step ) : b = a + skip + 1 for m in range ( a + 1 , b - vskip - 1 , vstep ) : n = m + vskip + 1 quadpoles . append ( ( a , b , m , n ) ) configs = np . array ( quadpoles ) if... | Generate gradient measurements | 146 | 4 |
8,369 | def remove_duplicates ( self , configs = None ) : if configs is None : c = self . configs else : c = configs struct = c . view ( c . dtype . descr * 4 ) configs_unique = np . unique ( struct ) . view ( c . dtype ) . reshape ( - 1 , 4 ) if configs is None : self . configs = configs_unique else : return configs_unique | remove duplicate entries from 4 - point configurations . If no configurations are provided then use self . configs . Unique configurations are only returned if configs is not None . | 99 | 33 |
8,370 | def gen_schlumberger ( self , M , N , a = None ) : if a is None : a = np . abs ( M - N ) nr_of_steps_left = int ( min ( M , N ) - 1 / a ) nr_of_steps_right = int ( ( self . nr_electrodes - max ( M , N ) ) / a ) configs = [ ] for i in range ( 0 , min ( nr_of_steps_left , nr_of_steps_right ) ) : A = min ( M , N ) - ( i +... | generate one Schlumberger sounding configuration that is one set of configurations for one potential dipole MN . | 193 | 21 |
8,371 | def add_to_configs ( self , configs ) : if len ( configs ) == 0 : return None if self . configs is None : self . configs = np . atleast_2d ( configs ) else : configs = np . atleast_2d ( configs ) self . configs = np . vstack ( ( self . configs , configs ) ) return self . configs | Add one or more measurement configurations to the stored configurations | 92 | 10 |
8,372 | def split_into_normal_and_reciprocal ( self , pad = False , return_indices = False ) : # for simplicity, we create an array where AB and MN are sorted configs = np . hstack ( ( np . sort ( self . configs [ : , 0 : 2 ] , axis = 1 ) , np . sort ( self . configs [ : , 2 : 4 ] , axis = 1 ) ) ) ab_min = configs [ : , 0 ] mn... | Split the stored configurations into normal and reciprocal measurements | 632 | 9 |
8,373 | def gen_reciprocals ( self , append = False ) : # Switch AB and MN reciprocals = self . configs . copy ( ) [ : , : : - 1 ] reciprocals [ : , 0 : 2 ] = np . sort ( reciprocals [ : , 0 : 2 ] , axis = 1 ) reciprocals [ : , 2 : 4 ] = np . sort ( reciprocals [ : , 2 : 4 ] , axis = 1 ) # # Sort by current dipoles ind = np . ... | Generate reciprocal configurations sort by AB and optionally append to configurations . | 177 | 13 |
8,374 | def gen_configs_permutate ( self , injections_raw , only_same_dipole_length = False , ignore_crossed_dipoles = False , silent = False ) : injections = np . atleast_2d ( injections_raw ) . astype ( int ) N = injections . shape [ 0 ] measurements = [ ] for injection in range ( 0 , N ) : dipole_length = np . abs ( injecti... | Create measurement configurations out of a pool of current injections . Use only the provided dipoles for potential dipole selection . This means that we have always reciprocal measurements . | 479 | 32 |
8,375 | def remove_max_dipole_sep ( self , maxsep = 10 ) : sep = np . abs ( self . configs [ : , 1 ] - self . configs [ : , 2 ] ) self . configs = self . configs [ sep <= maxsep ] | Remove configurations with dipole separations higher than maxsep . | 63 | 13 |
8,376 | def to_pg_scheme ( self , container = None , positions = None ) : if container is None and positions is None : raise Exception ( 'electrode positions are required for BERT export' ) if container is not None and container . electrodes is None : raise Exception ( 'container does not contain electrode positions' ) if cont... | Convert the configuration to a pygimli measurement scheme | 315 | 12 |
8,377 | def to_iris_syscal ( self , filename ) : with open ( filename , 'w' ) as fid : # fprintf(fod, '#\t X\t Y\t Z\n'); fid . write ( '#\t X\t Y\t Z\n' ) # fprintf(fod, '%d\t %.1f\t %d\t %d\n', D'); # loop over electrodes and assign increasing x-positions # TODO: use proper electrode positions, if available for nr in range (... | Export to IRIS Instrument configuration file | 277 | 7 |
8,378 | def create_plan ( self , * , plan_code , description , interval , interval_count , max_payments_allowed , payment_attempts_delay , plan_value , plan_tax , plan_tax_return_base , currency , max_payment_attempts = None , max_pending_payments = None , trial_days = None ) : payload = { "accountId" : self . client . account... | Creating a new plan for subscriptions associated with the merchant . | 331 | 11 |
8,379 | def get_plan ( self , plan_code ) : return self . client . _get ( self . url + 'plans/{}' . format ( plan_code ) , headers = self . get_headers ( ) ) | Check all the information of a plan for subscriptions associated with the merchant . | 49 | 14 |
8,380 | def delete_plan ( self , plan_code ) : return self . client . _delete ( self . url + 'plans/{}' . format ( plan_code ) , headers = self . get_headers ( ) ) | Delete an entire subscription plan associated with the merchant . | 49 | 10 |
8,381 | def create_customer ( self , * , full_name , email ) : payload = { "fullName" : full_name , "email" : email } return self . client . _post ( self . url + 'customers' , json = payload , headers = self . get_headers ( ) ) | Creation of a customer in the system . | 66 | 9 |
8,382 | def get_customer ( self , customer_id ) : return self . client . _get ( self . url + 'customers/{}' . format ( customer_id ) , headers = self . get_headers ( ) ) | Queries the information related to the customer . | 50 | 9 |
8,383 | def delete_customer ( self , customer_id ) : return self . client . _delete ( self . url + 'customers/{}' . format ( customer_id ) , headers = self . get_headers ( ) ) | Removes a user from the system . | 50 | 8 |
8,384 | def create_subscription ( self , * , customer_id , credit_card_token , plan_code , quantity = None , installments = None , trial_days = None , immediate_payment = None , extra1 = None , extra2 = None , delivery_address = None , notify_url = None , recurring_bill_items = None ) : payload = { "quantity" : quantity , "ins... | Creating a new subscription of a client to a plan . | 243 | 11 |
8,385 | def get_subscription ( self , subscription_id ) : return self . client . _put ( self . url + 'subscriptions/{}' . format ( subscription_id ) , headers = self . get_headers ( ) ) | Check the basic information associated with the specified subscription . | 51 | 10 |
8,386 | def update_subscription ( self , * , subscription_id , credit_card_token ) : payload = { "creditCardToken" : credit_card_token } fmt = 'subscriptions/{}' . format ( subscription_id ) return self . client . _put ( self . url + fmt , json = payload , headers = self . get_headers ( ) ) | Update information associated with the specified subscription . At the moment it is only possible to update the token of the credit card to which the charge of the subscription is made . | 81 | 33 |
8,387 | def delete_subscription ( self , subscription_id ) : return self . client . _delete ( self . url + 'subscriptions/{}' . format ( subscription_id ) , headers = self . get_headers ( ) ) | Unsubscribe delete the relationship of the customer with the plan . | 51 | 13 |
8,388 | def create_additional_charge ( self , * , subscription_id , description , plan_value , plan_tax , plan_tax_return_base , currency ) : payload = { "description" : description , "additionalValues" : [ { "name" : "ITEM_VALUE" , "value" : plan_value , "currency" : currency } , { "name" : "ITEM_TAX" , "value" : plan_tax , "... | Adds extra charges to the respective invoice for the current period . | 197 | 12 |
8,389 | def get_additional_charge_by_identifier ( self , recurring_billing_id ) : fmt = 'recurringBillItems/{}' . format ( recurring_billing_id ) return self . client . _get ( self . url + fmt , headers = self . get_headers ( ) ) | Query extra charge information of an invoice from its identifier . | 68 | 11 |
8,390 | def update_additional_charge ( self , * , recurring_billing_id , description , plan_value , plan_tax , plan_tax_return_base , currency ) : payload = { "description" : description , "additionalValues" : [ { "name" : "ITEM_VALUE" , "value" : plan_value , "currency" : currency } , { "name" : "ITEM_TAX" , "value" : plan_ta... | Updates the information from an additional charge in an invoice . | 199 | 12 |
8,391 | def delete_additional_charge ( self , recurring_billing_id ) : fmt = 'recurringBillItems/{}' . format ( recurring_billing_id ) return self . client . _delete ( self . url + fmt , headers = self . get_headers ( ) ) | Remove an extra charge from an invoice . | 63 | 8 |
8,392 | def thumbnail ( parser , token ) : args = token . split_contents ( ) tag = args [ 0 ] # Check to see if we're setting to a context variable. if len ( args ) > 4 and args [ - 2 ] == 'as' : context_name = args [ - 1 ] args = args [ : - 2 ] else : context_name = None if len ( args ) < 3 : raise TemplateSyntaxError ( "Inva... | Creates a thumbnail of for an ImageField . | 390 | 10 |
8,393 | def printStats ( self ) : print ( "--- Imagestats Results ---" ) if ( self . fields . find ( 'npix' ) != - 1 ) : print ( "Number of pixels : " , self . npix ) if ( self . fields . find ( 'min' ) != - 1 ) : print ( "Minimum value : " , self . min ) if ( self . fields . find ( 'max' ) != - 1 ) : print ( "Maximum value : ... | Print the requested statistics values for those fields specified on input . | 260 | 12 |
8,394 | def raw_request ( self , method , uri , * * kwargs ) : with warnings . catch_warnings ( ) : # catch warning about certs not being verified warnings . simplefilter ( "ignore" , urllib3 . exceptions . InsecureRequestWarning ) warnings . simplefilter ( "ignore" , urllib3 . exceptions . InsecurePlatformWarning ) try : resp... | Perform a WVA web services request and return the raw response object | 157 | 14 |
8,395 | def request ( self , method , uri , * * kwargs ) : response = self . raw_request ( method , uri , * * kwargs ) if response . status_code != 200 : exception_class = HTTP_STATUS_EXCEPTION_MAP . get ( response . status_code , WVAHttpError ) raise exception_class ( response ) if response . headers . get ( "content-type" ) ... | Perform a WVA web services request and return the decoded value if successful | 115 | 16 |
8,396 | def post ( self , uri , data , * * kwargs ) : return self . request ( "POST" , uri , data = data , * * kwargs ) | POST the provided data to the specified path | 39 | 8 |
8,397 | def post_json ( self , uri , data , * * kwargs ) : encoded_data = json . dumps ( data ) kwargs . setdefault ( "headers" , { } ) . update ( { "Content-Type" : "application/json" , # tell server we are sending json } ) return self . post ( uri , data = encoded_data , * * kwargs ) | POST the provided data as json to the specified path | 88 | 10 |
8,398 | def put ( self , uri , data , * * kwargs ) : return self . request ( "PUT" , uri , data = data , * * kwargs ) | PUT the provided data to the specified path | 39 | 8 |
8,399 | def put_json ( self , uri , data , * * kwargs ) : encoded_data = json . dumps ( data ) kwargs . setdefault ( "headers" , { } ) . update ( { "Content-Type" : "application/json" , # tell server we are sending json } ) return self . put ( uri , data = encoded_data , * * kwargs ) | PUT the provided data as json to the specified path | 88 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.